Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Server-Side Web Development

404 Articles
article-image-moodle-cims-installing-and-using-bulk-course-upload-tool
Packt
07 Jan 2011
7 min read
Save for later

Moodle CIMS: Installing and Using the Bulk Course Upload Tool

Packt
07 Jan 2011
7 min read
Moodle as a Curriculum and Information Management System Use Moodle to manage and organize your administrative duties; monitor attendance records, manage student enrolment, record exam results, and much more Transform your Moodle site into a system that will allow you to manage information such as monitoring attendance records, managing the number of students enrolled in a particular course, and inter-department communication Create courses for all subjects in no time with the Bulk Course Creation tool Create accounts for hundreds of users swiftly and enroll them in courses at the same time using a CSV file. Part of Packt's Beginner's Guide series: Readers are walked through each task as they read the book with the end result being a sample CIMS Moodle site Using the Bulk Course Upload tool Rather than creating course categories and then courses one at a time and assigning teachers to each course after the course is created, we can streamline the process through the use of the Bulk Course Upload tool. This tool allows you to organize all the information required to create your courses in a CSV (Comma Separated Values) file that is then uploaded into the creation tool and used to create all of your courses at once. Due to its design, the Bulk Course Upload tool only works with MySQL databases. Our MAMP package uses a MySQL database as do the LAMP packages. If your Moodle site is running on a database of a different variety you will not be able to use this tool. Time for action – installing the Bulk Course Upload tool Now that we have our teacher's accounts created, we are ready to use the Bulk Course Creation tool to create all of our courses. First we need to install the tool as an add-on admin report into our Moodle site. To install this tool, do the following: Go to the Modules and plugins area of www.moodle.org. Search for Bulk Course Upload tool. Click on Download latest version to download the tool to your computer. If this does not download the package to your hard drive and instead takes you to a forum in the Using Moodle course on Moodle.org, download the package that was posted in that forum on Sunday, 11 May 2008. Expand the package, contained within, and find the uploadcourse.php file. Place the uploadcourse.php file in your admin directory located inside your main Moodle directory. When logged in as admin, enter the following address in your browser address bar: http://localhost:8888/moodle19/admin/uploadcourse.php. (If you are not using a MAMP package, the first part of the address will of course be different.) You will then see the Upload Course tool explanation screen that looks like the following screenshot: The screen, shown in the previous screenshot, lists the thirty-nine different fields that can be included in a CSV file when creating courses in bulk via this tool. Most of the fields here control settings that are modified in individual courses by clicking on the Settings link found in the Administration block of each course. The following is an explanation of the fields with notes about which ones are especially useful when setting up Moodle as a CIMS: category: You will definitely want to specify categories in order to organize your courses. The best way to organize courses and categories here is such that the organization coincides with the organization of your curriculum as displayed in school documentation and student handbooks. If you already have categories in your Moodle site, make sure that you spell the categories exactly as they appear on your site, including capitalization. A mistake will result in the creation of a new category. This field should start with a forward slash followed by the category name with each subcategory also being followed by a forward slash (for example, /Listening/Advanced). cost: If students must pay to enroll in your courses, via the PayPal plugin, you may enter the cost here. You must have the PayPal plugin activated on your site, which can be done by accessing it via the Site Administration block by clicking on Courses and then Enrolments. Additionally, as this book goes to print, the ability to enter a field in the file used by the Bulk Course tool that allows you to set the enrolment plugin, is not yet available. Therefore, if you enter a cost value for a course, it will not be shown until the enrolment plugin for the course is changed manually by navigating to the course and editing the course through the Settings link found in the course Administration block. Check Moodle.org frequently for updates to the Bulk Course Upload tool as the feature should be added soon. enrolperiod: This controls the amount of time a student is enrolled in a course. The value must be entered in seconds so, for example, if you had a course that ran for one month and students were to be unenrolled after that period, you would set this value to 2,592,000 (60 seconds X 60 minutes per hour X 24 hours per day X 30 = 2,592,000). enrollable: This simply controls whether the course is enrollable or not. Entering a 0 will render the course unenrollable and a 1 will set the course to allow enrollments. enrolstartdate and enrolenddate: If you wish to set an enrollment period, you should enter the dates (start and end dates) in these two fields. The dates can be entered in the month/day/year format (for example, 8/1/10). expirynotify: Enter a 1 here to have e-mails sent to the teacher when a student is going to be unenrolled from a course. Enter a 0 to prevent e-mails from being sent when a student is going to be unenrolled. This setting is only functional when the enrolperiod value is set. expirythreshold: Enter the number of days in advance you want e-mails notifying of student unenrollment sent. The explanation file included calls for a value between 10 and 30 days but this value can actually be set to between 1 and 30 days. This setting is only functional when the enrolperiod value and expirynotify and/or notifystudents (see below) is/are set. format: This field controls the format of the course. As of Moodle 1.9.8+ there are six format options included in the standard package. The options are lams, scorm, social, topics, weeks, and weeks CSS, and any of these values can be entered in this field. fullname: This is the full name of the course you are creating (for example, History 101). groupmode: Set this to 0 for no groups, 1 for separate groups, and 2 for visible groups. groupmodeforce: Set this to 1 to force group mode at the course level and 0 to allow group mode to be set in each individual activity. guest: Use a 0 to prevent guests from accessing this course, a 1 to allow uests in the course, and a 2 to allow only guests who have the key into the course. idnumber: You can enter a course ID number using this field. This number is only used for administrative purposes and is not visible to students. This is a very useful field for institutions that use identification numbers for courses and can provide a link for connecting the courses within Moodle to other systems. If your institution uses any such numbering system it is recommended that you enter the appropriate numbers here. lang: This is the language setting for the course. Leaving this field blank will result in the Do not force language setting, which can be seen from the Settings menu accessed from within each individual course. Doing so will allow users to toggle between languages that have been installed in the site. To specify a language, and thus force the display of the course using this language, enter the language as it is displayed within the Moodle lang directory (for example, English = en_utf8). maxbytes: This field allows you to set the maximum size of individual files that are uploaded to the course. Leaving this blank will result in the course being created with the site wide maximum file upload size setting. Values must be entered in bytes (for example, 1 MB = 1,048,576 bytes). Refer to an online conversion site such as www.onlineconversion.com to help you determine the value you want to enter here. metacourse: If the course you are creating is a meta course, enter a 1, otherwise enter a 0 or leave the field blank.
Read more
  • 0
  • 0
  • 2439

article-image-moodle-19-testing-and-assessment-advanced-options-quiz
Packt
23 Dec 2010
7 min read
Save for later

Moodle 1.9 Testing and Assessment: Advanced Options in Quiz

Packt
23 Dec 2010
7 min read
  Moodle 1.9 Testing and Assessment Develop and evaluate quizzes and tests using Moodle modules Create and evaluate interesting and interactive tests using a variety of Moodle modules Create simple vocabulary or flash card tests and complex tests by setting up a Lesson module Motivate your students to excel through feedback and by keeping their grades online A well-structured practical guide packed with illustrative examples and screenshots           Read more about this book       (For more resources on Moodle 1.9, see here.) Adding images to multiple-choice questions You are not going to always want simple text-based questions or answers. One common type of question that instructors frequently use is the image-based question. This item incorporates an image into the question. These questions are easy to create and can offer new dimensions for questions, as well as make the questions and test much more interesting to students. You can add images to any question or any field that allows you to use the rich-text editor, but we are going to use a single-answer, multiple choice question. We will follow the same basic steps as before. Step 1 We need to create a new multiple-choice question. When we are editing the question, we need to add the question name. We then need to add the question text. The question text we will be using for ours will be Which holiday is this girl celebrating? Step 2 We now go to the toolbar and click on the Insert Image icon. It is the icon that looks like a framed picture of a mountain, located two places to the left of the smiley face icon. Once we click on this icon, a pop-up menu will appear, as shown in the next screenshot: Here we have a few options in regards to how to use images and how they will be displayed in the question. Image URL & Alternate text If we use this option, we are able to take images directly from the Internet and use them for our tests. To use it we first need to have the address where the image is found. We are not looking for the address of the site here, but just the image. If you simply link to the web page, it will not work. To get just the image address, click on the image and you should get a menu with one of the options being View Image. Select View Image and you will be taken to a different page with only that image. This is the address you want to use. Once you have the image address, you copy and paste it to the Image URL text area.With the image address entered, we need to give the image a title in the Alternate text area. You can use anything you'd like here, but I tend to use the image name itself if it describes the image. If not, I create a short descriptive text of the image, something like "Girl celebrating Halloween". After you have entered text in both the Image URL and the Alternate text, click on the OK button and the image will be added to your question. It is important to note that if the website you pulled the image from removes it or changes its location, it will not be available for the question. It is therefore advisable to download the image, so that it will always be available to you. When you have finished adding responses and saving the question, you will see something like the following screenshot: Source: Image: Tina Phillips / FreeDigitalPhotos.net Now, looking back at the options available in the Insert image pop-up, you see three formatting options directly under the Image URL and Alternate text box where we were just working. They are called: Layout, Spacing, and Size. Layout In this fieldset, we are given ways to alter the Alignment and the Border thickness. Note that the image may be displayed differently on different browsers, although the CSS of the theme you are using will usually provide the appropriate margins and padding Alignment There are several options available here that show how the text and the image will be displayed. The full list is shown in the next screenshot: Most of these options are self-explanatory: Left will place the image to the left of the text, Right will place the image to the right of the text, and so on. However, there are a few possibly new terms. Texttop, Baseline, and Absbottom are HTML terms that many people might be unsure of. Texttop simply means that the very top of the tallest text (for example, l, b) will be aligned with the top of the image. This function works same as Top with some browsers. Baseline means that the imaginary line that all letters sit on will be aligned with the bottom of the image. In most browsers today, this functions the same as Bottom. Absbottom means that the letters that go below the baseline are aligned with the bottom of the image (for example, g, j). The top option, Not Set will place the image wherever the cursor is, without any special guide as to how it should be displayed. Border thickness The image you put into the question should look identical to the image you chose to use. If you are placing this image inside of text, or the edges are indistinct, or you simply want to frame it, use Border Thickness By placing a number in the Border thickness box, we will create a black border around the image. A small number will give a narrow border and a bigger number will give a thicker one. Here are three images showing the difference in borders. The first is set with a border of 0, the second has a border of 5, and the third with 10. You will notice that the image size itself is the same, but the border causes the viewable area of the image to compress Source: Images courtesy of: freeimages.co.uk Spacing There are two spacing options available, Horizontal and Vertical. The larger the number entered, the more space there is between the text and the images. Horizontal This setting allows you to set the horizontal distance between the image and the text surrounding it. This option can be useful if you need to have the image set apart from the text in the question or explanation. Vertical This setting is like the horizontal setting. It allows you to set the vertical distance between text and the image. This option can be useful if you need to have set distances between the text or have multiple images in a list with text surrounding them. Size The two options here are Width and Height. These two settings allow you to alter the size of the image; smaller numbers will make the image smaller and probably easier to work with. Note that the actual images are not resized. For the best result, first resize the images on your computer to the size you want them to be. Width This setting allows you to alter the width of the image. Altering this setting without altering the height will produce narrow or wide images, depending on whether you adjust the value up or down. Height This setting allows you to alter the height of the image. This option functions just like Width, and will allow you to produce images that are vertically stretched or shrunk. File Browser In this space, you will see any images that have been uploaded to the course. As you can see in the previous screenshot, it is empty, which tells us that there aren't pictures available in the course yet. If you look below File Browser, you will see four options for images uploaded to the course. You can Delete, Move, Zip, or Rename any images that have already been uploaded into the course. Preview This is where you can view any images that have been added to the course. This feature can be useful if you have a lot of images and tend to forget which images are which.
Read more
  • 0
  • 0
  • 981

article-image-moodle-19-testing-and-assessment-multiple-choice-quizzes
Packt
22 Dec 2010
7 min read
Save for later

Moodle 1.9 Testing and Assessment: Multiple Choice Quizzes

