Moodle 19 Extension Development Customize And
Extend Moodle By Using Its Robust Plugin Systems
Jonathan Moore download
https://ebookbell.com/product/moodle-19-extension-development-
customize-and-extend-moodle-by-using-its-robust-plugin-systems-
jonathan-moore-2434524
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Moodle 19 Top Extensions Cookbook 1st Edition De Raadt Michael
https://ebookbell.com/product/moodle-19-top-extensions-cookbook-1st-
edition-de-raadt-michael-55201978
Moodle 19 Theme Design Beginners Guide Gadsdon Paul James
https://ebookbell.com/product/moodle-19-theme-design-beginners-guide-
gadsdon-paul-james-55201976
Moodle 19 For Design And Technology 1st Edition Taylor Paul
https://ebookbell.com/product/moodle-19-for-design-and-technology-1st-
edition-taylor-paul-55201984
Moodle 19 For Teaching 714 Year Olds Beginners Guide Cooch
https://ebookbell.com/product/moodle-19-for-teaching-714-year-olds-
beginners-guide-cooch-55201988
Moodle 19 Teaching Techniques 1st Edition Smith Nash Susan Rice
https://ebookbell.com/product/moodle-19-teaching-techniques-1st-
edition-smith-nash-susan-rice-55201992
Moodle 19 Elearning Course Development A Complete Guide To Successful
Learning Using Moodle 19 1st Edition William H Rice
https://ebookbell.com/product/moodle-19-elearning-course-development-
a-complete-guide-to-successful-learning-using-moodle-19-1st-edition-
william-h-rice-2358366
Moodle 19 Testing And Assessment Jason Myrick
https://ebookbell.com/product/moodle-19-testing-and-assessment-jason-
myrick-2532670
Moodle 19 Testing And Assessment Jason Myrick
https://ebookbell.com/product/moodle-19-testing-and-assessment-jason-
myrick-2568030
Moodle 19 Theme Design Beginners Guide Customize The Appearance Of
Your Moodle Theme By Using Moodles Powerful Theming Engine Paul James
Gadsdon
https://ebookbell.com/product/moodle-19-theme-design-beginners-guide-
customize-the-appearance-of-your-moodle-theme-by-using-moodles-
powerful-theming-engine-paul-james-gadsdon-4104696
Moodle 1.9
Extension Development
Customize and extend Moodle by using its robust
plugin systems
Jonathan Moore
Michael Churchward
BIRMINGHAM - MUMBAI
Moodle 1.9 Extension Development
Copyright © 2010 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the authors, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First published: April 2010
Production Reference: 1220410
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-847194-24-4
www.packtpub.com
Cover Image by Parag Kadam (paragvkadam@gmail.com)
Credits
Authors
Jonathan Moore
Michael Churchward
Reviewer
Anthony Borrow
Acquisition Editor
Rashmi Phadnis
Development Editor
Ved Prakash Jha
Technical Editors
Chris Rodrigues
Hithesh Uchil
Indexer
Hemangini Bari
Editorial Team Leader
Akshara Aware
Project Team Leader
Priya Mukherji
Project Coordinator
Ashwin Shetty
Proofreader
Dirk Manuel
Graphics
Geetanjali Sawant
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
About the Authors
Michael Churchward is currently the President and CTO of Remote Learner, a
Moodle partner based in the U.S. and Canada. Mike has been a developer of Moodle
since 2004, and contributes both core code and add-on functions to the open source
project. Mike and his development team are currently working on other extensions
to Moodle, and helping to define the new Moodle 2.0 architecture.
Michael began his career building computer-based simulations of internal aircraft
systems used in the training of ground and maintenance crews. Since then, he
has been involved in many types of software and computer-based learning.
Programming Moodle became a natural extension of that career.
Michael lives with his family in a small town in south-western Ontario, and thanks
all of them for their patience while he was writing this book.
I thank the Moodle community for their energy and input; my
wife, Janet; my sons, William, Cole, and Janson for their constant
encouragement; and lastly my parents, Bob and Lorane for pointing
me in the right direction.
Jonathan Moore is the Vice-President for Business Development at Remote
Learner. Jonathan began working with Moodle in 2003. Over the past four years,
Jonathan has worked with dozens of clients, delivering Moodle customizations.
Jonathan has a Bachelor of Science degree in Information Technology.
Jonathan formerly served as the Director of Technology for Winfield Public Schools.
He served in this capacity for almost ten years, and has developed a broad set of
educational technology and project management skills over the course of his career.
His student technology program, Student Technology Assistance Team (STAT), was
recognized nationally by CompTIA as the best rural student technology program.
Earlier in his career, Jonathan worked as a full-time developer, and studied computer
science prior to pursuing Information Technology. Jonathan started working with
open source technology in 1993 with an early release of Slackware Linux, and has
used and supported a variety of open source technologies in educational settings.
Jonathan lives with his wife, in Lenexa, Kansas, a suburb of Kansas City.
I wish to thank my co-author, Michael Churchward, for taking
on this crazy project to write a book while growing a company.
Thanks for taking this leap of faith. I would also like to thank my
wife for putting up with a cranky writer this past year, my parents
for emphasizing the importance of literacy, Bryan Williams and the
rest of our leadership team for their support, and finally the staff of
Winfield Public Schools for providing a wonderful place to grow.
About the Reviewer
Anthony Borrow, S.J. is a Jesuit of the New Orleans Province, who has been active
in the Moodle community for five years. Anthony has an M.A. in Counseling from
Saint Louis University. Anthony has worked on the design and implementation of
various database systems since 1992.
Anthony serves the Moodle community as its CONTRIB Coordinator. In that role,
Anthony has presented at various MoodleMoots (conferences) across the United
States, and has provided in-house training opportunities for institutions learning
how to implement Moodle. Anthony has taught at Dallas Jesuit College Preparatory
and provides technical advice to the Jesuit Secondary Education Association
(http://jsea.org) and the Jesuit Virtual Learning Academy (http://jvla.org/).
Anthony is the co-author of the Honduras chapter of Teen Gangs: A Global View.
Table of Contents
Preface 1
Chapter 1: Moodle Architecture 7
Understanding the stack 8
Database 9
Operating system 10
Web server 10
Directory and system structure 11
Moodle code 12
Moodle database 15
Moodle data 16
Installing Moodle 16
Moodle program execution 18
Executing config.php 18
Including Moodle libraries 19
Getting our data 20
Displaying in Moodle 20
Configuring Moodle 21
Setting configuration variables 22
Moodle's API 23
Other important libraries 25
PEAR 25
ADOdb 25
YUI 25
XMLDB 25
Access control, logins, and roles 26
Moodle permission contexts 26
Capabilities 27
Table of Contents
[ ii ]
Moodle roles 28
Assigning roles 28
Summary 29
Chapter 2: Creating and Modifying Blocks 31
Creating a block from scratch 31
Assigning content to our block 32
Adding a language file 33
Working with capabilities 34
Testing for built-in capabilities 34
Hiding a block based on capabilities 36
Adding your own capability 36
Checking for our new capability 37
Adding instance configuration 38
Capturing your configuration content 38
Displaying your content 39
Adding scheduled actions to our block 40
Reviewing a real world block 42
Reviewing block_instructor_contact.php 43
Configuring the instructor contact block 44
Using a block as a code container 45
Creating a block stub for our container 45
Creating capabilities for our container 46
Summary 47
Chapter 3: Creating and Modifying Filters 49
How a filter works 49
Building a filter 50
Getting started 51
Creating the language file 52
Creating the filter code 53
Activating the filter 54
Adding configuration settings 55
Using our settings 57
Summary 58
Chapter 4: Creating and Modifying Activity Modules 59
The scope of creating an activity module 59
Our module—activity Foo! 61
Getting started with the NEWMODULE template 62
Completing mod_form.php 62
Defining input values 64
Using common form elements 65
Table of Contents
[ iii ]
Making version.php 66
Setting icon.gif 66
Generating install.xml 66
Using the XMLDB editor 66
Defining our activity database 67
Defining the foo_responses table 68
Defining log types 69
Creating access.php 69
Updating index.php 69
Adding clean language strings 70
Looking up response data 70
Displaying our table of activities 71
Displaying course sections 71
Committing output 72
Finishing view.php 73
Including submit_form.php 73
Your code goes here 73
Context control 73
Developing a form 74
Cancel option 74
Submitted data 74
Setting grades 75
Displaying submission form 75
Displaying submissions 76
Group support 76
Coding lib.php 78
Function add_instance 78
Function foo_delete_instance 78
Function foo_user_outline 79
Function foo_user_complete 79
Function foo_get_participants 80
Function reset_course_form_definition 81
Function foo_reset_course_form_defaults 81
Function foo_reset_userdata 81
Inserting grades into the gradebook 82
Using grade_update 83
Upgrading our activity database 84
Using the XMLDB editor for database upgrades 84
Updating upgrade.php 84
Table of Contents
[ iv ]
Creating backup and restore support 85
Exploring backuplib.php functions 86
Common backup functions 86
Internal backup functions 87
Exploring restorelib.php functions 87
Common restore functions 87
Internal restore functions 88
Summary 88
Chapter 5: Customizing the Look and Feel 89
Themes 89
How themes work 90
Headers and footers 90
header.html 91
footer.html 92
Project 1: Changing the navigation breadcrumbs 93
Creating our own theme 93
Adding the category link 94
The navigation string 94
Project 2: Adding a standard footer with site links 96
Creating the code 97
Running the code 99
Course formats 101
How course formats work 101
Creating our own course format 102
Creating the course format language file 102
Modifying our course format function 103
Changing the forum display 104
Summary 105
Chapter 6: Developer's Guide to the Database 107
The database structure 107
Maintaining Moodle tables 109
install.xml 109
upgrade.php 110
Maintaining local database customization 112
The XMLDB editor 113
Using the Moodle database in your code 115
Retrieving data 115
Query by parameters 116
Query by "where" string 118
Query by full SQL 119
Storing data 119
set_field and set_field_select 120
insert_record and update_record 120
Table of Contents
[  ]
Common tables and relationships 121
Course and module relationships 121
Programming best practices 123
Take only what you need 123
Limiting your returned data 123
Using recordsets 124
Optimizing carefully with joins 124
Testing on more than one database engine 125
Summary 125
Chapter 7: Developing Pluggable Core Modules 127
Assignment types 127
What is an assignment type 128
Identifying assignment types 129
Assignment type basics 129
Building our own assignment type 130
Getting started 130
Planning our data 131
Adding custom settings 133
Making it do something useful 134
Resource types 140
What is a resource type? 140
Identifying resource types 140
Resource type basics 141
Question types 142
What is a question type? 143
Identifying question types 144
Question type basics 144
The main class 145
The editing form 145
The main language file 146
Other important question constructs 147
Grading 147
Backup and restore functions 147
Import and export function support 147
CSS and JavaScript support 148
Where to get more help 148
Summary 148
Chapter 8: Creating Moodle Reports 149
Creating course reports 150
Defining the non-participants report 150
Getting started 151
Updating mod.php 151
Table of Contents
[ vi ]
Controlling access 152
Language strings 152
Changes to Moodle's API 153
Exploring the People block 154
Setting $select 154
Setting $from 155
Setting $where 156
Making the query call 156
Modifying index.php 157
Making text substitutions 157
Changing the logical structure 158
Tracking active users using a hash array 159
Displaying the report 160
Cleaning up the final display 161
Using flexible_table 162
An exercise for you 163
Creating gradebook reports 163
Required components 164
Creating our report folder 164
Creating access.php 164
Assigning language strings 164
index.php requirements 164
Using version.php 165
Using the grade_report class 165
Fixing the outcomes report 165
Digging into the code 166
Reviewing our new report 167
Creating administrator reports 167
Generating the Hello World administrator report 168
Tweaking index.php 168
Viewing our administrator report 169
An exercise for you 170
Other output formats 170
Summary 170
Chapter 9: Integrating Moodle with Other Systems 171
Built-in services and plugins 171
Batch upload 172
Built-in authentication plugins 173
Manual/Internal authentication 173
LDAP/Active directory authentication 173
External database authentication 174
E-mail account based authentication plugins 174
Built-in enrollment plugins 174
LDAP enrollment plugin 175
Table of Contents
[ vii ]
External database enrollment plugin 175
E-commerce based enrollment plugins 175
Web services 176
Activity plugin as an integration bridge 176
Creating user authentication plugins 176
Exploring authentication requirements 176
Looking at auth.php 177
Making the language file 178
Testing simple authentication 178
Adding optional functionality to authentication 178
Creating the RLLDAP authentication plugin 179
Coding RLLDAP 180
Implementing Single Sign On 183
Creating a URL-based SSO 183
Digging into the code 184
Finding the user's account 184
Confirming that the login criteria have been met 184
Completing login 184
Redirecting the user to the correct location 185
Testing the URL SSO 185
Creating user enrollment plugins 186
Reviewing plugin requirements 186
Creating enrol.php 186
Creating the setup_enrolments function 186
Making the language file 187
Other requirements 187
Making the 'simple' enrollment plugin 187
Using optional enrollment functions 188
Assigning enrollment plugins to courses 188
Grade or completion passing 189
Working with the built-in import/export plugins 189
Creating grade import/export plugins 190
An exercise for you 190
Summary 190
Chapter 10: Writing Secure Code 191
User access issues 191
Making sure that a user has logged in 192
Making sure that the user's session is the current one 192
Making sure that the user has appropriate capabilities 194
SQL issues 195
Taking a look at vulnerable code 195
Quote protection 196
Database API 197
Use of addslashes 197
Table of Contents
[ viii ]
Form issues 198
The Moodle formslib library 199
Specifying a type 199
Validation rules 200
'param' functions 201
File system issues 201
Course file areas 202
User file areas 202
Other file areas 203
Getting a file URL 203
Screen output issues 204
The p() and s() functions 204
The format_text() and format_string() functions 205
Logging your actions 207
Summary 208
Chapter 11: Sending Notifications to Users 209
Requirements 209
Setup 210
Using e-mail 213
Send e-mail API 214
Creating the subject text 214
Creating the message text 215
Sending the e-mail 215
Using Moodle messaging 216
Moodle messaging internals 216
Creating the message 217
Sending the message 218
Using RSS feeds 219
Setup 219
Creating the RSS XML file 220
Viewing the RSS feed 222
Summary 225
Chapter 12: Constructing and Displaying Pages by
Using the pagelib Library 227
Introduction to pagelib 228
Class page_base 228
Class page_course 228
Class page_generic_activity 228
Core modules that use pagelib 228
Table of Contents
[ ix ]
Using pagelib factory functions 229
page_import_types 229
page_create_instance 230
page_create_object 230
page_map_class 230
page_base member functions 230
page_base() and construct() 231
get_id() 231
get_body_class() 231
get_body_id() 231
edit_always() 231
init_quick() 231
init_full() 232
user_allowed_editing() 232
user_is_editing() 232
print_header() 232
get_type() 232
get_format_name() 232
url_get_path() 232
url_get_parameters() 233
blocks_get_positions() 233
blocks_default_position() 233
blocks_get_default() 233
blocks_move_position() 233
Meeting pagelib requirements 233
Looking at page setup 234
Examining requirements by reviewing quiz's view.php 234
Working with quiz blocks 235
Investigating quiz page display 235
Converting activity Foo! to pagelib 236
Creating a local pagelib.php 236
Updating view.php 238
Initializing $PAGE 238
Outputting blocks 239
Outputting the middle column 239
Viewing the results 240
Related libraries 241
weblib 241
blocklib 241
graphlib 241
Summary 241
Table of Contents
[  ]
Chapter 13: Building Forms with formslib 243
Using formslib 244
Form definition and elements 244
addElement and createElement 245
Buttons 245
Checkboxes 247
Uploading and/or choosing a file 249
Date and time 250
htmleditor, textarea, and text 252
modgrade 253
password and passwordunmask 254
radio 254
select, multi-select, and selectyesno 255
hidden, html, and static text 256
Groups 257
Rules and validation 257
Rules 257
addRule 258
registerRule 259
Validation 260
Summary 261
Chapter 14: Development for the Adventuresome: Web Services 263
Using Remote-Learner Web Services 264
Advantages 264
Disadvantages 265
Installation 265
Server-side setup 265
Client setup 266
Testing with ppdemo_trace.php 266
Setting up your Web Services connection 267
Debugging setup 268
Managing users 269
Creating users 269
Updating users 272
Deleting users 273
Creating a Web Services based Single Sign On 273
Creating our HTML wrapper 274
Web service connection setup 275
Processing SSO parameters 275
Using authenticate_user() 275
Closing wrapper 276
Table of Contents
[ xi ]
Enrollment management 276
Creating enrollstudent.php 277
Using enrol_students() 277
Creating unenrollstudent.php 277
Grade passing 278
Creating the CSV grade script 278
Using Moodle Networking 280
Advantages 280
Disadvantages 280
What is XML-RPC? 281
MNet XML-RPC supported service types 281
MNet XML-RPC security model 281
Using MNet in activity modules 282
Using MNet in auth/enrol plugins 283
MNet SSO model 283
Summary 284
Index 285
Preface
Moodle has evolved into one of the most widely-used Learning Management
Systems in the world, with over 35,000 installed sites and 25 million users. Much of
its popularity is due to its ability to be extended by developers, by using its open
source architecture. Understanding how to develop on the Moodle platform provides
an organization using Moodle the flexibility to expand its functions.
This book will teach you the inner workings of Moodle, and provide you with
the ability to develop code the Moodle way. You will learn to develop standard
Moodle plugins, such as activities and blocks, by creating functioning code that
you can execute in your own Moodle installation.
This book will expose you to all of the core code functions in Moodle in a
progressive, understandable way. You will learn what libraries are available,
what the API calls are, how Moodle is structured, and how it can be expanded
beyond the plugin system.
Approach
This is a practical, hands-on book that will allow you to build plugins as you learn.
All of the technologies that you need are freely-available in the open source world.
You will begin by gaining an understanding of the basic architecture that Moodle
uses to operate in. Next, you will build your first plugin, a block. You will carry on
building other Moodle plugins, gaining knowledge of the Moodle way of coding,
before plunging deeper into the API and inner libraries. Lastly, you will learn how
to integrate Moodle with other systems, by using a variety of methods.
By the time you have finished this book, you will have a solid understanding of
Moodle programming, and will have the knowledge to extend its functionality in
whatever way you want.
Preface
[  ]
What this book covers
Chapter 1, Moodle Architecture, introduces some of the important concepts of Moodle
architecture: how Moodle is structured, and how Moodle works.
Chapter 2, Creating and Modifying Blocks, covers how to create a basic block in
Moodle, one of the easiest and most common customizations. Moodle blocks are
plugins that display content in the right-hand or left-hand side column of a Moodle
site. Several basic Moodle programming concepts that are used throughout the book
are introduced.
Chapter 3, Creating and Modifying Filters, covers the basic concepts of creating a
Moodle filter. The Moodle filter system is a method of processing the contents of the
Moodle database (typically, user-entered content) prior to display, so that it can be
modified in some beneficial way.
Chapter 4, Creating and Modifying Activity Modules, covers how to create a Moodle
activity that can send results to the gradebook. Moodle activities are plugins that
provide instructional activities for learners. One or more activities of each type can
be added to courses, and each activity typically has a graded component that sends
its results to the Moodle gradebook.
Chapter 5, Customizing the Look and Feel, elaborates on the common methods of
customizing the look and feel of a Moodle site. This chapter will discuss how to tell
the difference between a requirement that needs programming and one that can be
completed by a theme designer.
Chapter 6, Developer's Guide to the Database, covers both the overall structure of the
Moodle database and the coding methods used to access and store information there.
Moodle supports a variety of SQL databases to store program information.
Chapter 7, Developing Pluggable Core Modules, covers useful programming concepts
and considerations for the core Moodle system and modules. Some common ways
by which popular modules can be modified are explored in this chapter.
Chapter 8, Creating Moodle Reports, covers a variety of methods of adding to Moodle's
built-in reports. Moodle has an excellent logging system, but often users find they
need to write a custom reporting module in order to get the data in the exact format
that they desire.
Chapter 9, Integrating Moodle with Other Systems, covers four common types
of integrations: user authentication, user enrollment, performance results, and
Single Sign On. A common customization request for Moodle is to integrate
with a third-party system.
Preface
[  ]
Chapter 10, Writing Secure Code, covers various security concerns and best practices
when developing code for Moodle.
Chapter 11, Sending Notifications to Users, discusses methods of messaging and
notifying users through e-mail, RSS, and others.
Chapter 12, Constructing and Displaying Pages by Using the pagelib Library, covers the
basic concepts of using pagelib. The pagelib library is used in the construction of
display pages in Moodle.
Chapter 13, Building Forms with formslib, covers how to use the formslib library
for customizations. The formslib library controls Moodle forms, user input, and
input sanitation.
Chapter 14, Development for the Adventuresome: Web Services, covers two
separate Moodle implementations for web services: one SOAP-based and one
XML-RPC-based. The SOAP library allows remote manipulation and creation of
courses, users, user enrollments, and user grades. The XML-RPC library provides
a secure channel and full Moodle API exposure to the trusted site. This chapter
will explore basic concepts of using both libraries.
Who this book is for
This book is written for technologists who are interested in expanding Moodle's
functions through programming, either for their own organizations or to contribute
to the open source project.
This book is aimed at programmers already familiar with Moodle's basic
technologies: PHP, MySQL, and HTML/CSS.
You will need an understanding of PHP in order to follow along with coding
activities in the book.
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Code words in text are shown as follows: Finally, we display our table using the
print_html member function
Preface
[  ]
A block of code is set as follows:
?php
function learningisfunlink_filter($courseid, $text) {
return $text;
}
?
When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
function get_content() {
if ($this-content !== NULL) {
return $this-content;
}//if
$context = get_context_instance(CONTEXT_SYSTEM);
require_capability('moodle/site:doanything', $context);
$this-content = new stdClass;
$this-content-text = 'Hello World!';
return $this-content;
}//function get_content
New terms and important words are shown in bold. Words that you see on the
screen, in menus, or dialog boxes for example, appear in the text like this: Click
on the Notifications link in the Site Administration block.
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to feedback@packtpub.com,
and mention the book title in the subject of your message.
Preface
[  ]
If there is a book that you need and would like to see us publish, please send us a
note in the SUGGEST A TITLE form on www.packtpub.com or send an e-mail to
suggest@packtpub.com.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book on, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.
Downloading the example code for the book
Visit https://www.packtpub.com//sites/default/files/
downloads/4244_Code.zip to directly download the example code.
Errata
Although we have taken every care to ensure the accuracy of our content,
mistakes do happen. If you find a mistake in one of our books—maybe a mistake
in the text or the code—we would be grateful if you would report this to us. By
doing so, you can save other readers from frustration and help us to improve
subsequent versions of this book. If you find any errata, please report them by
visiting http://www.packtpub.com/support, selecting your book, clicking on
the let us know link, and entering the details of your errata. Once your errata are
verified, your submission will be accepted and the errata will be uploaded on our
website, or added to any list of existing errata under the Errata section of
that title. Any existing errata can be viewed by selecting your title from
http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately, so that we can
pursue a remedy.
Preface
[  ]
Please contact us at copyright@packtpub.com with a link to the suspected
pirated material.
We appreciate your help in protecting our authors and our ability to bring you
valuable content.
Questions
You can contact us at questions@packtpub.com if you are having a problem with
any aspect of the book, and we will do our best to address it.
Moodle Architecture
Moodle is an open source Learning Management System (LMS). It can be used
to deliver online learning in a variety of settings. These settings include virtual
schools, K12, higher education, corporate universities, charter schools, and
commercial training, to name but a few. Moodle is designed to be used primarily as
an asynchronous learning tool, where learners study at different times. However, it
also includes synchronous tools. Moodle is used both as the primary delivery vehicle
for courses as well as a supplemental tool for face-to-face learning. To put it simply,
Moodle is a teacher's toolkit to help improve learning. Moodle is designed in a
community with teachers interacting directly with programmers. Moodle's intuitive
and simple interface is the result of this collaboration.
Moodle originally stood for Modular Object-Oriented Dynamic Learning
Environment. From a programmer's perspective, the M in Moodle is a very
important concept. Modularity is designed throughout Moodle. This lets a developer
make significant modifications to Moodle without having to modify its code. This is
a very important capability in terms of reducing the amount of time taken to make
modifications when new versions of Moodle are released. Writing modular plugins
for Moodle will be a large focus of this book.
You can learn more about general Moodle functionality and history on the Moodle
Documentation site at http://docs.moodle.org/en/About_Moodle.
This chapter introduces some of the important concepts of Moodle architecture;
how Moodle is structured and how Moodle works. This chapter introduces the
following concepts:
Components of the system (operating system, web server, PHP interpreter,
database, and browser)
Directory and system structure (Moodle code, database, and file storage)
Installation (how to install, what happens during installation, and how
to upgrade)
•
•
•
Moodle Architecture
[  ]
Program execution (the major calling structure, included libraries, execution
paths, and separation of function/display/data)
Configuration (from the interface, from the config file, and from
the database)
Application Programming Interface (a brief description of what the major
libraries do)
Other common libraries (PEAR, ADOdb, YUI, and XMLDB)
Access control for users, courses, and other security objects
As you can see from the list, we will be covering a lot of ground in this chapter. Let's
get started with a discussion of the technology stack that drives Moodle.
Understanding the stack
Moodle is an example of a LAMP application. LAMP originally stood for Linux,
Apache, MySQL, and Perl. Over time, the various components of the acronym
have shifted. For example, PHP has become the predominate language for LAMP
applications. In truth, any of the components can be exchanged for another.
However, the title has stuck to refer to applications written in web scripting
languages, using an SQL database to store information. With the increasing
popularity of running open source web applications on both Windows and Mac
OS X, two new terms have been coined, respectively: WAMP and MAMP. See
the following figure, which illustrates components of the system in Moodle:
LAMP Stack
Web Server
Apache Interpreter
PHP
Database Server
MySQL
Linux Operating
System
Moodle is written in PHP, and the current version as of this writing (Version 1.9)
requires PHP Version 4.3.0 or higher. Version 2.0 of Moodle, which is currently
in development, will require PHP Version 5.2.8 or higher.
•
•
•
•
•
Chapter 1
[  ]
Database
Moodle's database layer is written using the PHP ADOdb library, which was created
to provide a standardized method of accessing various database systems, using
a consistent programming interface. PHP native database libraries are database
specific and as a result are difficult to use to write a program that can support
multiple database servers. Thanks to its use of ADOdb, Moodle provides support
for a variety of databases including: MySQL, PostgreSQL, Microsoft SQL, and
Oracle. Moodle supports a much longer list of databases for the purpose of external
system integrations, by using its plugin architecture. While Moodle does enjoy
broad database support, in practice, most systems are deployed using MySQL. As
a practical result of this, more eyes are looking at MySQL installations; it has the
fewest bugs, with the broadest set of third-party additions. PostgreSQL is the second
most popular backend and has a strong following amongst performance enthusiasts
and large deployments (tens of thousands or more users). Microsoft SQL and Oracle
installations are primarily used by organizations with a pre-existing investment in
one of these architectures. Because of their smaller user base, they are not as well
tested. It is also more difficult to find good support for using these database types
with Moodle. Many third-party add-on modules do not work under these systems
without patching.
Database version requirements for Moodle 1.9:
MySQL 4.1.16
PostgreSQL 8.0
Microsoft SQL 9.0
Oracle 9.0
Proposed database requirements for Moodle 2.0:
MySQL 4.1.16 or
PostgreSQL 8.0 or
Microsoft SQL 9.0 or
Oracle 9.0
SQLite 3 (experimental)
The latest version of these requirements can be viewed at the following URL:
http://docs.moodle.org/en/Environment#Moodle_version_1.9.
Note that the specifications for the Moodle 2.0 database layer can be found at the
following location: http://docs.moodle.org/en/Development:DB_layer_2.0.
•
•
•
•
•
•
•
•
•
Moodle Architecture
[ 10 ]
Operating system
Moodle can run on any operating system that supports the required version of PHP
and the database. Moodle is generally installed on one of the three major operating
systems: Windows, Mac OS X, or Linux (or Unix/Unix-like operating systems). As
compared to Linux, both Mac OS X and Windows operating systems suffer from less
efficient performance for large-scale deployments. For Windows, this is due to a less-
optimized PHP stack, and for Mac OS X it is due to poor process forking performance,
which both Apache and MySQL rely on for high concurrency. Windows Server
2008 is reported in press releases by both Microsoft and Zend, the creator of PHP, as
having improved PHP performance. In a development environment, you can use any
of these operating systems as an excellent platform. In a production environment,
each operating system will have different performance characteristics.
Web server
Moodle will typically work with any web server that supports running the
appropriate versions of PHP. In practice, the most used web server is Apache,
which is available for most operating systems. Internet Information Services (IIS)
is another popular web server for hosting Moodle. There are also a growing number
of advocates for Lighthttpd as a web server, and this is reported in the Moodle
community forums (http://moodle.org/forums/) as working well with Moodle.
Lighthttpd has a growing number of advocates due to its low memory design. It is
extremely popular for its use with virtual environments (VMware, Xen, and Amazon
Elastic Compute Cloud), where memory footprint is more of a concern.
Moodle as a web application has support and development constraints that are
different from the norm. This is due to the way in which Moodle is used. A user
interacting with Moodle will have a higher than normal amount of clicks, and
Moodle generates many SQL queries as it builds a page. Moodle is very efficient at
what it does. However, what it does is fairly complex. This means, as developers,
we need to be aware of the type of architectures that our modifications will likely be
used within. It also means that we need to be aware of the performance implications
of our coding. The following figure illustrates several common configurations used
for Moodle in a production environment. Moodle is deployed in a broad range of
settings—anywhere from a single teacher running it on his or her desktop all the
way up to multi-machine clusters of high performance servers:
Chapter 1
[ 11 ]
Common Moodle Architectures
Single Server Two Server Cluster
Web Server Database Server
High Performance Cluster
Load Balancer
Web 2
DB Server File Server
Web DB Moodle Data
Web DB
Moodle Data
Web 1 Web N
Moodle, as is common with the standard PHP application model, scales at particular
points. The first scaling point is the database, which can easily be moved to a
separate physical server. After that, we can bring in additional frontend web servers
by using a load balancer. When using multiple web servers we will also need shared
storage for our Moodle data. Session data can be stored in either Moodle data or in
the database. The database server is the point where Moodle's scalability is most
limited. To scale the database it is necessary to bring in a faster database server,
replacing the older server. Currently, there is no standard method for scaling a single
Moodle installation across multiple master database servers, as we do with the web
application servers. It is also common practice to use Moodle with a PHP accelerator
such as eAccelerator or APC. It's important to test your code in these environments
to make sure that it functions correctly.
Directory and system structure
As shown in the following figure, each working Moodle system can be divided into
three separate areas: Moodle code, the Moodle database, and Moodle data.
Three Areas of Moodle
Moodle Code
Apache/IIS/Lighthttpd
Moodle Database
MySQL/PostgreSQL/Microsoft SQL/Oracle
Moodle Data
Local disk, NFS, GFS, SAN, etc.
Moodle Architecture
[ 12 ]
Moodle code
Because PHP is an interpreted language, the Moodle code is stored as source code
files on the web server. When a particular file is requested on the server, the PHP
interpreter parses the code on the fly, and the resulting output is sent out via the
web server software. As mentioned earlier, the M in Moodle stands for Modular,
and its directory structure reflects that. Each top-level folder represents a major
component of Moodle. Many of the main components support plugin modules. Each
plugin has its own folder inside the component's folder. In some cases, modules
will also have support for additional plugins. An example of this is the quiz activity
module, which supports modular question types. From the end user point of view,
modules are installed by copying the module into the appropriate folder location
on the server. Moodle detects the new module the next time that an administrator
logs into the system, locates the module's SQL code, runs it, and finally displays
the results.
Upgrades work in much the same way with Moodle, tracking the database version
and automatically upgrading the database as needed. All of this easy interface for
end users comes at the cost of some elbow grease for the developer.
The following screenshot is a directory listing of a recent Moodle 1.9 installation:
We will not cover all of the directories in the main folder at this time. However, we
will explore the functions of some of the important folders used by developers who
make modifications to Moodle. Moodle uses a simple nomenclature for modules,
where all of the modules are enclosed in their own folder, and the name of the
folder is the name that Moodle displays in its interface when referring to the module.
Chapter 1
[ 13 ]
admin:
This folder stores the PHP files that control the administrative user's interface. They
also contain the cron.php file, which is run as a batch process to perform system
maintenance tasks such as message delivery and course backups. We will often
hook into the cron.php process to perform batch operations.
auth:
The auth folder contains all of the authentication modules for Moodle. Each module
will have its own directory in this area. Authentication modules control the creation
of users, user profile data, and user access to the system. Authentication modules
are great for automating system administration, and as a result are a common
customization project.
backup:
This folder contains the core course backup facilities for the system. These are not
system-wide backup facilities but functions for the backup, restore, and import of
courses. Each individual course module is responsible for its own backup code and
makes use of these functions as needed. Each module is self-contained, allowing us,
as developers, to add modules cleanly to Moodle without having to modify the
core code.
blocks:
blocks are used to display boxes of information in either the right-hand side or
left-hand side column of the Moodle page. This is one of the simplest module types
to make, and also tend to work across multiple versions of Moodle with little or
no modifications.
course:
This component of Moodle has obvious importance, given that Moodle is organized
around courses. As developers, we are most likely to modify or add course formats
and reports. Custom course formats can be used to change the layout of courses.
enrol:
The enrol folder contains all of the enrollment modules for Moodle. Enrollment
modules control the creation and management of course-level role assignments
(enrollments). Enrollment modules are another key automation hook.
Moodle Architecture
[ 14 ]
files:
The files component allows Moodle to incorporate files into the system. This
includes file uploads, access control, and the viewing of files. files will see a major
rewrite in Moodle 2.0. Moodle 2.0 will allow storing and using files in external file
repositories such as Alfresco, Box.net, and Google Docs.
filter:
The Moodle filtering system is a text/regular expression-based search-and-replace
facility. The filter system is fed user-entered content from the database during page
creation. Filters match and modify the page before it is displayed. For example, there
is a math filter that supports auto conversion of TEX markup language to equation
graphics. The Multimedia Plugins filter finds references to common media types and
wraps the text in the appropriate embed and/or object tags, in order to automatically
embed the media, along with player controls, into the page. This is a very powerful
capability. However, it needs to be carefully developed, with performance
implications in mind.
lang:
The lang folder stores the core system language strings. This is the foundation
of Moodle's localization and language support. All of the strings displayed to the
end user are mapped via this facility. Language string mappings are also stored in
the Moodle data lang folder. This structure allows for easy local customization of
language files.
The following is a small section of the /lang/en_utf8/moodle.php language file.
Notice how each string that is displayed to the end user is mapped to a string hash
by using a key value that is descriptive of the strings purpose (in English):
$string['abouttobeinstalled'] = 'about to be installed';
$string['action'] = 'Action';
$string['actions'] = 'Actions';
$string['active'] = 'Active';
$string['activeusers'] = 'Active users';
lib:
The lib folder stores the core system library functions. As we develop modules and
customizations, we will use classes and functions defined in this folder.
Chapter 1
[ 15 ]
mod:
The mod folder stores activity modules such as assignment, quiz, wiki, forum, and
lesson modules. Learning activities are the core of any course delivered using
Moodle. Activity modules are more challenging to create than blocks, because they
back up, restore, and store grades. Oh, and of course, they have to teach something
to the learner.
my:
my is a light-weight portal area in Moodle. It provides a listing of courses a learner is
assigned, including a summary of upcoming course activities. The user can also add
and remove blocks on his or her portal page. my provides a good location to display
custom information with minimal core changes to Moodle. For example, we use my
as a dashboard location in many of our customization projects.
theme:
The theme folder stores all of the built-in Moodle themes and any custom themes
installed on the system. Themes are a combination of CSS, HTML, and PHP. Each
theme has its own folder. The theme system is useful for defining the visual skin,
header, and footer of the Moodle page. It is, however, limited in how much of the
Moodle page it can modify. For example, certain components of the Moodle page
are hardcoded to display in a certain way.
Moodle database
The Moodle database is organized into roughly 200 related tables. The default
installation option prepends mdl_ in front of each table name. Each major component
of the system typically has one or more tables, each starting with the component's
name. For example, there are two tables related to the config component:
mdl_config and mdl_config_plugins. As programmers, we will have to
manipulate the database on a regular basis. It's also important for us to be able to
treat the entire database as an entity, copying and moving instances of an entire
Moodle database for the creation of staging and testing areas as we develop our
code. We generally do this by using command-line utilities such as mysqldump
and MySQL.
Moodle Architecture
[ 16 ]
Moodle data
Moodle data is the file storage location for user-uploaded content. Moodle data also
stores the session data for users logged into the system, if file-based sessions are being
used. Moodle data also stores optional language packs that can be downloaded from
Moodle's administration interface. Moodle structures the data in this folder by either
the user or by the course. Most of the data by file count and size will be in the courses.
Each course has a folder, which is named with an integer value. The integer value is
set to the internal database ID of the course in question. We can easily determine these
values by navigating to a course via the Moodle web interface and inspecting its URL.
For example, examine this URL for a course on my local test Moodle
http://localhost/workspace/moodle19/course/view.php?id=3.
Note the id=3 at the end of the URL. If we have uploaded any files to this course,
there will be a folder path_to_moodledata/3. Within a course folder, Moodle will
store module data in the moddata folder. When a module needs to store files, it
saves them here in a folder with the same name as the module. For example, the
wiki module will have a folder here named wiki. Additionally, Moodle will create
a folder called backupdata if any course backups have been created. Any files that
have been uploaded directly by a user using the course files interface will be loaded
into the root of this folder. Users can also create their own folders and sub folders
within the root folder.
Moodle 2.0 uses an entirely new organizational model for user-uploaded files,
which is based on a hashing algorithm. The primary goal of this new method is
to support efficient use of disk storage space and greater flexibility for using files
across multiple courses.
Installing Moodle
There are many ways to install Moodle. One of the simplest ways is to download
one of the all-in-one installers from http://moodle.org. These are labeled as
Moodle for Windows and Moodle for Mac OS X under the Downloads menu at
http://moodle.org. These all-in-one installers contain both Moodle and all of
the necessary server software, including Apache, PHP, and MySQL. While these
packages are not recommended for production use, they can provide a convenient
starting point for a developer new to Moodle.
To manually install Moodle, download the Moodle source code files from
http://moodle.org. You will find a variety of download packages. Each package is
labeled with the version number. Major versions of Moodle are numbered in tenths:
1.6, 1.7, 1.8, and so on. Major versions focus on adding new features and bug fixes,
which require major system changes to be implemented. Each major release has
Chapter 1
[ 17 ]
a number of minor point releases. For example: 1.9.1, 1.9.2, 1.9.3, and so on. Minor
point releases focus on bug fixes and security updates. Finally, there are 'plus'
releases that contain nightly or weekly fixes.
From a developer's perspective, it makes sense to use the official CVS feeds to get
Moodle's source code. This allows for easier updates and code merges, as well as
integrating with many popular development tools. See http://docs.moodle.org/
en/CVS_for_Administrators.
Once you have the source code, it needs to be copied to your server's web root.
You should then create a folder (outside of the web root) for Moodle data, which
is writable by the web server software. From your SQL server, create an empty
database for Moodle to use. Finally, once this is done, you should enter the server's
address and path to Moodle into your web browser. This will initiate the Moodle
web installer and walk you through the rest of the installation options. During the
installation you will be asked to enter details for your database. Once these have
been entered, Moodle will connect to the database and create all 200+ tables. At the
end of the installation it will write a config.php file to your Moodle directory with
the values that you entered during installation. The following screenshot illustrates
the first screen of the Moodle installer, where we select our default language:
Upgrades follow the same basic pattern. Download the new code, copy it on the
server in place of the old code (note that in most cases, you can copy the new code
over the top of the old folder contents), and then visit the Moodle site in your web
browser. Moodle will detect a version change by comparing the version tags stored
in its configuration database against the ones reported in the module code, and then
initiate the upgrade. Each module is responsible for its own database upgrades.
Moodle Architecture
[ 18 ]
The final consideration for our development environment is to have a development
tool for writing our code. While it is perfectly possible to write PHP code in any
text editor (and many do), a popular option is to use the PHP plugin for Eclipse,
or NetBeans. Detailed instructions for optimizing this setup can be found at
http://docs.moodle.org/en/Setting_up_Eclipse_for_Moodle_development.
Moodle program execution
Moodle has many entry points—scripts that are called for execution. These are the
files that are called by the browser to execute Moodle's functions. While there are
many, the main ones are:
/index.php: The front page
/login/index.php: The login page
/admin/index.php: The main administration page
/course/view.php: A course page
/mod/*/view.php: A module page
Let's walk through a typical script, and follow the execution path. For the walkthrough,
we will use the main course display script, /course/view.php. For this example, let's
assume that we are using http://localhost/course/view.php?id=23.
Before we jump in, let's analyze the URL a bit. The portion up to /course will
be the URL of your Moodle site. The /course/ portion is the directory in Moodle
that contains the course-handling scripts. The meat of the URL is the portion
view.php?id=23. This script displays a course page. The course it displays is identified
by the id=23 parameter, where 23 is the data ID of the course in question. If you look
in the course data table in the database for your Moodle site, you will find an entry
with the 'id' field equal to 23. The very first executable line we see in the script is:
require_once('../config.php');
Executing config.php
All of the entry scripts include the same important file: config.php. This is the only
file in Moodle that must be included by specifying the exact literal path. This file
performs a number of initial parameter assignments in the global $CFG variable.
This provides the minimal amount of information to run the rest of the system;
among this information are the database, web URL, script directory, and data
storage directory definitions.
Lastly, and most importantly, config.php includes /lib/setup.php.
•
•
•
•
•
Chapter 1
[ 19 ]
config.php performs some basic, important variable assignment, whereas
setup.php performs all of the initial program execution required to complete the
execution environment setup. This includes defining several other important global
variables, including $SESSION, $COURSE, $THEME, and $db.
Next, it sets up and connects your database according to the settings defined
in config.php. Moodle uses the open source ADOdb libraries to manage
database functions. These functions are loaded through the inclusion of
/lib/adodb/adodb.inc.php.
Next, some critical library files are included that will be used by pretty much every
other function in Moodle. These libraries include the functions required to manage
multibyte strings, HTML output, Moodle data, access controls, events, groups, and
general purpose Moodle and PEAR libraries.
The remainder of the file sets up some other critical global variables, loads
configuration variables from the database, sets up caching, sessions,
environment variables, themes, language, and locales.
Including Moodle libraries
After including config.php, our script includes some other library files:
require_once('lib.php');
require_once($CFG-libdir.'/blocklib.php');
...
This uses the PHP construct require_once, in case any of the files were included
elsewhere first. Any file not located in the same directory is fully specified using
directory definitions defined in config.php. You will notice lib.php has no
directory specification, as it is located in the same directory as view.php. Likewise,
the remaining files have full paths using directory definitions set up by config.php.
You will notice the use of $CFG-libdir and $CFG-dirroot. The first is the defined
file path to the main library directory (usually the lib subdirectory of the Moodle file
path), while the second is the defined Moodle file path. Next, our script checks for,
and loads, any parameters that it expects to get from the URL:
$id = optional_param('id', 0, PARAM_INT);
$name = optional_param('name', '', PARAM_RAW);
...
Moodle Architecture
[ 20 ]
It does this by using the Moodle optional_param function, which loads the
specified variable with a named parameter value if one is present, or a default value
if not. If the parameter is required for the script to work properly, then the function
required_param should be used instead. Both of these functions validate the data
based on the specified arguments, and will generate errors or warnings if something
other than what was expected is passed in. This is critical to securing user input
in case of any additions to Moodle. See Chapter 10, Writing Secure Code for
more information.
Getting our data
Next, our script loads the specific records that it needs from the database:
if (! ($course = get_record('course', 'id', $id)) ) {
error('Invalid course id');
}
This can be done with either a database call, as above, or a specific API call.
At this point, our script has enough information to check if the user has permissions
to access its basic functions. This is done by loading contexts, checking the user login,
and verifying capabilities:
preload_course_contexts($course-id);
if (!$context = get_context_instance(CONTEXT_COURSE,
$course-id)) {
print_error('nocontext');
}
require_login($course);
Much of the capability verification is performed by the require_login function. It
verifies that the user is logged in (if necessary—some courses may not require that)
and redirects them to the login function if required. It also loads and checks specific
capabilities, including whether or not the user has access to the course. It also verifies
enrollment and redirects the user to the enrollment function if necessary.
Displaying in Moodle
Next, our script will perform the necessary programming required to carry out
its functions. Once it has finished this, it will begin the display process. The main
functions for display are the print_header and print_header_simple functions.
The following script uses the print_header function from the PAGE object it set up:
$PAGE-print_header(get_string('course').': %fullname%', NULL, '',
$bodytags);
Chapter 1
[ 21 ]
This function starts the HTML output by writing the HTTP headers, the theme
information, requested JavaScript files, and other header section information.
Then it begins with the body section.
The body output is handled by the specific course format. Whatever format has
been specified for the course in question in its settings, handles the body output.
This is done as follows, by including the file format.php from the subdirectory
of the format in question:
require($CFG-dirroot .'/course/format/'. $course-format .'/
format.php');
If the course used the topics format (for example), then the file would be /course/
format/topics/format.php. This file handles the specific course page output,
including the blocks and main content. It uses library functions found in /course/
lib.php to output the section's content. Lastly, the script outputs the footer:
print_footer(NULL, $course);
This function closes the body and completes the output to the screen. In most cases,
this will be the last function executed for a script.
Configuring Moodle
Moodle is a highly-configurable application, with many complex settings in
many areas of its functionality. These settings can be modified by Moodle
administrators through:
Direct code in the main config.php file
The mdl_config table via administrative code and interfaces
The mdl_config_plugins table via plugin administration
During program execution, all of the main configuration values are stored in the
$CFG global variable. $CFG is a generic structure. Each configuration variable is an
element of the $CFG structure. For example, the $CFG-theme contains the text name
of your site's selected theme.
The elements of $CFG are loaded by direct assignment, and from values stored in the
database mdl_config table. The primary point of direct assignment takes place in
/config.php. Here, the initial, necessary configuration settings are made.
•
•
•
Moodle Architecture
[ 22 ]
There are minimal assignments that must be defined in this file. You are prompted
for these values when you install Moodle, and you can change them afterwards by
editing this file. The minimal settings are as follows:
$CFG-dbtype = 'mysql'; // mysql or postgres7 (for now)
$CFG-dbhost = 'localhost'; // eg localhost or db.isp.com
$CFG-dbname = 'moodle'; // database name, eg moodle
$CFG-dbuser = 'username'; // your database username
$CFG-dbpass = 'password'; // your database password
$CFG-prefix = 'mdl_'; // Prefix to use for all table names
$CFG-dbpersist = false; // Should database connections be
// reused?
$CFG-wwwroot = 'http://example.com/moodle';
$CFG-dirroot = '/home/example/public_html/moodle';
$CFG-dataroot = '/home/example/moodledata';
$CFG-directorypermissions = 02777;
$CFG-admin = 'admin';
There are other optional settings that can be made in this file. Review your
/config-dist.php file to see all of these settings.
Historically, any configuration settings that did not have a UI available to
set these were set via code statements in this file. These often include new,
experimental features.
The remainder of the $CFG elements are set from the database. This is done through
a call to the library function get_config (located in the /lib/moodlelib.php library
file) from /lib/setup.php, which is included as the last action of config.php.
The important thing to know about the function get_config is that it will not
overwrite any $CFG setting that has already been set. This means you can overrule
any database setting by hardcoding it into config.php. Also, config.php clears out
the $CFG structure before it does anything else. This guarantees that nothing sets any
configuration variables before config.php and setup.php.
Setting configuration variables
As a developer, you can set and use configuration variables for your functionality. You
can set a configuration variable through the set_config function. The set_config
function takes a name, a value, and an optional plugin name as arguments. The name
becomes the element of the $CFG structure and the passed value becomes its value.
Additionally, this will be stored into the database mdl_config table, so that it can be
loaded on every program execution from then on. You can also specifically request a
configuration variable at any time, by using the get_config function, but you won't
need to, because it will be loaded into the $CFG structure once it has been set.
Chapter 1
[ 23 ]
The one issue that you need to consider when creating your own configuration
variable is that the variable name you choose must be unique. Your variable becomes
meaningless if you choose one that already exists. As most customizations you will
be developing are likely to be plugins (modules, blocks, and so on), Moodle provides
an alternate way to store configuration variables that are plugin specific.
Plugin configuration variables are loaded into the plugin structure itself, rather
than into the $CFG global structure. This means that the configuration variable name
only needs to be unique to the plugin. Plugin configuration variables are stored in
the mdl_config_plugin table, with the name of the plugin. They can be set and
retrieved by using the same set_config and get_config functions as before.
Generally, configuration variables are set by using administration interfaces. Most
of the Moodle configuration variables are set through the various settings pages
in the Site Administration menu block, which is visible on the home page of your
Moodle site. In future sections, you will learn how the plugins add their interfaces
to this structure. The following screenshot displays an example of Moodle's Site
Administration block:
Moodle's API
Moodle's API is a mix of library functions and classes. Moodle was originally based
on the version 4 series of PHP, and as such, most of its API is built around functions
defined in PHP library files. However, some of the newer constructs of Moodle use
object-oriented structures and as such provide extensible classes.
Most of Moodle's main libraries are kept in the /lib/ directory. All of these files
generally adhere to the naming convention [function]lib.php. Some of the
examples are textlib.php and weblib.php. These library files contain Moodle's API.
Moodle Architecture
[ 24 ]
Almost all of the core libraries are included in the execution stream when you load
config.php via its inclusion of /lib/setup.php. The setup.php file includes these
via the following lines:
require_once($CFG-libdir .'/textlib.class.php');
// Functions to handle multibyte strings
require_once($CFG-libdir .'/weblib.php');
// Functions for producing HTML
require_once($CFG-libdir .'/dmllib.php');
// Functions to handle DB data (DML)
require_once($CFG-libdir .'/datalib.php');
// Legacy lib with a big-mix of functions.
require_once($CFG-libdir .'/accesslib.php');
// Access control functions
require_once($CFG-libdir .'/deprecatedlib.php');
// Deprecated functions included for backward compatibility
require_once($CFG-libdir .'/moodlelib.php');
// Other general-purpose functions
require_once($CFG-libdir .'/eventslib.php');
// Events functions
require_once($CFG-libdir .'/grouplib.php');
// Groups functions
These by no means define all of the functions available in Moodle, and in fact each
of these libraries may include other libraries. However, the core of the functions that
you will need are contained within these libraries. In fact, the ones that you will need
to look at the most are:
moodlelib.php
weblib.php
dmllib.php
accesslib.php
grouplib.php
There are many other libraries that you will use, as you start to carry out specific
functions. Most of these are stored in the /lib/ directory. However, others may
be in specific functional areas such as /course/ and /blocks/.
Many of the specific libraries define classes that you can use. Libraries such as
/lib/pagelib.php and /lib/formslib.php define classes that are designed to be
extended in order to handle output to screen. pagelib.php defines specific page
types, with all of the functions necessary to manage page output and create your
own page types. Likewise, formslib.php defines Moodle's implementation of the
PEAR QuickForm classes in order to handle web-based forms.
•
•
•
•
•
Chapter 1
[ 25 ]
There is no single, all-encompassing document for all of Moodle's API. However,
you can find out more about each specific area in the developer documentation at
Moodle Docs. A good place to start is http://docs.moodle.org/en/Development:
Developer_documentation#Core_components_that_affect_everything.
Another resource that can help is the Moodle code cross reference. This is an online
resource that is generated from the code and inline comments in order to produce
documentation. It is generated automatically by using PHPXref. The reference can be
found at http://docs.moodle.org/en/Development:Code_Cross-Reference. Note
that it may not be up-to-date and maintained. Still, it does provide an easy overview.
Other important libraries
Moodle relies on a number of libraries, both internal and external. Several of these
are explained below:
PEAR
PEAR stands for PHP Extension and Application Repository. As such, it's not a
single library but a set of tools for getting and updating PHP libraries and modules.
ADOdb
ADOdb is a database library that provides a unified programming interface for a
large variety of databases. Although Moodle supports a limited core set of databases
for its direct backend, ADOdb really shines through in the supported databases for
both the external database authentication and the enrollment plugins.
YUI
The Yahoo! User Interface (YUI) library is written in JavaScript, and is used to create
rich web interfaces using AJAX, DOM, and DHTML. The Moodle course editing
interface relies on this library for drag-and-drop placement of course elements.
XMLDB
XMLDB was added to Moodle as part of the initiative to add Microsoft SQL and
Oracle backend support for Moodle. XMLDB rationalized all of the database
configuration files to XML schemas, so that the same files could be used across
all four supported backends. This extended upon the capabilities available from
ADOdb, providing a single code base for accessing all databases supported, while
still providing appropriate performance.
Moodle Architecture
[ 26 ]
Access control, logins, and roles
As open as Moodle is, it is tight with its security. It goes to great efforts to make sure
that anyone accessing the system is supposed to be accessing the system, and they
are supposed to be accessing it the way they are trying to.
Moodle has a powerful access control and permission system. At the core of the
access system is the user account. Although it is possible to grant access to any
visitor to your site without authenticating them, it doesn't allow them to do many
interesting things. We will assume that you want to know who your users are, and
that you will want them to have their own accounts.
A user account provides individual access via a username and password
combination. These accounts are created by using authentication plugins. The bare
minimum authentication is manual, where a user is created using the administration
interface. The next, most common authentication is the e-mail-based system that
allows users to create their own accounts using e-mail verification. In either case, a
unique username and e-mail address are required as well as a password. Passwords
in Moodle are encoded with an MD5 hash function to make them unreadable and
difficult to guess.
To get into the system, a user enters their username and password, and if correctly
entered, they are granted access to the site. Logging in uses PHP's 'cookie' functions
to set cookies into the current session and help identify the user throughout the
site visit.
Moodle permission contexts
Permissions can be assigned within six contexts: site/global, course category,
course, blocks and activities, user, and front page. There are seven built-in roles:
administrator, teacher, non-editing teacher, student, course creator, authenticated
user, and guest, all of which can be assigned in any one or more of the above
contexts. Any number of customized roles can be created through the list of over
200 system capabilities. Each capability can be assigned one of four access levels:
Not Set, Allow, Prohibit, and Prevent. Each user can have multiple roles that inherit
permissions from all of the context levels applicable to a given access request from
the user. The combination of these provides a powerful and flexible solution
for administrators.
The standard system roles are:
Administrator: System administrator has all permissions
Course creator: Can create course shells and can be limited to a
course category
•
•
Chapter 1
[ 27 ]
Teacher: Can teach a course, develop, and update course content
Non-editing teacher: Can teach a course but can't edit course content
Student: Can take a course
Authenticated user: Any logged in user has this role
Guest: Access permission for non-logged in users
An infinite number of custom roles can be generated by using the Moodle GUI and
role definition screens.
To check and force a login from inside your code, a call to require_login is used.
This function allows you to check if the user is logged in, and forces them to log in
if this is required by the element that they are trying to access. For example, you
can create a specific activity in a course that requires the user to be logged in. If the
user is not logged in, then they will be redirected to the correct login function. This
function also remembers what the user was accessing, so they can be returned there
once they have successfully logged in.
Contexts are elements in the system associated with the defined context levels. On
the code-side, contexts are defined in /lib/accesslib.php as follows:
define('CONTEXT_SYSTEM', 10);
define('CONTEXT_USER', 30);
define('CONTEXT_COURSECAT', 40);
define('CONTEXT_COURSE', 50);
define('CONTEXT_GROUP', 60);
define('CONTEXT_MODULE', 70);
define('CONTEXT_BLOCK', 80);
This means every instance of any of these levels is a context. There is only one
'SYSTEM', but there are many of the others, such as users, courses, and modules.
Capabilities
Capabilities are associated with context levels, and are specific access rules that can
be granted to roles. Examples of capabilities are:
moodle/site:manageblocks: Can manage blocks at the site context level
moodle/user:viewdetails: Can view details of a user at the user
context level
moodle/course:view: Can view a course at the course context level
•
•
•
•
•
•
•
•
Moodle Architecture
[ 28 ]
As developers, we can create capabilities to control access to our new functionality.
Careful consideration should be given as to which context is the best location for a
new capability. Capabilities should generally be placed at the lowest context level at
which they can function. We will cover these topics in more detail as we work, in the
chapters ahead.
Moodle roles
Roles are specific identifiers that are associated with all contexts. Roles are primarily
used to group capabilities for a context, so that these capabilities can be given to
users. Capabilities are assigned to roles in specific contexts, either by default or by
specific assignment (overriding).
Assigning roles
Lastly, users can be assigned to roles in specific contexts. This assignment gives them
the accesses defined by the capabilities in that role for that context.
So, to summarize:
Contexts are specific elements in Moodle
Roles are associated with all contexts
Capabilities are assigned to roles in a given context
Users are assigned roles in a given context
It is the role assignment at the context level being checked, and the capability
that role has at that context, which determines whether a user can perform the
requested action.
As you develop code for Moodle, you will need to keep this functionality in mind,
so that you can design and build the access control that you want for your functions.
•
•
•
•
Chapter 1
[ 29 ]
Summary
In this chapter, you have started the journey towards becoming a proficient
Moodle developer, by studying Moodle's overall architecture. You should now
be comfortable with the underlying system requirements to run Moodle, and the
major elements that make up a Moodle installation. You have also looked into the
process to install and upgrade Moodle with some discussion of our development
environment. You have also gained some insights into the program execution for
Moodle and the key PHP files that serve as entry points to the system. You have
also understood the fundamentals of how Moodle stores its configuration. You now
know a bit about both the core internal libraries of Moodle and some of the external
library dependencies. Finally, you took a look at Moodle's security and access model.
In the next chapter, you will learn how to create and modify blocks.
Creating and Modifying Blocks
Moodle blocks are plugins that load in the right-hand side or left-hand side column
of a Moodle site and display information to the user in a rectangular block. Each side
column can have zero, one, or multiple blocks loaded. If a column contains no blocks,
the column will not be displayed. This allows Moodle to support one, two, or three
column page layouts. Examples of built-in Moodle blocks include: HTML content,
calendars, menus, and course lists, amongst others.
This chapter covers how to create a basic block in Moodle. This is one of the easiest
and most popular customizations. Several basic Moodle programming concepts will
be introduced that are used throughout the book. Here are some of the new skills
that you will develop:
Creating a block from scratch
Managing language files
Working with capabilities
Adding instance configuration
Adding scheduled actions to a block
Reviewing a real world block
Using a block as a code container
Creating a block from scratch
We will start our exploration of block plugins by revisiting a programming classic,
Hello World. Our first block will be about as simple a block as possible, simply
displaying the text Hello World.
Because our block will be called Hello World, let's start by creating a folder in the
block folder of our development site called helloworld. Inside of this folder,
create an empty PHP file called block_helloworld.php. Note that the pattern is
module-type_module-name.php.
•
•
•
•
•
•
•
Other documents randomly have
different content
Jefferson to be President of the United States?' Why is he
compelled to put his vote in the hands of another, and to incur
all the hazards of an irresponsible agency, when he himself
could immediately give his own vote for his own chosen
candidate, without the slightest assistance from agents or
managers?
But, said Mr. Benton, I have other objections to these
intermediate electors. They are the peculiar and favorite
institution of aristocratic republics, and elective monarchies. I
refer the Senate to the late republics of Venice and Genoa; of
France, and her litter; to the kingdom of Poland; the empire of
Germany, and the Pontificate of Rome. On the contrary, a direct
vote by the people is the peculiar and favorite institution of
democratic republics; as we have just seen in the governments
of Rome, Athens, Thebes, and Sparta; to which may be added
the principal cities of the Amphyctionic and Achaian leagues,
and the renowned republic of Carthage when the rival of Rome.
I have now answered the objections which were brought
forward in the year '87. I ask for no judgment upon their validity
at that day, but I affirm them to be without force or reason in
the year 1824. Time and experience have so decided. Yes, time
and experience, the only infallible tests of good or bad
institutions, have now shown that the continuance of the
electoral system will be both useless and dangerous to the
liberties of the people; and that 'the only effectual mode of
preserving our government from the corruptions which have
undermined the liberty of so many nations, is, to confide the
election of our chief magistrate to those who are farthest
removed from the influence of his patronage;'[1]
that is to say, to
the whole body of American citizens!
The electors are not independent; they have no superior
intelligence; they are not left to their own judgment in the
choice of President; they are not above the control of the
people; on the contrary, every elector is pledged, before he is
chosen, to give his vote according to the will of those who
choose him. He is nothing but an agent, tied down to the
execution of a precise trust. Every reason which induced the
convention to institute electors has failed. They are no longer of
any use, and may be dangerous to the liberties of the people.
They are not useful, because they have no power over their
own vote, and because the people can vote for a President as
easily as they can vote for an elector. They are dangerous to the
liberties of the people, because, in the first place, they introduce
extraneous considerations into the election of President; and, in
the second place, they may sell the vote which is intrusted to
their keeping. They introduce extraneous considerations, by
bringing their own character and their own exertions into the
presidential canvass. Every one sees this. Candidates for
electors are now selected, not for the reasons mentioned in the
Federalist, but for their devotion to a particular party, for their
manners, and their talent at electioneering. The elector may
betray the liberties of the people, by selling his vote. The
operation is easy, because he votes by ballot; detection is
impossible, because he does not sign his vote; the restraint is
nothing but his own conscience, for there is no legal
punishment for his breach of trust. If a swindler defrauds you
out of a few dollars in property or money, he is whipped and
pilloried, and rendered infamous in the eye of the law; but, if an
elector should defraud 40,000 people of their vote, there is no
remedy but to abuse him in the newspapers, where the best
men in the country may be abused, as much as Benedict
Arnold, or Judas Iscariot. Every reason for instituting electors
has failed, and every consideration of prudence requires them
to be discontinued. They are nothing but agents, in a case
which requires no agent; and no prudent man would, or ought,
to employ an agent to take care of his money, his property, or
his liberty, when he is equally capable to take care of them
himself.
But, if the plan of the constitution had not failed—if we were
now deriving from electors all the advantages expected from
their institution—I, for one, said Mr. B., would still be in favor of
getting rid of them. I should esteem the incorruptibility of the
people, their disinterested desire to get the best man for
President, to be more than a counterpoise to all the advantages
which might be derived from the superior intelligence of a more
enlightened, but smaller, and therefore, more corruptible body. I
should be opposed to the intervention of electors, because the
double process of electing a man to elect a man, would paralyze
the spirit of the people, and destroy the life of the election itself.
Doubtless this machinery was introduced into our constitution
for the purpose of softening the action of the democratic
element; but it also softens the interest of the people in the
result of the election itself. It places them at too great a
distance from their first servant. It interposes a body of men
between the people and the object of their choice, and gives a
false direction to the gratitude of the President elected. He feels
himself indebted to the electors who collected the votes of the
people, and not to the people, who gave their votes to the
electors. It enables a few men to govern many, and, in time, it
will transfer the whole power of the election into the hands of a
few, leaving to the people the humble occupation of confirming
what has been done by superior authority.
Mr Benton referred to historical examples to prove the
correctness of his opinion.
He mentioned the constitution of the French Republic, of the
year III. of French liberty. The people to choose electors; these
to choose the Councils of Five Hundred, and of Ancients; and
these, by a further process of filtration, to choose the Five
Directors. The effect was, that the people had no concern in the
election of their Chief Magistrates, and felt no interest in their
fate. They saw them enter and expel each other from the
political theatre, with the same indifference with which they
would see the entrance and the exit of so many players on the
stage. It was the same thing in all the subaltern Republics of
which the French armies were delivered, while overturning the
thrones of Europe. The constitutions of the Ligurian, Cisalpine,
and Parthenopian Republics, were all duplicates of the mother
institution, at Paris; and all shared the same fate. The French
consular constitution of the year VIII. (the last year of French
liberty) preserved all the vices of the electoral system; and from
this fact, alone, that profound observer, Neckar, from the bosom
of his retreat, in the midst of the Alps, predicted and proclaimed
the death of Liberty in France. He wrote a book to prove that
'Liberty would be ruined by providing any kind of substitute for
popular elections:' and the result verified his prediction in four
years.
CHAPTER XVI.
INTERNAL TRADE WITH NEW MEXICO.
The name of Mexico, the synonyme of gold and silver mines,
possessed always an invincible charm for the people of the western
States. Guarded from intrusion by Spanish jealousy and despotic
power, and imprisonment for life, or labor in the mines, the
inexorable penalty for every attempt to penetrate the forbidden
country, still the dazzled imaginations and daring spirits of the Great
West adventured upon the enterprise; and failure and misfortune,
chains and labor, were not sufficient to intimidate others. The journal
of (the then lieutenant, afterwards) General Pike inflamed this spirit,
and induced new adventurers to hazard the enterprise, only to meet
the fate of their predecessors. It was not until the Independence of
Mexico, in the year 1821, that the frontiers of this vast and hitherto
sealed up country, were thrown open to foreign ingress, and trade
and intercourse allowed to take their course. The State of Missouri,
from her geographical position, and the adventurous spirit of her
inhabitants, was among the first to engage in it; and the Western
Internal Provinces—the vast region comprehending New Mexico, El
Paso del Norte, New Biscay, Chihuahua, Sonora, Sinaloa, and all the
wide slope spreading down towards the Gulf of California, the
ancient Sea of Cortez—was the remote theatre of their courageous
enterprise—the further off and the less known, so much the more
attractive to their daring spirits. It was the work of individual
enterprise, without the protection or countenance of the government
—without even its knowledge—and exposed to constant danger of
life and property from the untamed and predatory savages, Arabs of
the New World, which roamed over the intermediate country of a
thousand miles, and considered the merchant and his goods their
lawful prey. In three years it had grown up to be a new and regular
branch of interior commerce, profitable to those engaged in it,
valuable to the country from the articles it carried out, and for the
silver, the furs, and the mules which it brought back; and well
entitled to the protection and care of the government. That
protection was sought, and in the form which the character of the
trade required—a right of way through the countries of the tribes
between Missouri and New Mexico, a road marked out and security
in travelling it, stipulations for good behavior from the Indians, and a
consular establishment in the provinces to be traded with. The
consuls could be appointed by the order of the government; but the
road, the treaty stipulations, and the substantial protection against
savages, required the aid of the federal legislative power, and for
that purpose a Bill was brought into the Senate by me in the session
of 1824-25; and being a novel and strange subject, and asking for
extraordinary legislation, it became necessary to lay a foundation of
facts, and to furnish a reason and an argument for every thing that
was asked. I produced a statement from those engaged in the trade,
among others from Mr. Augustus Storrs, late of New Hampshire,
then of Missouri—a gentleman of character and intelligence, very
capable of relating things as they were, and incapable of relating
them otherwise; and who had been personally engaged in the trade.
In presenting his statement, and moving to have it printed for the
use of the Senate, I said:
This gentleman had been one of a caravan of eighty persons,
one hundred and fifty-six horses, and twenty-three wagons and
carriages, which had made the expedition from Missouri to
Santa Fé (of New Mexico), in the months of May and June last.
His account was full of interest and novelty. It sounded like
romance to hear of caravans of men, horses, and wagons,
traversing with their merchandise the vast plain which lies
between the Mississippi and the Rio del Norte. The story
seemed better adapted to Asia than to North America. But,
romantic as it might seem, the reality had already exceeded the
visions of the wildest imagination. The journey to New Mexico,
but lately deemed a chimerical project, had become an affair of
ordinary occurrence. Santa Fé, but lately the Ultima Thule of
American enterprise, was now considered as a stage only in the
progress, or rather, a new point of departure to our invincible
citizens. Instead of turning back from that point, the caravans
broke up there, and the subdivisions branched off in different
directions in search of new theatres for their enterprise. Some
proceeded down the river to the Paso del Norte; some to the
mines of Chihuahua and Durango, in the province of New
Biscay; some to Sonora and Sinaloa, on the Gulf of California;
and some, seeking new lines of communication with the Pacific,
had undertaken to descend the western slope of our continent,
through the unexplored regions of the Colorado. The fruit of
these enterprises, for the present year, amounted to $190,000
in gold and silver bullion, and coin, and precious furs; a sum
considerable, in itself, in the commerce of an infant State, but
chiefly deserving a statesman's notice, as an earnest of what
might be expected from a regulated and protected trade. The
principal article given in exchange, is that of which we have the
greatest abundance, and which has the peculiar advantage of
making the circuit of the Union before it departs from the
territories of the republic—cotton—which grows in the South, is
manufactured in the North, and exported from the West.
That the trade will be beneficial to the inhabitants of the
Internal Provinces, is a proposition too plain to be argued. They
are a people among whom all the arts are lost—the ample
catalogue of whose wants may be inferred from the lamentable
details of Mr. Storrs. No books! no newspapers! iron a dollar a
pound! cultivating the earth with wooden tools! and spinning
upon a stick! Such is the picture of a people whose fathers wore
the proud title of Conquerors; whose ancestors, in the time of
Charles the Fifth, were the pride, the terror, and the model of
Europe; and such has been the power of civil and religious
despotism in accomplishing the degradation of the human
species! To a people thus abased, and so lately arrived at the
possession of their liberties, a supply of merchandise, upon the
cheapest terms, is the least of the benefits to be derived from a
commerce with the people of the United States. The
consolidation of their republican institutions, the improvement of
their moral and social condition, the restoration of their lost
arts, and the development of their national resources, are
among the grand results which philanthropy anticipates from
such a commerce.
To the Indians themselves, the opening of a road through
their country is an object of vital importance. It is connected
with the preservation and improvement of their race. For two
hundred years the problem of Indian civilization has been
successively presented to each generation of the Americans,
and solved by each in the same way. Schools have been set up,
colleges founded, and missions established; a wonderful success
has attended the commencement of every undertaking; and,
after some time, the schools, the colleges, the missions, and the
Indians, have all disappeared together. In the south alone have
we seen an exception. There the nations have preserved
themselves, and have made a cheering progress in the arts of
civilization. Their advance is the work of twenty years. It dates
its commencement from the opening of roads through their
country. Roads induced separate families to settle at the
crossing of rivers, to establish themselves at the best springs
and tracts of land, and to begin to sell grain and provisions to
the travellers, whom, a few years before, they would kill and
plunder. This imparted the idea of exclusive property in the soil,
and created an attachment for a fixed residence. Gradually,
fields were opened, houses built, orchards planted, flocks and
herds acquired, and slaves bought. The acquisition of these
comforts, relieving the body from the torturing wants of cold
and hunger, placed the mind in a condition to pursue its
improvement.—This, Mr. President, is the true secret of the
happy advance which the southern tribes have made in
acquiring the arts of civilization; this has fitted them for the
reception of schools and missions; and doubtless, the same
cause will produce the same effects among the tribes beyond,
which it has produced among the tribes on this side of the
Mississippi.
The right of way is indispensable, and the committee have
begun with directing a bill to be reported for that purpose.
Happily, there are no constitutional objections to it. State rights
are in no danger! The road which is contemplated will trespass
upon the soil, or infringe upon the jurisdiction of no State
whatsoever. It runs a course and a distance to avoid all that; for
it begins upon the outside line of the outside State, and runs
directly off towards the setting sun—far away from all the
States. The Congress and the Indians are alone to be consulted,
and the statute book is full of precedents. Protesting against the
necessity of producing precedents for an act in itself pregnant
with propriety, I will yet name a few in order to illustrate the
policy of the government, and show its readiness to make roads
through Indian countries to facilitate the intercourse of its
citizens, and even upon foreign territory to promote commerce
and national communications.
Precedents were then shown. 1, A road from Nashville, Tennessee,
through the Chicasaw and Choctaw tribes, to Natchez, 1806; 2, a
road through the Creek nations, from Athens, in Georgia, to the 31st
degree of north latitude, in the direction to New Orleans, 1806, and
continued by act of 1807, with the consent of the Spanish
government, through the then Spanish territory of West Florida to
New Orleans; 3, three roads through the Cherokee nation, to open
an intercourse between Georgia, Tennessee, and the lower
Mississippi; and more than twenty others upon the territory of the
United States. But the precedent chiefly relied upon was that from
Athens through the Creek Indian territory and the Spanish dominions
to New Orleans. It was up to the exigency of the occasion in every
particular—being both upon Indian territory within our dominions,
and upon foreign territory beyond them. The road I wanted fell
within the terms of both these qualifications. It was to pass through
tribes within our own territory, until it reached the Arkansas River:
there it met the foreign boundary established by the treaty of 1819,
which gave away, not only Texas, but half the Arkansas besides; and
the bill which I brought in provided for continuing the road, with the
assent of Mexico, from this boundary to Santa Fé, on the Upper del
Norte. I deemed it fair to give additional emphasis to this precedent,
by showing that I had it from Mr. Jefferson, and said:
For a knowledge of this precedent, I am indebted to a
conversation with Mr. Jefferson himself. In a late excursion to
Virginia, I availed myself of a broken day to call and pay my
respects to that patriarchal statesman. The individual must
manage badly, Mr. President, who can find himself in the
presence of that great man, and retire from it without bringing
off some fact, or some maxim, of eminent utility to the human
race. I trust that I did not so manage. I trust that, in bringing
off a fact which led to the discovery of the precedent, which is
to remove the only serious objection to the road in question, I
have done a service, if not to the human family, at least to the
citizens of the two greatest Republics in the world. It was on the
evening of Christmas day that I called upon Mr. Jefferson. The
conversation, among other things, turned upon roads. He spoke
of one from Georgia to New Orleans, made during the last term
of his own administration. He said there was a manuscript map
of it in the library of Congress (formerly his own), bound up in a
certain volume of maps, which he described to me. On my
return to Washington, I searched the statute book, and I found
the acts which authorized the road to be made: they are the
same which I have just read to the Senate. I searched the
Congress Library, and I found the volume of maps which he had
described; and here it is (presenting a huge folio), and there is
the map of the road from Georgia to New Orleans, more than
two hundred miles of which, marked in blue ink, is traced
through the then dominions of the King of Spain!
The foreign part of the road was the difficulty and was not entirely
covered by the precedent. That was a road to our own city, and no
other direct territorial way from the Southern States than through
the Spanish province of West Florida: this was a road to be, not only
on foreign territory, but to go to a foreign country. Some Senators,
favorable to the bill, were startled at it, and Mr. Lloyd, of
Massachusetts, moved to strike out the part of the section which
provided for this ex-territorial national highway; but not in a spirit of
hostility to the bill itself providing for protection to a branch of
commerce. Mr. Lowrie, of Pennsylvania, could not admit the force of
the objection, and held it to be only a modification of what was now
done for the protection of commerce—the substitution of land for
water; and instanced the sums annually spent in maintaining a fleet
in the Mediterranean Sea, and in the most remote oceans for the
same purpose. Mr. Van Buren, thought the government was bound
to extend the same protection to this branch of trade as to any
other; and the road upon the foreign territory was only to be marked
out, not made. Mr. Macon thought the question no great matter.
Formerly Indian traders followed traces now they must have roads.
He did not care for precedents: they are generally good or bad as
they suit or cross our purposes. The case of the road made by Mr.
Jefferson was different. That road was made among Indians
comparatively civilized, and who had some notions of property. But
the proposed road now to be marked out would pass through wild
tribes who think of nothing but killing and robbing a white man the
moment they see him, and would not be restrained by treaty
obligations even if they entered into them. Col. Johnson, of
Kentucky, had never hesitated to vote the money which was
necessary to protect the lives or property of our sea-faring men, or
for Atlantic fortifications, or to suppress piracies. We had, at this
session voted $500,000 to suppress piracy in the West Indies. We
build ships of war, erect light-houses, spend annual millions for the
protection of ocean commerce; and he could not suppose that the
sum proposed in this bill for the protection of an inland branch of
trade so valuable to the West could be denied. Mr. Kelly, of Alabama,
said the great object of the bill was to cherish and foster a branch of
commerce already in existence. It is carried on by land through
several Indian tribes. To be safe, a road must be had—a right of way
—a trace, if you please. To answer its purpose, this road, or
trace, must pass the boundary of the United States, and extend
several hundred miles through the wilderness country, in the
Mexican Republic to the settlements with which the traffic must be
carried on. It may be well to remember that the Mexican
government is in the germ of its existence, struggling with difficulties
that we have long since surmounted, and may not feel it convenient
to make the road, and that it is enough to permit us to mark it out
upon her soil; which is all that this bill proposes to do within her
limits. Mr. Smith, of Maryland, would vote for the bill. The only
question with him was, whether commerce could be carried on to
advantage on the proposed route; and, being satisfied that it could
be, he should vote for the bill. Mr. Brown, of Ohio (Ethan A.), was
very glad to hear such sentiments from the Senator from Maryland,
and hoped that a reciprocal good feeling would always prevail
between different sections of the Union. He thought there could be
no objection to the bill, and approved the policy of getting the road
upon Mexican territory with the consent of the Mexican government.
The bill passed the Senate by a large vote—30 to 12; and these are
the names of the Senators voting for and against it:
Yeas.—Messrs. Barton, Benton, Bouligny, Brown, D'Wolf, Eaton,
Edwards, Elliott, Holmes of Miss., Jackson (the General), Johnson of
Kentucky, Johnston of Lou., Kelly, Knight, Lanman, Lloyd of Mass.,
Lowrie, McIlvaine, McLean, Noble, Palmer, Parrott, Ruggles,
Seymour, Smith, Talbot, Taylor, Thomas, Van Buren, Van Dyke—30.
Nays.—Messrs. Branch, Chandler, Clayton, Cobb, Gaillard, Hayne,
Holmes of Maine, King of Ala., King of N. Y., Macon, Tazewell,
Williams—12.
It passed the House of Representatives by a majority of thirty—
received the approving signature of Mr. Monroe, among the last acts
of his public life—was carried into effect by his successor, Mr. John
Quincy Adams—and this road has remained a thoroughfare of
commerce between Missouri and New Mexico, and all the western
internal provinces ever since.
CHAPTER XVII.
PRESIDENTIAL AND VICE-PRESIDENTIAL
ELECTION IN THE ELECTORAL COLLEGES.
Four candidates were before the people for the office of President
—General Jackson, Mr. John Quincy Adams, Mr. William H. Crawford,
and Mr. Henry Clay. Mr. Crawford had been nominated in a caucus of
democratic members of Congress; but being a minority of the
members, and the nomination not in accordance with public opinion,
it carried no authority along with it, and was of no service to the
object of its choice. General Jackson was the candidate of the
people, brought forward by the masses. Mr. Adams and Mr. Clay
were brought forward by bodies of their friends in different States.
The whole number of electoral votes was 261 of which it required
131 to make an election. No one had that number. General Jackson
was the highest on the list, and had 99 votes; Mr. Adams 84; Mr.
Crawford 41; Mr. Clay 37. No one having a majority of the whole of
electors, the election devolved upon the House of Representatives;
of which an account will be given in a separate chapter.
In the vice-presidential election it was different. Mr. John C.
Calhoun (who in the beginning of the canvass had been a candidate
for the Presidency, but had been withdrawn by his friends in
Pennsylvania, and put forward for Vice-President), received 182
votes in the electoral college, and was elected. Mr. Nathan Sandford,
Senator in Congress from New-York, had been placed on the ticket
with Mr. Clay, and received 30 votes. The 24 votes of Virginia were
given to Mr. Macon, as a compliment, he not being a candidate, and
having refused to become one. The nine votes of Georgia were given
to Mr. Van Buren, also as a compliment, he not being on the list of
candidates. Mr. Albert Gallatin had been nominated in the Congress
caucus with Mr. Crawford, but finding the proceedings of that caucus
unacceptable to the people he had withdrawn from the canvass. Mr.
Calhoun was the only substantive vice-presidential candidate before
the people, and his election was an evidence of good feeling in the
North towards southern men—he receiving the main part of his
votes from that quarter—114 votes from the non-slaveholding
States, and only 68 from the slaveholding. A southern man, and a
slaveholder, Mr. Calhoun was indebted to northern men and non-
slaveholders, for the honorable distinction of an election in the
electoral colleges—the only one in the electoral colleges—the only
one on all the lists of presidential and vice-presidential candidates
who had that honor. Surely there was no disposition in the free
States at that time to be unjust, or unkind to the South.
CHAPTER XVIII.
DEATH OF JOHN TAYLOR, OF CAROLINE.
For by that designation was discriminated, in his own State, the
eminent republican statesman of Virginia, who was a Senator in
Congress in the first term of General Washington's administration,
and in the last term of Mr. Monroe—and who, having voluntarily
withdrawn himself from that high station during the intermediate
thirty years, devoted himself to the noble pursuits of agriculture,
literature, the study of political economy, and the service of his State
or county when called by his fellow-citizens. Personally I knew him
but slightly, our meeting in the Senate being our first acquaintance,
and our senatorial association limited to the single session of which
he was a member—1823-24;—at the end of which he died. But all
my observation of him, and his whole appearance and deportment,
went to confirm the reputation of his individuality of character, and
high qualities of the head and the heart. I can hardly figure to
myself the ideal of a republican statesman more perfect and
complete than he was in reality:—plain and solid, a wise counsellor, a
ready and vigorous debater, acute and comprehensive, ripe in all
historical and political knowledge, innately republican—modest,
courteous, benevolent, hospitable—a skilful, practical farmer, giving
his time to his farm and his books, when not called by an emergency
to the public service—and returning to his books and his farm when
the emergency was over. His whole character was announced in his
looks and deportment, and in his uniform (senatorial) dress—the
coat, waistcoat, and pantaloons of the same London brown, and in
the cut of a former fashion—beaver hat with ample brim—fine white
linen—and a gold-headed cane, carried not for show, but for use and
support when walking and bending under the heaviness of years. He
seemed to have been cast in the same mould with Mr. Macon, and it
was pleasant to see them together, looking like two Grecian sages,
and showing that regard for each other which every one felt for
them both. He belonged to that constellation of great men which
shone so brightly in Virginia in his day, and the light of which was
not limited to Virginia, or our America, but spread through the
bounds of the civilized world. He was the author of several works,
political and agricultural, of which his Arator in one class, and his
Construction Construed in another, were the principal—one adorning
and exalting the plough with the attributes of science; the other
exploring the confines of the federal and the State governments, and
presenting a mine of constitutional law very profitably to be
examined by the political student who will not be repulsed from a
banquet of rich ideas, by the quaint Sir Edward Coke style—(the only
point of resemblance between the republican statesman, and the
crown officer of Elizabeth and James)—in which it is dressed.
Devotion to State rights was the ruling feature of his policy; and to
keep both governments, State and federal, within their respective
constitutional orbits, was the labor of his political life.
In the years 1798 and '99, Mr. Taylor was a member of the
General Assembly of his State, called into service by the
circumstances of the times; and was selected on account of the
dignity and gravity of his character, his power and readiness in
debate, and his signal devotion to the rights of the States, to bring
forward those celebrated resolutions which Mr. Jefferson conceived,
which his friends sanctioned, which Mr. Madison drew up, and which
John Taylor, of Caroline, presented;—which are a perfect
exposition of the principles of our duplicate form of government, and
of the limitations upon the power of the federal government;—and
which, in their declaration of the unconstitutionality of the alien and
sedition laws, and appeal to other States for their co-operation, had
nothing in view but to initiate a State movement by two-thirds of the
States (the number required by the fifth article of the federal
constitution), to amend, or authoritatively expound the constitution;
—the idea of forcible resistance to the execution of any act of
Congress being expressly disclaimed at the time.
CHAPTER XIX.
PRESIDENTIAL ELECTION IN THE HOUSE OF
REPRESENTATIVES.
It has already been shown that the theory of the constitution, and
its practical working, was entirely different in the election of
President and Vice-President—that by the theory, the people were
only to choose electors, to whose superior intelligence the choice of
fit persons for these high stations was entirely committed—and that,
in practice, this theory had entirely failed from the beginning. From
the very first election the electors were made subordinate to the
people, having no choice of their own, and pledged to deliver their
votes for a particular person, according to the will of those who
elected them. Thus the theory had failed in its application to the
electoral college; but there might be a second or contingent election,
and has been; and here the theory of the constitution has failed
again. In the event of no choice being made by the electors, either
for want of a majority of electoral votes being given to any one, or
on account of an equal majority for two, the House of
Representatives became an electoral college for the occasion, limited
to a choice out of the five highest (before the constitution was
amended), or the two highest having an equal majority. The
President and Vice-President were not then voted for separately, or
with any designation of their office. All appeared upon the record as
presidential nominees—the highest on the list having a majority, to
be President; the next highest, also having a majority, to be Vice-
President; but the people, from the beginning, had discriminated
between the persons for these respective places, always meaning
one on their ticket for President, the other for Vice-President. But, by
the theory of the constitution and its words, those intended Vice-
Presidents might be elected President in the House of
Representatives, either by being among the five highest when there
was no majority, or being one of two in an equal majority. This
theory failed in the House of Representatives from the first election,
the demos krateo principle—the people to govern—prevailing there
as in the electoral colleges, and overruling the constitutional design
in each.
The first election in the House of Representatives was that of Mr.
Jefferson and Mr. Burr, in the session of 1800-1801. These
gentlemen had each a majority of the whole number of electoral
votes, and an equal majority—73 each—Mr. Burr being intended for
Vice-President. One of the contingencies had then occurred in which
the election went to the House of Representatives. The federalists
had acted more wisely, one of their State electoral colleges (that of
Rhode Island), having withheld a vote from the intended Vice-
President on their side, Mr. Charles Colesworth Pinckney, of South
Carolina; and so prevented an equality of votes between him and Mr.
John Adams. It would have been entirely constitutional in the House
of Representatives to have elected Mr. Burr President, but at the
same time, a gross violation of the democratic principle, which
requires the will of the majority to be complied with. The federal
States undertook to elect Mr. Burr, and kept up the struggle for
seven days and nights, and until the thirty-sixth ballot. There were
sixteen States, and it required the concurrence of nine to effect an
election. Until the thirty-sixth Mr. Jefferson had eight, Mr. Burr six,
and two were divided. On the thirty-sixth ballot Mr. Jefferson had ten
States and was elected. General Hamilton, though not then in public
life, took a decided part in this election, rising above all personal and
all party considerations, and urging the federalists from the
beginning to vote for Mr. Jefferson. Thus the democratic principle
prevailed. The choice of the people was elected by the House of
Representatives; and the struggle was fatal to those who had
opposed that principle. The federal party was broken down, and at
the ensuing Congress elections, was left in a small minority. Its
candidate at the ensuing presidential election received but fourteen
votes out of one hundred and seventy-six. Burr, in whose favor, and
with whose connivance the struggle had been made, was ruined—
fell under the ban of the republican party, disappeared from public
life, and was only seen afterwards in criminal enterprises, and
ending his life in want and misery. The constitution itself, in that
particular (the mode of election), was broken down, and had to be
amended so as to separate the presidential from the vice-
presidential ticket, giving each a separate vote; and in the event of
no election by the electoral colleges, sending each to separate
houses—the three highest on the presidential lists to the House of
Representatives,—the two highest on the vice-presidential, to the
Senate. And thus ended the first struggle in the House of
Representatives (in relation to the election of President), between
the theory of the constitution and the democratic principle—triumph
to the principle, ruin to its opposers, and destruction to the clause in
the constitution, which permitted such a struggle.
The second presidential election in the House of Representatives
was after the lapse of a quarter of a century, and under the
amended constitution, which carried the three highest on the list to
the House when no one had a majority of the electoral votes.
General Jackson, Mr. John Quincy Adams, and Mr. William H.
Crawford, were the three, their respective votes being 99, 84, 41;
and in this case a second struggle took place between the theory of
the constitution and the democratic principle; and with eventual
defeat to the opposers of that principle, though temporarily
successful. Mr. Adams was elected, though General Jackson was the
choice of the people, having received the greatest number of votes,
and being undoubtedly the second choice of several States whose
votes had been given to Mr. Crawford and Mr. Clay (at the general
election). The representatives from some of these States gave the
vote of the State to Mr. Adams, upon the argument that he was best
qualified for the station, and that it was dangerous to our institutions
to elect a military chieftain—an argument which assumed a
guardianship over the people, and implied the necessity of a superior
intelligence to guide them for their own good. The election of Mr.
Adams was perfectly constitutional, and as such fully submitted to by
the people; but it was also a violation of the demos krateo principle;
and that violation was signally rebuked. All the representatives who
voted against the will of their constituents, lost their favor, and
disappeared from public life. The representation in the House of
Representatives was largely changed at the first general election,
and presented a full opposition to the new President. Mr. Adams
himself was injured by it, and at the ensuing presidential election
was beaten by General Jackson more than two to one—178 to 83.
Mr. Clay, who took the lead in the House for Mr. Adams, and
afterwards took upon himself the mission of reconciling the people
to his election in a series of public speeches, was himself crippled in
the effort, lost his place in the democratic party, joined the whigs
(then called national republicans), and has since presented the
disheartening spectacle of a former great leader figuring at the head
of his ancient foes in all their defeats, and lingering on their rear in
their victories. The democratic principle was again victor over the
theory of the constitution, and great and good were the results that
ensued. It vindicated the demos in their right and their power, and
showed that the prefix to the constitution, We, the people, do
ordain and establish, c., may also be added to its administration,
showing them to be as able to administer as to make that
instrument. It re-established parties upon the basis of principle, and
drew anew party lines, then almost obliterated under the fusion of
parties during the era of good feeling, and the efforts of leading
men to make personal parties for themselves. It showed the
conservative power of our government to lie in the people, more
than in its constituted authorities. It showed that they were capable
of exercising the function of self-government. It assured the
supremacy of the democracy for a long time, and until temporarily
lost by causes to be shown in their proper place. Finally, it was a
caution to all public men against future attempts to govern
presidential elections in the House of Representatives.
It is no part of the object of this Thirty Years' View to dwell upon
the conduct of individuals, except as showing the causes and the
consequences of events; and, under this aspect, it becomes the
gravity of history to tell that, in these two struggles for the election
of President, those who struggled against the democratic principle
lost their places on the political theatre,—the mere voting members
being put down in their States and districts, and the eminent actors
for ever ostracised from the high object of their ambition. A
subordinate cause may have had its effect, and unjustly, in
prejudicing the public mind against Mr. Adams and Mr. Clay. They
had been political adversaries, had co-operated in the election, and
went into the administration together. Mr. Clay received the office of
Secretary of State from Mr. Adams, and this gave rise to the
imputation of a bargain between them.
It came within my knowledge (for I was then intimate with Mr.
Clay), long before the election, and probably before Mr. Adams knew
it himself, that Mr. Clay intended to support him against General
Jackson; and for the reasons afterward averred in his public
speeches. I made this known when occasions required me to speak
of it, and in the presence of the friends of the impugned parties. It
went into the newspapers upon the information of these friends, and
Mr. Clay made me acknowledgments for it in a letter, of which this is
the exact copy:
I have received a paper published on the 20th ultimo, at
Lemington, in Virginia, in which is contained an article stating that
you had, to a gentleman of that place, expressed your disbelief of a
charge injurious to me, touching the late presidential election, and
that I had communicated to you unequivocally, before the 15th of
December, 1824, my determination to vote for Mr. Adams and not for
General Jackson. Presuming that the publication was with your
authority, I cannot deny the expression of proper acknowledgments
for the sense of justice which has prompted you to render this
voluntary and faithful testimony.
This letter, of which I now have the original, was dated at
Washington City, December 6th, 1827—that is to say, in the very
heat and middle of the canvass in which Mr. Adams was beaten by
General Jackson, and when the testimony could be of most service
to him. It went the rounds of the papers, and was quoted and relied
upon in debates in Congress, greatly to the dissatisfaction of many
of my own party. There was no mistake in the date, or the fact. I left
Washington the 15th of December, on a visit to my father-in-law,
Colonel James McDowell, of Rockbridge county, Virginia, where Mrs.
Benton then was; and it was before I left Washington that I learned
from Mr. Clay himself that his intention was to support Mr. Adams. I
told this at that time to Colonel McDowell, and any friends that
chanced to be present, and gave it to the public in a letter which
was copied into many newspapers, and is preserved in Niles'
Register. I told it as my belief to Mr. Jefferson on Christmas evening
of the same year, when returning to Washington and making a call
on that illustrious man at his seat, Monticello; and believing then
that Mr. Adams would be elected, and, from the necessity of the
case, would have to make up a mixed cabinet, I expressed that
belief to Mr. Jefferson, using the term, familiar in English history, of
broad bottomed; and asked him how it would do? He answered,
Not at all—would never succeed—would ruin all engaged in it. Mr.
Clay told his intentions to others of his friends from an early period,
but as they remained his friends, their testimony was but little
heeded. Even my own, in the violence of party, and from my
relationship to Mrs. Clay, seemed to have but little effect. The
imputation of bargain stuck, and doubtless had an influence in the
election. In fact, the circumstances of the whole affair—previous
antagonism between the parties, actual support in the election, and
acceptance of high office, made up a case against Messrs. Adams
and Clay which it was hardly safe for public men to create and to
brave, however strong in their own consciousness of integrity. Still,
the great objection to the election of Mr. Adams was in the violation
of the principle demos krateo; and in the question which it raised of
the capacity of the demos to choose a safe President for themselves.
A letter which I wrote to the representative from Missouri, before he
gave the vote of the State to Mr. Adams, and which was published
immediately afterwards, placed the objection upon this high ground;
and upon it the battle was mainly fought, and won. It was a victory
of principle, and should not be disparaged by the admission of an
unfounded and subordinate cause.
This presidential election of 1824 is remarkable under another
aspect—as having put an end to the practice of caucus nominations
for the Presidency by members of Congress. This mode of
concentrating public opinion began to be practised as the eminent
men of the Revolution, to whom public opinion awarded a
preference, were passing away, and when new men, of more equal
pretensions, were coming upon the stage. It was tried several times
with success and general approbation, public sentiment having been
followed, and not led, by the caucus. It was attempted in 1824, and
failed, the friends of Mr. Crawford only attending—others not
attending, not from any repugnance to the practice, as their
previous conduct had shown, but because it was known that Mr.
Crawford had the largest number of friends in Congress, and would
assuredly receive the nomination. All the rest, therefore, refused to
go into it: all joined in opposing the caucus candidate, as Mr.
Crawford was called; all united in painting the intrigue and
corruption of these caucus nominations, and the anomaly of
members of Congress joining in them. By their joint efforts they
succeeded, and justly in the fact though not in the motive, in
rendering these Congress caucus nominations odious to the people,
and broke them down. They were dropped, and a different mode of
concentrating public opinion was adopted—that of party nominations
by conventions of delegates from the States. This worked well at
first, the will of the people being strictly obeyed by the delegates,
and the majority making the nomination. But it quickly degenerated,
and became obnoxious to all the objections to Congress caucus
nominations, and many others besides. Members of Congress still
attended them, either as delegates or as lobby managers. Persons
attended as delegates who had no constituency. Delegates attended
upon equivocal appointments. Double sets of delegates sometimes
came from the State, and either were admitted or repulsed, as
suited the views of the majority. Proxies were invented. Many
delegates attended with the sole view of establishing a claim for
office, and voted accordingly. The two-thirds rule was invented, to
enable the minority to control the majority; and the whole
proceeding became anomalous and irresponsible, and subversive of
the will of the people, leaving them no more control over the
nomination than the subjects of kings have over the birth of the
child which is born to rule over them. King Caucus is as potent as
any other king in this respect; for whoever gets the nomination—no
matter how effected—becomes the candidate of the party, from the
necessity of union against the opposite party, and from the
indisposition of the great States to go into the House of
Representatives to be balanced by the small ones. This is the mode
of making Presidents, practised by both parties now. It is the virtual
election! and thus the election of the President and Vice-President of
the United States has passed—not only from the college of electors
to which the constitution confided it, and from the people to whom
the practice under the constitution gave it, and from the House of
Representatives which the constitution provided as ultimate arbiter—
but has gone to an anomalous, irresponsible body, unknown to law
or constitution, unknown to the early ages of our government, and
of which a large proportion of the members composing it, and a
much larger proportion of interlopers attending it, have no other
view either in attending or in promoting the nomination of any
particular man, than to get one elected who will enable them to eat
out of the public crib—who will give them a key to the public crib.
The evil is destructive to the rights and sovereignty of the people,
and to the purity of elections. The remedy is in the application of the
democratic principle—the people to vote direct for President and
Vice-President; and a second election to be held immediately
between the two highest, if no one has a majority of the whole
number on the first trial. But this would require an amendment of
the constitution, not to be effected but by a concurrence of two
thirds of each house of Congress, and the sanction of three fourths
of the States—a consummation to which the strength of the people
has not yet been equal, but of which there is no reason to despair.
The great parliamentary reform in Great Britain was only carried
after forty years of continued, annual, persevering exertion. Our
constitutional reform, in this point of the presidential election, may
require but a few years; in the meanwhile I am for the people to
select, as well as elect, their candidates, and for a reference to the
House to choose one out of three presented by the people, instead
of a caucus nomination of whom it pleased. The House of
Representatives is no longer the small and dangerous electoral
college that it once was. Instead of thirteen States we now have
thirty-one; instead of sixty-five representatives, we have now above
two hundred. Responsibility in the House is now well established,
and political ruin, and personal humiliation, attend the violation of
the will of the State. No man could be elected now, or endeavor to
be elected (after the experience of 1800 and 1824), who is not at
the head of the list, and the choice of a majority of the Union. The
lesson of those times would deter imitation, and the democratic
principle would again crush all that were instrumental in thwarting
the public will. There is no longer the former danger from the House
of Representatives, nor any thing in it to justify a previous resort to
such assemblages as our national conventions have got to be. The
House is legal and responsible, which the convention is not, with a
better chance for integrity, as having been actually elected by the
people; and more restrained by position, by public opinion, and a
clause in the constitution from the acceptance of office from the
man they elect. It is the constitutional umpire; and until the
constitution is amended, I am for acting upon it as it is.
CHAPTER XX.
THE OCCUPATION OF THE COLUMBIA.
This subject had begun to make a lodgment in the public mind,
and I brought a bill into the Senate to enable the President to
possess and retain the country. The joint occupation treaty of 1818
was drawing to a close, and it was my policy to terminate such
occupation, and hold the Columbia (or Oregon) exclusively, as we
had the admitted right to do while the question of title was
depending. The British had no title, and were simply working for a
division—for the right bank of the river, and the harbor at its mouth
—and waiting on time to ripen their joint occupation into a claim for
half. I knew this, and wished to terminate a joint tenancy which
could only be injurious to ourselves while it lasted, and jeopard our
rights when it terminated. The bill which I brought in proposed an
appropriation to enable the President to act efficiently, with a
detatchment of the army and navy; and in the discussion of this bill
the whole question of title and of policy came up; and, in a reply to
Mr. Dickerson, of New Jersey, I found it to be my duty to defend
both. I now give some extracts from that reply, as a careful
examination of the British pretension, founded upon her own
exhibition of title, and showing that she had none south of forty-nine
degrees, and that we were only giving her a claim, by putting her
possession on an equality with our own. These extracts will show the
history of the case as it then stood—as it remained invalidated in all
subsequent discussion—and according to which, and after twenty
years, and when the question had assumed a war aspect, it was
finally settled. The bill did not pass, but received an encouraging
vote—fourteen senators voting favorably to it. They were:
Messrs. Barbour, Benton, Bouligny, Cobb, Hayne, Jackson (the
General), Johnson of Kentucky, Johnston of Louisiana, Lloyd of
Massachusetts, Mills, Noble, Ruggles, Talbot, Thomas.
Mr. Benton, in reply to Mr. Dickerson, said that he had not
intended to speak to this bill. Always unwilling to trespass upon
the time and patience of the Senate, he was particularly so at
this moment, when the session was drawing to a close, and a
hundred bills upon the table were each demanding attention.
The occupation of the Columbia River was a subject which had
engaged the deliberations of Congress for four years past, and
the minds of gentlemen might be supposed to be made up upon
it. Resting upon this belief, Mr. B., as reporter of the bill, had
limited himself to the duty of watching its progress, and of
holding himself in readiness to answer any inquiries which might
be put. Inquiries he certainly expected; but a general assault, at
this late stage of the session, upon the principle, the policy, and
the details of the bill, had not been anticipated. Such an assault
had, however, been made by the senator from New Jersey (Mr.
D.), and Mr. B. would be unfaithful to his duty if he did not repel
it. In discharging this duty, he would lose no time in going over
the gentleman's calculations about the expense of getting a
member of Congress from the Oregon to the Potomac; nor
would he solve his difficulties about the shortest and best route
—whether Cape Horn should be doubled, a new route explored
under the north pole, or mountains climbed, whose aspiring
summits present twelve feet of defying snow to the burning rays
of a July sun. Mr. B. looked upon these calculations and
problems as so many dashes of the gentleman's wit, and
admitted that wit was an excellent article in debate, equally
convenient for embellishing an argument, and concealing the
want of one. For which of these purposes the senator from New
Jersey had amused the Senate with the wit in question, it was
not for Mr. B. to say, nor should he undertake to disturb him in
the quiet enjoyment of the honor which he had won thereby,
and would proceed directly to speak to the merits of the bill.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

Moodle 19 Extension Development Customize And Extend Moodle By Using Its Robust Plugin Systems Jonathan Moore

  • 1.
    Moodle 19 ExtensionDevelopment Customize And Extend Moodle By Using Its Robust Plugin Systems Jonathan Moore download https://ebookbell.com/product/moodle-19-extension-development- customize-and-extend-moodle-by-using-its-robust-plugin-systems- jonathan-moore-2434524 Explore and download more ebooks at ebookbell.com
  • 2.
    Here are somerecommended products that we believe you will be interested in. You can click the link to download. Moodle 19 Top Extensions Cookbook 1st Edition De Raadt Michael https://ebookbell.com/product/moodle-19-top-extensions-cookbook-1st- edition-de-raadt-michael-55201978 Moodle 19 Theme Design Beginners Guide Gadsdon Paul James https://ebookbell.com/product/moodle-19-theme-design-beginners-guide- gadsdon-paul-james-55201976 Moodle 19 For Design And Technology 1st Edition Taylor Paul https://ebookbell.com/product/moodle-19-for-design-and-technology-1st- edition-taylor-paul-55201984 Moodle 19 For Teaching 714 Year Olds Beginners Guide Cooch https://ebookbell.com/product/moodle-19-for-teaching-714-year-olds- beginners-guide-cooch-55201988
  • 3.
    Moodle 19 TeachingTechniques 1st Edition Smith Nash Susan Rice https://ebookbell.com/product/moodle-19-teaching-techniques-1st- edition-smith-nash-susan-rice-55201992 Moodle 19 Elearning Course Development A Complete Guide To Successful Learning Using Moodle 19 1st Edition William H Rice https://ebookbell.com/product/moodle-19-elearning-course-development- a-complete-guide-to-successful-learning-using-moodle-19-1st-edition- william-h-rice-2358366 Moodle 19 Testing And Assessment Jason Myrick https://ebookbell.com/product/moodle-19-testing-and-assessment-jason- myrick-2532670 Moodle 19 Testing And Assessment Jason Myrick https://ebookbell.com/product/moodle-19-testing-and-assessment-jason- myrick-2568030 Moodle 19 Theme Design Beginners Guide Customize The Appearance Of Your Moodle Theme By Using Moodles Powerful Theming Engine Paul James Gadsdon https://ebookbell.com/product/moodle-19-theme-design-beginners-guide- customize-the-appearance-of-your-moodle-theme-by-using-moodles- powerful-theming-engine-paul-james-gadsdon-4104696
  • 6.
    Moodle 1.9 Extension Development Customizeand extend Moodle by using its robust plugin systems Jonathan Moore Michael Churchward BIRMINGHAM - MUMBAI
  • 7.
    Moodle 1.9 ExtensionDevelopment Copyright © 2010 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: April 2010 Production Reference: 1220410 Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 978-1-847194-24-4 www.packtpub.com Cover Image by Parag Kadam (paragvkadam@gmail.com)
  • 8.
    Credits Authors Jonathan Moore Michael Churchward Reviewer AnthonyBorrow Acquisition Editor Rashmi Phadnis Development Editor Ved Prakash Jha Technical Editors Chris Rodrigues Hithesh Uchil Indexer Hemangini Bari Editorial Team Leader Akshara Aware Project Team Leader Priya Mukherji Project Coordinator Ashwin Shetty Proofreader Dirk Manuel Graphics Geetanjali Sawant Production Coordinator Aparna Bhagat Cover Work Aparna Bhagat
  • 9.
    About the Authors MichaelChurchward is currently the President and CTO of Remote Learner, a Moodle partner based in the U.S. and Canada. Mike has been a developer of Moodle since 2004, and contributes both core code and add-on functions to the open source project. Mike and his development team are currently working on other extensions to Moodle, and helping to define the new Moodle 2.0 architecture. Michael began his career building computer-based simulations of internal aircraft systems used in the training of ground and maintenance crews. Since then, he has been involved in many types of software and computer-based learning. Programming Moodle became a natural extension of that career. Michael lives with his family in a small town in south-western Ontario, and thanks all of them for their patience while he was writing this book. I thank the Moodle community for their energy and input; my wife, Janet; my sons, William, Cole, and Janson for their constant encouragement; and lastly my parents, Bob and Lorane for pointing me in the right direction.
  • 10.
    Jonathan Moore isthe Vice-President for Business Development at Remote Learner. Jonathan began working with Moodle in 2003. Over the past four years, Jonathan has worked with dozens of clients, delivering Moodle customizations. Jonathan has a Bachelor of Science degree in Information Technology. Jonathan formerly served as the Director of Technology for Winfield Public Schools. He served in this capacity for almost ten years, and has developed a broad set of educational technology and project management skills over the course of his career. His student technology program, Student Technology Assistance Team (STAT), was recognized nationally by CompTIA as the best rural student technology program. Earlier in his career, Jonathan worked as a full-time developer, and studied computer science prior to pursuing Information Technology. Jonathan started working with open source technology in 1993 with an early release of Slackware Linux, and has used and supported a variety of open source technologies in educational settings. Jonathan lives with his wife, in Lenexa, Kansas, a suburb of Kansas City. I wish to thank my co-author, Michael Churchward, for taking on this crazy project to write a book while growing a company. Thanks for taking this leap of faith. I would also like to thank my wife for putting up with a cranky writer this past year, my parents for emphasizing the importance of literacy, Bryan Williams and the rest of our leadership team for their support, and finally the staff of Winfield Public Schools for providing a wonderful place to grow.
  • 11.
    About the Reviewer AnthonyBorrow, S.J. is a Jesuit of the New Orleans Province, who has been active in the Moodle community for five years. Anthony has an M.A. in Counseling from Saint Louis University. Anthony has worked on the design and implementation of various database systems since 1992. Anthony serves the Moodle community as its CONTRIB Coordinator. In that role, Anthony has presented at various MoodleMoots (conferences) across the United States, and has provided in-house training opportunities for institutions learning how to implement Moodle. Anthony has taught at Dallas Jesuit College Preparatory and provides technical advice to the Jesuit Secondary Education Association (http://jsea.org) and the Jesuit Virtual Learning Academy (http://jvla.org/). Anthony is the co-author of the Honduras chapter of Teen Gangs: A Global View.
  • 12.
    Table of Contents Preface1 Chapter 1: Moodle Architecture 7 Understanding the stack 8 Database 9 Operating system 10 Web server 10 Directory and system structure 11 Moodle code 12 Moodle database 15 Moodle data 16 Installing Moodle 16 Moodle program execution 18 Executing config.php 18 Including Moodle libraries 19 Getting our data 20 Displaying in Moodle 20 Configuring Moodle 21 Setting configuration variables 22 Moodle's API 23 Other important libraries 25 PEAR 25 ADOdb 25 YUI 25 XMLDB 25 Access control, logins, and roles 26 Moodle permission contexts 26 Capabilities 27
  • 13.
    Table of Contents [ii ] Moodle roles 28 Assigning roles 28 Summary 29 Chapter 2: Creating and Modifying Blocks 31 Creating a block from scratch 31 Assigning content to our block 32 Adding a language file 33 Working with capabilities 34 Testing for built-in capabilities 34 Hiding a block based on capabilities 36 Adding your own capability 36 Checking for our new capability 37 Adding instance configuration 38 Capturing your configuration content 38 Displaying your content 39 Adding scheduled actions to our block 40 Reviewing a real world block 42 Reviewing block_instructor_contact.php 43 Configuring the instructor contact block 44 Using a block as a code container 45 Creating a block stub for our container 45 Creating capabilities for our container 46 Summary 47 Chapter 3: Creating and Modifying Filters 49 How a filter works 49 Building a filter 50 Getting started 51 Creating the language file 52 Creating the filter code 53 Activating the filter 54 Adding configuration settings 55 Using our settings 57 Summary 58 Chapter 4: Creating and Modifying Activity Modules 59 The scope of creating an activity module 59 Our module—activity Foo! 61 Getting started with the NEWMODULE template 62 Completing mod_form.php 62 Defining input values 64 Using common form elements 65
  • 14.
    Table of Contents [iii ] Making version.php 66 Setting icon.gif 66 Generating install.xml 66 Using the XMLDB editor 66 Defining our activity database 67 Defining the foo_responses table 68 Defining log types 69 Creating access.php 69 Updating index.php 69 Adding clean language strings 70 Looking up response data 70 Displaying our table of activities 71 Displaying course sections 71 Committing output 72 Finishing view.php 73 Including submit_form.php 73 Your code goes here 73 Context control 73 Developing a form 74 Cancel option 74 Submitted data 74 Setting grades 75 Displaying submission form 75 Displaying submissions 76 Group support 76 Coding lib.php 78 Function add_instance 78 Function foo_delete_instance 78 Function foo_user_outline 79 Function foo_user_complete 79 Function foo_get_participants 80 Function reset_course_form_definition 81 Function foo_reset_course_form_defaults 81 Function foo_reset_userdata 81 Inserting grades into the gradebook 82 Using grade_update 83 Upgrading our activity database 84 Using the XMLDB editor for database upgrades 84 Updating upgrade.php 84
  • 15.
    Table of Contents [iv ] Creating backup and restore support 85 Exploring backuplib.php functions 86 Common backup functions 86 Internal backup functions 87 Exploring restorelib.php functions 87 Common restore functions 87 Internal restore functions 88 Summary 88 Chapter 5: Customizing the Look and Feel 89 Themes 89 How themes work 90 Headers and footers 90 header.html 91 footer.html 92 Project 1: Changing the navigation breadcrumbs 93 Creating our own theme 93 Adding the category link 94 The navigation string 94 Project 2: Adding a standard footer with site links 96 Creating the code 97 Running the code 99 Course formats 101 How course formats work 101 Creating our own course format 102 Creating the course format language file 102 Modifying our course format function 103 Changing the forum display 104 Summary 105 Chapter 6: Developer's Guide to the Database 107 The database structure 107 Maintaining Moodle tables 109 install.xml 109 upgrade.php 110 Maintaining local database customization 112 The XMLDB editor 113 Using the Moodle database in your code 115 Retrieving data 115 Query by parameters 116 Query by "where" string 118 Query by full SQL 119 Storing data 119 set_field and set_field_select 120 insert_record and update_record 120
  • 16.
    Table of Contents [ ] Common tables and relationships 121 Course and module relationships 121 Programming best practices 123 Take only what you need 123 Limiting your returned data 123 Using recordsets 124 Optimizing carefully with joins 124 Testing on more than one database engine 125 Summary 125 Chapter 7: Developing Pluggable Core Modules 127 Assignment types 127 What is an assignment type 128 Identifying assignment types 129 Assignment type basics 129 Building our own assignment type 130 Getting started 130 Planning our data 131 Adding custom settings 133 Making it do something useful 134 Resource types 140 What is a resource type? 140 Identifying resource types 140 Resource type basics 141 Question types 142 What is a question type? 143 Identifying question types 144 Question type basics 144 The main class 145 The editing form 145 The main language file 146 Other important question constructs 147 Grading 147 Backup and restore functions 147 Import and export function support 147 CSS and JavaScript support 148 Where to get more help 148 Summary 148 Chapter 8: Creating Moodle Reports 149 Creating course reports 150 Defining the non-participants report 150 Getting started 151 Updating mod.php 151
  • 17.
    Table of Contents [vi ] Controlling access 152 Language strings 152 Changes to Moodle's API 153 Exploring the People block 154 Setting $select 154 Setting $from 155 Setting $where 156 Making the query call 156 Modifying index.php 157 Making text substitutions 157 Changing the logical structure 158 Tracking active users using a hash array 159 Displaying the report 160 Cleaning up the final display 161 Using flexible_table 162 An exercise for you 163 Creating gradebook reports 163 Required components 164 Creating our report folder 164 Creating access.php 164 Assigning language strings 164 index.php requirements 164 Using version.php 165 Using the grade_report class 165 Fixing the outcomes report 165 Digging into the code 166 Reviewing our new report 167 Creating administrator reports 167 Generating the Hello World administrator report 168 Tweaking index.php 168 Viewing our administrator report 169 An exercise for you 170 Other output formats 170 Summary 170 Chapter 9: Integrating Moodle with Other Systems 171 Built-in services and plugins 171 Batch upload 172 Built-in authentication plugins 173 Manual/Internal authentication 173 LDAP/Active directory authentication 173 External database authentication 174 E-mail account based authentication plugins 174 Built-in enrollment plugins 174 LDAP enrollment plugin 175
  • 18.
    Table of Contents [vii ] External database enrollment plugin 175 E-commerce based enrollment plugins 175 Web services 176 Activity plugin as an integration bridge 176 Creating user authentication plugins 176 Exploring authentication requirements 176 Looking at auth.php 177 Making the language file 178 Testing simple authentication 178 Adding optional functionality to authentication 178 Creating the RLLDAP authentication plugin 179 Coding RLLDAP 180 Implementing Single Sign On 183 Creating a URL-based SSO 183 Digging into the code 184 Finding the user's account 184 Confirming that the login criteria have been met 184 Completing login 184 Redirecting the user to the correct location 185 Testing the URL SSO 185 Creating user enrollment plugins 186 Reviewing plugin requirements 186 Creating enrol.php 186 Creating the setup_enrolments function 186 Making the language file 187 Other requirements 187 Making the 'simple' enrollment plugin 187 Using optional enrollment functions 188 Assigning enrollment plugins to courses 188 Grade or completion passing 189 Working with the built-in import/export plugins 189 Creating grade import/export plugins 190 An exercise for you 190 Summary 190 Chapter 10: Writing Secure Code 191 User access issues 191 Making sure that a user has logged in 192 Making sure that the user's session is the current one 192 Making sure that the user has appropriate capabilities 194 SQL issues 195 Taking a look at vulnerable code 195 Quote protection 196 Database API 197 Use of addslashes 197
  • 19.
    Table of Contents [viii ] Form issues 198 The Moodle formslib library 199 Specifying a type 199 Validation rules 200 'param' functions 201 File system issues 201 Course file areas 202 User file areas 202 Other file areas 203 Getting a file URL 203 Screen output issues 204 The p() and s() functions 204 The format_text() and format_string() functions 205 Logging your actions 207 Summary 208 Chapter 11: Sending Notifications to Users 209 Requirements 209 Setup 210 Using e-mail 213 Send e-mail API 214 Creating the subject text 214 Creating the message text 215 Sending the e-mail 215 Using Moodle messaging 216 Moodle messaging internals 216 Creating the message 217 Sending the message 218 Using RSS feeds 219 Setup 219 Creating the RSS XML file 220 Viewing the RSS feed 222 Summary 225 Chapter 12: Constructing and Displaying Pages by Using the pagelib Library 227 Introduction to pagelib 228 Class page_base 228 Class page_course 228 Class page_generic_activity 228 Core modules that use pagelib 228
  • 20.
    Table of Contents [ix ] Using pagelib factory functions 229 page_import_types 229 page_create_instance 230 page_create_object 230 page_map_class 230 page_base member functions 230 page_base() and construct() 231 get_id() 231 get_body_class() 231 get_body_id() 231 edit_always() 231 init_quick() 231 init_full() 232 user_allowed_editing() 232 user_is_editing() 232 print_header() 232 get_type() 232 get_format_name() 232 url_get_path() 232 url_get_parameters() 233 blocks_get_positions() 233 blocks_default_position() 233 blocks_get_default() 233 blocks_move_position() 233 Meeting pagelib requirements 233 Looking at page setup 234 Examining requirements by reviewing quiz's view.php 234 Working with quiz blocks 235 Investigating quiz page display 235 Converting activity Foo! to pagelib 236 Creating a local pagelib.php 236 Updating view.php 238 Initializing $PAGE 238 Outputting blocks 239 Outputting the middle column 239 Viewing the results 240 Related libraries 241 weblib 241 blocklib 241 graphlib 241 Summary 241
  • 21.
    Table of Contents [ ] Chapter 13: Building Forms with formslib 243 Using formslib 244 Form definition and elements 244 addElement and createElement 245 Buttons 245 Checkboxes 247 Uploading and/or choosing a file 249 Date and time 250 htmleditor, textarea, and text 252 modgrade 253 password and passwordunmask 254 radio 254 select, multi-select, and selectyesno 255 hidden, html, and static text 256 Groups 257 Rules and validation 257 Rules 257 addRule 258 registerRule 259 Validation 260 Summary 261 Chapter 14: Development for the Adventuresome: Web Services 263 Using Remote-Learner Web Services 264 Advantages 264 Disadvantages 265 Installation 265 Server-side setup 265 Client setup 266 Testing with ppdemo_trace.php 266 Setting up your Web Services connection 267 Debugging setup 268 Managing users 269 Creating users 269 Updating users 272 Deleting users 273 Creating a Web Services based Single Sign On 273 Creating our HTML wrapper 274 Web service connection setup 275 Processing SSO parameters 275 Using authenticate_user() 275 Closing wrapper 276
  • 22.
    Table of Contents [xi ] Enrollment management 276 Creating enrollstudent.php 277 Using enrol_students() 277 Creating unenrollstudent.php 277 Grade passing 278 Creating the CSV grade script 278 Using Moodle Networking 280 Advantages 280 Disadvantages 280 What is XML-RPC? 281 MNet XML-RPC supported service types 281 MNet XML-RPC security model 281 Using MNet in activity modules 282 Using MNet in auth/enrol plugins 283 MNet SSO model 283 Summary 284 Index 285
  • 24.
    Preface Moodle has evolvedinto one of the most widely-used Learning Management Systems in the world, with over 35,000 installed sites and 25 million users. Much of its popularity is due to its ability to be extended by developers, by using its open source architecture. Understanding how to develop on the Moodle platform provides an organization using Moodle the flexibility to expand its functions. This book will teach you the inner workings of Moodle, and provide you with the ability to develop code the Moodle way. You will learn to develop standard Moodle plugins, such as activities and blocks, by creating functioning code that you can execute in your own Moodle installation. This book will expose you to all of the core code functions in Moodle in a progressive, understandable way. You will learn what libraries are available, what the API calls are, how Moodle is structured, and how it can be expanded beyond the plugin system. Approach This is a practical, hands-on book that will allow you to build plugins as you learn. All of the technologies that you need are freely-available in the open source world. You will begin by gaining an understanding of the basic architecture that Moodle uses to operate in. Next, you will build your first plugin, a block. You will carry on building other Moodle plugins, gaining knowledge of the Moodle way of coding, before plunging deeper into the API and inner libraries. Lastly, you will learn how to integrate Moodle with other systems, by using a variety of methods. By the time you have finished this book, you will have a solid understanding of Moodle programming, and will have the knowledge to extend its functionality in whatever way you want.
  • 25.
    Preface [ ] Whatthis book covers Chapter 1, Moodle Architecture, introduces some of the important concepts of Moodle architecture: how Moodle is structured, and how Moodle works. Chapter 2, Creating and Modifying Blocks, covers how to create a basic block in Moodle, one of the easiest and most common customizations. Moodle blocks are plugins that display content in the right-hand or left-hand side column of a Moodle site. Several basic Moodle programming concepts that are used throughout the book are introduced. Chapter 3, Creating and Modifying Filters, covers the basic concepts of creating a Moodle filter. The Moodle filter system is a method of processing the contents of the Moodle database (typically, user-entered content) prior to display, so that it can be modified in some beneficial way. Chapter 4, Creating and Modifying Activity Modules, covers how to create a Moodle activity that can send results to the gradebook. Moodle activities are plugins that provide instructional activities for learners. One or more activities of each type can be added to courses, and each activity typically has a graded component that sends its results to the Moodle gradebook. Chapter 5, Customizing the Look and Feel, elaborates on the common methods of customizing the look and feel of a Moodle site. This chapter will discuss how to tell the difference between a requirement that needs programming and one that can be completed by a theme designer. Chapter 6, Developer's Guide to the Database, covers both the overall structure of the Moodle database and the coding methods used to access and store information there. Moodle supports a variety of SQL databases to store program information. Chapter 7, Developing Pluggable Core Modules, covers useful programming concepts and considerations for the core Moodle system and modules. Some common ways by which popular modules can be modified are explored in this chapter. Chapter 8, Creating Moodle Reports, covers a variety of methods of adding to Moodle's built-in reports. Moodle has an excellent logging system, but often users find they need to write a custom reporting module in order to get the data in the exact format that they desire. Chapter 9, Integrating Moodle with Other Systems, covers four common types of integrations: user authentication, user enrollment, performance results, and Single Sign On. A common customization request for Moodle is to integrate with a third-party system.
  • 26.
    Preface [ ] Chapter10, Writing Secure Code, covers various security concerns and best practices when developing code for Moodle. Chapter 11, Sending Notifications to Users, discusses methods of messaging and notifying users through e-mail, RSS, and others. Chapter 12, Constructing and Displaying Pages by Using the pagelib Library, covers the basic concepts of using pagelib. The pagelib library is used in the construction of display pages in Moodle. Chapter 13, Building Forms with formslib, covers how to use the formslib library for customizations. The formslib library controls Moodle forms, user input, and input sanitation. Chapter 14, Development for the Adventuresome: Web Services, covers two separate Moodle implementations for web services: one SOAP-based and one XML-RPC-based. The SOAP library allows remote manipulation and creation of courses, users, user enrollments, and user grades. The XML-RPC library provides a secure channel and full Moodle API exposure to the trusted site. This chapter will explore basic concepts of using both libraries. Who this book is for This book is written for technologists who are interested in expanding Moodle's functions through programming, either for their own organizations or to contribute to the open source project. This book is aimed at programmers already familiar with Moodle's basic technologies: PHP, MySQL, and HTML/CSS. You will need an understanding of PHP in order to follow along with coding activities in the book. Conventions In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: Finally, we display our table using the print_html member function
  • 27.
    Preface [ ] Ablock of code is set as follows: ?php function learningisfunlink_filter($courseid, $text) { return $text; } ? When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: function get_content() { if ($this-content !== NULL) { return $this-content; }//if $context = get_context_instance(CONTEXT_SYSTEM); require_capability('moodle/site:doanything', $context); $this-content = new stdClass; $this-content-text = 'Hello World!'; return $this-content; }//function get_content New terms and important words are shown in bold. Words that you see on the screen, in menus, or dialog boxes for example, appear in the text like this: Click on the Notifications link in the Site Administration block. Warnings or important notes appear in a box like this. Tips and tricks appear like this. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to feedback@packtpub.com, and mention the book title in the subject of your message.
  • 28.
    Preface [ ] Ifthere is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or send an e-mail to suggest@packtpub.com. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the example code for the book Visit https://www.packtpub.com//sites/default/files/ downloads/4244_Code.zip to directly download the example code. Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support. Piracy Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately, so that we can pursue a remedy.
  • 29.
    Preface [ ] Pleasecontact us at copyright@packtpub.com with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content. Questions You can contact us at questions@packtpub.com if you are having a problem with any aspect of the book, and we will do our best to address it.
  • 30.
    Moodle Architecture Moodle isan open source Learning Management System (LMS). It can be used to deliver online learning in a variety of settings. These settings include virtual schools, K12, higher education, corporate universities, charter schools, and commercial training, to name but a few. Moodle is designed to be used primarily as an asynchronous learning tool, where learners study at different times. However, it also includes synchronous tools. Moodle is used both as the primary delivery vehicle for courses as well as a supplemental tool for face-to-face learning. To put it simply, Moodle is a teacher's toolkit to help improve learning. Moodle is designed in a community with teachers interacting directly with programmers. Moodle's intuitive and simple interface is the result of this collaboration. Moodle originally stood for Modular Object-Oriented Dynamic Learning Environment. From a programmer's perspective, the M in Moodle is a very important concept. Modularity is designed throughout Moodle. This lets a developer make significant modifications to Moodle without having to modify its code. This is a very important capability in terms of reducing the amount of time taken to make modifications when new versions of Moodle are released. Writing modular plugins for Moodle will be a large focus of this book. You can learn more about general Moodle functionality and history on the Moodle Documentation site at http://docs.moodle.org/en/About_Moodle. This chapter introduces some of the important concepts of Moodle architecture; how Moodle is structured and how Moodle works. This chapter introduces the following concepts: Components of the system (operating system, web server, PHP interpreter, database, and browser) Directory and system structure (Moodle code, database, and file storage) Installation (how to install, what happens during installation, and how to upgrade) • • •
  • 31.
    Moodle Architecture [ ] Program execution (the major calling structure, included libraries, execution paths, and separation of function/display/data) Configuration (from the interface, from the config file, and from the database) Application Programming Interface (a brief description of what the major libraries do) Other common libraries (PEAR, ADOdb, YUI, and XMLDB) Access control for users, courses, and other security objects As you can see from the list, we will be covering a lot of ground in this chapter. Let's get started with a discussion of the technology stack that drives Moodle. Understanding the stack Moodle is an example of a LAMP application. LAMP originally stood for Linux, Apache, MySQL, and Perl. Over time, the various components of the acronym have shifted. For example, PHP has become the predominate language for LAMP applications. In truth, any of the components can be exchanged for another. However, the title has stuck to refer to applications written in web scripting languages, using an SQL database to store information. With the increasing popularity of running open source web applications on both Windows and Mac OS X, two new terms have been coined, respectively: WAMP and MAMP. See the following figure, which illustrates components of the system in Moodle: LAMP Stack Web Server Apache Interpreter PHP Database Server MySQL Linux Operating System Moodle is written in PHP, and the current version as of this writing (Version 1.9) requires PHP Version 4.3.0 or higher. Version 2.0 of Moodle, which is currently in development, will require PHP Version 5.2.8 or higher. • • • • •
  • 32.
    Chapter 1 [ ] Database Moodle's database layer is written using the PHP ADOdb library, which was created to provide a standardized method of accessing various database systems, using a consistent programming interface. PHP native database libraries are database specific and as a result are difficult to use to write a program that can support multiple database servers. Thanks to its use of ADOdb, Moodle provides support for a variety of databases including: MySQL, PostgreSQL, Microsoft SQL, and Oracle. Moodle supports a much longer list of databases for the purpose of external system integrations, by using its plugin architecture. While Moodle does enjoy broad database support, in practice, most systems are deployed using MySQL. As a practical result of this, more eyes are looking at MySQL installations; it has the fewest bugs, with the broadest set of third-party additions. PostgreSQL is the second most popular backend and has a strong following amongst performance enthusiasts and large deployments (tens of thousands or more users). Microsoft SQL and Oracle installations are primarily used by organizations with a pre-existing investment in one of these architectures. Because of their smaller user base, they are not as well tested. It is also more difficult to find good support for using these database types with Moodle. Many third-party add-on modules do not work under these systems without patching. Database version requirements for Moodle 1.9: MySQL 4.1.16 PostgreSQL 8.0 Microsoft SQL 9.0 Oracle 9.0 Proposed database requirements for Moodle 2.0: MySQL 4.1.16 or PostgreSQL 8.0 or Microsoft SQL 9.0 or Oracle 9.0 SQLite 3 (experimental) The latest version of these requirements can be viewed at the following URL: http://docs.moodle.org/en/Environment#Moodle_version_1.9. Note that the specifications for the Moodle 2.0 database layer can be found at the following location: http://docs.moodle.org/en/Development:DB_layer_2.0. • • • • • • • • •
  • 33.
    Moodle Architecture [ 10] Operating system Moodle can run on any operating system that supports the required version of PHP and the database. Moodle is generally installed on one of the three major operating systems: Windows, Mac OS X, or Linux (or Unix/Unix-like operating systems). As compared to Linux, both Mac OS X and Windows operating systems suffer from less efficient performance for large-scale deployments. For Windows, this is due to a less- optimized PHP stack, and for Mac OS X it is due to poor process forking performance, which both Apache and MySQL rely on for high concurrency. Windows Server 2008 is reported in press releases by both Microsoft and Zend, the creator of PHP, as having improved PHP performance. In a development environment, you can use any of these operating systems as an excellent platform. In a production environment, each operating system will have different performance characteristics. Web server Moodle will typically work with any web server that supports running the appropriate versions of PHP. In practice, the most used web server is Apache, which is available for most operating systems. Internet Information Services (IIS) is another popular web server for hosting Moodle. There are also a growing number of advocates for Lighthttpd as a web server, and this is reported in the Moodle community forums (http://moodle.org/forums/) as working well with Moodle. Lighthttpd has a growing number of advocates due to its low memory design. It is extremely popular for its use with virtual environments (VMware, Xen, and Amazon Elastic Compute Cloud), where memory footprint is more of a concern. Moodle as a web application has support and development constraints that are different from the norm. This is due to the way in which Moodle is used. A user interacting with Moodle will have a higher than normal amount of clicks, and Moodle generates many SQL queries as it builds a page. Moodle is very efficient at what it does. However, what it does is fairly complex. This means, as developers, we need to be aware of the type of architectures that our modifications will likely be used within. It also means that we need to be aware of the performance implications of our coding. The following figure illustrates several common configurations used for Moodle in a production environment. Moodle is deployed in a broad range of settings—anywhere from a single teacher running it on his or her desktop all the way up to multi-machine clusters of high performance servers:
  • 34.
    Chapter 1 [ 11] Common Moodle Architectures Single Server Two Server Cluster Web Server Database Server High Performance Cluster Load Balancer Web 2 DB Server File Server Web DB Moodle Data Web DB Moodle Data Web 1 Web N Moodle, as is common with the standard PHP application model, scales at particular points. The first scaling point is the database, which can easily be moved to a separate physical server. After that, we can bring in additional frontend web servers by using a load balancer. When using multiple web servers we will also need shared storage for our Moodle data. Session data can be stored in either Moodle data or in the database. The database server is the point where Moodle's scalability is most limited. To scale the database it is necessary to bring in a faster database server, replacing the older server. Currently, there is no standard method for scaling a single Moodle installation across multiple master database servers, as we do with the web application servers. It is also common practice to use Moodle with a PHP accelerator such as eAccelerator or APC. It's important to test your code in these environments to make sure that it functions correctly. Directory and system structure As shown in the following figure, each working Moodle system can be divided into three separate areas: Moodle code, the Moodle database, and Moodle data. Three Areas of Moodle Moodle Code Apache/IIS/Lighthttpd Moodle Database MySQL/PostgreSQL/Microsoft SQL/Oracle Moodle Data Local disk, NFS, GFS, SAN, etc.
  • 35.
    Moodle Architecture [ 12] Moodle code Because PHP is an interpreted language, the Moodle code is stored as source code files on the web server. When a particular file is requested on the server, the PHP interpreter parses the code on the fly, and the resulting output is sent out via the web server software. As mentioned earlier, the M in Moodle stands for Modular, and its directory structure reflects that. Each top-level folder represents a major component of Moodle. Many of the main components support plugin modules. Each plugin has its own folder inside the component's folder. In some cases, modules will also have support for additional plugins. An example of this is the quiz activity module, which supports modular question types. From the end user point of view, modules are installed by copying the module into the appropriate folder location on the server. Moodle detects the new module the next time that an administrator logs into the system, locates the module's SQL code, runs it, and finally displays the results. Upgrades work in much the same way with Moodle, tracking the database version and automatically upgrading the database as needed. All of this easy interface for end users comes at the cost of some elbow grease for the developer. The following screenshot is a directory listing of a recent Moodle 1.9 installation: We will not cover all of the directories in the main folder at this time. However, we will explore the functions of some of the important folders used by developers who make modifications to Moodle. Moodle uses a simple nomenclature for modules, where all of the modules are enclosed in their own folder, and the name of the folder is the name that Moodle displays in its interface when referring to the module.
  • 36.
    Chapter 1 [ 13] admin: This folder stores the PHP files that control the administrative user's interface. They also contain the cron.php file, which is run as a batch process to perform system maintenance tasks such as message delivery and course backups. We will often hook into the cron.php process to perform batch operations. auth: The auth folder contains all of the authentication modules for Moodle. Each module will have its own directory in this area. Authentication modules control the creation of users, user profile data, and user access to the system. Authentication modules are great for automating system administration, and as a result are a common customization project. backup: This folder contains the core course backup facilities for the system. These are not system-wide backup facilities but functions for the backup, restore, and import of courses. Each individual course module is responsible for its own backup code and makes use of these functions as needed. Each module is self-contained, allowing us, as developers, to add modules cleanly to Moodle without having to modify the core code. blocks: blocks are used to display boxes of information in either the right-hand side or left-hand side column of the Moodle page. This is one of the simplest module types to make, and also tend to work across multiple versions of Moodle with little or no modifications. course: This component of Moodle has obvious importance, given that Moodle is organized around courses. As developers, we are most likely to modify or add course formats and reports. Custom course formats can be used to change the layout of courses. enrol: The enrol folder contains all of the enrollment modules for Moodle. Enrollment modules control the creation and management of course-level role assignments (enrollments). Enrollment modules are another key automation hook.
  • 37.
    Moodle Architecture [ 14] files: The files component allows Moodle to incorporate files into the system. This includes file uploads, access control, and the viewing of files. files will see a major rewrite in Moodle 2.0. Moodle 2.0 will allow storing and using files in external file repositories such as Alfresco, Box.net, and Google Docs. filter: The Moodle filtering system is a text/regular expression-based search-and-replace facility. The filter system is fed user-entered content from the database during page creation. Filters match and modify the page before it is displayed. For example, there is a math filter that supports auto conversion of TEX markup language to equation graphics. The Multimedia Plugins filter finds references to common media types and wraps the text in the appropriate embed and/or object tags, in order to automatically embed the media, along with player controls, into the page. This is a very powerful capability. However, it needs to be carefully developed, with performance implications in mind. lang: The lang folder stores the core system language strings. This is the foundation of Moodle's localization and language support. All of the strings displayed to the end user are mapped via this facility. Language string mappings are also stored in the Moodle data lang folder. This structure allows for easy local customization of language files. The following is a small section of the /lang/en_utf8/moodle.php language file. Notice how each string that is displayed to the end user is mapped to a string hash by using a key value that is descriptive of the strings purpose (in English): $string['abouttobeinstalled'] = 'about to be installed'; $string['action'] = 'Action'; $string['actions'] = 'Actions'; $string['active'] = 'Active'; $string['activeusers'] = 'Active users'; lib: The lib folder stores the core system library functions. As we develop modules and customizations, we will use classes and functions defined in this folder.
  • 38.
    Chapter 1 [ 15] mod: The mod folder stores activity modules such as assignment, quiz, wiki, forum, and lesson modules. Learning activities are the core of any course delivered using Moodle. Activity modules are more challenging to create than blocks, because they back up, restore, and store grades. Oh, and of course, they have to teach something to the learner. my: my is a light-weight portal area in Moodle. It provides a listing of courses a learner is assigned, including a summary of upcoming course activities. The user can also add and remove blocks on his or her portal page. my provides a good location to display custom information with minimal core changes to Moodle. For example, we use my as a dashboard location in many of our customization projects. theme: The theme folder stores all of the built-in Moodle themes and any custom themes installed on the system. Themes are a combination of CSS, HTML, and PHP. Each theme has its own folder. The theme system is useful for defining the visual skin, header, and footer of the Moodle page. It is, however, limited in how much of the Moodle page it can modify. For example, certain components of the Moodle page are hardcoded to display in a certain way. Moodle database The Moodle database is organized into roughly 200 related tables. The default installation option prepends mdl_ in front of each table name. Each major component of the system typically has one or more tables, each starting with the component's name. For example, there are two tables related to the config component: mdl_config and mdl_config_plugins. As programmers, we will have to manipulate the database on a regular basis. It's also important for us to be able to treat the entire database as an entity, copying and moving instances of an entire Moodle database for the creation of staging and testing areas as we develop our code. We generally do this by using command-line utilities such as mysqldump and MySQL.
  • 39.
    Moodle Architecture [ 16] Moodle data Moodle data is the file storage location for user-uploaded content. Moodle data also stores the session data for users logged into the system, if file-based sessions are being used. Moodle data also stores optional language packs that can be downloaded from Moodle's administration interface. Moodle structures the data in this folder by either the user or by the course. Most of the data by file count and size will be in the courses. Each course has a folder, which is named with an integer value. The integer value is set to the internal database ID of the course in question. We can easily determine these values by navigating to a course via the Moodle web interface and inspecting its URL. For example, examine this URL for a course on my local test Moodle http://localhost/workspace/moodle19/course/view.php?id=3. Note the id=3 at the end of the URL. If we have uploaded any files to this course, there will be a folder path_to_moodledata/3. Within a course folder, Moodle will store module data in the moddata folder. When a module needs to store files, it saves them here in a folder with the same name as the module. For example, the wiki module will have a folder here named wiki. Additionally, Moodle will create a folder called backupdata if any course backups have been created. Any files that have been uploaded directly by a user using the course files interface will be loaded into the root of this folder. Users can also create their own folders and sub folders within the root folder. Moodle 2.0 uses an entirely new organizational model for user-uploaded files, which is based on a hashing algorithm. The primary goal of this new method is to support efficient use of disk storage space and greater flexibility for using files across multiple courses. Installing Moodle There are many ways to install Moodle. One of the simplest ways is to download one of the all-in-one installers from http://moodle.org. These are labeled as Moodle for Windows and Moodle for Mac OS X under the Downloads menu at http://moodle.org. These all-in-one installers contain both Moodle and all of the necessary server software, including Apache, PHP, and MySQL. While these packages are not recommended for production use, they can provide a convenient starting point for a developer new to Moodle. To manually install Moodle, download the Moodle source code files from http://moodle.org. You will find a variety of download packages. Each package is labeled with the version number. Major versions of Moodle are numbered in tenths: 1.6, 1.7, 1.8, and so on. Major versions focus on adding new features and bug fixes, which require major system changes to be implemented. Each major release has
  • 40.
    Chapter 1 [ 17] a number of minor point releases. For example: 1.9.1, 1.9.2, 1.9.3, and so on. Minor point releases focus on bug fixes and security updates. Finally, there are 'plus' releases that contain nightly or weekly fixes. From a developer's perspective, it makes sense to use the official CVS feeds to get Moodle's source code. This allows for easier updates and code merges, as well as integrating with many popular development tools. See http://docs.moodle.org/ en/CVS_for_Administrators. Once you have the source code, it needs to be copied to your server's web root. You should then create a folder (outside of the web root) for Moodle data, which is writable by the web server software. From your SQL server, create an empty database for Moodle to use. Finally, once this is done, you should enter the server's address and path to Moodle into your web browser. This will initiate the Moodle web installer and walk you through the rest of the installation options. During the installation you will be asked to enter details for your database. Once these have been entered, Moodle will connect to the database and create all 200+ tables. At the end of the installation it will write a config.php file to your Moodle directory with the values that you entered during installation. The following screenshot illustrates the first screen of the Moodle installer, where we select our default language: Upgrades follow the same basic pattern. Download the new code, copy it on the server in place of the old code (note that in most cases, you can copy the new code over the top of the old folder contents), and then visit the Moodle site in your web browser. Moodle will detect a version change by comparing the version tags stored in its configuration database against the ones reported in the module code, and then initiate the upgrade. Each module is responsible for its own database upgrades.
  • 41.
    Moodle Architecture [ 18] The final consideration for our development environment is to have a development tool for writing our code. While it is perfectly possible to write PHP code in any text editor (and many do), a popular option is to use the PHP plugin for Eclipse, or NetBeans. Detailed instructions for optimizing this setup can be found at http://docs.moodle.org/en/Setting_up_Eclipse_for_Moodle_development. Moodle program execution Moodle has many entry points—scripts that are called for execution. These are the files that are called by the browser to execute Moodle's functions. While there are many, the main ones are: /index.php: The front page /login/index.php: The login page /admin/index.php: The main administration page /course/view.php: A course page /mod/*/view.php: A module page Let's walk through a typical script, and follow the execution path. For the walkthrough, we will use the main course display script, /course/view.php. For this example, let's assume that we are using http://localhost/course/view.php?id=23. Before we jump in, let's analyze the URL a bit. The portion up to /course will be the URL of your Moodle site. The /course/ portion is the directory in Moodle that contains the course-handling scripts. The meat of the URL is the portion view.php?id=23. This script displays a course page. The course it displays is identified by the id=23 parameter, where 23 is the data ID of the course in question. If you look in the course data table in the database for your Moodle site, you will find an entry with the 'id' field equal to 23. The very first executable line we see in the script is: require_once('../config.php'); Executing config.php All of the entry scripts include the same important file: config.php. This is the only file in Moodle that must be included by specifying the exact literal path. This file performs a number of initial parameter assignments in the global $CFG variable. This provides the minimal amount of information to run the rest of the system; among this information are the database, web URL, script directory, and data storage directory definitions. Lastly, and most importantly, config.php includes /lib/setup.php. • • • • •
  • 42.
    Chapter 1 [ 19] config.php performs some basic, important variable assignment, whereas setup.php performs all of the initial program execution required to complete the execution environment setup. This includes defining several other important global variables, including $SESSION, $COURSE, $THEME, and $db. Next, it sets up and connects your database according to the settings defined in config.php. Moodle uses the open source ADOdb libraries to manage database functions. These functions are loaded through the inclusion of /lib/adodb/adodb.inc.php. Next, some critical library files are included that will be used by pretty much every other function in Moodle. These libraries include the functions required to manage multibyte strings, HTML output, Moodle data, access controls, events, groups, and general purpose Moodle and PEAR libraries. The remainder of the file sets up some other critical global variables, loads configuration variables from the database, sets up caching, sessions, environment variables, themes, language, and locales. Including Moodle libraries After including config.php, our script includes some other library files: require_once('lib.php'); require_once($CFG-libdir.'/blocklib.php'); ... This uses the PHP construct require_once, in case any of the files were included elsewhere first. Any file not located in the same directory is fully specified using directory definitions defined in config.php. You will notice lib.php has no directory specification, as it is located in the same directory as view.php. Likewise, the remaining files have full paths using directory definitions set up by config.php. You will notice the use of $CFG-libdir and $CFG-dirroot. The first is the defined file path to the main library directory (usually the lib subdirectory of the Moodle file path), while the second is the defined Moodle file path. Next, our script checks for, and loads, any parameters that it expects to get from the URL: $id = optional_param('id', 0, PARAM_INT); $name = optional_param('name', '', PARAM_RAW); ...
  • 43.
    Moodle Architecture [ 20] It does this by using the Moodle optional_param function, which loads the specified variable with a named parameter value if one is present, or a default value if not. If the parameter is required for the script to work properly, then the function required_param should be used instead. Both of these functions validate the data based on the specified arguments, and will generate errors or warnings if something other than what was expected is passed in. This is critical to securing user input in case of any additions to Moodle. See Chapter 10, Writing Secure Code for more information. Getting our data Next, our script loads the specific records that it needs from the database: if (! ($course = get_record('course', 'id', $id)) ) { error('Invalid course id'); } This can be done with either a database call, as above, or a specific API call. At this point, our script has enough information to check if the user has permissions to access its basic functions. This is done by loading contexts, checking the user login, and verifying capabilities: preload_course_contexts($course-id); if (!$context = get_context_instance(CONTEXT_COURSE, $course-id)) { print_error('nocontext'); } require_login($course); Much of the capability verification is performed by the require_login function. It verifies that the user is logged in (if necessary—some courses may not require that) and redirects them to the login function if required. It also loads and checks specific capabilities, including whether or not the user has access to the course. It also verifies enrollment and redirects the user to the enrollment function if necessary. Displaying in Moodle Next, our script will perform the necessary programming required to carry out its functions. Once it has finished this, it will begin the display process. The main functions for display are the print_header and print_header_simple functions. The following script uses the print_header function from the PAGE object it set up: $PAGE-print_header(get_string('course').': %fullname%', NULL, '', $bodytags);
  • 44.
    Chapter 1 [ 21] This function starts the HTML output by writing the HTTP headers, the theme information, requested JavaScript files, and other header section information. Then it begins with the body section. The body output is handled by the specific course format. Whatever format has been specified for the course in question in its settings, handles the body output. This is done as follows, by including the file format.php from the subdirectory of the format in question: require($CFG-dirroot .'/course/format/'. $course-format .'/ format.php'); If the course used the topics format (for example), then the file would be /course/ format/topics/format.php. This file handles the specific course page output, including the blocks and main content. It uses library functions found in /course/ lib.php to output the section's content. Lastly, the script outputs the footer: print_footer(NULL, $course); This function closes the body and completes the output to the screen. In most cases, this will be the last function executed for a script. Configuring Moodle Moodle is a highly-configurable application, with many complex settings in many areas of its functionality. These settings can be modified by Moodle administrators through: Direct code in the main config.php file The mdl_config table via administrative code and interfaces The mdl_config_plugins table via plugin administration During program execution, all of the main configuration values are stored in the $CFG global variable. $CFG is a generic structure. Each configuration variable is an element of the $CFG structure. For example, the $CFG-theme contains the text name of your site's selected theme. The elements of $CFG are loaded by direct assignment, and from values stored in the database mdl_config table. The primary point of direct assignment takes place in /config.php. Here, the initial, necessary configuration settings are made. • • •
  • 45.
    Moodle Architecture [ 22] There are minimal assignments that must be defined in this file. You are prompted for these values when you install Moodle, and you can change them afterwards by editing this file. The minimal settings are as follows: $CFG-dbtype = 'mysql'; // mysql or postgres7 (for now) $CFG-dbhost = 'localhost'; // eg localhost or db.isp.com $CFG-dbname = 'moodle'; // database name, eg moodle $CFG-dbuser = 'username'; // your database username $CFG-dbpass = 'password'; // your database password $CFG-prefix = 'mdl_'; // Prefix to use for all table names $CFG-dbpersist = false; // Should database connections be // reused? $CFG-wwwroot = 'http://example.com/moodle'; $CFG-dirroot = '/home/example/public_html/moodle'; $CFG-dataroot = '/home/example/moodledata'; $CFG-directorypermissions = 02777; $CFG-admin = 'admin'; There are other optional settings that can be made in this file. Review your /config-dist.php file to see all of these settings. Historically, any configuration settings that did not have a UI available to set these were set via code statements in this file. These often include new, experimental features. The remainder of the $CFG elements are set from the database. This is done through a call to the library function get_config (located in the /lib/moodlelib.php library file) from /lib/setup.php, which is included as the last action of config.php. The important thing to know about the function get_config is that it will not overwrite any $CFG setting that has already been set. This means you can overrule any database setting by hardcoding it into config.php. Also, config.php clears out the $CFG structure before it does anything else. This guarantees that nothing sets any configuration variables before config.php and setup.php. Setting configuration variables As a developer, you can set and use configuration variables for your functionality. You can set a configuration variable through the set_config function. The set_config function takes a name, a value, and an optional plugin name as arguments. The name becomes the element of the $CFG structure and the passed value becomes its value. Additionally, this will be stored into the database mdl_config table, so that it can be loaded on every program execution from then on. You can also specifically request a configuration variable at any time, by using the get_config function, but you won't need to, because it will be loaded into the $CFG structure once it has been set.
  • 46.
    Chapter 1 [ 23] The one issue that you need to consider when creating your own configuration variable is that the variable name you choose must be unique. Your variable becomes meaningless if you choose one that already exists. As most customizations you will be developing are likely to be plugins (modules, blocks, and so on), Moodle provides an alternate way to store configuration variables that are plugin specific. Plugin configuration variables are loaded into the plugin structure itself, rather than into the $CFG global structure. This means that the configuration variable name only needs to be unique to the plugin. Plugin configuration variables are stored in the mdl_config_plugin table, with the name of the plugin. They can be set and retrieved by using the same set_config and get_config functions as before. Generally, configuration variables are set by using administration interfaces. Most of the Moodle configuration variables are set through the various settings pages in the Site Administration menu block, which is visible on the home page of your Moodle site. In future sections, you will learn how the plugins add their interfaces to this structure. The following screenshot displays an example of Moodle's Site Administration block: Moodle's API Moodle's API is a mix of library functions and classes. Moodle was originally based on the version 4 series of PHP, and as such, most of its API is built around functions defined in PHP library files. However, some of the newer constructs of Moodle use object-oriented structures and as such provide extensible classes. Most of Moodle's main libraries are kept in the /lib/ directory. All of these files generally adhere to the naming convention [function]lib.php. Some of the examples are textlib.php and weblib.php. These library files contain Moodle's API.
  • 47.
    Moodle Architecture [ 24] Almost all of the core libraries are included in the execution stream when you load config.php via its inclusion of /lib/setup.php. The setup.php file includes these via the following lines: require_once($CFG-libdir .'/textlib.class.php'); // Functions to handle multibyte strings require_once($CFG-libdir .'/weblib.php'); // Functions for producing HTML require_once($CFG-libdir .'/dmllib.php'); // Functions to handle DB data (DML) require_once($CFG-libdir .'/datalib.php'); // Legacy lib with a big-mix of functions. require_once($CFG-libdir .'/accesslib.php'); // Access control functions require_once($CFG-libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility require_once($CFG-libdir .'/moodlelib.php'); // Other general-purpose functions require_once($CFG-libdir .'/eventslib.php'); // Events functions require_once($CFG-libdir .'/grouplib.php'); // Groups functions These by no means define all of the functions available in Moodle, and in fact each of these libraries may include other libraries. However, the core of the functions that you will need are contained within these libraries. In fact, the ones that you will need to look at the most are: moodlelib.php weblib.php dmllib.php accesslib.php grouplib.php There are many other libraries that you will use, as you start to carry out specific functions. Most of these are stored in the /lib/ directory. However, others may be in specific functional areas such as /course/ and /blocks/. Many of the specific libraries define classes that you can use. Libraries such as /lib/pagelib.php and /lib/formslib.php define classes that are designed to be extended in order to handle output to screen. pagelib.php defines specific page types, with all of the functions necessary to manage page output and create your own page types. Likewise, formslib.php defines Moodle's implementation of the PEAR QuickForm classes in order to handle web-based forms. • • • • •
  • 48.
    Chapter 1 [ 25] There is no single, all-encompassing document for all of Moodle's API. However, you can find out more about each specific area in the developer documentation at Moodle Docs. A good place to start is http://docs.moodle.org/en/Development: Developer_documentation#Core_components_that_affect_everything. Another resource that can help is the Moodle code cross reference. This is an online resource that is generated from the code and inline comments in order to produce documentation. It is generated automatically by using PHPXref. The reference can be found at http://docs.moodle.org/en/Development:Code_Cross-Reference. Note that it may not be up-to-date and maintained. Still, it does provide an easy overview. Other important libraries Moodle relies on a number of libraries, both internal and external. Several of these are explained below: PEAR PEAR stands for PHP Extension and Application Repository. As such, it's not a single library but a set of tools for getting and updating PHP libraries and modules. ADOdb ADOdb is a database library that provides a unified programming interface for a large variety of databases. Although Moodle supports a limited core set of databases for its direct backend, ADOdb really shines through in the supported databases for both the external database authentication and the enrollment plugins. YUI The Yahoo! User Interface (YUI) library is written in JavaScript, and is used to create rich web interfaces using AJAX, DOM, and DHTML. The Moodle course editing interface relies on this library for drag-and-drop placement of course elements. XMLDB XMLDB was added to Moodle as part of the initiative to add Microsoft SQL and Oracle backend support for Moodle. XMLDB rationalized all of the database configuration files to XML schemas, so that the same files could be used across all four supported backends. This extended upon the capabilities available from ADOdb, providing a single code base for accessing all databases supported, while still providing appropriate performance.
  • 49.
    Moodle Architecture [ 26] Access control, logins, and roles As open as Moodle is, it is tight with its security. It goes to great efforts to make sure that anyone accessing the system is supposed to be accessing the system, and they are supposed to be accessing it the way they are trying to. Moodle has a powerful access control and permission system. At the core of the access system is the user account. Although it is possible to grant access to any visitor to your site without authenticating them, it doesn't allow them to do many interesting things. We will assume that you want to know who your users are, and that you will want them to have their own accounts. A user account provides individual access via a username and password combination. These accounts are created by using authentication plugins. The bare minimum authentication is manual, where a user is created using the administration interface. The next, most common authentication is the e-mail-based system that allows users to create their own accounts using e-mail verification. In either case, a unique username and e-mail address are required as well as a password. Passwords in Moodle are encoded with an MD5 hash function to make them unreadable and difficult to guess. To get into the system, a user enters their username and password, and if correctly entered, they are granted access to the site. Logging in uses PHP's 'cookie' functions to set cookies into the current session and help identify the user throughout the site visit. Moodle permission contexts Permissions can be assigned within six contexts: site/global, course category, course, blocks and activities, user, and front page. There are seven built-in roles: administrator, teacher, non-editing teacher, student, course creator, authenticated user, and guest, all of which can be assigned in any one or more of the above contexts. Any number of customized roles can be created through the list of over 200 system capabilities. Each capability can be assigned one of four access levels: Not Set, Allow, Prohibit, and Prevent. Each user can have multiple roles that inherit permissions from all of the context levels applicable to a given access request from the user. The combination of these provides a powerful and flexible solution for administrators. The standard system roles are: Administrator: System administrator has all permissions Course creator: Can create course shells and can be limited to a course category • •
  • 50.
    Chapter 1 [ 27] Teacher: Can teach a course, develop, and update course content Non-editing teacher: Can teach a course but can't edit course content Student: Can take a course Authenticated user: Any logged in user has this role Guest: Access permission for non-logged in users An infinite number of custom roles can be generated by using the Moodle GUI and role definition screens. To check and force a login from inside your code, a call to require_login is used. This function allows you to check if the user is logged in, and forces them to log in if this is required by the element that they are trying to access. For example, you can create a specific activity in a course that requires the user to be logged in. If the user is not logged in, then they will be redirected to the correct login function. This function also remembers what the user was accessing, so they can be returned there once they have successfully logged in. Contexts are elements in the system associated with the defined context levels. On the code-side, contexts are defined in /lib/accesslib.php as follows: define('CONTEXT_SYSTEM', 10); define('CONTEXT_USER', 30); define('CONTEXT_COURSECAT', 40); define('CONTEXT_COURSE', 50); define('CONTEXT_GROUP', 60); define('CONTEXT_MODULE', 70); define('CONTEXT_BLOCK', 80); This means every instance of any of these levels is a context. There is only one 'SYSTEM', but there are many of the others, such as users, courses, and modules. Capabilities Capabilities are associated with context levels, and are specific access rules that can be granted to roles. Examples of capabilities are: moodle/site:manageblocks: Can manage blocks at the site context level moodle/user:viewdetails: Can view details of a user at the user context level moodle/course:view: Can view a course at the course context level • • • • • • • •
  • 51.
    Moodle Architecture [ 28] As developers, we can create capabilities to control access to our new functionality. Careful consideration should be given as to which context is the best location for a new capability. Capabilities should generally be placed at the lowest context level at which they can function. We will cover these topics in more detail as we work, in the chapters ahead. Moodle roles Roles are specific identifiers that are associated with all contexts. Roles are primarily used to group capabilities for a context, so that these capabilities can be given to users. Capabilities are assigned to roles in specific contexts, either by default or by specific assignment (overriding). Assigning roles Lastly, users can be assigned to roles in specific contexts. This assignment gives them the accesses defined by the capabilities in that role for that context. So, to summarize: Contexts are specific elements in Moodle Roles are associated with all contexts Capabilities are assigned to roles in a given context Users are assigned roles in a given context It is the role assignment at the context level being checked, and the capability that role has at that context, which determines whether a user can perform the requested action. As you develop code for Moodle, you will need to keep this functionality in mind, so that you can design and build the access control that you want for your functions. • • • •
  • 52.
    Chapter 1 [ 29] Summary In this chapter, you have started the journey towards becoming a proficient Moodle developer, by studying Moodle's overall architecture. You should now be comfortable with the underlying system requirements to run Moodle, and the major elements that make up a Moodle installation. You have also looked into the process to install and upgrade Moodle with some discussion of our development environment. You have also gained some insights into the program execution for Moodle and the key PHP files that serve as entry points to the system. You have also understood the fundamentals of how Moodle stores its configuration. You now know a bit about both the core internal libraries of Moodle and some of the external library dependencies. Finally, you took a look at Moodle's security and access model. In the next chapter, you will learn how to create and modify blocks.
  • 54.
    Creating and ModifyingBlocks Moodle blocks are plugins that load in the right-hand side or left-hand side column of a Moodle site and display information to the user in a rectangular block. Each side column can have zero, one, or multiple blocks loaded. If a column contains no blocks, the column will not be displayed. This allows Moodle to support one, two, or three column page layouts. Examples of built-in Moodle blocks include: HTML content, calendars, menus, and course lists, amongst others. This chapter covers how to create a basic block in Moodle. This is one of the easiest and most popular customizations. Several basic Moodle programming concepts will be introduced that are used throughout the book. Here are some of the new skills that you will develop: Creating a block from scratch Managing language files Working with capabilities Adding instance configuration Adding scheduled actions to a block Reviewing a real world block Using a block as a code container Creating a block from scratch We will start our exploration of block plugins by revisiting a programming classic, Hello World. Our first block will be about as simple a block as possible, simply displaying the text Hello World. Because our block will be called Hello World, let's start by creating a folder in the block folder of our development site called helloworld. Inside of this folder, create an empty PHP file called block_helloworld.php. Note that the pattern is module-type_module-name.php. • • • • • • •
  • 55.
    Other documents randomlyhave different content
  • 56.
    Jefferson to bePresident of the United States?' Why is he compelled to put his vote in the hands of another, and to incur all the hazards of an irresponsible agency, when he himself could immediately give his own vote for his own chosen candidate, without the slightest assistance from agents or managers? But, said Mr. Benton, I have other objections to these intermediate electors. They are the peculiar and favorite institution of aristocratic republics, and elective monarchies. I refer the Senate to the late republics of Venice and Genoa; of France, and her litter; to the kingdom of Poland; the empire of Germany, and the Pontificate of Rome. On the contrary, a direct vote by the people is the peculiar and favorite institution of democratic republics; as we have just seen in the governments of Rome, Athens, Thebes, and Sparta; to which may be added the principal cities of the Amphyctionic and Achaian leagues, and the renowned republic of Carthage when the rival of Rome. I have now answered the objections which were brought forward in the year '87. I ask for no judgment upon their validity at that day, but I affirm them to be without force or reason in the year 1824. Time and experience have so decided. Yes, time and experience, the only infallible tests of good or bad institutions, have now shown that the continuance of the electoral system will be both useless and dangerous to the liberties of the people; and that 'the only effectual mode of preserving our government from the corruptions which have undermined the liberty of so many nations, is, to confide the election of our chief magistrate to those who are farthest removed from the influence of his patronage;'[1] that is to say, to the whole body of American citizens! The electors are not independent; they have no superior intelligence; they are not left to their own judgment in the choice of President; they are not above the control of the people; on the contrary, every elector is pledged, before he is
  • 57.
    chosen, to givehis vote according to the will of those who choose him. He is nothing but an agent, tied down to the execution of a precise trust. Every reason which induced the convention to institute electors has failed. They are no longer of any use, and may be dangerous to the liberties of the people. They are not useful, because they have no power over their own vote, and because the people can vote for a President as easily as they can vote for an elector. They are dangerous to the liberties of the people, because, in the first place, they introduce extraneous considerations into the election of President; and, in the second place, they may sell the vote which is intrusted to their keeping. They introduce extraneous considerations, by bringing their own character and their own exertions into the presidential canvass. Every one sees this. Candidates for electors are now selected, not for the reasons mentioned in the Federalist, but for their devotion to a particular party, for their manners, and their talent at electioneering. The elector may betray the liberties of the people, by selling his vote. The operation is easy, because he votes by ballot; detection is impossible, because he does not sign his vote; the restraint is nothing but his own conscience, for there is no legal punishment for his breach of trust. If a swindler defrauds you out of a few dollars in property or money, he is whipped and pilloried, and rendered infamous in the eye of the law; but, if an elector should defraud 40,000 people of their vote, there is no remedy but to abuse him in the newspapers, where the best men in the country may be abused, as much as Benedict Arnold, or Judas Iscariot. Every reason for instituting electors has failed, and every consideration of prudence requires them to be discontinued. They are nothing but agents, in a case which requires no agent; and no prudent man would, or ought, to employ an agent to take care of his money, his property, or his liberty, when he is equally capable to take care of them himself.
  • 58.
    But, if theplan of the constitution had not failed—if we were now deriving from electors all the advantages expected from their institution—I, for one, said Mr. B., would still be in favor of getting rid of them. I should esteem the incorruptibility of the people, their disinterested desire to get the best man for President, to be more than a counterpoise to all the advantages which might be derived from the superior intelligence of a more enlightened, but smaller, and therefore, more corruptible body. I should be opposed to the intervention of electors, because the double process of electing a man to elect a man, would paralyze the spirit of the people, and destroy the life of the election itself. Doubtless this machinery was introduced into our constitution for the purpose of softening the action of the democratic element; but it also softens the interest of the people in the result of the election itself. It places them at too great a distance from their first servant. It interposes a body of men between the people and the object of their choice, and gives a false direction to the gratitude of the President elected. He feels himself indebted to the electors who collected the votes of the people, and not to the people, who gave their votes to the electors. It enables a few men to govern many, and, in time, it will transfer the whole power of the election into the hands of a few, leaving to the people the humble occupation of confirming what has been done by superior authority. Mr Benton referred to historical examples to prove the correctness of his opinion. He mentioned the constitution of the French Republic, of the year III. of French liberty. The people to choose electors; these to choose the Councils of Five Hundred, and of Ancients; and these, by a further process of filtration, to choose the Five Directors. The effect was, that the people had no concern in the election of their Chief Magistrates, and felt no interest in their fate. They saw them enter and expel each other from the political theatre, with the same indifference with which they would see the entrance and the exit of so many players on the
  • 59.
    stage. It wasthe same thing in all the subaltern Republics of which the French armies were delivered, while overturning the thrones of Europe. The constitutions of the Ligurian, Cisalpine, and Parthenopian Republics, were all duplicates of the mother institution, at Paris; and all shared the same fate. The French consular constitution of the year VIII. (the last year of French liberty) preserved all the vices of the electoral system; and from this fact, alone, that profound observer, Neckar, from the bosom of his retreat, in the midst of the Alps, predicted and proclaimed the death of Liberty in France. He wrote a book to prove that 'Liberty would be ruined by providing any kind of substitute for popular elections:' and the result verified his prediction in four years.
  • 60.
    CHAPTER XVI. INTERNAL TRADEWITH NEW MEXICO. The name of Mexico, the synonyme of gold and silver mines, possessed always an invincible charm for the people of the western States. Guarded from intrusion by Spanish jealousy and despotic power, and imprisonment for life, or labor in the mines, the inexorable penalty for every attempt to penetrate the forbidden country, still the dazzled imaginations and daring spirits of the Great West adventured upon the enterprise; and failure and misfortune, chains and labor, were not sufficient to intimidate others. The journal of (the then lieutenant, afterwards) General Pike inflamed this spirit, and induced new adventurers to hazard the enterprise, only to meet the fate of their predecessors. It was not until the Independence of Mexico, in the year 1821, that the frontiers of this vast and hitherto sealed up country, were thrown open to foreign ingress, and trade and intercourse allowed to take their course. The State of Missouri, from her geographical position, and the adventurous spirit of her inhabitants, was among the first to engage in it; and the Western Internal Provinces—the vast region comprehending New Mexico, El Paso del Norte, New Biscay, Chihuahua, Sonora, Sinaloa, and all the wide slope spreading down towards the Gulf of California, the ancient Sea of Cortez—was the remote theatre of their courageous enterprise—the further off and the less known, so much the more attractive to their daring spirits. It was the work of individual enterprise, without the protection or countenance of the government —without even its knowledge—and exposed to constant danger of life and property from the untamed and predatory savages, Arabs of the New World, which roamed over the intermediate country of a thousand miles, and considered the merchant and his goods their lawful prey. In three years it had grown up to be a new and regular
  • 61.
    branch of interiorcommerce, profitable to those engaged in it, valuable to the country from the articles it carried out, and for the silver, the furs, and the mules which it brought back; and well entitled to the protection and care of the government. That protection was sought, and in the form which the character of the trade required—a right of way through the countries of the tribes between Missouri and New Mexico, a road marked out and security in travelling it, stipulations for good behavior from the Indians, and a consular establishment in the provinces to be traded with. The consuls could be appointed by the order of the government; but the road, the treaty stipulations, and the substantial protection against savages, required the aid of the federal legislative power, and for that purpose a Bill was brought into the Senate by me in the session of 1824-25; and being a novel and strange subject, and asking for extraordinary legislation, it became necessary to lay a foundation of facts, and to furnish a reason and an argument for every thing that was asked. I produced a statement from those engaged in the trade, among others from Mr. Augustus Storrs, late of New Hampshire, then of Missouri—a gentleman of character and intelligence, very capable of relating things as they were, and incapable of relating them otherwise; and who had been personally engaged in the trade. In presenting his statement, and moving to have it printed for the use of the Senate, I said: This gentleman had been one of a caravan of eighty persons, one hundred and fifty-six horses, and twenty-three wagons and carriages, which had made the expedition from Missouri to Santa Fé (of New Mexico), in the months of May and June last. His account was full of interest and novelty. It sounded like romance to hear of caravans of men, horses, and wagons, traversing with their merchandise the vast plain which lies between the Mississippi and the Rio del Norte. The story seemed better adapted to Asia than to North America. But, romantic as it might seem, the reality had already exceeded the visions of the wildest imagination. The journey to New Mexico, but lately deemed a chimerical project, had become an affair of
  • 62.
    ordinary occurrence. SantaFé, but lately the Ultima Thule of American enterprise, was now considered as a stage only in the progress, or rather, a new point of departure to our invincible citizens. Instead of turning back from that point, the caravans broke up there, and the subdivisions branched off in different directions in search of new theatres for their enterprise. Some proceeded down the river to the Paso del Norte; some to the mines of Chihuahua and Durango, in the province of New Biscay; some to Sonora and Sinaloa, on the Gulf of California; and some, seeking new lines of communication with the Pacific, had undertaken to descend the western slope of our continent, through the unexplored regions of the Colorado. The fruit of these enterprises, for the present year, amounted to $190,000 in gold and silver bullion, and coin, and precious furs; a sum considerable, in itself, in the commerce of an infant State, but chiefly deserving a statesman's notice, as an earnest of what might be expected from a regulated and protected trade. The principal article given in exchange, is that of which we have the greatest abundance, and which has the peculiar advantage of making the circuit of the Union before it departs from the territories of the republic—cotton—which grows in the South, is manufactured in the North, and exported from the West. That the trade will be beneficial to the inhabitants of the Internal Provinces, is a proposition too plain to be argued. They are a people among whom all the arts are lost—the ample catalogue of whose wants may be inferred from the lamentable details of Mr. Storrs. No books! no newspapers! iron a dollar a pound! cultivating the earth with wooden tools! and spinning upon a stick! Such is the picture of a people whose fathers wore the proud title of Conquerors; whose ancestors, in the time of Charles the Fifth, were the pride, the terror, and the model of Europe; and such has been the power of civil and religious despotism in accomplishing the degradation of the human species! To a people thus abased, and so lately arrived at the possession of their liberties, a supply of merchandise, upon the
  • 63.
    cheapest terms, isthe least of the benefits to be derived from a commerce with the people of the United States. The consolidation of their republican institutions, the improvement of their moral and social condition, the restoration of their lost arts, and the development of their national resources, are among the grand results which philanthropy anticipates from such a commerce. To the Indians themselves, the opening of a road through their country is an object of vital importance. It is connected with the preservation and improvement of their race. For two hundred years the problem of Indian civilization has been successively presented to each generation of the Americans, and solved by each in the same way. Schools have been set up, colleges founded, and missions established; a wonderful success has attended the commencement of every undertaking; and, after some time, the schools, the colleges, the missions, and the Indians, have all disappeared together. In the south alone have we seen an exception. There the nations have preserved themselves, and have made a cheering progress in the arts of civilization. Their advance is the work of twenty years. It dates its commencement from the opening of roads through their country. Roads induced separate families to settle at the crossing of rivers, to establish themselves at the best springs and tracts of land, and to begin to sell grain and provisions to the travellers, whom, a few years before, they would kill and plunder. This imparted the idea of exclusive property in the soil, and created an attachment for a fixed residence. Gradually, fields were opened, houses built, orchards planted, flocks and herds acquired, and slaves bought. The acquisition of these comforts, relieving the body from the torturing wants of cold and hunger, placed the mind in a condition to pursue its improvement.—This, Mr. President, is the true secret of the happy advance which the southern tribes have made in acquiring the arts of civilization; this has fitted them for the reception of schools and missions; and doubtless, the same
  • 64.
    cause will producethe same effects among the tribes beyond, which it has produced among the tribes on this side of the Mississippi. The right of way is indispensable, and the committee have begun with directing a bill to be reported for that purpose. Happily, there are no constitutional objections to it. State rights are in no danger! The road which is contemplated will trespass upon the soil, or infringe upon the jurisdiction of no State whatsoever. It runs a course and a distance to avoid all that; for it begins upon the outside line of the outside State, and runs directly off towards the setting sun—far away from all the States. The Congress and the Indians are alone to be consulted, and the statute book is full of precedents. Protesting against the necessity of producing precedents for an act in itself pregnant with propriety, I will yet name a few in order to illustrate the policy of the government, and show its readiness to make roads through Indian countries to facilitate the intercourse of its citizens, and even upon foreign territory to promote commerce and national communications. Precedents were then shown. 1, A road from Nashville, Tennessee, through the Chicasaw and Choctaw tribes, to Natchez, 1806; 2, a road through the Creek nations, from Athens, in Georgia, to the 31st degree of north latitude, in the direction to New Orleans, 1806, and continued by act of 1807, with the consent of the Spanish government, through the then Spanish territory of West Florida to New Orleans; 3, three roads through the Cherokee nation, to open an intercourse between Georgia, Tennessee, and the lower Mississippi; and more than twenty others upon the territory of the United States. But the precedent chiefly relied upon was that from Athens through the Creek Indian territory and the Spanish dominions to New Orleans. It was up to the exigency of the occasion in every particular—being both upon Indian territory within our dominions, and upon foreign territory beyond them. The road I wanted fell within the terms of both these qualifications. It was to pass through
  • 65.
    tribes within ourown territory, until it reached the Arkansas River: there it met the foreign boundary established by the treaty of 1819, which gave away, not only Texas, but half the Arkansas besides; and the bill which I brought in provided for continuing the road, with the assent of Mexico, from this boundary to Santa Fé, on the Upper del Norte. I deemed it fair to give additional emphasis to this precedent, by showing that I had it from Mr. Jefferson, and said: For a knowledge of this precedent, I am indebted to a conversation with Mr. Jefferson himself. In a late excursion to Virginia, I availed myself of a broken day to call and pay my respects to that patriarchal statesman. The individual must manage badly, Mr. President, who can find himself in the presence of that great man, and retire from it without bringing off some fact, or some maxim, of eminent utility to the human race. I trust that I did not so manage. I trust that, in bringing off a fact which led to the discovery of the precedent, which is to remove the only serious objection to the road in question, I have done a service, if not to the human family, at least to the citizens of the two greatest Republics in the world. It was on the evening of Christmas day that I called upon Mr. Jefferson. The conversation, among other things, turned upon roads. He spoke of one from Georgia to New Orleans, made during the last term of his own administration. He said there was a manuscript map of it in the library of Congress (formerly his own), bound up in a certain volume of maps, which he described to me. On my return to Washington, I searched the statute book, and I found the acts which authorized the road to be made: they are the same which I have just read to the Senate. I searched the Congress Library, and I found the volume of maps which he had described; and here it is (presenting a huge folio), and there is the map of the road from Georgia to New Orleans, more than two hundred miles of which, marked in blue ink, is traced through the then dominions of the King of Spain!
  • 66.
    The foreign partof the road was the difficulty and was not entirely covered by the precedent. That was a road to our own city, and no other direct territorial way from the Southern States than through the Spanish province of West Florida: this was a road to be, not only on foreign territory, but to go to a foreign country. Some Senators, favorable to the bill, were startled at it, and Mr. Lloyd, of Massachusetts, moved to strike out the part of the section which provided for this ex-territorial national highway; but not in a spirit of hostility to the bill itself providing for protection to a branch of commerce. Mr. Lowrie, of Pennsylvania, could not admit the force of the objection, and held it to be only a modification of what was now done for the protection of commerce—the substitution of land for water; and instanced the sums annually spent in maintaining a fleet in the Mediterranean Sea, and in the most remote oceans for the same purpose. Mr. Van Buren, thought the government was bound to extend the same protection to this branch of trade as to any other; and the road upon the foreign territory was only to be marked out, not made. Mr. Macon thought the question no great matter. Formerly Indian traders followed traces now they must have roads. He did not care for precedents: they are generally good or bad as they suit or cross our purposes. The case of the road made by Mr. Jefferson was different. That road was made among Indians comparatively civilized, and who had some notions of property. But the proposed road now to be marked out would pass through wild tribes who think of nothing but killing and robbing a white man the moment they see him, and would not be restrained by treaty obligations even if they entered into them. Col. Johnson, of Kentucky, had never hesitated to vote the money which was necessary to protect the lives or property of our sea-faring men, or for Atlantic fortifications, or to suppress piracies. We had, at this session voted $500,000 to suppress piracy in the West Indies. We build ships of war, erect light-houses, spend annual millions for the protection of ocean commerce; and he could not suppose that the sum proposed in this bill for the protection of an inland branch of trade so valuable to the West could be denied. Mr. Kelly, of Alabama, said the great object of the bill was to cherish and foster a branch of
  • 67.
    commerce already inexistence. It is carried on by land through several Indian tribes. To be safe, a road must be had—a right of way —a trace, if you please. To answer its purpose, this road, or trace, must pass the boundary of the United States, and extend several hundred miles through the wilderness country, in the Mexican Republic to the settlements with which the traffic must be carried on. It may be well to remember that the Mexican government is in the germ of its existence, struggling with difficulties that we have long since surmounted, and may not feel it convenient to make the road, and that it is enough to permit us to mark it out upon her soil; which is all that this bill proposes to do within her limits. Mr. Smith, of Maryland, would vote for the bill. The only question with him was, whether commerce could be carried on to advantage on the proposed route; and, being satisfied that it could be, he should vote for the bill. Mr. Brown, of Ohio (Ethan A.), was very glad to hear such sentiments from the Senator from Maryland, and hoped that a reciprocal good feeling would always prevail between different sections of the Union. He thought there could be no objection to the bill, and approved the policy of getting the road upon Mexican territory with the consent of the Mexican government. The bill passed the Senate by a large vote—30 to 12; and these are the names of the Senators voting for and against it: Yeas.—Messrs. Barton, Benton, Bouligny, Brown, D'Wolf, Eaton, Edwards, Elliott, Holmes of Miss., Jackson (the General), Johnson of Kentucky, Johnston of Lou., Kelly, Knight, Lanman, Lloyd of Mass., Lowrie, McIlvaine, McLean, Noble, Palmer, Parrott, Ruggles, Seymour, Smith, Talbot, Taylor, Thomas, Van Buren, Van Dyke—30. Nays.—Messrs. Branch, Chandler, Clayton, Cobb, Gaillard, Hayne, Holmes of Maine, King of Ala., King of N. Y., Macon, Tazewell, Williams—12. It passed the House of Representatives by a majority of thirty— received the approving signature of Mr. Monroe, among the last acts of his public life—was carried into effect by his successor, Mr. John Quincy Adams—and this road has remained a thoroughfare of
  • 68.
    commerce between Missouriand New Mexico, and all the western internal provinces ever since.
  • 69.
    CHAPTER XVII. PRESIDENTIAL ANDVICE-PRESIDENTIAL ELECTION IN THE ELECTORAL COLLEGES. Four candidates were before the people for the office of President —General Jackson, Mr. John Quincy Adams, Mr. William H. Crawford, and Mr. Henry Clay. Mr. Crawford had been nominated in a caucus of democratic members of Congress; but being a minority of the members, and the nomination not in accordance with public opinion, it carried no authority along with it, and was of no service to the object of its choice. General Jackson was the candidate of the people, brought forward by the masses. Mr. Adams and Mr. Clay were brought forward by bodies of their friends in different States. The whole number of electoral votes was 261 of which it required 131 to make an election. No one had that number. General Jackson was the highest on the list, and had 99 votes; Mr. Adams 84; Mr. Crawford 41; Mr. Clay 37. No one having a majority of the whole of electors, the election devolved upon the House of Representatives; of which an account will be given in a separate chapter. In the vice-presidential election it was different. Mr. John C. Calhoun (who in the beginning of the canvass had been a candidate for the Presidency, but had been withdrawn by his friends in Pennsylvania, and put forward for Vice-President), received 182 votes in the electoral college, and was elected. Mr. Nathan Sandford, Senator in Congress from New-York, had been placed on the ticket with Mr. Clay, and received 30 votes. The 24 votes of Virginia were given to Mr. Macon, as a compliment, he not being a candidate, and having refused to become one. The nine votes of Georgia were given to Mr. Van Buren, also as a compliment, he not being on the list of candidates. Mr. Albert Gallatin had been nominated in the Congress
  • 70.
    caucus with Mr.Crawford, but finding the proceedings of that caucus unacceptable to the people he had withdrawn from the canvass. Mr. Calhoun was the only substantive vice-presidential candidate before the people, and his election was an evidence of good feeling in the North towards southern men—he receiving the main part of his votes from that quarter—114 votes from the non-slaveholding States, and only 68 from the slaveholding. A southern man, and a slaveholder, Mr. Calhoun was indebted to northern men and non- slaveholders, for the honorable distinction of an election in the electoral colleges—the only one in the electoral colleges—the only one on all the lists of presidential and vice-presidential candidates who had that honor. Surely there was no disposition in the free States at that time to be unjust, or unkind to the South.
  • 71.
    CHAPTER XVIII. DEATH OFJOHN TAYLOR, OF CAROLINE. For by that designation was discriminated, in his own State, the eminent republican statesman of Virginia, who was a Senator in Congress in the first term of General Washington's administration, and in the last term of Mr. Monroe—and who, having voluntarily withdrawn himself from that high station during the intermediate thirty years, devoted himself to the noble pursuits of agriculture, literature, the study of political economy, and the service of his State or county when called by his fellow-citizens. Personally I knew him but slightly, our meeting in the Senate being our first acquaintance, and our senatorial association limited to the single session of which he was a member—1823-24;—at the end of which he died. But all my observation of him, and his whole appearance and deportment, went to confirm the reputation of his individuality of character, and high qualities of the head and the heart. I can hardly figure to myself the ideal of a republican statesman more perfect and complete than he was in reality:—plain and solid, a wise counsellor, a ready and vigorous debater, acute and comprehensive, ripe in all historical and political knowledge, innately republican—modest, courteous, benevolent, hospitable—a skilful, practical farmer, giving his time to his farm and his books, when not called by an emergency to the public service—and returning to his books and his farm when the emergency was over. His whole character was announced in his looks and deportment, and in his uniform (senatorial) dress—the coat, waistcoat, and pantaloons of the same London brown, and in the cut of a former fashion—beaver hat with ample brim—fine white linen—and a gold-headed cane, carried not for show, but for use and support when walking and bending under the heaviness of years. He seemed to have been cast in the same mould with Mr. Macon, and it
  • 72.
    was pleasant tosee them together, looking like two Grecian sages, and showing that regard for each other which every one felt for them both. He belonged to that constellation of great men which shone so brightly in Virginia in his day, and the light of which was not limited to Virginia, or our America, but spread through the bounds of the civilized world. He was the author of several works, political and agricultural, of which his Arator in one class, and his Construction Construed in another, were the principal—one adorning and exalting the plough with the attributes of science; the other exploring the confines of the federal and the State governments, and presenting a mine of constitutional law very profitably to be examined by the political student who will not be repulsed from a banquet of rich ideas, by the quaint Sir Edward Coke style—(the only point of resemblance between the republican statesman, and the crown officer of Elizabeth and James)—in which it is dressed. Devotion to State rights was the ruling feature of his policy; and to keep both governments, State and federal, within their respective constitutional orbits, was the labor of his political life. In the years 1798 and '99, Mr. Taylor was a member of the General Assembly of his State, called into service by the circumstances of the times; and was selected on account of the dignity and gravity of his character, his power and readiness in debate, and his signal devotion to the rights of the States, to bring forward those celebrated resolutions which Mr. Jefferson conceived, which his friends sanctioned, which Mr. Madison drew up, and which John Taylor, of Caroline, presented;—which are a perfect exposition of the principles of our duplicate form of government, and of the limitations upon the power of the federal government;—and which, in their declaration of the unconstitutionality of the alien and sedition laws, and appeal to other States for their co-operation, had nothing in view but to initiate a State movement by two-thirds of the States (the number required by the fifth article of the federal constitution), to amend, or authoritatively expound the constitution; —the idea of forcible resistance to the execution of any act of Congress being expressly disclaimed at the time.
  • 74.
    CHAPTER XIX. PRESIDENTIAL ELECTIONIN THE HOUSE OF REPRESENTATIVES. It has already been shown that the theory of the constitution, and its practical working, was entirely different in the election of President and Vice-President—that by the theory, the people were only to choose electors, to whose superior intelligence the choice of fit persons for these high stations was entirely committed—and that, in practice, this theory had entirely failed from the beginning. From the very first election the electors were made subordinate to the people, having no choice of their own, and pledged to deliver their votes for a particular person, according to the will of those who elected them. Thus the theory had failed in its application to the electoral college; but there might be a second or contingent election, and has been; and here the theory of the constitution has failed again. In the event of no choice being made by the electors, either for want of a majority of electoral votes being given to any one, or on account of an equal majority for two, the House of Representatives became an electoral college for the occasion, limited to a choice out of the five highest (before the constitution was amended), or the two highest having an equal majority. The President and Vice-President were not then voted for separately, or with any designation of their office. All appeared upon the record as presidential nominees—the highest on the list having a majority, to be President; the next highest, also having a majority, to be Vice- President; but the people, from the beginning, had discriminated between the persons for these respective places, always meaning one on their ticket for President, the other for Vice-President. But, by the theory of the constitution and its words, those intended Vice-
  • 75.
    Presidents might beelected President in the House of Representatives, either by being among the five highest when there was no majority, or being one of two in an equal majority. This theory failed in the House of Representatives from the first election, the demos krateo principle—the people to govern—prevailing there as in the electoral colleges, and overruling the constitutional design in each. The first election in the House of Representatives was that of Mr. Jefferson and Mr. Burr, in the session of 1800-1801. These gentlemen had each a majority of the whole number of electoral votes, and an equal majority—73 each—Mr. Burr being intended for Vice-President. One of the contingencies had then occurred in which the election went to the House of Representatives. The federalists had acted more wisely, one of their State electoral colleges (that of Rhode Island), having withheld a vote from the intended Vice- President on their side, Mr. Charles Colesworth Pinckney, of South Carolina; and so prevented an equality of votes between him and Mr. John Adams. It would have been entirely constitutional in the House of Representatives to have elected Mr. Burr President, but at the same time, a gross violation of the democratic principle, which requires the will of the majority to be complied with. The federal States undertook to elect Mr. Burr, and kept up the struggle for seven days and nights, and until the thirty-sixth ballot. There were sixteen States, and it required the concurrence of nine to effect an election. Until the thirty-sixth Mr. Jefferson had eight, Mr. Burr six, and two were divided. On the thirty-sixth ballot Mr. Jefferson had ten States and was elected. General Hamilton, though not then in public life, took a decided part in this election, rising above all personal and all party considerations, and urging the federalists from the beginning to vote for Mr. Jefferson. Thus the democratic principle prevailed. The choice of the people was elected by the House of Representatives; and the struggle was fatal to those who had opposed that principle. The federal party was broken down, and at the ensuing Congress elections, was left in a small minority. Its candidate at the ensuing presidential election received but fourteen
  • 76.
    votes out ofone hundred and seventy-six. Burr, in whose favor, and with whose connivance the struggle had been made, was ruined— fell under the ban of the republican party, disappeared from public life, and was only seen afterwards in criminal enterprises, and ending his life in want and misery. The constitution itself, in that particular (the mode of election), was broken down, and had to be amended so as to separate the presidential from the vice- presidential ticket, giving each a separate vote; and in the event of no election by the electoral colleges, sending each to separate houses—the three highest on the presidential lists to the House of Representatives,—the two highest on the vice-presidential, to the Senate. And thus ended the first struggle in the House of Representatives (in relation to the election of President), between the theory of the constitution and the democratic principle—triumph to the principle, ruin to its opposers, and destruction to the clause in the constitution, which permitted such a struggle. The second presidential election in the House of Representatives was after the lapse of a quarter of a century, and under the amended constitution, which carried the three highest on the list to the House when no one had a majority of the electoral votes. General Jackson, Mr. John Quincy Adams, and Mr. William H. Crawford, were the three, their respective votes being 99, 84, 41; and in this case a second struggle took place between the theory of the constitution and the democratic principle; and with eventual defeat to the opposers of that principle, though temporarily successful. Mr. Adams was elected, though General Jackson was the choice of the people, having received the greatest number of votes, and being undoubtedly the second choice of several States whose votes had been given to Mr. Crawford and Mr. Clay (at the general election). The representatives from some of these States gave the vote of the State to Mr. Adams, upon the argument that he was best qualified for the station, and that it was dangerous to our institutions to elect a military chieftain—an argument which assumed a guardianship over the people, and implied the necessity of a superior intelligence to guide them for their own good. The election of Mr.
  • 77.
    Adams was perfectlyconstitutional, and as such fully submitted to by the people; but it was also a violation of the demos krateo principle; and that violation was signally rebuked. All the representatives who voted against the will of their constituents, lost their favor, and disappeared from public life. The representation in the House of Representatives was largely changed at the first general election, and presented a full opposition to the new President. Mr. Adams himself was injured by it, and at the ensuing presidential election was beaten by General Jackson more than two to one—178 to 83. Mr. Clay, who took the lead in the House for Mr. Adams, and afterwards took upon himself the mission of reconciling the people to his election in a series of public speeches, was himself crippled in the effort, lost his place in the democratic party, joined the whigs (then called national republicans), and has since presented the disheartening spectacle of a former great leader figuring at the head of his ancient foes in all their defeats, and lingering on their rear in their victories. The democratic principle was again victor over the theory of the constitution, and great and good were the results that ensued. It vindicated the demos in their right and their power, and showed that the prefix to the constitution, We, the people, do ordain and establish, c., may also be added to its administration, showing them to be as able to administer as to make that instrument. It re-established parties upon the basis of principle, and drew anew party lines, then almost obliterated under the fusion of parties during the era of good feeling, and the efforts of leading men to make personal parties for themselves. It showed the conservative power of our government to lie in the people, more than in its constituted authorities. It showed that they were capable of exercising the function of self-government. It assured the supremacy of the democracy for a long time, and until temporarily lost by causes to be shown in their proper place. Finally, it was a caution to all public men against future attempts to govern presidential elections in the House of Representatives. It is no part of the object of this Thirty Years' View to dwell upon the conduct of individuals, except as showing the causes and the
  • 78.
    consequences of events;and, under this aspect, it becomes the gravity of history to tell that, in these two struggles for the election of President, those who struggled against the democratic principle lost their places on the political theatre,—the mere voting members being put down in their States and districts, and the eminent actors for ever ostracised from the high object of their ambition. A subordinate cause may have had its effect, and unjustly, in prejudicing the public mind against Mr. Adams and Mr. Clay. They had been political adversaries, had co-operated in the election, and went into the administration together. Mr. Clay received the office of Secretary of State from Mr. Adams, and this gave rise to the imputation of a bargain between them. It came within my knowledge (for I was then intimate with Mr. Clay), long before the election, and probably before Mr. Adams knew it himself, that Mr. Clay intended to support him against General Jackson; and for the reasons afterward averred in his public speeches. I made this known when occasions required me to speak of it, and in the presence of the friends of the impugned parties. It went into the newspapers upon the information of these friends, and Mr. Clay made me acknowledgments for it in a letter, of which this is the exact copy: I have received a paper published on the 20th ultimo, at Lemington, in Virginia, in which is contained an article stating that you had, to a gentleman of that place, expressed your disbelief of a charge injurious to me, touching the late presidential election, and that I had communicated to you unequivocally, before the 15th of December, 1824, my determination to vote for Mr. Adams and not for General Jackson. Presuming that the publication was with your authority, I cannot deny the expression of proper acknowledgments for the sense of justice which has prompted you to render this voluntary and faithful testimony. This letter, of which I now have the original, was dated at Washington City, December 6th, 1827—that is to say, in the very heat and middle of the canvass in which Mr. Adams was beaten by
  • 79.
    General Jackson, andwhen the testimony could be of most service to him. It went the rounds of the papers, and was quoted and relied upon in debates in Congress, greatly to the dissatisfaction of many of my own party. There was no mistake in the date, or the fact. I left Washington the 15th of December, on a visit to my father-in-law, Colonel James McDowell, of Rockbridge county, Virginia, where Mrs. Benton then was; and it was before I left Washington that I learned from Mr. Clay himself that his intention was to support Mr. Adams. I told this at that time to Colonel McDowell, and any friends that chanced to be present, and gave it to the public in a letter which was copied into many newspapers, and is preserved in Niles' Register. I told it as my belief to Mr. Jefferson on Christmas evening of the same year, when returning to Washington and making a call on that illustrious man at his seat, Monticello; and believing then that Mr. Adams would be elected, and, from the necessity of the case, would have to make up a mixed cabinet, I expressed that belief to Mr. Jefferson, using the term, familiar in English history, of broad bottomed; and asked him how it would do? He answered, Not at all—would never succeed—would ruin all engaged in it. Mr. Clay told his intentions to others of his friends from an early period, but as they remained his friends, their testimony was but little heeded. Even my own, in the violence of party, and from my relationship to Mrs. Clay, seemed to have but little effect. The imputation of bargain stuck, and doubtless had an influence in the election. In fact, the circumstances of the whole affair—previous antagonism between the parties, actual support in the election, and acceptance of high office, made up a case against Messrs. Adams and Clay which it was hardly safe for public men to create and to brave, however strong in their own consciousness of integrity. Still, the great objection to the election of Mr. Adams was in the violation of the principle demos krateo; and in the question which it raised of the capacity of the demos to choose a safe President for themselves. A letter which I wrote to the representative from Missouri, before he gave the vote of the State to Mr. Adams, and which was published immediately afterwards, placed the objection upon this high ground; and upon it the battle was mainly fought, and won. It was a victory
  • 80.
    of principle, andshould not be disparaged by the admission of an unfounded and subordinate cause. This presidential election of 1824 is remarkable under another aspect—as having put an end to the practice of caucus nominations for the Presidency by members of Congress. This mode of concentrating public opinion began to be practised as the eminent men of the Revolution, to whom public opinion awarded a preference, were passing away, and when new men, of more equal pretensions, were coming upon the stage. It was tried several times with success and general approbation, public sentiment having been followed, and not led, by the caucus. It was attempted in 1824, and failed, the friends of Mr. Crawford only attending—others not attending, not from any repugnance to the practice, as their previous conduct had shown, but because it was known that Mr. Crawford had the largest number of friends in Congress, and would assuredly receive the nomination. All the rest, therefore, refused to go into it: all joined in opposing the caucus candidate, as Mr. Crawford was called; all united in painting the intrigue and corruption of these caucus nominations, and the anomaly of members of Congress joining in them. By their joint efforts they succeeded, and justly in the fact though not in the motive, in rendering these Congress caucus nominations odious to the people, and broke them down. They were dropped, and a different mode of concentrating public opinion was adopted—that of party nominations by conventions of delegates from the States. This worked well at first, the will of the people being strictly obeyed by the delegates, and the majority making the nomination. But it quickly degenerated, and became obnoxious to all the objections to Congress caucus nominations, and many others besides. Members of Congress still attended them, either as delegates or as lobby managers. Persons attended as delegates who had no constituency. Delegates attended upon equivocal appointments. Double sets of delegates sometimes came from the State, and either were admitted or repulsed, as suited the views of the majority. Proxies were invented. Many delegates attended with the sole view of establishing a claim for
  • 81.
    office, and votedaccordingly. The two-thirds rule was invented, to enable the minority to control the majority; and the whole proceeding became anomalous and irresponsible, and subversive of the will of the people, leaving them no more control over the nomination than the subjects of kings have over the birth of the child which is born to rule over them. King Caucus is as potent as any other king in this respect; for whoever gets the nomination—no matter how effected—becomes the candidate of the party, from the necessity of union against the opposite party, and from the indisposition of the great States to go into the House of Representatives to be balanced by the small ones. This is the mode of making Presidents, practised by both parties now. It is the virtual election! and thus the election of the President and Vice-President of the United States has passed—not only from the college of electors to which the constitution confided it, and from the people to whom the practice under the constitution gave it, and from the House of Representatives which the constitution provided as ultimate arbiter— but has gone to an anomalous, irresponsible body, unknown to law or constitution, unknown to the early ages of our government, and of which a large proportion of the members composing it, and a much larger proportion of interlopers attending it, have no other view either in attending or in promoting the nomination of any particular man, than to get one elected who will enable them to eat out of the public crib—who will give them a key to the public crib. The evil is destructive to the rights and sovereignty of the people, and to the purity of elections. The remedy is in the application of the democratic principle—the people to vote direct for President and Vice-President; and a second election to be held immediately between the two highest, if no one has a majority of the whole number on the first trial. But this would require an amendment of the constitution, not to be effected but by a concurrence of two thirds of each house of Congress, and the sanction of three fourths of the States—a consummation to which the strength of the people has not yet been equal, but of which there is no reason to despair. The great parliamentary reform in Great Britain was only carried
  • 82.
    after forty yearsof continued, annual, persevering exertion. Our constitutional reform, in this point of the presidential election, may require but a few years; in the meanwhile I am for the people to select, as well as elect, their candidates, and for a reference to the House to choose one out of three presented by the people, instead of a caucus nomination of whom it pleased. The House of Representatives is no longer the small and dangerous electoral college that it once was. Instead of thirteen States we now have thirty-one; instead of sixty-five representatives, we have now above two hundred. Responsibility in the House is now well established, and political ruin, and personal humiliation, attend the violation of the will of the State. No man could be elected now, or endeavor to be elected (after the experience of 1800 and 1824), who is not at the head of the list, and the choice of a majority of the Union. The lesson of those times would deter imitation, and the democratic principle would again crush all that were instrumental in thwarting the public will. There is no longer the former danger from the House of Representatives, nor any thing in it to justify a previous resort to such assemblages as our national conventions have got to be. The House is legal and responsible, which the convention is not, with a better chance for integrity, as having been actually elected by the people; and more restrained by position, by public opinion, and a clause in the constitution from the acceptance of office from the man they elect. It is the constitutional umpire; and until the constitution is amended, I am for acting upon it as it is.
  • 83.
    CHAPTER XX. THE OCCUPATIONOF THE COLUMBIA. This subject had begun to make a lodgment in the public mind, and I brought a bill into the Senate to enable the President to possess and retain the country. The joint occupation treaty of 1818 was drawing to a close, and it was my policy to terminate such occupation, and hold the Columbia (or Oregon) exclusively, as we had the admitted right to do while the question of title was depending. The British had no title, and were simply working for a division—for the right bank of the river, and the harbor at its mouth —and waiting on time to ripen their joint occupation into a claim for half. I knew this, and wished to terminate a joint tenancy which could only be injurious to ourselves while it lasted, and jeopard our rights when it terminated. The bill which I brought in proposed an appropriation to enable the President to act efficiently, with a detatchment of the army and navy; and in the discussion of this bill the whole question of title and of policy came up; and, in a reply to Mr. Dickerson, of New Jersey, I found it to be my duty to defend both. I now give some extracts from that reply, as a careful examination of the British pretension, founded upon her own exhibition of title, and showing that she had none south of forty-nine degrees, and that we were only giving her a claim, by putting her possession on an equality with our own. These extracts will show the history of the case as it then stood—as it remained invalidated in all subsequent discussion—and according to which, and after twenty years, and when the question had assumed a war aspect, it was finally settled. The bill did not pass, but received an encouraging vote—fourteen senators voting favorably to it. They were:
  • 84.
    Messrs. Barbour, Benton,Bouligny, Cobb, Hayne, Jackson (the General), Johnson of Kentucky, Johnston of Louisiana, Lloyd of Massachusetts, Mills, Noble, Ruggles, Talbot, Thomas. Mr. Benton, in reply to Mr. Dickerson, said that he had not intended to speak to this bill. Always unwilling to trespass upon the time and patience of the Senate, he was particularly so at this moment, when the session was drawing to a close, and a hundred bills upon the table were each demanding attention. The occupation of the Columbia River was a subject which had engaged the deliberations of Congress for four years past, and the minds of gentlemen might be supposed to be made up upon it. Resting upon this belief, Mr. B., as reporter of the bill, had limited himself to the duty of watching its progress, and of holding himself in readiness to answer any inquiries which might be put. Inquiries he certainly expected; but a general assault, at this late stage of the session, upon the principle, the policy, and the details of the bill, had not been anticipated. Such an assault had, however, been made by the senator from New Jersey (Mr. D.), and Mr. B. would be unfaithful to his duty if he did not repel it. In discharging this duty, he would lose no time in going over the gentleman's calculations about the expense of getting a member of Congress from the Oregon to the Potomac; nor would he solve his difficulties about the shortest and best route —whether Cape Horn should be doubled, a new route explored under the north pole, or mountains climbed, whose aspiring summits present twelve feet of defying snow to the burning rays of a July sun. Mr. B. looked upon these calculations and problems as so many dashes of the gentleman's wit, and admitted that wit was an excellent article in debate, equally convenient for embellishing an argument, and concealing the want of one. For which of these purposes the senator from New Jersey had amused the Senate with the wit in question, it was not for Mr. B. to say, nor should he undertake to disturb him in the quiet enjoyment of the honor which he had won thereby, and would proceed directly to speak to the merits of the bill.
  • 85.
    Welcome to ourwebsite – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com