Packt
22 Dec 2010
7 min read
  Moodle 1.9 Testing and Assessment Develop and evaluate quizzes and tests using Moodle modules Create and evaluate interesting and interactive tests using a variety of Moodle modules Create simple vocabulary or flash card tests and complex tests by setting up a Lesson module Motivate your students to excel through feedback and by keeping their grades online A well-structured practical guide packed with illustrative examples and screenshots        Getting started We need to get to the Question bank and Question Editing pages. One quick way to do this is through the Course Admin Menu. There is a link titled Questions, which will bring you to the correct place. The first thing we need to do is name the quiz. We are going to call this one Multiple Choice Quiz. For the introduction, we are just going to write the purpose of this quiz to teach you a few things about this item type. Once we click on the Save and Display button, we will see the Question bank. Notice the questions from the True/False quiz? They are there because the category they are associated with is Course. If I want to get rid of them so that they don't interfere with anything new I am doing, I have a few options. Categories and contexts There are four default categories: System, Miscellaneous, Course, and Activity. The categories act like folders or directories, allowing the questions to be accessed at different levels or hierarchies. They are set up in what are known as contexts. Each context has its own question hierarchies, with the highest context being the Core System, moving down to Course Category, Course, and Activity. What this means is that you can select the context in which you can share your questions. By selecting the System option from the menu, any questions that have been created at this level will be available in all courses and for any quiz you have created on the site. Miscellaneous/Course Category The next level below System to store questions is Miscellaneous, like the Course Category. This category is where all the courses you are enrolled in are found. The questions placed in this context are available to all courses and activities in the Course Category. Course This is where questions directly related to the course the quiz is being made for are stored. Course is the default, and most Moodle users find this is a good place for their questions. Placing the items here allows you to create items specific to the course, based on exactly what was covered. It will also only use the questions developed in the course to draw on for random questions. You can also make a subcategory for questions you'd like to draw from. As long as questions are in one category, they can end up in a quiz that randomly draws questions from that category. Creating subcategories for different units in the course makes it easy to keep track of exactly which questions were used. It also helps in organization and administration of courses The drawback is that the questions are only able to be used in the course. So, looking at the previous graph, the Question bank in Course B would not be able to use anything from Course A. This does not mean we can't ever use them again; we will just need to export them to wherever we want to use them. We'll look at this activity later. Activity Creating items in the quiz Activity itself is also possible. This means that questions being created will only be available for the specific test being made. The benefit to this is that you are assured that the questions are not available anywhere else, so, for example, if you want your test's questions to be completely isolated and unable to be used as random items in other formative or summative tests, this area would be a good place to place all the items. The only real drawback is that the questions you spent all that time working on are limited to a single activity, a single exam. I don't have the space here to go into how to use categories and contexts, but it isn't too hard to figure out. For a detailed and complete overview of how to create and use categories or contexts, check out these links http://docs.moodle.org/en/ Question_categories/ and http://docs.moodle.org/en/Question_contexts Multiple Choice item creation page Since composing Multiple Choice items is nearly the same as creating True/False questions, we are going to be working on a few of them now. Once we have the hang of making them, we will look at a few options that we didn't use in the previous test and see how they work. Returning to the Question bank, I go to the Create New Question drop-down and select Multiple Choice. Make sure you have the appropriate category selected. When the Adding a Multiple Choice question page opens, you will notice that it looks very similar to the True/False question page. That's because it is. There are a few new options available here, but the page looks basically the same. In the top section of the page, General, all the same information from True/False, such as item name and description are there. There are also three new options directly under the General feedback> text area. One or multiple answers This drop-down option has only two choices. It enables us to either accept only a single response or more than one answer as a response. The two options in the drop-down menu are called One answer only and Multiple answers allowed. Shuffle the choices This option takes the possible responses and randomly orders them. This is useful for reducing cheating, and also allows each student to be given a slightly different version of the test. This option will shuffle only if the Shuffle options for the quiz and the question are both turned on. The default is to shuffle or not based on the settings for the quiz module the Moodle administrator has set. These defaults can be overridden in the Quiz settings or here. Number the choices This section allows you to decide on how you want to mark the responses. You have four options: lowercase letters, uppercase letters, numbers, or nothing. From here, we scroll down the page and we will see that we are offered five sections, called Choice 1, Choice 2, and others for entering the answers. These choices can be seen in the next screenshot: Here, we can enter our potential answers, the grade students will get for choosing the particular potential answer, and some feedback based on their response. Under the five answer sections, you have the option to create more choices using a button titled Blanks for 3 More Choices. Clicking on this button will create Choices 6 to 8. There is no way to get rid of Choices, but it is possible to have fewer responses. If we only want to have three responses available, then all we need to do is fill in the three choices we want. At the bottom of the page, we see the three feedback boxes: one is for correct responses, one for partially correct responses, and the final one for incorrect responses. As for choices, these can be filled or left empty.
Read more
  • 0
  • 0
  • 1566
Banner background image

article-image-introduction-developing-facebook-applications
Packt
20 Dec 2010
6 min read
Save for later

Introduction to Developing Facebook Applications

Packt
20 Dec 2010
6 min read
  Facebook Graph API Development with Flash Build social Flash applications fully integrated with the Facebook Graph API Build your own interactive applications and games that integrate with Facebook Add social features to your AS3 projects without having to build a new social network from scratch Learn how to retrieve information from Facebook's database A hands-on guide with step-by-step instructions and clear explanation that encourages experimentation and play         Read more about this book       So let's get on with it... What's so great about Facebook? Seems like everyone's on Facebook these days—people are on it to socialize; businesses are on it to try to attract those people's attention. But the same is true for other older social networks such as LinkedIn, Friendster, and MySpace. Facebook's reach goes far beyond these; my small town's high street car park proudly displays a "Like Us On Facebook" sign. More and more Flash games and Rich Internet Applications (RIAs) are allowing users to log in using their Facebook account—it's a safe assumption that most users will have one. Companies are asking freelancers for deeper Facebook integration in their projects. It's practically a buzzword. But why the big fuss? It's popular Facebook benefits from the snowball effect: it's big, so it gets bigger. People sign up because most of their friends are already on it, which is generally not the case for, say, Twitter. Businesses sign up because they can reach so many people. It's a virtuous circle. There's a low barrier to entry, too; it's not just for techies, or even people who are "pretty good with computers;" even old people and luddites use Facebook. In February 2010, the technology blog ReadWriteWeb published an article called "Facebook Wants to Be Your One True Login," about Facebook's attempts to become the de facto login system throughout the Web. Within minutes, the comments filled up with posts from confused Facebook users: (Source: http://www.readwriteweb.com/archives/facebook_wants_to_be_your_one_true_login.php.) Evidently, the ReadWriteWeb article had temporarily become the top search result for Facebook Login, leading hundreds of Facebook users, equating Google or Bing with the Internet, to believe that this blog post was actually a redesigned Facebook.com. The comment form, fittingly, had a Sign in with Facebook button that could be used instead of manually typing in a name and e-mail address to sign a comment—and of course, the Facebook users misinterpreted this as the new Log in button. And yet… all of those people manage to use Facebook, keenly enough to throw a fit when it apparently became impossible to use. It's not just a site for geeks and students; it has serious mass market appeal. Even "The Social Network"—a movie based on the creation of Facebook—held this level of appeal: it opened at #1 and remained there for its second weekend. Numbers According to Facebook's statistics page (http://www.facebook.com/press/info.php?statistics), over 500 million people log in to Facebook in any given month (as of November 2010). For perspective, the population of the entire world is just under 7,000 million. Twitter is estimated to have 95 million monthly active users (according to the eMarketer.com September 2010 report), as is MySpace. FarmVille, the biggest game based on the Facebook platform, has over 50 million: more than half the population of either competing social network. FarmVille has been reported to be hugely profitable, with some outsider reports claiming that its parent company, Zynga, has generated twice as much profit as Facebook itself (though take this with a grain of salt). Now, of course, not every Facebook game or application can be that successful, and FarmVille does benefit from the same snowball effect as Facebook itself, making it hard to compete with—but that almost doesn't matter; these numbers validate Facebook as a platform on which a money-making business can be built. It's everywhere As the aforementioned ReadWriteWeb article explained, Facebook has become a standard login across many websites. Why add yet another username/password combination to your browser's list (or your memory) if you can replace them all with one Facebook login? This isn't restricted to posting blog comments. UK TV broadcaster, Channel 4, allows viewers to access their entire TV lineup on demand, with no need to sign up for a specific Channel 4 account: Again, Facebook benefits from that snowball effect: as more sites enable a Facebook login, it becomes more of a standard, and yet more sites decide to add a Facebook login in order to keep up with everyone else. Besides login capabilities, many sites also allow users to share their content via Facebook. Another UK TV broadcaster, the BBC, lets users post links for their recommended TV programs straight to Facebook: Blogs—or, indeed, many websites with articles—allow readers to Like a post, publishing this fact on Facebook and on the site itself: So half a billion people use the Facebook website every month, and at the same time, Facebook spreads further and further across the Internet—and even beyond. "Facebook Messages" stores user's entire conversational histories, across e-mail, SMS, chat, and Facebook itself; "Facebook Places" lets users check into a physical location, letting friends know that they're there. No other network has this reach. It's interesting to develop for With all this expansion, it's difficult for a developer to keep up with the Facebook platform. And sometimes there are bugs, and undocumented areas, and periods of downtime, all of which can make development harder still. But the underlying system—the Graph API, introduced in April 2010—is fascinating. The previous API had become bloated and cumbersome over its four years; the Graph API feels well-designed with plenty of room for expansion. Have a go hero – get on Facebook If you're not on Facebook already, sign up now (for free) at http://facebook.com. You'll need an account in order to develop applications that use it. Spend some time getting used to it: Set up a personal profile. Post messages to your friends on their Walls. See what all the FarmVille fuss is about at http://apps.facebook.com/onthefarm. Check in to a location using Facebook Places. Log in to some blogs using your Facebook account. Share some YouTube videos on your own Wall from the YouTube website. "Like" something. Go native!
Read more
  • 0
  • 0
  • 1089

article-image-getting-modular-moodle
Packt
22 Nov 2010
9 min read
Save for later

Getting Modular with Moodle

Packt
22 Nov 2010
9 min read
  Moodle 1.9 Top Extensions Cookbook Over 60 simple and incredibly effective recipes for harnessing the power of the best Moodle modules to create effective online learning sites Packed with recipes to help you get the most out of Moodle modules Improve education outcomes by situating learning in a real-world context using Moodle Organize your content and customize your courses Reviews of the best Moodle modules—out of the available 600 modules Installation and configuration guides Written in a conversational and easy-to-follow manner         Read more about this book       (For more resources on Moodle, see here.) Changing site-wide settings Activity modules and blocks can have site-wide settings that you can adjust. These settings allow consistent changes in the use of the module across an entire site, but even during testing you might want to change such settings. It may be that you just want to see what settings can be changed globally for a module. Getting ready To achieve this you must have your web server running with Moodle installed. You need to be able to log in as the administrator, or get the help of someone who can. You should have installed the modules that you want to change settings for. The following steps assume you have installed the Progress Bar block, which has global settings that can be changed. How to do it... Log in as the site administrator and visit the root page of the site. To get to the global settings of a module, on the Site Administration menu, select Modules, then Activities or Blocks, whichever is appropriate. The Progress Bar block is a block, so select Blocks to reach its global settings. The next step is to select the name of the module. For our test, the module name is Progress Bar. The settings for the module should appear in a form. Not all activity modules or blocks have global settings. For many modules, this is not necessary. Changes to the global settings affect the configuration of the module, including any instances that may already exist, and any that are added in future, across the site. There's more... Be a little careful when changing global settings on a live site. If the module is currently in use, changing global settings can affect the experience of students and teachers. Accidentally using invalid global settings can detrimentally affect the running of the module on the site. See also Adding modules to Moodle Getting rid of modules Getting modules to speak your language Another feature of Moodle is its capacity for internationalization. This means that the same software can be used by people speaking different languages. While translations for over 80 languages are available for the core functionality of Moodle, most modules only offer translations for a smaller number of languages, and the language you are teaching in may not be one of them. Adding a translation for a module is simple to do. If you give your translation to the author of the module, your efforts could also benefit others who speak your language. Getting ready It is assumed that you have set the default language for your site. If not, there is more information about adding a language pack and setting the language for your site later. In order to create a translation for a module, you don't need any real programming experience; it's actually quite simple. Some understanding of HTML tags can be an advantage. You will need a text editor that can create and edit Unicode files. Word processors are not appropriate for this task, and a simple editor, such as Windows Notepad, is not up to the job. There are many free editors available that will allow you to create and edit Unicode files. One example available for Windows is Notepad++, which is a free editor and is also available as a portable application. The steps that follow provide an example that assumes the Progress Bar block has been installed. How to do it... Where the module was installed, there will usually be a /lang folder. For the Progress Bar block this is located at moodle/blocks/progress/lang. Within this folder, there are folders for different languages, most of them contributed by users around the world. If you are reading this, it is assumed you have an understanding of English, so have a look inside the en_utf8/ folder. You will see a file called block_progress.php and another directory called help/. The block_progress.php file contains strings of text used in the module, each with a code and the string displayed on screen. Open this file in your editor to see the contents. Inside the lang/help/progress/ directory there are a number of HTML files, each relating to a help topic. These appear when a help icon (usually appearing as a question mark) is clicked. Opening these files in your web browser will show you the rendered version of these files and opening them in your editor will show you the HTML source of the documents. To add a new language, you first need to find out the two letter code for your language. To see the list of supported languages visit the following site. You will also see the code letters for each language, and you need to follow the same code. Refer to http://download.moodle.org/lang16/. Return to the lang/ folder. For the Progress Bar block this is at moodle/blocks/progress/lang/. Assuming that you know English as a second language, copy the en_utf8/ folder and all of its content. Rename the folder with the two letter code for your language, for example, the folder for Afrikaans would be af_utf8/. Be sure to preserve the filenames and folder names within (they do not need translation, only the contents). Open the block_progress.php file in your Unicode editor. You need to translate the string on the right of the = symbol, within the quotes. Do not translate the code value for the string on the left. You may need to see the string in use to get a sense of what the string is intended for, in order to make an accurate translation. If you include any apostrophes within the string, escape the quote with a slash, as shown in the following example, otherwise the string will be seen as coming to an end earlier than it should. $string['owners'] = 'Owner's'; If there is code within the strings, or HTML tags, that you are unsure about, leave these and just translate any text around them. You can also translate the HTML files in moodle/blocks/progress/lang/help/progress/ to produce help files in your language. Open these in your editor and translate the text within the files. Again, avoid changing any HTML or code you don't understand. Some help files also include PHP code segments within <?php and ?> tags, avoid changing this content. Be sure to test your translated files. If, after changing a translation file, nothing appears on the course page, it may be that you have inadvertently created an error. Typically this comes from mismatched quotes around strings. Be sure each starting quote is matched with a closing quote, and any enclosed quotes are escaped. Test that your translated text items are appearing correctly and have an appropriate meaning in your language. Once created, you can use this translation throughout your site. The final step is to send your translation to the author of the module. You should be able to find their contact details on the Moodle Modules and plugins database entry page for the module. If you have translated the language strings but not translated the help files, this is still a helpful contribution that can be shared. Zip up the files you have translated and e-mail them to the author who will usually be more than happy to include your contribution within the module for future downloaders. How it works... Each time the module is loaded, its code is interpreted by the web server and HTML is produced to form the part of the page where the module will appear. Within the code, instead of writing text strings in the author's language, there are calls to functions that check the language and draw the appropriate strings from the language files. This way, all that is needed to change from one language to another is a different language file. There's more... If you want to use another language throughout your Moodle site, the following sections are a basic guide for installing and selecting the language. Adding a language pack Visit the following site to find if a language pack is available for your language: http://download.moodle.org/lang16/. If your language is available, download the appropriate zip file and extract its contents to the directory moodle/lang/. If your language is Afrikaans, for example, the language files should be contained in moodle/lang/af_utf8/. Ensure you do not introduce additional unnecessary directory levels. Selecting a language for your site and courses A language can be set as a default for courses on the site. This can be overridden at the course level if desired, or by students individually. To set the default language, log in as administrator and go to the site root page. On the Site Administration menu, select Language, then Language Settings. The default language can be set on the page that appears. Individual users can set a preferred language in their profile settings. For individual courses a language can be set. This will "force" students to use that particular language rather than their preferred language. See also If it's not quite what you want...
Read more
  • 0
  • 0
  • 1022

article-image-introduction-moodle-modules
Packt
22 Nov 2010
8 min read
Save for later

Introduction to Moodle Modules

Packt
22 Nov 2010
8 min read
  Moodle 1.9 Top Extensions Cookbook Over 60 simple and incredibly effective recipes for harnessing the power of the best Moodle modules to create effective online learning sites Packed with recipes to help you get the most out of Moodle modules Improve education outcomes by situating learning in a real-world context using Moodle Organize your content and customize your courses Reviews of the best Moodle modules—out of the available 600 modules Installation and configuration guides Written in a conversational and easy-to-follow manner       Introduction Moodle is an open source Learning Management System (LMS). Image source: http://moodle.org/ The word Moodle is actually an acronym. The 'M' in Moodle stands for Modular and the modularity of Moodle has been one of the key aspects of its success. Being modular means you can: Add modules to your Moodle instance Selectively use the modules you need M.O.O.D.L.E. The acronym Moodle stands for Modular Object-Oriented Dynamic Learning Environment. It is modular because you can add and remove modules. The programming paradigm used to create Moodle code is Object-Oriented. It is dynamic because it can be used for information delivery and interactivity, in a changeable and flexible way. It is a learning environment designed for teaching at many levels. Because Moodle is modular and open source, many people have created modules for Moodle, and many of those modules are available freely for you to use. At time of writing, there are over 600 modules that you can download from the Moodle Modules and plugins database. Some of these are popular, well designed, and well maintained modules. Others are ideas that didn't seem to get off the ground. Some are contributed and maintained by large institutions, but most are contributed by individuals, often teachers themselves, who want to share what they have created. If you have an idea for something you would like to do with Moodle, it's possible that someone has had that idea before and has created and shared a module you can use. This article will show you how to download and test contributed Moodle modules, to see if they suit your needs. Origins of Moodle Moodle began in 1999 as postgraduate work of Martin Dougiamas, "out of frustration with the existing commercial software at the time". Considering the widespread use of Moodle around the world (over 40,000 registered sites in over 200 countries), Martin is a very humble man. If you ever make it to a MoodleMoot and Martin is in attendance, be sure to introduce yourself. A test server If you only want to test modules, consider setting up your own basic web server, such as XAMPP (http://www.apachefriends.org/en/xampp.html) and installing Moodle from the Moodle Downloads page (http://download.moodle.org/). If you are a Windows or Mac user, you can even download and install Moodle packages where these two ingredients are already combined and ready to go. Once installed, add a course or two. Create some dummy students to see how modules work within a course. Have a play around with the modules available—Moodle is quite hard to break—don't be afraid to experiment. Getting modules you can trust The Moodle Modules and plugins database is filled with modules great and small. This article will help you to know how you can find modules yourself. Getting ready You may have an idea in mind, or you may just want to see what's out there. You'll need a web browser and an active Internet connection. How to do it... Point your browser to the Moodle Modules and plugins database. Refer http://moodle.org/mod/data/view.php?id=6009: Image source: http://moodle.org/mod/data/view.php?id=6009 As you scroll down you will see list of modules that can be downloaded. At the bottom of the page is a Search facility: Image source: http://moodle.org/mod/data/view.php?id=6009 You can also try an advanced search to get more specific about the following: What type of module you want What version of Moodle you have A number of other features The following is a search result for the term 'progress': Image source: http://moodle.org/mod/data/view.php?id=6009 Each entry has a type, the version of Moodle that it is compatible with, and a brief description. Clicking on the name of the module will take you to a page with details about the module. This is the module's 'entry': Image source: http://moodle.org/mod/data/view.php?d=13&rid=2524&filter=1 On each entry page there is a wealth of information about the module. The following is a list of questions you will want to answer when determining if the module is worth testing. Will it work with your version of Moodle? Is documentation provided? When was the module released and has there been activity (postings on the page below) since then? Is the module author active in the discussion about the module? Is the discussion positive (don't be too discouraged by bug reports if the author is involved and reporting that bugs have been fixed)? From discussion, can you tell if the module is widely used with a community of users behind it? What is the rating of the module? If you are happy with your answers to these questions, then you may have found a useful module. Be wary of modules that do what you want, but are not supported; you may be wasting your time and putting the security of your system and the integrity your teaching at risk. There's more... Here is some additional information that may help you on a module hunt. Types of modules In order to get a sense of how modules will work, you need to have an understanding of the distinction between different module types. The following table describes common module types. Amid the array of modules available, the majority are blocks and activity modules. Activity moduleActivity modules deliver information or facilitate interactivity within a course. Links to activity modules are added on a course main page and the activity module itself appears on a new page when clicked. Examples in the core installation are 'Forums' and 'Quizzes'.Assignment typeAssignment types are a specific type of activity module that focus on assessable work. They are all based on a common assignment framework and appear under 'Assignments' in the activities list. Examples in the core installation are 'Advanced upload of files' and 'Online text' assignments.BlockBlocks usually appear down each side of a course main page. They are usually passive, presenting specific information, and links to more information and activities. A block is a simpler type of module. Because they are easy to create, there are a large number of these in the Modules and Plugins database. Examples in the core installation are the 'Calendar' and 'Online Users' blocks.Course formatA course format allows the structure of a course main page to be changed to reflect the nature of the delivery of the course, for example, by schedule or by topic.FilterFilters allow targeted text appearing around a Moodle site to be replaced with other content, for example, equations, videos, or audio clips.IntegrationAn integration module allows Moodle to make use of systems outside the Moodle instance itself.Question typeWithin a quiz, question types can be added to enable different forms of questions to be asked. Checking your version If you are setting up your own Moodle instance for teaching or just for testing, take note of the version you are installing. If you have access to the Site Administration interface (the Moodle site root page when logged in as an administrator), clicking on Notifi cations will show you the version number near the bottom, for example Moodle 1.9.8 (Build: 20100325). The first part of this is the Moodle version; this is what you need when searching through modules on the Modules and plugins database. The second part, labeled "Build" shows the date when the installed version was released in YYYYMMDD format. This version information reflects what is stored in the /version.php file. If you are not the administrator of your system, consult the person who is. They should usually be able to tell you the version without looking it up. Moodle 2.0 The next version of Moodle to follow version 1.9 has been "on the cards" for some time. The process of installing modules will not change in the new version, so most of the information in this book will still be valid. You will need to look for versions of modules ready for Moodle 2.0 as earlier versions will not work without adjustment. As modules are usually contributed by volunteers, there may be some waiting before this happens; the best way to encourage this re-development is to suggest an improvement for the module on the Moodle bug tracker system at http://tracker.moodle.org/. See also Adding modules to Moodle
Read more
  • 0
  • 0
  • 2373
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €14.99/month. Cancel anytime
article-image-moodle-modules-assessment
Packt
08 Nov 2010
8 min read
Save for later

Moodle Modules for Assessment

Packt
08 Nov 2010
8 min read
  Moodle 1.9 Top Extensions Cookbook Over 60 simple and incredibly effective recipes for harnessing the power of the best Moodle modules to create effective online learning sites Packed with recipes to help you get the most out of Moodle modules Improve education outcomes by situating learning in a real-world context using Moodle Organize your content and customize your courses Reviews of the best Moodle modules—out of the available 600 modules Installation and configuration guides Written in a conversational and easy-to-follow manner Assignment alternatives An assignment is a significant form of assessment, allowing students to demonstrate the understanding they have developed over a period of learning. Many teachers struggle to break away from traditional essays and reports. As well as the assignment types available in core Moodle, there are some well constructed, contributed assignment types that are sure to lure the most ardent traditionalist away from "red pen on paper". Peer Review Assignment Type NanoGong Assignment Type UploadPDF Assignment Type Using peer assessment Name Peer Review Module typeAssignment typeAuthorMichael de RaadtReleased2010MaintainedActivelyLanguagesEnglishComplianceGoodDocumentationOnline documentation, help filesErrorsNone displayed Peer assessment can benefit students by causing them to evaluate the work of their peers. Evaluation is a higher order thinking skill, and requiring students to evaluate the work of others can enhance their learning experience. Other benefits are student involvement in the assessment process and the fact that they will receive more than just instructor feedback. When used in conjunction with communication tools, peer assessment has the potential to encourage a learning community. This is particularly useful when students are studying in the Moodle environment, but physically separated from each other. The Workshop module—a core Moodle module, was the first contributed Moodle module. It brought peer assessment to Moodle, exemplifying the constructivist nature that has driven Moodle development over the years. However, in recent years, the Workshop module has not been maintained, and is disabled by default in Moodle. The Workshop module is currently being revived for Moodle 2.0 and shows great promise. Various peer assessment tools (outside Moodle) can reduce the quantity of marking for teachers, by relying on the student feedback as a basis for marking. This can be somewhat controversial when student feedback is the only source of grades. The Peer Review Assignment Type uses peer-feedback moderated by teachers as the basis for marks. The Peer Review Assignment Type attempts to simplify the peer assessment experience of the Workshop module for both teachers and students. Only one deadline is needed (students can even submit late and still be involved); most students will submit then immediately move on to reviewing, while the assignment is fresh in their minds. The Peer Review Assignment Type manages the relationships between students automatically, so all the teacher has to do is set up the assignment, then moderate reviews after the assignment deadline. Getting ready Being an Assignment Type, you need to unzip the peerreview directory into the /moodle/mod/assignment/type/ directory before visiting the Notifications page. How to do it... Once installed, a Peer Review assignment can be added from the Add an activity... menu. You will find it nested below Assignments. As it is an Assignment Type, the Peer Review Assignment Type has the same General settings as other Assignment Types (including a name, description, grade value, and due date). There are four settings specific to this Assignment Type listed in the Peer Review section of the configuration page. The first setting allows the teacher to decide if submissions will be in the form of a submitted file or text entered online in a WYSIWYG editor. If Submitted document is selected, the maximum file size and file type must be specified. These two settings should be made while keeping in mind that students will be downloading and reviewing each other's documents. Keep the maximum file size as low as practically possible, otherwise file transfer problems may arise. A file type that all students can work with should be selected. So, for instance, if students have a mix of Office 2003, Office 2007, and OpenOffice, using the .doc file type would allow all students be able to open and review submitted documents. Each student is expected to complete two reviews and this is seen as part of the learning experience. The final setting in this section allows a reward value to be set for each of the reviews the student completes. With the assignment configuration complete, click on Save and Display and you will be taken to a page where review criteria can be written. On this page, the criteria descriptions and values can be set. Some help is provided on writing good criteria; this is worth reading. For each criterion, you can enter a textual description that will appear to the student with the assignment description. This can include HTML tags if formatting is needed. For each criterion, a second alternate description can be provided, which can contain information that you want hidden from students before they submit (such as answers or test data); this is only shown to students as they complete reviews. A value also needs to be set for each criterion. The values of criteria and the reward students will receive for completing reviews need to add up to the total grade value for the assignment. At the bottom of the Criteria page, there is a JavaScript driven calculator that indicates if values sum correctly. Once you have entered the criteria, save them and you will be taken to the description of the assignment showing the criteria added at the end. Students will also see a facility to submit a file, or a WYSIWYG editor if online-text is to be entered. With the Description and the Criteria set, there is nothing to do until students have submitted and the assignment deadline has passed. If you are running this Assignment Type on a test server and want to see how it works, you will need to set up at least five dummy student accounts and use these to submit assignments and complete reviews. After students have submitted and completed reviews, they are shown a wealth of information about their submission, reviews they have conducted, and reviews they have received from their peers and teachers. Students have the opportunity to flag reviews they are unhappy with. When students have submitted and reviewed, it is the teacher's job to resolve conflicts. The Peer Review Assignment Type shows a submission table, like other Assignment Types, but adds information about review relationships and conflicts. (Move the mouse over the image to enlarge.) The teacher must add additional "moderation" reviews to override reviews that are conflicting. The tail end of the submissions list must also be reviewed by the teacher if there are not sufficient reviews for the system to suggest a mark. When conducting moderation reviews, the teacher is provided with information that students do not get to see. The teacher can see which criteria students have checked, and also the comments they have written about the submission currently being moderated. Teachers can see which student conducted each review and how long they spent reviewing. The teacher has access to a textbox, in which they can add and save comments to be re-used later. Multiple markers have access to this same saved comments list. When all conflicts are resolved, and all status indicators are green, the system is able to suggest marks for all students. These can be released individually or all at once by clicking the button labeled Set all unset calculatable grades at the bottom of the submissions list. The Peer Review Assignment Type also includes an Analysis page which may be useful when refining an assignment for later re-use, or for teachers conducting research around assessment. How it works... The Peer Review Assignment Type achieves a simpler model of peer assessment by altering the way review relationships are allocated. With the Workshop module and other peer assessment systems, a phased approach is taken, with students submitting before one deadline, waiting for relationships to be arranged, then reviewing before another deadline. Such a phased model does not leave room for late submissions, and the delay while students wait for reviews may cause them to lose track of the context of the assignment. With the Peer Review Assignment Type, there is an initial pooling period where early submitters must wait for more submissions to be made. When the fifth student submits, this triggers an event causing reviews to be allocated among the initial pool. When later students submit they are allocated earlier submissions to review, so these students can go directly from submission to reviewing without delay. This leaves some submissions at the tail end that require teacher moderation, however it also means late submitters can simply join the tail end. Because of the review allocation method, only a single submission is permitted. Students are warned about this. If a student submits the wrong file, a teacher can replace their submission (and ensure the replacement is moderated). There's more... The Peer Review Assignment Type can be used for teaching in a number of ways: As an extension of a regular assignment For a series of streamlined, small scale, focused assignments As a draft stage review before a final submission (submitted as a normal, instructor marked assignment) Outside regular teaching, the Peer Review Assignment Type could be used for the review of research papers submitted to a conference.
Read more
  • 0
  • 0
  • 1280

article-image-modules-assessing-students-moodle
Packt
08 Nov 2010
6 min read
Save for later

Modules for Assessing Students in Moodle

Packt
08 Nov 2010
6 min read
  Moodle 1.9 Top Extensions Cookbook Over 60 simple and incredibly effective recipes for harnessing the power of the best Moodle modules to create effective online learning sites Packed with recipes to help you get the most out of Moodle modules Improve education outcomes by situating learning in a real-world context using Moodle Organize your content and customize your courses Reviews of the best Moodle modules—out of the available 600 modules Installation and configuration guides Written in a conversational and easy-to-follow manner         Read more about this book       (For more resources on Moodle, see here.) Involving students in assessment design Who said writing questions was the teacher's job? For students, the challenge of creating questions encourages them to think in a new and different way about the material they are studying. The incentive of being able to create questions that may be used in their own future assessment is also a thrill. Question Creation module Extending quizzes Like many parts of Moodle, the Quiz module is extensible. New question types can be added to the Quiz module so that teachers can produce more creative questions and challenge learners from a wider range. Drag-and-drop matching question type Drag-and-drop ordering question type Image target question type Simple formative feedback Students are motivated to earn marks, but that doesn't mean you can't sneak in a bit of formative assessment without them realizing it. Simply encouraging students to anticipate small snippets of the material can probe their knowledge, reinforcing their correct understandings and challenging their misunderstandings. Hidden Text filter Encouraging competition It is a disservice to delude students into believing that they standout when they are in fact falling behind. Displaying the highest standard for assignments and other assessable items on a leader-board can motivate students to compete, while recognizing those who are excelling. Course Results block Allowing students to contribute to assessment Name Question Creation Module Module type Activity Author Jamie Pratt Released 2008 Maintained Actively Languages English, Spanish Compliance Good Documentation Limited online documentation, help files Errors Some errors displayed when error reporting is turned on The Question Creation Module allows students to contribute Quiz questions and be rewarded with marks. This is a great pedagogical activity and the questions produced by students can be used in creative ways. Getting ready Unzip and copy the module directory into the /moodle/mod/ directory then visit the Notifications page. How to do it... After adding the Question Creation Module you can create an instance of this activity from the Add an activity... menu. The configuration page for this module is somewhat overcomplicated, however, once you have used it, the settings become apparent. (Move the mouse over the image to enlarge.) Like most modules, there is a Name. There is also a description that appears as an Introduction to students in their view of the activity. A time period for the activity can be specified with an opening and closing date. In the Grading section, there are a number of options, some of which are obvious and some that require explanation. A Question Creation activity can contribute to a course assessment and as such there is a Grade value. This grade value is constituted from a mix of: Automatic grading (based on number of questions created by a student, that is, a participation mark) Manual grading (based on a judgment of quality by the teacher A 50%/50% mix means that the student gains half the available marks by simply creating the required number of questions and the other half based on the judgment of the teacher. A different ratio can be chose to shift this balance depending on the teacher's preference. For a fully automated assessment, a ratio of 100%/0% can be used. For a grade that is wholly based on the teacher's judgment a ratio of 0%/100% can be used. The number of questions that need to be created can be specified. The grade value is then distributed across this number of questions. The types of Quiz questions can be restricted to specific types or students can be allowed to create questions of any type. The teacher can direct that the student create a minimum number of questions of specified question types. For example, the teacher could direct that two of the questions that a student creates should be Multiple Choice. Such enforcement is achieved in the sections labeled (rather incomprehensibly) as Will Grade Minimum Number of Questions of Type (optional). At the bottom of the configuration page, there is a setting that controls what level of editing students have over their own questions. It is not clear at first what each level of access means, nor why access needs to be restricted. Students can be controlled in their freedom to create, preview, edit, and delete questions. The module author suggests that there may be complications if a student edits a question after it has been graded, although he also suggests that students could improve questions based on feedback and such questions could then be re-graded (and the module facilitates this). For the most intuitive setup for students, the highest level of access is probably best. The teacher could then grade the questions after a set deadline. In a two phased approach that allows questions to be improved, questions could be checked at a specified date, with final question edits required by the set deadline. Students have an interface to launch the question creation process. When a question type is selected, students then create a question of that type using the same interface that a teacher uses when they create questions for a quiz. Students can create more than the required number of questions. Their final mark is based on the best questions they have created. Questions created by students appear in a list much like an assignments submission table. In this view, a teacher can preview a question and grade it. They can also provide comments on each question. The final grade is calculated when the teacher clicks the button at the bottom of this page labeled Save all grades & feedback. Grades are calculated according to how many of the required questions a student has created and the quality of each question. The student's final grade is the calculated value across all of their questions. How it works... Questions created by students are stored in the Moodle Question Bank. In that form they can be used by teachers in the course like any other question in the Question Bank. There's more... Requiring students to create questions is a great learning exercise. It forces students to think about the course materials at a higher level in order to form questions that someone else will find challenging. The real possibilities of this activity fall not in what the students can create, but in what the teacher can do with the questions that students have made. Here are some ideas: Using the best questions for regular quizzes (keeping in mind that at least one student will already know the answer) Using the best questions for quizzes for a successive cohort Using student created questions as the basis for a final exam
Read more
  • 0
  • 0
  • 924

article-image-php-5-social-networking-private-messages
Packt
26 Oct 2010
7 min read
Save for later

PHP 5 Social Networking: Private Messages

Packt
26 Oct 2010
7 min read
PHP 5 Social Networking We obviously need to keep private messages separate from the rest of the site, and ensure that they are only accessible to the sender and the receiver. While we could alter the public messages feature developed earlier, this would raise a few issues, such as being more difficult to tell whether the message being sent or read was private, and when using the Internet in a public area, the message would be shown on the area of the social network the user would most likely be visiting, which isn't ideal for private information. Because private messages will be separate from statuses, and won't need to make use of other media types to make them more interesting (though, we could set them up to make use of other media if we wanted), it makes sense for us to also use separate database tables and models for this feature. Database Our database needs provisions for the sender of the message, the recipient of the message, the subject of the message, and of course the message itself. We should also provide for if the message has been read, when the message was sent, and an ID for the message. The following illustrates a suitable structure for a messages table in our database:   Field Type Description ID Integer, Autoincrement, Primary Key Reference ID for the message Sender Integer The sender of the message Recipient Integer The recipient of the message Subject Varchar The subject the message relates to Sent Timestamp When the message was sent Message Longtext The contents of the message itself Read Boolean Indicates whether the message has been read or not More than one recipient? This database structure, and the code that follows, only supports one recipient per message. Our users might want to send to more than one recipient—feel free to add this functionality if you wish. Message model As with the majority of our database access, we require a model (models/message. php) to create, update, and retrieve message-related data from the database and encapsulate it within itself. It would also be helpful if the model pulled in a little more information from the database, including: A more user friendly representation of the date (we can get this via the MySQL DATE_FORMAT function) The name of the sender, by joining the messages table to the profile table The name of the recipient, by joining the messages table to the profile table again The first part of our model simply defines the class variables: <?php /** * Private message class */ class Message { /** * The registry object */ private $registry; /** * ID of the message */ private $id=0; /** * ID of the sender */ private $sender; /** * Name of the sender */ private $senderName; /** * ID of the recipient */ private $recipient; /** * Name of the recipient */ private $recipientName; /** * Subject of the message */ private $subject; /** * When the message was sent (TIMESTAMP) */ private $sent; /** * User readable, friendly format of the time the message was sent */ private $sentFriendlyTime; /** * Has the message been read */ private $read=0; /** * The message content itself */ private $message; The constructor takes the registry and ID of the message as parameters, if the ID has been defined, then it queries the database and sets the class variables. The database query here also formats a copy of the date into a friendlier format, and looks up the names of the sender and recipient of the message: /** * Message constructor * @param Registry $registry the registry object * @param int $id the ID of the message * @return void */ public function __construct( Registry $registry, $id=0 ) { $this->registry = $registry; $this->id = $id; if( $this->id > 0 ) { $sql = "SELECT m.*, DATE_FORMAT(m.sent, '%D %M %Y') as sent_friendly, psender.name as sender_name, precipient.name as recipient_name FROM messages m, profile psender, profile precipient WHERE precipient.user_id=m.recipient AND psender.user_id=m.sender AND m.ID=" . $this->id; $this->registry->getObject('db')->executeQuery( $sql ); if( $this->registry->getObject('db')->numRows() > 0 ) { $data = $this->registry->getObject('db')->getRows(); $this->sender = $data['sender']; $this->recipient = $data['recipient']; $this->sent = $data['sent']; $this->read = $data['read']; $this->subject = $data['subject']; $this->message = $data['message']; $this->sentFriendlyTime = $data['sent_friendly']; $this->senderName = $data['sender_name']; $this->recipientName = $data['recipient_name']; } else { $this->id = 0; } } } Next, we have setter methods for most of the class variables: /** * Set the sender of the message * @param int $sender * @return void */ public function setSender( $sender ) { $this->sender = $sender; } /** * Set the recipient of the message * @param int $recipient * @return void */ public function setRecipient( $recipient ) { $this->recipient = $recipient; } /** * Set the subject of the message * @param String $subject * @return void */ public function setSubject( $subject ) { $this->subject = $subject; } /** * Set if the message has been read * @param boolean $read * @return void */ public function setRead( $read ) { $this->read = $read; } /** * Set the message itself * @param String $message * @return void */ public function setMessage( $message ) { $this->message = $message; } The save method takes the class variables that directly relate to the messages table in the database and either inserts them as a new record, or updates the existing record: /** * Save the message into the database * @return void */ public function save() { if( $this->id > 0 ) { $update = array(); $update['sender'] = $this->sender; $update['recipient'] = $this->recipient; $update['read'] = $this->read; $update['subject'] = $this->subject; $update['message'] = $this->message; $this->registry->getObject('db')->updateRecords( 'messages', $update, 'ID=' . $this->id ); } else { $insert = array(); $insert['sender'] = $this->sender; $insert['recipient'] = $this->recipient; $insert['read'] = $this->read; $insert['subject'] = $this->subject; $insert['message'] = $this->message; $this->registry->getObject('db')->insertRecords( 'messages', $insert ); $this->id = $this->registry->getObject('db')->lastInsertID(); } } One getter method that we need, is to return the user ID of the recipient, so we can check that the currently logged in user has permission to read the message: /** * Get the recipient of the message * @return int */ public function getRecipient() { return $this->recipient; } We should also provide a method to delete the message from the database, should the user wish to delete a message: /** * Delete the current message * @return boolean */ public function delete() { $sql = "DELETE FROM messages WHERE ID=" . $this->id; $this->registry->getObject('db')->executeQuery( $sql ); if( $this->registry->getObject('db')->affectedRows() > 0 ) { $this->id =0; return true; } else { return false; } } Finally, we have a toTags method, which converts all of the non-object and non-array variables into template tags, so when we create a view message method in the controller, we simply need to construct the message object and call the toTags method: /** * Convert the message data to template tags * @param String $prefix prefix for the template tags * @return void */ public function toTags( $prefix='' ) { foreach( $this as $field => $data ) { if( ! is_object( $data ) && ! is_array( $data ) ) { $this->registry->getObject('template')->getPage()->addTag( $prefix.$field, $data ); } } } } ?> Messages model Similar to how we have a model for representing a single relationship and another for representing a number of relationships, we also need a model to represent a number of messages within the site. This is to handle the lookup of a user's private message inbox. <?php /** * Messages model */ class Messages { /** * Messages constructor * @param Registry $registry * @return void */ public function __construct( Registry $registry ) { $this->registry = $registry; } /** * Get a users inbox * @param int $user the user * @return int the cache of messages */ public function getInbox( $user ) { $sql = "SELECT IF(m.read=0,'unread','read') as read_style, m.subject, m.ID, m.sender, m.recipient, DATE_FORMAT(m.sent, '%D %M %Y') as sent_friendly, psender.name as sender_name FROM messages m, profile psender WHERE psender.user_id=m.sender AND m.recipient=" . $user . " ORDER BY m.ID DESC"; $cache = $this->registry->getObject('db')->cacheQuery( $sql ); return $cache; } } ?>
Read more
  • 0
  • 0
  • 2579

article-image-php-5-social-networking-implementing-public-messages
Packt
26 Oct 2010
7 min read
Save for later

PHP 5 Social Networking: Implementing Public Messages

Packt
26 Oct 2010
7 min read
PHP 5 Social Networking Create a powerful and dynamic Social Networking website in PHP by building a flexible framework   Build a flexible Social Networking framework using PHP which can be extended to fit the needs of any Social Networking site Develop a suitable structure for our framework, with MVC to structure the architecture and a Registry to store core Objects Allow users to connect and communicate with each other using communication with friends list, flexible user profiles, messages, discussions, and much more Plan marketing and scaling strategies, to entice more users and ensure the site can cope with the demand Packed with real-world code and clear explanation, this book uses an ongoing case study for creating a Social Networking framework Throughout the course of this article we will be using a social networking site for keepers of pet dinosaurs (of course nobody owns a real pet dinosaur, but for the sake of this article, let's pretend!), which we will call DinoSpace. Public messages The status stream fully supports public messages and streaming them to the Dino Space members. What we don't yet have, however, is support for users to post messages on the profiles of other users, so, let's add that in now. Controller A user should only be able to post a message on another user's profile if they are connected. The post message form should only be displayed if the users are connected. Similarly, a public message post should only be processed if the two users are connected. The controller also needs to display messages that have been posted on a user's profile too. Displaying profile messages If we look at our Profilestatusescontroller (controllers/profile/ profilestatusescontroller.php), in the listRecentStatuses method, we have our query for listing recent profile statuses: $sql = "SELECT t.type_reference, t.type_name, s.*, p.name as poster_name FROM statuses s, status_types t, profile p WHERE t.ID=s.type AND p.user_id=s.poster AND p.user_id={$user} ORDER BY s.ID DESC LIMIT 20"; At the moment, this query pulls in any posts on a user's profile by the user whose profile it is. If that user has made a post on someone else's profile, the message instead shows on the user's own profile, which we don't want. We need to change this to pull in the profiles table twice, once for the user who made the post, and again for the user whose profile is being viewed. We will also want to only pull in posts made on the user's profile, and not posts made by the user on another user's profile (though this is something we can expand on in the future, perhaps to indicate that a user has made a post on the profile of another user). The following query should meet our requirements nicely: $sql = "SELECT t.type_reference, t.type_name, s.*, pa.name as poster_name FROM statuses s, status_types t, profile p, profile pa WHERE t.ID=s.type AND p.user_id=s.profile AND pa.user_id=s.poster AND p.user_id={$user} ORDER BY s.ID DESC LIMIT 20"; Now, if we view a user's profile, we see their own status updates, and messages posted on their profile by other users, as shown in the following screenshot: Displaying the post message box The listRecentStatuses method we were just editing is the method we need to edit to display the post message box. This box should only be displayed if the user is logged in, and is connected to the user. If the user is viewing their own profile, then they should see a box to update their own status: // post status / public message box if( $this->registry->getObject('authenticate')->isLoggedIn() == true ) { $loggedInUser = $this->registry->getObject('authenticate')- >getUser()->getUserID(); If the logged in user is viewing their own profile, then we add the update template to the view, so they can update their status: if( $loggedInUser == $user ) { $this->registry->getObject('template')->addTemplateBit('status_ update', 'profile/statuses/update.tpl.php' ); } else { If the user isn't viewing their own profile, but is logged in, we get any connections the user has: require_once( FRAMEWORK_PATH . 'models/relationships.php' ); $relationships = new Relationships( $this->registry ); $connections = $relationships->getNetwork( $user, false ); if( in_array( $loggedInUser, $connections ) ) { If the user is connected to the user whose profile they are viewing, then we allow them to post a message on the users profile with the post template: $this->registry->getObject('template')->addTemplateBit( 'status_update', 'profile/statuses/post.tpl.php' ); } else { If the user isn't connected to the user, or isn't logged in, then we simply remove the template tag from the view so they don't see any update or post box on the page: $this->registry->getObject('template')->getPage()- >addTag( 'status_update', '' ); } } } else { $this->registry->getObject('template')->getPage()- >addTag( 'status_update', '' ); } Now, we need to process status updates and profile posts, and create the templates that make up the final aspect of our view. Process a new message The same logic that we used to determine whether the user should see a post form is what we need to use to determine if we should process a status update, or public message submission. Status model To save the status update or public profile post in the database, we will need a status model; as with our previous models, this simply needs to represent the fields from the database, with setter methods for these fields, and a save method to insert a new record into the database. In the future, we may wish to extend this to pull in statuses from the database, and save changes to them, as well as deleting statuses, perhaps if the owner of the message or the owner of the profile the message was posted on wishes to edit or delete it. The following is suitable code for our status model (models/status.php): <?php /** * Status model */ class Status { /** * The registry object */ private $registry; /** * Statuses ID */ private $id; /** * Poster of the status update / profile message */ private $poster; /** * The profile the status update / profile message was posted on */ sprivate $profile; /** * Type of status */ private $type; /** * The update / profile message itself */ private $update; /** * Reference for the type of status */ private $typeReference = 'update'; /** * Constructor * @param Registry $registry the registry object * @param int $id ID of the status update / profile message * @return void */ public function __construct( Registry $registry, $id=0 ) { $this->registry = $registry; $this->id = 0; } /** * Set the poster of the status / profile message * @param int $poster the id of the poster * @return void */ public function setPoster( $poster ) { $this->poster = $poster; } /** * Set the profile that the message / status is posted on * @param int $profile the profile ID * @return void */ public function setProfile( $profile ) { $this->profile = $profile; } /** * Set the status / profile message itself * @param String $status * @return void */ public function setStatus( $status ) { $this->status = $status; } /** * Set the type of status / profile message * @param int $type * @return void */ public function setType( $type ) { $this->type = $type; } /** * Set the type reference, so we can get the type ID from the database * @param String $typeReference the reference of the type * @return void */ public function setTypeReference( $typeReference ) { $this->type = $typeReference; } /** * Generate the type of status based of the type reference * @return void */ public function generateType() { $sql = "SELECT * FROM status_types WHERE type_reference='{$this->typeReference}'"; $this->registry->getObject('db')->executeQuery( $sql ); $data = $this->registry->getObject('db')->getRows(); $this->type = $data['ID']; } /** * Save the status / profile message * @return void */ public function save() { if( $this->id == 0 ) { $insert = array(); $insert['update'] = $this->status; $insert['type'] = $this->type; $insert['poster'] = $this->poster; $insert['profile'] = $this->profile; $this->registry->getObject('db')- >insertRecords( 'statuses', $insert ); $this->id = $this->registry->getObject('db')->lastInsertID(); } } } ?> Now that we have some functionality to easily insert the status into the database, we need to update our profile controller to process the new status update.
Read more
  • 0
  • 0
  • 2298
article-image-php-5-social-networking-integrating-media-profile-posts
Packt
22 Oct 2010
13 min read
Save for later

PHP 5 Social Networking: Integrating Media in Profile Posts

Packt
22 Oct 2010
13 min read
Since different status types will use different status tables, we should use a left join to connect the tables, so we can keep just a single query to look up the statuses. It also pulls in the extra information when it is required. Let's get started with extending our profiles and the status stream! Changes to the view Since all of the media types we are going to support require at least one additional database field in a table that extends the statuses table, we are going to need to display any additional fields on the post status form. The standard type of status doesn't require additional fields, and new media types that we haven't discussed, which we may wish to support in the future, may require more than one additional field. To support a varying number of additional fields depending on the type, we could use some JavaScript (in this case, we will use the jQuery framework) to change the form depending on the context of the status. Beneath the main status box, we can add radio buttons for each of the status types, and depending on the one the user selects, the JavaScript can show or hide the additional fields, making the form more relevant. Template Our update status template needs a few changes: We need to set the enctype on the form, so that we can upload files (for posting images) We need radio buttons for the new types of statuses We need additional fields for those statuses The changes are highlighted in the following code segment: <p>Tell your network what you are up to</p> <form action="profile/statuses/{profile_user_id}" method="post" enctype="multipart/form-data"> <textarea id="status" name="status"></textarea> <br /> <input type="radio" name="status_type" id="status_checker_update" class="status_checker" value="update" />Update <input type="radio" name="status_type" id="status_checker_video" class="status_checker" value="video" />Video <input type="radio" name="status_type" id="status_checker_image" class="status_checker" value="image" />Image <input type="radio" name="status_type" id="status_checker_link" class="status_checker" value="link" />Link <br /> <div class="video_input extra_field"> <label for="video_url" class="">YouTube URL</label> <input type="text" id="" name="video_url" class="" /><br /> </div> <div class="image_input extra_field"> <label for="image_file" class="">Upload image</label> <input type="file" id="" name="image_file" class="" /><br /> </div> <div class="link_input extra_field"> <label for="link_url" class="">Link</label> <input type="text" id="" name="link_url" class="" /><br /> <label for="link_description" class="">Description</label> <input type="text" id="" name="link_description" class="" /><br /> </div> <input type="submit" id="updatestatus" name="updatestatus" value="Update" /> </form> These changes also need to be made to the post template, for posting on another user's profile. jQuery to enhance the user experience For accessibility purposes, we need this form to function regardless of whether the user has JavaScript enabled on their browser. To that end, we should use JavaScript to hide the unused form elements. So, even if the user has JavaScript disabled, they can still use all aspects of the form. We can then use JavaScript to enhance the user experience, toggling which aspects of the form are hidden or shown. <script type="text/javascript"> $(function() { First, we hide all of the extended status fields. $('.extra_field').hide(); $("input[name='status_type']").change(function(){ When the user changes the type of status, we hide all of the extended fields. $('.extra_field').hide(); We then show the fields directly related to the status type they have chosen. $('.'+ $("input[name='status_type']:checked").val() + '_input').show(); }); }); </script> View in action If we now take a look at our status updates page for our profile, we have some radio buttons that we can use to toggle elements of the form. Images To process images as a new status type, we will need a new database table and a new model to extend from the main status model. We will also need some new views, and to change the profile and status stream controllers (though we will make those changes after adding the three new status types). Database table The database table for images simply needs two fields:     Field Type Description ID Integer, Primary key To relate to the main statuses table Image Varchar The image filename These two fields will be connected to the statuses table via a left join, to bring in the image filename for statuses that are images. Model The model needs to extend our statuses model, providing setters for any new fields, call the parent constructor, call the parent setTypeReference method to inform that it is an image, call the parent save method to save the status, and then insert a new record into the image status table with the image information. Class, variable, and constructor Firstly, we define the class as an extension of the status class. We then define a variable for the image, and construct the object. The constructor calls the parent setTypeReference method to ensure it generates the correct type ID for an image, and then calls the parent constructor so it too has reference to the registry object. This file is saved as /models/imagestatus.php. <?php /** * Image status object * extends the base status object */ class Imagestatus extends status { private $image; /** * Constructor * @param Registry $registry * @param int $id * @return void */ public function __construct( Registry $registry, $id = 0 ) { $this->registry = $registry; parent::setTypeReference('image'); parent::__construct( $this->registry, $id ); } To call a method from an object's parent class, we use the parent keyword, followed by the scope resolution operator, followed by the method we wish to call. Processing the image upload When dealing with image uploads, resizing, and saving, there are different PHP functions that should be used depending on the type of the image. To make this easier and to provide a centralized place for dealing with image uploads and other image-related tasks, we should create a library file (lib/images/imagemanager. class.php) to make this easier. Let's discuss what an image manager library file should do to make our lives easier: Process uploading of an image from $_POST data Verify the type of file and the file extension Process images from the file system so that we can modify them Display an image to the browser Resize an image Rescale an image by resizing either the x or y co-ordinate, and scaling the other co-ordinate proportionally Get image information such as size and name Save the changes to the image The following is the code required to perform the above-mentioned tasks: <?php /** * Image manager class * @author Michael Peacock */ class Imagemanager { /** * Type of the image */ private $type = ''; /** * Extensions that the user can upload */ private $uploadExtentions = array( 'png', 'jpg', 'jpeg', 'gif' ); /** * Mime types of files the user can upload */ private $uploadTypes = array( 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png' ); /** * The image itself */ private $image; /** * The image name */ private $name; public function __construct(){} We need a method to load a local image, so that we can work with images saved on the servers file system. /** * Load image from local file system * @param String $filepath * @return void */ public function loadFromFile( $filepath ) { Based on the path to the image, we can get information on the image including the type of image (getimagesize gives us an array of information on the image; the second element in the array is the type). $info = getimagesize( $filepath ); $this->type = $info[2]; We can then compare the image type to various PHP constants, and depending on the image type (JPEG, GIF, or PNG) we use the appropriate imagecreatefrom function. if( $this->type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg($filepath); } elseif( $this->type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif($filepath); } elseif( $this->type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng($filepath); } } We require a couple of getter methods to return the height or width of the image. /** * Get the image width * @return int */ public function getWidth() { return imagesx($this->image); } /** * Get the height of the image * @return int */ public function getHeight() { return imagesy($this->image); } We use a simple resize method that resizes the image to the dimensions we request. /** * Resize the image * @param int $x width * @param int $y height * @return void */ public function resize( $x, $y ) { $new = imagecreatetruecolor($x, $y); imagecopyresampled($new, $this->image, 0, 0, 0, 0, $x, $y, $this->getWidth(), $this->getHeight()); $this->image = $new; } Here we use a scaling function that takes a height parameter to resize to and scales the width accordingly. /** * Resize the image, scaling the width, based on a new height * @param int $height * @return void */ public function resizeScaleWidth( $height ) { $width = $this->getWidth() * ( $height / $this->getHeight() ); $this->resize( $width, $height ); } Similar to the above method, this method takes a width parameter, resizes the width, and rescales the height based on the width. /** * Resize the image, scaling the height, based on a new width * @param int $width * @return void */ public function resizeScaleHeight( $width ) { $height = $this->getHeight() * ( $width / $this->getWidth() ); $this->resize( $width, $height ); } The following is another scaling function, this time to rescale the image to a percentage of its current size: /** * Scale an image * @param int $percentage * @return void */ public function scale( $percentage ) { $width = $this->getWidth() * $percentage / 100; $height = $this->getheight() * $percentage / 100; $this->resize( $width, $height ); } To output the image to the browser from PHP, we need to check the type of the image, set the appropriate header based off the type, and then use the appropriate image function to render the image. After calling this method, we need to call exit() to ensure the image is displayed correctly. /** * Display the image to the browser - called before output is sent, exit() should be called straight after. * @return void */ public function display() { if( $this->type == IMAGETYPE_JPEG ) { $type = 'image/jpeg'; } elseif( $this->type == IMAGETYPE_GIF ) { $type = 'image/gif'; } elseif( $this->type == IMAGETYPE_PNG ) { $type = 'image/png'; } header('Content-Type: ' . $type ); if( $this->type == IMAGETYPE_JPEG ) { imagejpeg( $this->image ); } elseif( $this->type == IMAGETYPE_GIF ) { imagegif( $this->image ); } elseif( $this->type == IMAGETYPE_PNG ) { imagepng( $this->image ); } } To load an image from $_POST data, we need to know the post field the image is being sent through, the directory we wish to place the image in, and any additional prefix we may wish to add to the image's name (to prevent conflicts with images with the same name). /** * Load image from postdata * @param String $postfield the field the image was uploaded via * @param String $moveto the location for the upload * @param String $name_prefix a prefix for the filename * @return boolean */ public function loadFromPost( $postfield, $moveto, $name_prefix='' ) { Before doing anything, we should check that the file requested is actually a file that has been uploaded (and that this isn't a malicious user trying to access other files). if( is_uploaded_file( $_FILES[ $postfield ]['tmp_name'] ) ) { $i = strrpos( $_FILES[ $postfield ]['name'], '.'); if (! $i ) { //'no extention'; return false; } else { We then check that the extension of the file is in our allowed extensions array. $l = strlen( $_FILES[ $postfield ]['name'] ) - $i; $ext = strtolower ( substr( $_FILES[ $postfield ]['name'], $i+1, $l ) ); if( in_array( $ext, $this->uploadExtentions ) ) { Next, we check if the file type is an allowed file type. if( in_array( $_FILES[ $postfield ]['type'], $this->uploadTypes ) ) { Then, we move the file, as it has already been uploaded to our server's temp folder, to our own uploads directory and load it into our image manager class for any further processing we wish to make. $name = str_replace( ' ', '', $_FILES[ $postfield ]['name'] ); $this->name = $name_prefix . $name; $path = $moveto . $name_prefix.$name; move_uploaded_file( $_FILES[ $postfield ]['tmp_name'] , $path ); $this->loadFromFile( $path ); return true; } else { // 'invalid type'; return false; } } else { // 'invalid extention'; return false; } } } else { // 'not uploaded file'; return false; } } The following getter method is used to return the name of the image we are working with: /** * Get the image name * @return String */ public function getName() { return $this->name; } Finally, we have our save method, which again must detect the type of image, to work out which function to use. /** * Save changes to an image e.g. after resize * @param String $location location of image * @param String $type type of the image * @param int $quality image quality /100 * @return void */ public function save( $location, $type='', $quality=100 ) { $type = ( $type == '' ) ? $this->type : $type; if( $type == IMAGETYPE_JPEG ) { imagejpeg( $this->image, $location, $quality); } elseif( $type == IMAGETYPE_GIF ) { imagegif( $this->image, $location ); } elseif( $type == IMAGETYPE_PNG ) { imagepng( $this->image, $location ); } } } ?> Using the image manager library to process the file upload Now that we have a simple, centralized way of processing file uploads and resizing them, we can process the image the user is trying to upload as their extended status. /** * Process an image upload and set the image * @param String $postfield the $_POST field the image was uploaded through * @return boolean */ public function processImage( $postfield ) { require_once( FRAMEWORK_PATH . 'lib/images/imagemanager.class.php' ); $im = new Imagemanager(); $prefix = time() . '_'; if( $im->loadFromPost( $postfield, $this->registry- >getSetting('upload_path') . 'statusimages/', $prefix ) ) { $im->resizeScaleWidth( 150 ); $im->save( $this->registry->getSetting('upload_path') . 'statusimages/' . $im->getName() ); $this->image = $im->getName(); return true; } else { return false; } } Saving the status This leaves us with the final method for saving the status. This calls the parent object's save method to create the record in the statuses table. Then it gets the ID, and inserts a new record into the images table with this ID as the ID. /** * Save the image status * @return void */ public function save() { // save the parent object and thus the status table parent::save(); // grab the newly inserted status ID $id = $this->getID(); // insert into the images status table, using the same ID $extended = array(); $extended['id'] = $id; $extended['image'] = $this->image; $this->registry->getObject('db')->insertRecords( 'statuses_images', $extended ); } } ?>
Read more
  • 0
  • 0
  • 1959

article-image-moodle-20-faqs
Packt
14 Oct 2010
8 min read
Save for later

Moodle 2.0 FAQs

Packt
14 Oct 2010
8 min read
Moodle 2.0 First Look Discover what's new in Moodle 2.0, how the new features work, and how it will impact you Get an insight into the new features of Moodle 2.0 Discover the benefits of brand new additions such as Comments and Conditional Activities Master the changes in administration with Moodle 2.0 The first and only book that covers all of the fantastic new features of Moodle 2.0         Read more about this book       (For more resources on Moodle, see here.)   Question: What are the basic requirements for Moodle 2.0 to function? Answer: It's important that either you (if you're doing this yourself) or your Moodle admin or webhost are aware of the requirements for Moodle 2.0. It needs: PHP must be 5.2.8 or later One of the following databases: MySQL 5.0.25 or later (InnoDB storage engine highly recommended) PostgreSQL 8.3 or later Oracle 10.2 or later MS SQL 2005 or later One of the following browsers: Firefox 3 or later Safari 3 or later Google Chrome 4 or later Opera 9 or later MS Internet Explorer 7 or later   Question: How can I upgrade to Moodle 2.0? Answer: If you already have an installation of Moodle, you will find instructions for upgrading in the docs on the main Moodle site here http://docs.moodle.org/en/Upgrading_to_Moodle_2.0. If you are upgrading from an earlier version of Moodle (such as 1.8) then you should upgrade to Moodle 1.9 first before going to 2.0. You must update incrementally; shortcuts – for example. updating from 1.7 directly to 2.0 -- are simply not possible. Read the docs carefully if you are planning on upgrading from very early versions such as 1.5 or 1.6.   Question: What are the potential problems with upgrading? Answer: There are a few challenges that one may come across while upgrading from Moodle 1.9 to 2.0 which are listed below: Themes: The way themes work has changed completely. While this allows for more flexible coding and templating, it does mean that if you had a customized theme it will not transfer over to Moodle 2 without some redesigning beforehand. Third party add-ons and custom code: The same applies to third party add-ons and custom code: it is highly unlikely they will work without significant alterations. Backup and Restore: Making courses from 1.9 or earlier restore into Moodle 2. 0 has proved very problematic and is still not entirely achievable. Although this is a priority for the Moodle developers, there is at the time of writing only a workaround involving restoring your course to a 1.9 site and then upgrading it to 2.0.   Question: How can teachers and students manage their learning? Answer: The two new features of Moodle 2.0 help teacher and students manage their learning: Conditional activities: A way to organize a course so that tasks are only available dependent on certain grades being obtained or criteria being met beforehand. Completion tracking: A way for students to have checkboxes next to their tasks that are either automatically marked as complete or which students themselves can manually mark if they feel they've finished the exercise – or alternatively a way for whole courses to be checked off as finished.   Question: What are the changes in the Themes structure for Moodle 2.0? Answer: The themes structure has been completely rewritten for Moodle 2.0. Themes that worked in 1.9 needed to be updated to work in 2.0. There is a wide variety of attractive new themes available. If you need to update your own theme or would like information on Moodle 2.0 theming, you will find the documentation at http://docs.moodle.org/en/Development:Themes_2.0 helpful. New to Moodle 2.0 are the following: Designer Mode: Turn this on so you're not served cached versions of themes, if you are designing themes or developing code. Allow theme changes in the URL: Enabling this will let users alter their theme via their Moodle URL using the syntax Allow blocks to use the dock: Enabling this will allow users to dock blocks if the theme supports it.   Question: Can we customize the MyMoodle page in Moodle 2.0? Answer: Yes, we can customize the default MyMoodle page. It's worth noting that on the MyMoodle page we can add blocks to the middle as well as the sides. With editing turned on, we're given the option to move a block to a central location.   Question: Can we Comment on the Moodle blog? Answer: Commenting on the Moodle blog is a bit of a workaround really; the Moodle blog doesn't really have a built-in commenting facility like, say WordPress. Rather, Moodle is making use of the new Comments feature which ordinarily appears as a block anywhere you want to add it.   Question: What are the improvements in the Blog option in Moodle 2.0 as compared to the previous version? Answer: There has always been a blogging option in a standard Moodle install. However, some users have found it unsatisfactory because of the following reasons: The blog is attached to the user profile so you can only have one blog There is no way to attach a blog or blog entry to a particular course There is no way for other people to comment on your blog For this reason, alternative blog systems (such as the contributed OU blog module) have become popular as they give users a wider range of options. The standard blog in Moodle 2.0 has changed, and now: A blog entry can optionally be associated with a course It is possible to comment on a blog entry Blog entries from outside of Moodle can be copied in It is now possible to search blog entries   Question: How to enable/disable the docking facility in Moodle 2.0? Answer: The docking facility can be managed in Moodle 2.0 as follows: The "docking" facility may be enabled or disabled for themes in Site Administration | Appearance | Themes | Theme settings. If we click the icon shown in the following screenshot, we also have the option of "docking" this over to the far left as a narrow tab.   Question: Has the HTML editor been replaced by some other editing tool? What is its advantage? Answer: In Moodle 2.0, the HTML editor has been replaced with a version known as Tiny MCE, a very popular Open Source editor you might have encountered in content management systems or blogging software such as WordPress. Along with Internet Explorer and Firefox, it will work with web browsers such as Safari, Chrome, and Opera, unlike Moodle's previous HTML editor. The following screenshot shows the new editor (on the bottom) with the original editor (on the top): There are many more options available to us when adding descriptions of our materials or summaries of our courses. However, one of the most powerful new features is the ability to add and embed media directly from within this new HTML editor.   Question: What have been the improvements related to Moodle Quiz? Answer: The following are the improvements to Moodle Quiz: The set up page has been simplified Creating questions has been simplified It's possible to flag questions for later referral Questions can be accessed with one click in the post-quiz review and correct/ incorrect questions are color-coded in an easy-to access navigation block   Question: What are Cohorts? Answer: Cohort is Moodle 2.0's take on the long wished for site-wide groups. When we click on the link we're taken to the following screen where we click on Add to enter details of the cohort we want to create:   Question: Has there been any modification in the Filters menu as compared to the previous versions On/Off options? Answer: The Manage Filters in Moodle 2.0 equates to the Filters menu in Moodle 1.9. The Manage Filters screen looks like the following screenshot (note—the screenshot only displays the first three filters): Previously, filters were either On or Off. Now we have three choices: Disabled: Nobody, in any course, can enable a filter. On: A filter is enabled by default and teachers can disable if they wish to. Off but available: A filter is off but teachers can enable it in their own courses.   Question: What are the changes in Site Administration? Answer: Perhaps the simplest way to explore this is to look at how this menu has altered since Moodle 1.9: Notifications/Registrations: A small but important change in Moodle 1.9, the Notifications screen contained a button you could click to register your site with http://moodle.org/. The page this took you to now has its own billing in Moodle 2.0, as the Registration link. Community hubs: The main Moodle community hub is known as MOOCH and you register with it here. You can also register your site with other community hubs. If you register with hubs, then teachers can add a Community block in their courses where users can search for a suitable course to enroll in or download. Summary In this article we took a look at the queries regarding what Moodle 2.0 has to offer with the exciting new modules and enhanced features, and the major overhauls in the file uploading and navigation system. Further resources on this subject: Moodle 1.9 Math [Book] Moodle Administration [Book] Moodle 1.9 for Teaching Special Education Children (5-10): Beginner's Guide [Book] Moodle 2.0: What's New in Add a Resource [Article] What's New in Moodle 2.0 [Article]
Read more
  • 0
  • 0
  • 1438

article-image-advanced-aspects-inserting-and-deleting-data-mysql
Packt
01 Oct 2010
10 min read
Save for later

Advanced aspects of Inserting and Deleting data in MySQL

Packt
01 Oct 2010
10 min read
  MySQL Admin Cookbook 99 great recipes for mastering MySQL configuration and administration Set up MySQL to perform administrative tasks such as efficiently managing data and database schema, improving the performance of MySQL servers, and managing user credentials Deal with typical performance bottlenecks and lock-contention problems Restrict access sensibly and regain access to your database in case of loss of administrative user credentials Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible Read more about this book (For more resources on MySQL, see here.) Inserting new data and updating data if it already exists Manipulating data in a database is part of everyday work and the basic SQL means of INSERT, UPDATE, and DELETE make this a pretty straightforward, almost trivial task—but is this always true? When considering data manipulation, most of the time we think of a situation where we know the content of the database. With this information, it is usually pretty easy to find a way of changing the data the way you intend to. But what if you have to change data in circumstances where you do not know the actual database content beforehand? You might answer: "Well, then look at your data before changing it!" Unfortunately, you do not always have this option. Think of distributed installations of any software that includes a database. If you have to design an update option for this software (and the respective databases), you might easily come to a situation where you simply do not know about the actual database content. One example of a problem arising in these cases is the question of whether to insert or to update data: "Does the data in question already (partially) exist?" Let us assume a database table config that stores configuration settings. It holds key-value pairs, with name being the name (and thus the key) of the setting and value its value. This table exists in different database installations, one for every branch office of your company. Your task is to create an update package to set a uniform upper limit of 25% for the price discount that is allowed in your sales software. If no such limit has been defined yet, there is no respective entry in the config table, and you have to insert a new record. If the limit, however, has been set before (for example by the local manager), the entry does already exist, in which case you have to update it to hold the new value. While the update of a potentially existing entry does not pose a problem, an INSERT statement that violates uniqueness constraints will simply cause an error. This is, however, typically not acceptable in an automated update procedure. The following recipe will show you how to solve this problem with only one SQL command. Getting ready Besides a running MySQL server, a SQL client, and an account with appropriate user rights (INSERT, UPDATE), we need a table to update. In the earlier example, we assumed a table named sample.config with two character columns name and value. The name column is defined as the primary key: CREATE TABLE sample.config ( name VARCHAR(64) PRIMARY KEY, value VARCHAR(64)); How to do it... Connect to your database using your SQL client Execute the following command: mysql> INSERT INTO sample.config VALUES ("maxPriceDiscount","25%") ON DUPLICATE KEY UPDATE value='25%';Query OK, 1 row affected (0.05 sec) How it works... This command is easily explained because it simply does what it says: it inserts a new row in the table using the given values, as long as this does not cause a duplicate entry in either the primary key or another unique index. If a duplicate record exists, the existing row is updated according to the clauses defined after ON DUPLICATE KEY UPDATE. While it is sometimes tedious to enter some of the data and columns two times (once for the INSERT and a second time for the UPDATE), this statement allows for a lot of flexibility when it comes to the manipulation of potentially existing data. Please note that when executing the above statement, the result differs slightly with respect to the number of affected rows, depending on the actual data present in the database: When the record does not exist yet, it is inserted, which results in one affected row. But if the record is updated rather than inserted, it reports two affected rows instead, even if only one row gets updated. There's more... The INSERT INTO … ON DUPLICATE UPDATE construct does not work when there is no UNIQUE or PRIMARY KEY defined on the target table. If you have to provide the same semantics without having appropriate key definitions in place, it is recommended to use the techniques discussed in the next recipe. Inserting data based on existing database content In the previous recipe Inserting new data and updating data if it already exists, we discussed a method to either insert or update records depending on whether the records already exist in the database. A similar problem arises when you need to insert data to your database, but the data to insert depends on the data in your database. As an example, consider a situation in which you need to insert a record with a certain message into a table logMsgs, but the message itself should be different depending on the current system language that is stored in a configuration table (config). It is fairly easy to achieve a similar behavior for an UPDATE statement because this supports a WHERE clause that can be used to only perform an update if a certain precondition is met: UPDATE logMsgs SET message= CONCAT('Last update: ', NOW()) WHERE EXISTS (SELECT value FROM config WHERE name='lang' AND value = 'en');UPDATE logMsgs SET message= CONCAT('Letztes Update: ', NOW()) WHERE EXISTS (SELECT value FROM config WHERE name='lang' AND value = 'de');UPDATE logMsgs SET message= CONCAT('Actualisation derniere: ', NOW()) WHERE EXISTS (SELECT value FROM config WHERE name='lang' AND value = 'fr'); Unfortunately, this approach is not applicable to INSERT commands, as these do not support a WHERE clause. Despite this missing option, the following recipe describes a method to make INSERT statements execute only if an appropriate precondition in the database is met. Getting ready As before, we assume a database, a SQL client (mysql), and a MySQL user with sufficient privileges (INSERT and SELECT in this case). Additionally, we need a table to insert data into (here: logMsgs) and a configuration table config (please refer to the previous recipe for details). How to do it... Connect to your database using your SQL client. Execute the following SQL commands: mysql> INSERT INTO sample.logMsgs(message) -> SELECT CONCAT('Last update: ', NOW()) -> FROM sample.config WHERE name='lang' AND value='en';Query OK, 0 rows affected (0.00 sec)Records: 0 Duplicates: 0 Warnings: 0 How it works... Our goal is to have an INSERT statement take into account the present language stored in the database. The trick to do so is to use a SELECT statement as input for the INSERT. The SELECT command provides a WHERE clause, so you can use a condition that only matches for the respective language. One restriction of this solution is that you can only insert one record at a time, so the size of scripts might grow considerably if you have to insert lots of data and/or have to cover many alternatives. There's more... If you have more than just a few values to insert, it is more convenient to have the data in one place rather than distributed over several individual INSERT statements. In this case, it might make sense to consolidate the data by putting it inside a temporary table; the final INSERT statement uses this temporary table to select the appropriate data rows for insertion into the target table. The downside of this approach is that the user needs the CREATE TEMPORARY TABLES privilege, but it typically compensates with much cleaner scripts: After creating the temporary table with the first statement, we insert data into the table with the following INSERT statement. The next statement inserts the appropriate data into the target table sample.logMsgs by selecting the appropriate data from the temporary data that matches the language entry from the config table. The temporary table is then removed again. The final SELECT statement is solely for checking the results of the operation. Deleting all data from large tables Almost everyone who works with databases experiences the constant growth of the data stored in their database and it is typically well beyond the initial estimates. Because of that you often end up with rather large data sets. Another common observation is that in most databases, there are some tables that have a special tendency to grow especially big. If a table's size reaches a virtual threshold (which is hard to define, as it depends heavily on the access patterns and the data structures), it gets harder and harder to maintain and performance degradation might occur. From a certain point on, it is even difficult to get rid of data in the table again, as the sheer number of records makes deletion a pretty expensive task. This particularly holds true for storage engines with Multi-Version Concurrency Control (MVCC): if you order the database to delete data from the table, it must not be deleted right away because you might still roll back the deletion. So even while the deletion was initiated, a concurrent query on the table still has to be able to see all the records (depending on the transaction isolation level). To achieve this, the storage engine will only mark the records as deleted, but the actual deletion takes place after the operation is committed and all other transactions that access this table are closed as well. If you have to deal with large data sets, the most difficult task is to operate on the production system while other processes concurrently work on the data. In these circumstances, you have to keep the duration of your maintenance operations as low as possible in order to minimize the impact on the running system. As the deletion of data from a large table (typically starting at several millions of rows) might take quite some time, the following recipe shows a way of minimizing the duration of this operation in order to reduce side effects (like locking effects or performance degradation). Getting ready Besides a user account with appropriate privileges (DELETE), you need a sufficiently large table to delete data from. For this recipe, we will use the employees database, which is an example database available from MySQL: http://dev.mysql.com/doc/employee/en/employee.html This database provides some tables with sensible data and some pretty large tables, the largest having more than 2.8 million records. We assume that the Employees database was installed with an InnoDB storage engine enabled. To delete all rows of the largest table employees.salaries in a quick way, please read on. How to do it...
Read more
  • 0
  • 0
  • 3795
article-image-mysql-admin-configuring-innodb-and-installing-mysql-windows-service
Packt
01 Oct 2010
3 min read
Save for later

MySQL Admin: Configuring InnoDB and Installing MySQL as a Windows Service

Packt
01 Oct 2010
3 min read
In order to prevent the transactional nature of InnoDB from completely thwarting its performance, it implements what is called the redo log. In this recipe, we will present the relevant settings to (re-)configure a database server's redo log. Getting ready As the redo log setup is a part of the server configuration, you will need an operating system user account and sufficient rights to modify the server's configuration file. You will also need rights to restart the MySQL service because the redo log cannot be reconfigured on the fly. Moreover, an administrative MySQL user account is required to prepare the server for the shutdown, necessary as part of the procedure. Caution: As this recipe will modify the configuration of parameters critical to data integrity, you should make a backup copy of the configuration file before editing it! How to do it... Connect to the server using your administrative account. Issue the following command: mysql> SET GLOBAL innodb_fast_shutdown=0;Query OK, 0 rows affected (0.00 sec) Verify the setting like this: mysql> SHOW VARIABLES LIKE 'innodb_fast_shutdown'; Log off from MySQL and stop the MySQL server. Locate the MySQL configuration file, usually called my.cnf or my.ini (on Windows) and open it in a text editor. Locate the following parameters in the [mysqld] section (you values will vary, of course): [mysqld]...innodb_log_group_home_dir=/var/lib/mysql/redologinnodb_log_file_size=32Minnodb_log_buffer_size=64Minnodb_log_files_in_group=2... Edit the above configuration settings to their new values. If you require help on how to find suitable values, see the There's more... section of this recipe. Save the configuration file. Navigate to the directory configured for innodb_log_group_home_dir. If there is no such setting in your configuration file, navigate to MySQL's data directory that is then taken as the default. Move the files whose names start with ib_logfile to a backup location. Do not copy them; they must be removed from their original location. Restart the MySQL server. Verify that new files are created as you configured them: $ ls -l /var/lib/mysqld/redolog If you do not see the new files appear and the server does not start up correctly, check the MySQL error log for messages. Usually, the only thing that can go wrong here is that you either mistyped the directory name or did not actually remove the previous ib_logfile files. To restore everything back to the original configuration, restore your configuration file from the backup and restore the ib_logfile files you moved out to the backup to their original location. What just happened... By setting innodb_fast_shutdown to 0, you told the server to finish writing any pending changes to the disk before actually exiting. This makes sure there are no remaining transactions in the current redo logs that could get lost when these files are replaced. After that you could change the configuration to new values, possibly using a different number of files and different sizes. Then, before restarting, you could move the old redo log files out of the way. This is important because otherwise MySQL would complain about a mismatch between the settings file and the actual situation on disk. When it comes up finding no redo log files, it will create new ones with the settings just configured.
Read more
  • 0
  • 0
  • 1358

article-image-running-multiple-mysql-server-instances-parallel-linux-server
Packt
01 Oct 2010
5 min read
Save for later

Running Multiple MySQL Server Instances in Parallel on a Linux Server

Packt
01 Oct 2010
5 min read
  MySQL Admin Cookbook 99 great recipes for mastering MySQL configuration and administration Set up MySQL to perform administrative tasks such as efficiently managing data and database schema, improving the performance of MySQL servers, and managing user credentials Deal with typical performance bottlenecks and lock-contention problems Restrict access sensibly and regain access to your database in case of loss of administrative user credentials Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible Read more about this book (For more resources on MySQL, see here.) Introduction On most Linux setups, MySQL comes as a readymade installation package, making it easy to get started. It is, however, a little more complicated to run multiple instances in parallel, often a setup handy for development. This is because in contrast to Windows, MySQL is usually not installed in a self-contained directory, but most Linux distribution packages spread it across the appropriate system folders for programs, configuration files, and so on. You can, however, also install MySQL in its own directory, for example, if you need to use a version not available as a prepared package for your Linux distribution. While this gives you the greatest flexibility, as a downside you will have to take care of wiring up your MySQL server with the operating system manually. For example, you will need to hook up the startup and shutdown scripts with the appropriate facilities of your distribution. In more recent distributions, you can make use of a tool called mysqld_multi, a solution that lets you set up multiple instances of MySQL daemons with varying configurations. In this recipe, we will show you how to set up two parallel MySQL servers, listening on different TCP ports and using separate data directories for their respective databases. Getting ready This recipe is based on an Ubuntu Linux machine with the 8.04 LTS version. mysqld_multi comes with the MySQL packages for that operating system. If you are using other distributions, you need to make sure you have mysqld_multi installed to be able to follow along. Refer to your distribution's package repositories for information on which packages you need to install. You will also need an operating system user with sufficient privileges to edit the MySQL configuration file—typically /etc/mysql/my.cnf on Ubuntu—and restart services. As for AppArmor or SELinux, we assume these have been disabled before you start to simplify the process. How to do it... Locate and open the my.cnf configuration file in a text editor. Create the following two sections in the file: # mysqld_multi test, instance 1[mysqld1]server-id=10001socket=/var/run/mysqld/mysqld1.sockport=23306pid-file=/var/run/mysqld/mysqld1.piddatadir=/var/lib/mysql1log_bin=/var/log/mysql1/mysql1-bin.log# mysqld_multi test, instance 2[mysqld2]server-id=10002socket=/var/run/mysqld/mysqld2.sockport=33306pid-file=/var/run/mysqld/mysqld2.piddatadir=/var/lib/mysql2log_bin=/var/log/mysql2/mysql2-bin.log Save the configuration file. Issue the following command to verify the two sections are found by mysqld_multi: $ sudo mysqld_multi report Initialize the data directories: $ sudo mysql_install_db --user=mysql --datadir=/var/lib/mysql1$ sudo mysql_install_db --user=mysql --datadir=/var/lib/mysql2 Start both instances and verify they have been started: $ sudo mysqld_multi start 1$ sudo mysqld_multi report Connect to both instances and verify their settings: $ mysql -S /var/run/mysqld/mysql1.sockmysql> SHOW VARIABLES LIKE 'server_id'; How it works... mysqld_multi uses a single configuration file for all MySQL server instances, but inside that file each instance has its individual [mysqld] section with its specific options. mysqld_multi then takes care of launching the MySQL executable with the correct options to use the options from its corresponding section. The sections are distinguished by a positive number directly appended to the word mysqld in the section header. You can specify all the usual MySQL configuration file options in these sections, just as you would for a single instance. Make sure, however, to specify the minimum set of options as in the recipe steps previously stated, as these are required to be unique for every single instance. There's more... Some special preparation might be needed, depending on the particular operating system you are using. Turning off AppArmor / SELinux for Linux distributions If your system uses the AppArmor or SELinux security features, you will need to make sure these are either turned off while you try this out, or configured (for permanent use once your configuration has been finished) to allow access to the newly defined directories and files. See the documentation for your respective Linux distribution for more details on how to do this. Windows On Windows, running multiple server instances is usually more straightforward. MySQL is normally installed in a separate, self-contained folder. To run two or more independent server instances, you only need to install a Windows service for each of them and point them to an individual configuration file. Considering the alternative MySQL Sandbox project As an alternative to mysqld_multi you might want to have a look at MySQL Sandbox, which offers a different approach to hosting multiple independent MySQL installations on a single operating system. While mysqld_multi manages multiple configurations in a single file, MySQL Sandbox aims at completely separating MySQL installations from each other, easily allowing even several MySQL releases to run side by side. For more details, visit the project's website at http://mysqlsandbox.net Preventing invalid date values from being stored in DATE or DATETIME columns In this recipe, we will show you how to configure MySQL in a way such that invalid dates are rejected when a client attempts to store them in a DATE or DATETIME column using a combination of flags for the SQL mode setting. See the There's more... section of this recipe for some more detailed information on the server mode setting in general and on how to use it on a per-session basis. Getting ready
Read more
  • 0
  • 0
  • 6143