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 - CMS & E-Commerce

830 Articles
article-image-dynamic-theming-drupal-6-part-2
Packt
24 Oct 2009
8 min read
Save for later

Dynamic Theming in Drupal 6 - Part 2

Packt
24 Oct 2009
8 min read
Creating Dynamic CSS Styling In addition to creating dynamic templates, the Drupal system also enables you to apply CSS dynamically. Drupal creates unique identifiers for various elements of the system and you can use those identifiers to create specific CSS selectors. As a result, you can provide styling that responds to the presence (or absence) of specific conditions on any given page. Two of the most common uses of this technique are covered below: The creation of node-specific styles and the use of $body_classes. Using Dynamic Selectors for Nodes The system generates a unique ID for each node on the website. We can use that unique ID to activate a unique selector by applying this nomenclature for the selector: #node-[nid] {} For example, assume you wish to add a border to the node with the ID of 2. Simply create a new div in style.css with the name: #node-2 {border: 1px solid #336600} Changing the Body Class Based on body_classes One of the most useful dynamic styling tools introduced in Drupal 6 is the implementation of $body_classes. This variable is intended specifically as an aid to dynamic CSS styling. It allows for the easy creation of CSS selectors that are responsive to the layout of the page. This technique is typically used to control the styling where there may be one, two or three columns displayed, depending on the page and the content. Prior to Drupal 6, $layout was used to detect the page layout, that is, one, two or three columns. While $layout can technically still be used, the better practice is to use $body_classes. Implementing $body_classes is a simple matter; just add $body_classes to the body tag of your page.tpl.php file—the Drupal system will do the rest. Once the body tag is altered to include this variable, the class associated with the body tag will change automatically in response to the conditions on the page at that time. Now, all you have to do is create the CSS selectors that you wish to see applied in the various situations. Let's step through this with a quick example. Open up your page.tpl.php file and modify the body tag as follows: <body class="<?php print $body_classes; ?>"> This will now automatically create a class for the page based on the conditions on the page. The chart below shows the options this presents: Condition Class Available no sidebars .no-sidebar one sidebar .one-sidebar left sidebar visible .sidebar-left right sidebar visible .sidebar-right two sidebars .two-sidebars front page .front not front page .not-front logged in .logged-in not logged in .not-logged-in page visible .page-[page type               node visible .node-type-[name of type]       $body_classes provides the key to easily creating a theme that includes collapsible sidebars. To set up this functionality, modify the page.tpl.php file to include $body_classes. Now, go to the style.css file and create the following selectors: .one-sidebar {}.sidebar-left {}.sidebar-right {}.no-sidebar {}.two-sidebars {} The final step is to create the styling for each of the selectors above (as you see fit). When the site is viewed, the system-generated value of $body_classes will determine which selector is applied. You can now specify, through the selectors above, exactly how the page appears—whether the columns collapse, the resulting widths of the remaining columns, and so on , and so on. Working with Template Variables As we have seen, above, Drupal produces variables that can be used to enhance the functionality of themes. Typically, a theme-related function returns values reflecting the state of the page on the screen. A function may indicate, for example, whether the page is the front page of the site, or whether there are one, two, or three active columns (for example, the variable $body_classes). Tapping into this information is a convenient way for a theme developer to style a site dynamically. The default Drupal variables cover the most common (and essential) functions, including creating unique identifiers for items. Some of the Drupal variables are unique to particular templates; others are common to all. In addition to the default variables, you can also define your own variables. Using the function theme_preprocess(), you can either set new variables, or unset existing ones that you do not want to use. In Drupal 6, preprocess functions have made working with variables easier and cleaner. By using the preprocessor, you can set up variables within your theme that can be accessed by any of your templates. The code for the preprocess function is added to your template.php file, thereby keeping the actual template files (the .tpl.php files) free of unnecessary clutter. Note that the preprocess functions only apply to theming hooks implemented as templates; plain theme functions do not interact with the preprocessors. In Drupal 5 and below, the function _phptemplate_variables served the same purpose as the preprocess function. For a list of the expected preprocess functions and their order of precedence, see http://drupal.org/node/223430 Typically, if you wish to implement a preprocessor applicable to your theme, you will use one of the following:   Name of preprocessor Application [engineName]_preprocess This namespace should be used for your base theme. Should be named after the theme engine used by the theme. Will apply to all hooks. [engineName]_preprocess_ [hookname] Should be used for your base theme. Also named after the theme engine applicable to the theme but note that it is specific to a single hook. [themeName]_preprocess This namespace should be used for subthemes. Will apply to all hooks. [themeName]_preprocess_ [hookname] Should be used for subthemes. Note that it is specific to a single hook. Let's look first at intercepting and overriding the default variables and then at creating your own variables. Intercepting and Overriding Variables You can intercept and override the system's existing variables. Intercepting a variable is no different in practice from intercepting a themable function: you simply restate it in the template.php file and make your modifications there, leaving the original code in the core intact. To intercept an existing variable and override it with your new variable, you need to use the function _phptemplate_preprocess(). Add this to your template.php file according to the following syntax: <?phpfunction phptemplate_preprocess(&$vars) {$vars['name'] = add your code here...;}?> Note that nothing should be returned from these functions. The variables have to be passed by reference, as indicated by the ampersand before variables, e.g., &$vars. Let's take a very basic example and apply this. Let's override $title inpage.tpl.php. To accomplish this task, add the following code to the template.php file: <?php function phptemplate_preprocess(&$vars) { $vars['title'] = 'override title';}?> Remember to clear your theme registry! With this change made and the file saved to your theme, the string override title will appear, substituted for the original $title value. Making New Variables Available The preprocess function also allows you to define additional variables in your theme. To create a new variable, you must declare the function in the template.php file. In order for your theme to have its preprocessors recognized, the template associated with the hook must exist inside the theme. If the template does not exist in your theme, copy one and place it in the theme directory. The syntax is the same as that just used for intercepting and overriding a variable, as seen above. The ability to add new variables to the system is a powerful tool and gives you the ability to add more complex logic to your theme. Summary In this two part article we covered the basics needed to make your Drupal theme responsive to the contents and the users. By applying the techniques discussed here, you can control the theming of pages based on content, state of the page or the users viewing them. Taking the principles one step further, you can also make the theming of elements within a page conditional. The ability to control the templates used and the styling of the page and its elements is what we call dynamic theming. We covered not only the basic ideas behind dynamic theming, but also the techniques needed to implement this powerful tool. Among the items discussed at length were the use of suggestions to control template display, and the implementation of $body_classes. Also covered in this article, was the use of the preprocess function to work with variables inside your theme
Read more
  • 0
  • 0
  • 1158

article-image-dynamic-theming-drupal-6-part-1
Packt
24 Oct 2009
9 min read
Save for later

Dynamic Theming in Drupal 6 - Part 1

Packt
24 Oct 2009
9 min read
Using Multiple Templates Most advanced sites built today employ multiple page templates. In this section, we will look at the most common scenarios and how to address them with a PHPTemplate theme. While there are many good reasons for running multiple page templates, you should not create additional templates solely for the purpose of disabling regions to hide blocks. While the approach will work, it will result in a performance hit for the site, as the system will still produce the blocks, only to then wind up not displaying them for the pages. The better practice is to control your block visibility. Using a Separate Admin Theme With the arrival of Drupal 5, one of the most common Drupal user requests was satisfied; that is, the ability to easily designate a separate admin theme. In Drupal, designating a separate theme for your admin interface remains a simple matter that you can handle directly from within the admin system. To designate a separate theme for your admin section, follow these steps: Log in and access your site's admin system. Go to Administer | Site configuration | Administration theme. Select the theme you desire from the drop-down box listing all the installed themes. Click Save configuration, and your selected theme should appear immediately. Multiple Page or Section Templates In contrast to the complete ease of setting up a separate administration theme is the comparative difficulty of setting up multiple templates for different pages or sections. The bad news is that there is no admin system shortcut—you must manually create the various templates and customize them to suit your needs. The good news is that creating and implementing additional templates is not difficult and it is possible to attain a high degree of granularity with the techniques described below. Indeed, should you be so inclined, you could literally define a distinct template for each individual page of your site. Drupal employs an order of precedence based on a naming convention (or "suggestions" as they are now being called on the Drupal site). You can unlock the granularity of the system through proper application of the naming convention. It is possible, for example, to associate templates with every element on the path, or with specific users, or with a particular functionality—all through the simple process of creating a new template and naming it appropriately. The system will search for alternative templates, preferring the specific to the general, and failing to find a more specific template, will apply the default page.tpl.php. Consider the following example of the order of precedence and the naming convention in action. The custom templates above could be used to override the default page.tpl.php and theme either an entire node (page-node.tpl.php), or simply the node with an ID of 1 (page-node-1.tpl.php),or the node in edit mode (page-node-edit.tpl.php), depending on the name given the template. In the example above, the page-node templates would be applied to the node in full page view. In contrast, should you wish to theme the node in its entirety, you would need to intercept and override the default node.tpl.php. The fundamental methodology of the system is to use the first template file it finds and ignore other, more general templates (if any). This basic principle, combined with proper naming of the templates, gives you control over the template used in various situations. The default suggestions provided by the Drupal system should be sufficient for the vast majority of theme developers. However, if you find that you need additional suggestions beyond those provided by the system, it is possible to extend your site and add new suggestions. See http://drupal.org/node/223440 for a discussion of this advanced Drupal theming technique. Let's take a series of four examples to show how this feature can be used to provide solutions to common problems: Create a unique homepage template. Use a different template for a group of pages. Assign a specific template to a specific page. Designate a specific template for a specific user. Create a Unique Homepage Template Let's assume that you wish to set up a unique template for the homepage of a site. Employing separate templates for the homepage and the interior pages is one of the most common requests web developers hear. With Drupal, you can, without having to create a new template, achieve some variety within a theme by controlling the visibility of blocks on the homepage. If that simple technique does not give you enough flexibility, you will need to consider using a dedicated template that is purpose-built for your homepage content. The easiest way to set up a distinct front page template is to copy the existing page.tpl.php file, rename it, and make your changes to the new file. Alternatively, you can create a new file from scratch. In either situation, your front-page-specific template must be named page-front.tpl.php. The system will automatically display your new file for the site's homepage, and use the default page.tpl.php for the rest of the site. Note that page-front.tpl.php is whatever page you specify as the site's front page via the site configuration settings. To override the default homepage setting visit Administer | Site configuration | Site information, then enter the URL you desire into the field labeled Default home page. Use a Different Template for a Group of Pages Next, let's associate a template with a group of pages. You can provide a template to be used by any distinct group of pages, using as your guide the path for the pages. For example, to theme all the user pages you would create the template page-user.tpl.php. To theme according to the type of content, you can associate your page template with a specific node, for example, all blog entry pages can be controlled by the filepage-blog-tpl.php. The table below presents a list of suggestions you can employ to theme various pages associated with the default functionalities in the Drupal system. Suggestion Affected Page page-user.tpl.php user pages page-blog.tpl.php blog pages (but not the individual node pages) page-forum.tpl.php forum pages (but not the individual node pages) page-book.tpl.php book pages (but not the individual node pages) page-contact.tpl.php contact form (but not the form content)   Assign a Specific Template to a Specific Page Taking this to its extreme, you can associate a specific template with a specific page. By way of example, assume we wish to provide a unique template for a specific content item. Let's assume our example page is located at http://www.demosite.com/node/2/edit. The path of this specific page gives you a number of options. We could theme this page with any of the following templates (in addition to the default page.tpl.php): page-node.tpl.php page-node-2.tpl.php page-node-edit.tpl.php A Note on Templates and URLsDrupal bases the template order of precedence on the default path generated by the system. If the site is using a module like pathauto, which alters the path that appears to site visitors, remember that your templates will still be displayed based on the original paths. The exception here being page-front.tpl.php, which will be applied to whatever page you specify as the site's front page via the site configuration settings (Administer | Site configuration| Site information). Designate a Specific Template for a Specific User Assume that you want to add a personalized theme for the user with the ID of 1(the Drupal equivalent of a Super Administrator). To do this, copy the existing page.tpl.php file, rename it to reflect its association with the specific user, and make any changes to the new file. To associate the new template file with the user, name the file: page-user-1.tpl. Now, when user 1 logs into the site, they will be presented with this template. Only user 1 will see this template and only when he or she is logged in and visiting the account page. The official Drupal site includes a collection of snippets relating to the creation of custom templates for user profile pages. The discussion is instructive and worth review, though you should always be a bit cautious with user-submitted code snippets as they are not official releases from the Drupal Association. See, http://drupal.org/node/35728 Dynamically Theming Page Elements In addition to being able to style particular pages or groups of pages, Drupal and PHPTemplate make it possible to provide specific styling for different page elements. Associating Elements with the Front Page Drupal provides $is_front as a means of determining whether the page currently displayed is the front page. $is_front is set to true if Drupal is rendering the front page; otherwise it is set to false. We can use $is_front in our page.tpl.php file to help toggle display of items we want to associate with the front page. To display an element on only the front page, make it conditional on the state of $is_front. For example, to display the site mission on only the front page of the site, wrap $mission (in your page.tpl.php file) as follows: <?php if ($is_front): ?> <div id="mission"> <?php print $mission; ?> </div><?php endif; ?> To set up an alternative condition, so that one element will appear on the front page but a different element will appear on other pages, modify the statement like this: <?php if ($is_front): ?> //whatever you want to display on front page<?php else: ?> //what is displayed when not on the front page<?php endif; ?> $is_front is one of the default baseline variables available to all templates.
Read more
  • 0
  • 0
  • 2197

article-image-miro-interview-nicholas-reville
Packt
24 Oct 2009
6 min read
Save for later

Miro: An Interview with Nicholas Reville

Packt
24 Oct 2009
6 min read
Kushal Sharma: What is the vision behind Miro? Nicholas Reville: There's an opportunity to build a new, open mass medium of online television. We're developing the Miro Internet TV platform so that watching Internet video channels will be as easy as watching TV and broadcasting a channel will be open to everyone. Unlike traditional TV, everyone will have a voice. KS: Does PCF finance the entire project or do you have any other contributors? NR: We have tons of help from volunteers – translating the software, coding, testing, and providing user support. We would not be able to do nearly enough without our community. KS: Are the developers full-time PCF employees or is it similar to other Open Source projects where people voluntarily contribute to the community in their spare-time? NR: We have 6 full-time developers and also volunteers. We're a hybrid model, like Mozilla. KS: Please highlight the most crucial features of Miro, and the idea behind having those features as part of this application. NR: The most crucial feature of Miro is the ability to download and play video RSS feeds. It's a truly open way to distribute video online. Using RSS means that creators can publish with any company they want and users can bring together video from multiple sources into one application. KS: How many languages is Miro translated into? NR: Miro is at least partially translated into more than 40 languages, but we always need helping revising and improving the translations. KS: How is Miro different from other players from the technological perspective? NR: Above all, Miro is open-source. That means that anyone can work on the code, improve, and customize it. Beyond this, Miro is unique in a number of ways. It runs on Mac, Windows, and Linux. It can play almost any video format. And it has more HD content available than any other Internet TV application. KS: Are the Torrent download capabilities as well developed as any other standalone Bit Torrent Client? Please tell us something more about it's download capabilities, the share ratio, configurable upload limits while downloading the torrents etc. compared to other software? NR: Our current version of Miro keeps the BitTorrent capabilities very simple and doesn't provide many options. We think that most users don't even notice when they are downloading a torrent feed, however, we want to expand our options and features for power users in future versions – expect much more bit torrent control in 3 months or so. KS: What type of support do you have for Miro? NR: Most of our support is provided user-to-user in the discussion forums – they are very useful, actually. In addition, because we are an open project, anyone can file a bug or even fix a bug. In the long-term this means we will have a more stable user experience than closed competitors. KS: With a host of TV channels and video content going online, viewers could really use a common solution for all their media needs rather than keeping tabs on multiple sources. How do you see Miro being instrumental in providing this? NR: We think that an open platform for video is the only way to create a unified experience for video. Miro is the only really open Internet video solution right now and we think we have a crucial role to play in unifying Internet TV in an open way. KS: Does Miro download Internet TV programs and store it on the hard disk or does it stream live media like any other online service? NR: For now, Miro downloads everything that's watched. This is useful in two key ways: first, you can watch HD video with no skipping or buffering delays. Second, you can move those files onto any external device, with no DRM or other restrictions. In the future we may add a streaming option for some special cases, or the ability to start watching while the download is in progress. KS: Subscription-free content is a great gift that viewers get with Internet TV, however, bandwidth issues could be a concern for some users. What minimum bandwidth requirements would you suggest for satisfactory Internet TV performance on Miro? Furthermore, does Miro have an alternate solution for users having low Internet bandwidth? NR: Miro actually works better than most Internet video solutions for low bandwidth users. On a dial-up connection, streaming video solutions are unusable. Miro will download videos in those circumstances – it may happen slowly, but once you have the video you can watch it full speed with no skipping. KS: I remember a statement on the PCF site saying “Miro is designed to eliminate gatekeepers”. Could you please elaborate on this? NR: Miro works with open standards and is designed to be decentralized, like the web. That means that users can use Miro to connect directly to any video publisher – they don't need our permission and the files don't travel through our servers. Companies like Joost design their software to be highly centralized so that they can control both users and creators. It's time to leave that model behind. KS: So far, what has the response been like? NR: Response has been great. Last month alone, we had more than 200,000 downloads and we've been growing with each release. I expect that when we release version 1.0 in November we'll see even faster growth. KS: What are your future plans for Miro in terms of releases, updates, functionality, etc.? NR: After version 1.0 is released, we'll be making major changes to Miro to improve performance and add an extension system that will give people new ways of customizing the software to fit their needs. KS: To me, Miro’s agenda is a lot more than simply creating a good player. You’re attempting to change the face of Internet Video and the way it’s being hosted right now. How would you describe the future of Miro and Internet Video to our readers? NR: We want Miro to push online video in an open direction. We're hoping to build the best video experience possible, something that can be a true substitute for traditional television. But that doesn't mean we want to control the future of online video – we want other people to build open video distribution platforms as well. Openness is vital to the future of our mass media. KS: What other projects is the PCF involved in? NR: Right now, PCF is exclusively focused on making video more open and Miro is at the center of that. KS: Thank you for your time Nicholas, and good luck developing Miro!
Read more
  • 0
  • 0
  • 1503
Visually different images

article-image-jquery-table-manipulation-part-2
Packt
24 Oct 2009
6 min read
Save for later

jQuery Table Manipulation: Part 2

Packt
24 Oct 2009
6 min read
Advanced Row Striping Row striping can be as simple as two lines of code to alternate the background color: $(document).ready(function() {   $('table.sortable tbody tr:odd').addClass('odd');   $('table.sortable tbody tr:even').addClass('even'); }); If we declare background colors for the odd and even classes as follows, we can see the rows in alternating shades of gray: tr.even {   background-color: #eee; } tr.odd {   background-color: #ddd; } While this code works fine for simple table structures, if we introduce non‑standard rows into the table, such as sub-headings, the basic odd-even pattern no longer suffices. For example, suppose we have a table of news items grouped by year, with columns for date, headline, author, and topic. One way to express this information is to wrap each year's news items in a <tbody> element and use <th colspan="4"> for the subheading. Such a table's HTML (in abridged form) would look like this: <table class="striped"> <thead> <tr> <th>Date</th> <th>Headline</th> <th>Author</th> <th class="filter-column">Topic</th> </tr> </thead><tbody> <tr> <th colspan="4">2007</th> </tr> <tr> <td>Mar 11</td> <td>SXSWi jQuery Meetup</td> <td>John Resig</td> <td>conference</td> </tr> <tr> <td>Feb 28</td> <td>jQuery 1.1.2</td> <td>John Resig</td> <td>release</td> </tr> <tr> <td>Feb 21</td> <td>jQuery is OpenAjax Compliant</td> <td>John Resig</td> <td>standards</td> </tr> <tr> <td>Feb 20</td> <td>jQuery and Jack Slocum's Ext</td> <td>John Resig</td> <td>third-party</td> </tr></tbody><tbody> <tr> <th colspan="4">2006</th> </tr> <tr> <td>Dec 27</td> <td>The Path to 1.1</td> <td>John Resig</td> <td>source</td> </tr> <tr> <td>Dec 18</td> <td>Meet The People Behind jQuery</td> <td>John Resig</td> <td>announcement</td> </tr> <tr> <td>Dec 13</td> <td>Helping you understand jQuery</td> <td>John Resig</td> <td>tutorial</td> </tr></tbody><tbody> <tr> <th colspan="4">2005</th> </tr> <tr> <td>Dec 17</td> <td>JSON and RSS</td> <td>John Resig</td> <td>miscellaneous</td> </tr></tbody></table> With separate CSS styles applied to <th> elements within <thead> and <tbody>, a snippet of the table might look like this: To ensure that the alternating gray rows do not override the color of the subheading rows, we need to adjust the selector expression: $(document).ready(function() { $('table.striped tbody tr:not([th]):odd').addClass('odd'); $('table.striped tbody tr:not([th]):even').addClass('even');}); The added selector, :not([th]), removes any table row that contains a <th> from the matched set of elements. Now the table will look like this: Three-color Alternating Pattern There may be times when we want to apply more complex striping. For example, we can apply a pattern of three alternating row colors rather than just two. To do so, we first need to define another CSS rule for the third row. We'll also reuse the odd and even styles for the other two, but add more appropriate class names for them: tr.even,tr.first { background-color: #eee;}tr.odd,tr.second { background-color: #ddd;}tr.third { background-color: #ccc;} To apply this pattern, we start the same way as the previous example—by selecting all rows that are descendants of a <tbody>, but filtering out the rows that contain a <th<. This time, however, we attach the .each() method so that we can use its built-in index: $(document).ready(function() { $('table.striped tbody tr').not('[th]').each(function(index) { //Code to be applied to each element in the matched set. });}); To make use of the index, we can assign our three classes to a numeric key: 0, 1, or 2. We'll do this by creating an object, or map: $(document).ready(function() { var classNames = { 0: 'first', 1: 'second', 2: 'third' }; $('table.striped tbody tr').not('[th]').each(function(index) { // Code to be applied to each element in the matched set. });}); Finally, we need to add the class that corresponds to those three numbers, sequentially, and then repeat the sequence. The modulus operator, designated by a %, is especially convenient for such calculations. A modulus returns the remainder of one number divided by another. This modulus, or remainder value, will always range between 0 and one less than the dividend. Using 3 as an example, we can see this pattern: 3/3 = 1, remainder 0.4/3 = 1, remainder 1.5/3 = 1, remainder 2.6/3 = 2, remainder 0.7/3 = 2, remainder 1.8/3 = 3, remainder 2. And so on. Since we want the remainder range to be 0 – 2, we can use 3 as the divisor (second number) and the value of index as the dividend (first number). Now we simply put that calculation in square brackets after classNames to retrieve the corresponding class from the object variable as the .each() method steps through the matched set of rows: $(document).ready(function() { var classNames = { 0: 'first', 1: 'second', 2: 'third' }; $('table.striped tbody tr').not('[th]').each(function(index) { $(this).addClass(classNames[index % 3]); });}); With this code in place, we now have the table striped with three alternating background colors: We could of course extend this pattern to four, five, six, or more background colors by adding key-value pairs to the object variable and increasing the value of the divisor in classNames[index % n].
Read more
  • 0
  • 0
  • 3674

article-image-development-login-management-module-and-comment-management-module
Packt
24 Oct 2009
12 min read
Save for later

Development of Login Management Module and Comment Management Module

Packt
24 Oct 2009
12 min read
Lets get started right away. Developing the Login Management Module Even though Login and session handling are separate functionalities from User management, they depend on the same table—user. Also, the functionalities are more alike than different. Hence, instead of creating a new Controller, we will be using the UserController itself as the Controller for the Login module. Keeping this point in mind, let us look at the steps involved in developing the Login Management, which are: Creating the Login page Implementing the Authentication Method Setting up the Session Applying Authorization Leaving aside the first step, all other steps mainly focus on the Controller. Here we go. Creating the Login Page We need a login page with text boxes for user name and password in which users can put their credentials and submit to the login authenticator (fancy name for the action method that will contain the logic to authenticate the user). That's what we are going to create now. The convention for any website is to show the login page when the user enters the URL without any specific page in mind. RoR also follows this convention. For example, if you enter the URL as http://localhost:3000/user, it displays the list of users. The reason is that the index action method of the UserController class calls the list method whenever the aforementioned URL is used. From this, we can understand two things—first, the default action method is index, and second, the first page to be shown is changeable if we change the index method. What we need is to show the login page whenever a user enters the URLhttp://localhost:3000/user. So let's change the index method. Open theuser_controller.rb file from the app/views/user folder and remove all the statements from the body of the index method so that it looks like as follows: def indexend Next, let us create an index.rhtml file, which will be shown when the index method is called. This file will be the login page. In the app/views/user folder, create an index.rhtml file. It will be as follows <%= form_tag :action=> 'authenticate'%><table ><tr align="center" class="tablebody"><td>User name:</td><td><%= text_field("user", "user_name",:size=>"15" ) %></td></tr><tr align="center" class="tablebody"><td>Password:</td><td><%= password_field("user","password",:size=>"17" ) %></td></tr><tr align="center" class="tablebody"><td></td><td><input type="submit" value=" LOGIN " /></td></tr></table> It uses two new form helpers—text_field and password_field. The text_field creates a text field with the name passed as the parameter, and the password_field creates a password field again with the name passed as the parameter. We have passed the authenticate method as the action parameter so that the form is submitted to the authenticate method. That completes the login page creation. Next, we will work on the authenticate method. Implementing the Authenticate method Implementing the Authenticate method Authenticating a user essentially means checking whether the user name and password given by the user corresponds to the one in database or not. In our case, the user gives us the user name and password through the login page. What we will be doing is checking whether the user is in database and does the password that we got corresponds to the password stored in the database for the user? Here, we will be working on two levels: Model Controller We can put the data access part in the action method that being the Controller itself. But it will create problems in the future if we want to add something extra to the user name/password checking code. That's why we are going to put (or delegate) the data access part into Model. Model We will be modifying the User class by adding a method that will check whether the user name and password provided by the user is correct or not. The name of the method is login. It is as follows: def self.login(name,password)find(:first,:conditions => ["user_name = ? and password =?",name, password])end It is defined as a singleton method of the User class by using the self keyword. The singleton methods are special class-level methods. The conditions parameter of the find method takes an array of condition and the corresponding values. The find method generates an SQL statement from the passed parameters. Here, the find method finds the first record that matches the provided user_name and password. Now, let us create the method that the Controller will call to check the validity of the user. Let us name it check_login. The definition is as follows: def check_loginUser.login(self.user_name, self.password)end This function calls the login method. Now if you observe closely, check_login calls the login function. One more point to remember—if a method 'test' returns a value and you call 'test' from another method 'test1,' then you don't need to say 'return test' from within 'test1'.The value returned from 'test' will be returned by 'test1' implicitly. That completes the changes to be done at the Model level. Now let us see the changes at the Controller-level. Controller In the Controller for User—UserController—add a new method named authenticate. The method will first create a User object based on the user name and password. Then it will invoke check_login on the newly created User object. If check_login is successful, that is, it does not return nil, then the user is redirected to the list view of Tales. Otherwise, the user is redirected to the login page itself. Here is what the method will look like: def authenticate@user = User.new(params[:user])valid_user = @user.check_loginif logged_in_userflash[:note]="Welcome "+logged_in_user.nameredirect_to(:controller=>'tale',:action => "list")elseflash[:notice] = "Invalid User/Password"redirect_to :action=> "index"endend The redirect_to method accepts two parameters—the name of the Controller and the method within the Controller. If the user is valid, then the list method of TaleController is called, or in other words, the user is redirected to the list of tales. Next, let us make it more robust by checking for the get method. If a user directly types a URL to an action, then the get method is received by the method. If any user does that, we want him/her to be redirected to the login page. To do this, we wrap up the user validation logic in an if/else block. The code will be the following: def authenticate if request.get?render :action=> 'index'else@user = User.new(params[:user])valid_user = @user.check_loginif valid_userflash[:note]="Welcome "+valid_user.user_nameredirect_to(:controller=>'tale',:action => 'list')else flash[:notice] = "Invalid User/Password"redirect_to :action=> 'index'endendend The get? method returns true if the URL has the GET method else it returns false. That completes the login authentication part. Next, let us set up the session. In Ruby, any method that returns a Boolean value—true or false—is suffixed with a question mark (?). The get method of the request object returns a boolean value. So it is suffixed with a question mark (?). Setting up the Session Once a user is authenticated, the next step is to set up the session to track the user. Session, by definition, is the conversation between the user and the server from the moment the user logs in to the moment the user logs out. A conversation is a pair of requests by the user and the response from the server. In RoR, the session can be tracked either by using cookies or the session object. The session is an object provided by RoR. The session object can hold objects where as cookies cannot. Therefore, we will be using the session object. The session object is a hash like structure, which can hold the key and the corresponding value. Setting up a session is as easy as providing a key to the session object and assigning it a value. The following code illustrates this aspect: def authenticateif request.get?render :action=> 'index'else@user = User.new(params[:user])valid_user = @user.check_loginif valid_usersession[:user_id]=valid_user.idflash[:note]="Welcome "+valid_user.user_nameredirect_to(:controller=>'tale',:action => 'list')elseflash[:notice] = "Invalid User/Password"redirect_to :action=> 'index'endendend That completes setting up the session part. That brings us to the last step—applying authorization. Applying Authorization Until now, we have authenticated the user and set up a session for him/her. However, we still haven't ensured that only the authenticated users can access the different functionalities of TaleWiki. This is where authorization comes into the picture. Authorization has two levels—coarse grained and fine grained. Coarse grained authorization looks at the whole picture whereas the fine grained authorization looks at the individual 'pixels' of the picture. Ensuring that only the authenticated users can get into TaleWiki is a part of coarse grained authorization while checking the privileges for each functionality comes under the fine grained authorization. In this article, we will be working with the coarse grained authorization. The best place to apply the coarse grained authorization is the Controller as it is the central point of data exchange. Just like other aspects, RoR provides a functionality to easily apply any kind of logic on the Controller as a whole in the form of filters. To jog your memory, a filter contains a set of statements that need to be executed before, after (or before and after) the methods within the Controllers are executed. Our problem is to check whether the user is authenticated or not, before any method in a Controller is executed. The solution to our problem is using a 'before filter'. But we have to apply authorization to all the Controllers. Hence, the filter should be callable from any of the Controller. If you look at the definition of a Controller, you can find such a place. Each Controller is inherited from the ApplicationController. Anything placed in ApplicationController will be callable from other Controllers. In other words, any method placed in ApplicationController becomes global to all the Controllers within your application. So, we will place the method containing the filter logic in ApplicationController. To check whether a user is authentic or not, the simplest way is to check whether a session exists for that person or not. If it exists, then we can continue with the normal execution. Let us name it check_authentic_user. The implementation will be as follows: def check_authentic_userunless session[:user_id]flash[:notice] = "Please log in"redirect_to(:controller => "user", :action =>"index")endend It checks for the user_id key in a session. If it is not present, the user is redirected to the login page. Place the code in the application.rb file as a method of ApplicationController. Next, let us use it as a filter. First, we will tell UserController to apply the filter for all the action methods except index and authenticate methods. Add the following statement to the UserController. It should be the first statement after the starting of the Controller class. class UserController < ApplicationControllerbefore_filter :check_authentic_user, :except =>[ :index, :authenticate ]::end Similarly, we will place the filter in other Controllers as well. However, in their case, there are no exceptions. So TaleController will have: class TaleController < ApplicationControllerbefore_filter :check_authentic_user::end GenreController and RoleController will be the same as TaleController. Thus, we have completed the 'applying authorization' part for the time being. Now, let's tie up one loose end—the problem of adding a new tale. Tying Up the Loose Ends When we developed the User management, the Tale management was affected as the tales table has a many-to-one relationship with the users table. Now we can solve the problem created by the foreign key reference. First, open the user.rb file and add the following statement indicating that it is at the 'one' end of the relationship: has_many :tale After addition of the statement, the class will look like the following: class User < ActiveRecord::Basevalidates_presence_of :user_name, :password, :first_name,:last_name, :age, :email, :country validates_uniqueness_of :user_namevalidates_numericality_of :age validates_format_of :email, :with => /A([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})Z/ibelongs_to :rolehas_many :taledef check_loginUser.login(self.name, self.password)enddef self.login(name,password)find(:first,:conditions => ["user_name = ? and password=?",name, password])endend Next, add the following statement to the tale.rb file: belongs_to :user The file will look like as follows: class Tale < ActiveRecord::Basevalidates_presence_of :title, :body_text, :sourcebelongs_to:genrebelongs_to :userend Next, open the tale_controller.rb file. In the create method, we need to add the user's id to the tale's user id reference so that the referential integrity can be satisfied. For that, we will get the current user's id from the session and set it as the value of the user_id attribute of the tale object. The create method will look like as follows, after doing the changes: def create @tale = Tale.new(params[:tale])@tale.genre_id=params[:genre]@tale.user_id=session[:user_id]@tale.status="new" if @tale.saveflash[:notice] = 'Tale was successfully created.'redirect_to :action => 'list'elserender :action => 'new'endend That's it. The 'loose ends' related to the User management are tied up. Now let us move onto the Comment Management module.
Read more
  • 0
  • 0
  • 965

Packt
23 Oct 2009
3 min read
Save for later

Lotus Notes 8 — Productivity Tools

Packt
23 Oct 2009
3 min read
IBM Lotus Documents      IBM Lotus Presentations      IBM Lotus Spreadsheets These productivity tools are also referred to as document editors, since you use them to create and edit documents in various formats (word processing, presentations, and spreadsheets respectively). Productivity Tools Integration with Notes 8 The Eclipse architecture of the Notes 8 client supports the integration of other applications. One key example of this is the integration of the productivity tools. The preferences for the tools are in the Preferences interface. When opening the preference options for the productivity tools, you will see the following: This setting will load a file called soffice.exe. This file corresponds to a stub that remains resident so that the tools will launch more quickly. If you do not want this to occur, choose the setting not to pre-load the productivity tools. The productivity tools are independent of the Domino 8 server. This means that the tools will function without a Lotus Domino 8 server. They can even be launched when the Notes client is not running. To do this, either double-click on the icon on your desktop, or select the program from the Start menu. Productivity Tools and Domino Policies A Domino administrator can control the productivity tools through a Productivity Tools policy setting. This gives the administrator the ability to control who can use the tools (and also control whether or not macros are permitted to run). It will also control what document types will be opened by the productivity tools. IBM Lotus Documents The IBM Lotus Documents productivity tool is a document editor that allows you to create documents containing graphics, charts, and tables. You can save your documents in multiple formats. IBM Lotus Documents has a spell checker, which provides for instant corrections, and many other tools that can be used to enhance documents. No matter what the complexity of the documents that you are creating or editing, this productivity tool can handle the job. IBM Lotus Presentations The IBM Lotus Presentations tool will allow you to create professional presentations featuring multimedia, charts, and graphics. The presentations tool comes with templates that you can use to create your slide shows. If you wish, you can create and save your own templates as well. The templates that you create should be saved to the following directory: Notesframeworksharedeclipsepluginscom. ibm.productivity.tools.template.en_3.0.0.20070428-1644layout. (You can save a template in a different directory, but you'll need to navigate to it when creating a new presentation from that template.) Not only can you apply dynamic effects to the presentations, but you can also publish them in a variety of formats. IBM Lotus Spreadsheets As its name indicates, IBM Lotus Spreadsheets is a tool used to create spreadsheets. You can use this tool to calculate, display, and analyze your data. As with other spreadsheet applications, the tool allows you to use functions to create formulas that perform advanced calculations with your data. One feature gives you the ability to change one factor in a calculation with many factors so that the user can see how it effects the calculation. This is useful when exploring multiple scenarios. IBM Lotus Spreadsheets also has a dynamic function that will automatically update charts when the data changes. Summary In this article, we have reviewed the productivity tools provided with the Notes 8 client. These tools include IBM Lotus Documents, IBM Lotus Presentations, and IBM Lotus Spreadsheets. We have briefly examined how these tools are integrated with Notes 8, and how they are controlled by Domino policy documents.
Read more
  • 0
  • 0
  • 1253
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 $15.99/month. Cancel anytime
article-image-local-user-management-freenas
Packt
23 Oct 2009
6 min read
Save for later

Local User Management in FreeNAS

Packt
23 Oct 2009
6 min read
Local User Management The first step to creating a user is in fact to create a group. Each user must belong to a group. Groups are sets of users who are associated with one another. So in your business, you might have a sales group and a engineering group. At home, you probably only want one group, for example home. To create a group, go to Access: Users and Groups and click on the Group tab. Now click on the add circle. The form is very simple; you need to add a name and a description. For example sales and "The sales people". Now click Add and then apply the changes. Only a-z, A-Z, and 0-9 are supported in the group name. _ (underscores) and spaces are not supported, neither are punctuation characters like $%&* etc. Now that you have a group created, you can create a user. Click on the Users tab. And then on the add circle. Login: This is the unique login name of user. If the user already has a login name on other servers or workstations, like a Windows user name or a Linux user name, it is best to keep it the same here. This way the user doesn't need to try an remember an extra username and also some programs (particularly Windows) try and log in with the Windows user name before asking which name it should use. Keeping them the same will ease integration. Full Name: The user's full name. Often, the login name is an abbreviation or short name for the user like john, gary. Here you need to enter the full name so that it is easy to tell which login name belongs to which person. Password: Their password (with confirmation). The colon ':' character isn't allowed in the password. Primary Group: The group to which they belong, for example sales. There are four mandatory fields: To finish, you need to click Add and apply the changes. You now have a user added to your FreeNAS server. Let's look at what effect adding a user has on the rest of the FreeNAS server. Using CIFS with Local Users To use the users you have defined with Windows networking, you need to go to the Services: CIFS/SMB page and change the Authentication field to Local User. Then click Save and Restart to apply your changes. What this means is that only authenticated users can now access the FreeNAS shares via CIFS. In version 0.6, this user authentication is for all the shares, the user has access to everything or nothing. This should change with 0.7. When trying to connect now from a Windows Vista machine, a window pops up asking for a user name and password. Once authenticated, the user has access to all the user shares on the FreeNAS server. FTP and User Login On the Services: FTP, there are two fields that control how users log in to the FreeNAS server: Anonymous login: This allows you to enable anonymous login. This means the user connects with the user name anonymous and any password. Local User: This enables a local user login. Users log in using the user name and passwords defined in the Access: Users and Groups page. The two can be used together; however, they do negate one another in terms of security. It is best to run the FTP with either anonymous logins enabled and local user logins disabled or vice versa. If you run with both enabled, then people can still log in using the anonymous method even if they don't have a user account and so, it diminishes the benefits of having the user accounts enabled. Other than the security benefits, another advantage of local user login with FTP is that you can define a home directory for the user and when the user logs in, they will be taken to that directory and only they have access to that directory and those below it. This effectively offers each user their own space on the server and other users cannot interfere with their files. To get this working, you need to create a directory on your shared disk. You can do this with any of the access protocols CIFS, NFS, FTP, and AFS. You need to connect to the shared disk and create a new folder. Then, in Access: Users, either create a new user or edit an existing one (by clicking on the 'e' in a circle). In the Homedirectory, you need to enter the directory for that user. For example for the user john, you might create a directory cunningly named john. Assuming the disk is named store (as per the quick start guide) then the path for the home directory would be: /mnt/store/john. Click Save and apply the changes. Now when John logs in using the user name john he will be taken directly to the john directory. He doesn't have access to other files or folders on the store disk, only those in john and any sub folder. chroot() Everyone, but Root In the advanced settings section of the Services: FTP page, there is a field called chroot() everyone, but root. What this means is that when a user logs in via FTP, the root directory (top or start directory) for them will be the directory set in the Home directory field. Without this set, the user will log in to the server at the physical / and will see the server in its entirety including the FreeNAS and FreeBSD system files. It is much safer to have this box checked. The exception to this is the user root (which in FreeBSD terms is the system administer account). If Permit root login is enabled, then the user root can log in and they will be taken to the root of the actual server. This can be useful if you ever need to alter any of the system files on the FreeNAS, but this isn't recommend unless you absolutely know what you are doing!
Read more
  • 0
  • 0
  • 8910

article-image-integrating-twitter-and-youtube-mediawiki
Packt
23 Oct 2009
5 min read
Save for later

Integrating Twitter and YouTube with MediaWiki

Packt
23 Oct 2009
5 min read
Twitter in MediaWiki Twitter (http://www.twitter.com) is a micro-blogging service that allows users to convey the world (or at least the small portion of it on Twitter) what they are doing, in messages of 140 characters or less. It is possible to embed these messages in external websites, which is what we will be doing for JazzMeet. We can use the updates to inform our wiki's visitors of the latest JazzMeet being held across the world, and they can send a response to the JazzMeet Twitter account. Shorter Links Because Twitter only allows posts of up to 140 characters, many Twitter usersmake use of URL-shortening services such as Tiny URL (http://tinyurl.com), and notlong (http://notlong.com) to turn long web addresses into short, more manageable URLs. Tiny URL assigns a random URL such as http://tinyurl.com/3ut9p4, while notlong allows you to pick a free sub-domain to redirect to your chosen address, such as http://asgkasdgadg.notlong.com. Twitter automatically shortens web addresses in your posts. Creating a Twitter Account Creating a Twitter account is quite easy. Just fill in the username, password, and email address fields, and submit the registration form, once you have read and accepted the terms and conditions. If your chosen username is free, your account is created instantly. Once your account has been created, you can change the settings such as your display name and your profile's background image, to help blur the distinction between your website and your Twitter profile. Colors can be specified as "hex" values under the Design tab of your Twitter account's settings section. The following color codes change the link colors to our JazzMeet's palette of browns and reds: As you can see in the screenshot, JazzMeet's Twitter profile now looks a little more like the JazzMeet wiki. By doing this, the visitors catching up with JazzMeet's events on Twitter will not be confused by a sudden change in color scheme:   Embedding Twitter Feeds in MediaWiki Twitter provides a few ways to embed your latest posts in to your own website(s); simply log in and go to http://www.twitter.com/badges. Flash: With this option you can show just your posts, or your posts and your friends' most recent posts on Twitter. HTML and JavaScript: You can configure the code to show between 1 and 20 of your most recent Twitter posts. As JazzMeet isn't really the sort of wiki the visitors would expect to find on Flash, we will be using the HTML and JavaScript version. You are provided with the necessary code to embed in your website or wiki. We will add it to the JazzMeet skin template, as we want it to be displayed on every page of our wiki, just beneath our sponsor links. Refer to the following code: <div id="twitter_div"><h2 class="twitter-title">Twitter Updates</h2><ul id="twitter_update_list"></ul></div><script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script><script type="text/javascript" src="http://twitter.com/statuses/user_timeline/jazzmeet.json?callback=twitterCallback2&count=5"></script> The JavaScript given at the bottom of the code can be moved just above the </body> tag of your wiki's skin template. This will help your wiki to load other important elements of your wiki before the Twitter status. You will need to replace "jazzmeet" in the code with your own Twitter username, otherwise you will receive JazzMeet's Twitter updates, and not your own. It is important to leave the unordered list of ID twitter_update_list as it is, as this is the element the JavaScript code looks for to insert a list item containing each of your twitter messages in the page. Styling Twitter's HTML We need to style the Twitter HTML by adding some CSS to change the colors and style of the Twitter status code: #twitter_div {background: #FFF;border: 3px #BEB798 solid;color: #BEB798;margin: 0;padding: 5px;width: 165px;}#twitter_div a {color: #8D1425 !important;}ul#twitter_update_list {list-style-type: none;margin: 0;padding: 0;}#twitter_update_list li {color: #38230C;display: block;}h2.twitter-title {color: #BEB798;font-size: 100%;} There are only a few CSS IDs and classes that need to be taken care of. They are as follows: #twitter_div is the element that contains the Twitter feeds. #twitter_update_list is the ID applied to the unordered list. Styling this affects how your Twitter feeds are displayed. .twitter-title is the class applied to the Twitter feed's heading (which you can remove, if necessary). Our wiki's skin for JazzMeet now has JazzMeet's Twitter feed embedded in the righthand column, allowing visitors to keep up-to-date with the latest JazzMeet news. Inserting Twitter as Page Content Media Wiki does not allow JavaScript to be embedded in a page via the "edit" function, so you won't be able to insert a Twitter status feed directly in a page unless it is in the template itself. Even if you inserted the relevant JavaScript links into your MediaWiki skin template, they are relevant only for one Twitter profile ("jazzmeet", in our case).  
Read more
  • 0
  • 0
  • 3471

article-image-openfire-effectively-managing-users
Packt
23 Oct 2009
14 min read
Save for later

Openfire: Effectively Managing Users

Packt
23 Oct 2009
14 min read
Despite the way it sounds, managing users isn't an all-involving activity—at least it shouldn't be. Most system administrators tend to follow the "install-it-forget-it" methodology to running their servers. You can do so with Openfire as well, but with a user-centeric service such as an IM server, keeping track of things isn't a bad idea. Openfire makes your job easier with its web-based admin interface. There are several things that you can setup via the web interface that'll help you manage the users. You can install some plugins that'll help you run and manage the server more effectively, such as the plugin for importing/exporting users, and dual-benefit plugins such as the search plugin, which help users find other users in the network, and also let you check up on users using the IM service. In this article, we will cover: Searching for users Getting email alerts via IM Broadcasting messages to all users Managing user clients Importing/exporting users Searching for Users with the SearchPlugin Irrespective of whether you have pre-populated user rosters, letting users find other users on the network is always a good idea. The Search Plugin works both ways—it helps your users find each other, and also helps you, the administrator, to find users and modify their settings if required. To install the plugin, head over to the Plugins tab (refer to the following screenshot). The Search plugin is automatically installed along with Openfire, and will be listed as a plugin that is already installed. It's still a good idea to restart the plugin just to make sure that everything's ok. Locate and click the icon in the Restart column that corresponds to the Search plugin. This should restart the plugin. The Search plugin has various configurable options, but by default the pluginis deployed with all of its features enabled. So your users can immediately start searching for users. To tweak the Search plugin options, head over to the Server | Server Settings |Search Service Properties in the Openfire admin interface. From this page, you can enable or disable the service. Once enabled, users will be able to search for other users on the network from their clients. Not all clients have the Search feature but Spark, Exodus, Psi, and some others do. Even if you disable this plugin, you, the admin, will still be able to search for users from the Openfire admin interface as described in the following section. In addition to enabling the Search option, you'll have to name it. The plugin is offered as a network "service" to the users. The Openfire server offers other services and also includes the group chat feature which we will discuss in the Appendix. Calling the search service by its default name, search.< your-domain-name > is a goodidea. You should only change it if you have another service on your network with the same name. Finally, you'll have to select the fields users can search on. The three options available are Username, Name, and Email (refer to the previous screenshot). You can enable any of these options, or all the three for a better success rate. Once you're done with setting up the options, click the Save Properties button to apply them. To use the plugin, your users will have to use their clients to query the Openfire server and then select the search service from the ones listed. This will present them with a search interface through which they'll be able to search for their peers(refer to the following screenshot) using one or more of the three options (Username,Name, Email), depending on what you have enabled. Searching for Users from Within The Admin Interface So we've let our users look for their peers, but how do you, the Openfire admin, look for users? You too can use your client, but it's better to do it from the interface since you can tweak the user's settings from there as well. To search for users from within the admin interface, head over to the Users/Groups tab. You'll notice an AdvancedUser Search option in the sidebar. When you click on this option, you'll be presented with a single text field withthree checkboxes (refer to the previous screenshot). In the textfield, enter the user'sName, Username, and Email that you want to find. The plugin can also handle the * wildcard character so that you can search using a part of the user's details as well.For example, if you want to find a user "James", but don't know if his last name isspelled "Allen" or "Allan", try entering "James A*" in the search field and make sure that the Name checkbox is selected. Another example would be "* Smith", which looks for all the users with the last name "Smith". The search box is case-sensitive. So why were you looking for "James Allan", the guy with two first names? It was because his last name is in fact "Allen" and he wants to get it corrected. So you find his record with the plugin and click on his username. This brings up a summary of his properties including his status, the groups he belongs to, when he was registeredon the network, and so on. Find and click the Edit Properties button below the details, make the required changes, and click the Save Properties > button. Get Email Alerts via IM Instant Messaging is an alternate line of enterprise communication, along with electronic ones such as email and traditional ones such as the telephone. Some critical tasks require instant notification and nothing beats IM when it comes to time-critical alerts. For example, most critical server software applications, especially the ones facing outwards on to the Internet, are configured to send an email to the admin in case of an emergency—for example, a break-in attempt, abnormal shutdown, hardware failure, and so on. You can configure Openfire to route these messages to you as an IM, if you're online. If you're a startup that only advertises a single [email protected] email address which is read by all seven employees of the company, you can configure Openfire to send IMs to all of you when the VCs come calling! Setting this up isn't an issue if you have the necessary settings handy. The email alert service connects to the email server using IMAP and requires the following options: Mail Host: The host running the email service. Example: imap.example.com Mail Port: The port through which Openfire listens for new email. SSL can also be used if it is enabled on your mail server. Example: 993. Server Username: The username of the account you want to monitor.Example: [email protected]. Server Password: The accounts password. Folder: The folder in which Openfire must look for new messages. Typically this will be the "Inbox" but if your server filters email that meet a preset criteria into a particular folder, you need to specify it here. Check Frequency: How frequently Openfire should check the account for new email. The default value is 300000 ms which is equal to 5 minutes. JID of users to notify: This is where you specify the Openfire Jabber IDs(userids) of the users you want to notify when a new email pops up. If you need to alert multiple users, separate their JID's with commas. But first head over to the Plugins tab and install the Email Listener plugin from the list of available plugins. Once you have done this, head back to the Server tab and choose the Email Listener option in the sidebar and enter the settings in the form that pops up (refer to the following screenshot). Click the Test Settings button to allow Openfire to try to connect to the server using the settings provided. If the test is successful, finish off the setup procedure by clicking the Save button to save your settings. If the test fails, check the settings and make sure that the email server is up and running. You can test and hook them with your Gmail account as well. That's it. Now close that email client you have running in the background, and let Openfire play secretary, while you write your world domination application! Broadcasting Messages Since Openfire is a communication tool, it reserves the coolest tricks in the bag for that purpose. The primary purpose of Openfire remains one-to-one personal interactions and many-to-many group discussion, but it can also be used as a one-to-many broadcasting tool. This might sound familiar to you. But don't sweat, I'm not repeating myself. The one-to-many broadcasting we cover in this section is different from the Send Message tool. The Send Message tool from the web-based Openfire administration console is available only to the Openfire administrator. But the plugin we cover in this section has a much broader perspective. For one, the Broadcast plugin can be used by non-admin users, though of course, you can limit access. Secondly, the Broadcast plugin can be used to send messages to a select group of users which can grow to include everyone in the organization using Openfire. One use of the broadcast plugin is for sending important reminders. Here are some examples: The Chief Accounts Officer broadcasts a message to everyone in the organization reminding them to file their returns by a certain date. The CEO broadcasts a message explaining the company's plans to merge with or acquire another company, or just to share a motivational message. You, the Openfire administrator, use the plugin to announce system outages. The Sales Department Head is upset because sales targets haven't been met and calls for a group meeting at 10:00 a.m. on the day after tomorrow and in forms everyone in the Sales department via the plugin. The intern in the advertisement department sends a list of his accounts to everyone in the department before returning to college and saves everyone a lot of running around, thanks to the plugin. Setting up the Plugin To reap the benefits of the Broadcast plugin, begin by installing it from under theAvailable Plugins list on the Plugins tab. This plugin has a few configuration options which should be set carefully—using a misconfigured broadcast plugin, the new guy in the purchase department could send a message of "Have you seen my stapler?" to everyone in the organization, including the CEO! The broadcast plugin is configured via the Openfire system properties. Remember these? They are listed under the Server tab's System Properties option in the sidebar. You'll have to manually specify the settings using properties (refer to the following screenshot): plugin.broadcast.serviceName— This is the name of the broadcast service. By default, the service is called "broadcast", but you can call it something else, such as "shout", or "notify". plugin.broadcast.groupMembersAllowed— This property accepts two values—true and false. If you select the "true" option, all group members will be allowed to broadcast messages to all users in the group they belong to. If set to "false", only group admins can send messages to all members of their groups. The default value is "true". plugin.broadcast.disableGroupPermissions— Like the previous property, this property also accepts either true or false values. By selecting the "true" option, you will allow any user in the network to broadcast messages to any group and vice versa, the "false" option restricts the broadcasting option to group members and admins. The default value of this group is "false". As you can imagine, if you set this value to "true" and allow anyone to send broadcast messages to a group, you effectively override the restrictive value of the previous setting. plugin.broadcast.allowedUsers—Do not forget to set this property! If it is not set, anyone on the network can send a message to everyone else on the network. There are a only a few people you'd want to have the ability to broadcast a message to everyone in the organization. This list of users who can talk to everyone should be specified with this property by a string of comma-separated JIDs. In most cases, the default options of these properties should suffice. If you don't change any variables, your service will be called "broadcast" and will allow group members to broadcast messages to their own groups and not to anyone else. You should also add the JIDs of executive members of the company (CEO, MD, etc.) to the list of users allowed to send messages to everyone in the organization. Using The Plugin Once you have configured the plugin, you'll have to instruct users on how to use the plugin according to the configuration. To send a message using the broadcast plugin, users must add a user with the JID in the following format @. (refer to the following screenshot). If the CEO wants to send a message to everyone, he has to send it to a user called [email protected], assuming that you kept the default settings, and that your Openfire server is called serverfoo. Similarly, when members of the sales department want to communicate with their departmental collegues, they have to send the message to [email protected]. Managing User Clients There's no dearth of IM clients. It's said that if you have ten users on your network, you'll have at least fifteen different clients. Managing user's clients is like bringing order to chaos. In this regard you'll find that Openfire is biased towards its own IMclient, Spark. But as it has all the features you'd expect from an IM client and runs on multiple platforms as well, one really can't complain. So what can you control using the client control features? Here's a snapshot: Don't like users transferring files? Turn it off, irrespective of the IM client. Don't like users experimenting with clients? Restrict their options Don't want to manually install Spark on each and every user's desktop? Put it on the network, and send them an email with a link, along with installation and sign-in instructions. Do users keep forgetting the intranet website address? Add it as a bookmark in their clients. Don't let users bug you all the time asking for the always-on "hang-out"conference room. Add it as a bookmark to their client! Don't these features sound as if they can take some of the work off your shoulders? Sure, but you'll only truly realize how cool and useful they are when you implement them! So what are you waiting for? Head over to the Plugins tab and install the Client Control plugin. When it is installed, head over to the Server | ClientManagement tab. Here you'll notice several options. The first option under client management, Client Features, lets you enable or disable certain client features (refer to the following screenshot). These are: Broadcasting: If you don't want your users to broadcast messages, disable this feature. This applies only to Spark. File Transfer: Disabling this feature will stop your users from sharing files.This applies to all IM clients. Avatar/VCard: You can turn off indiscriminate changes to a user's avatar or virtual visiting card by disabling this experimental feature which only applies to Spark. Group Chat: Don't want users to join group chat rooms? Then disable this feature which will prevent all the users from joining discussion groups, irrespective of the IM client they are using. By default, all of these features are enabled. When you've made changes as per your requirements, remember to save the settings using the Save Settings button. Next, head over to the Permitted Clients option (refer to the following screenshot) to restrict the clients that users can employ. By default, Openfire allows all XMPPclients to connect to the server. If you want to run a tight ship, you can decide to limit the number of clients allowed by selecting the Specify Clients option button. From the nine clients listed for the three platforms supported by Openfire (Windows,Linux, and Mac), choose the clients you trust by selecting the checkbox next to them.If your client isn't listed, use the Add Other Client text box to add that client. When you've made your choices, click on the Save Settings button to save and implement the client control settings. The manually-added clients are automatically added to the list of allowed clients. If you don't trust them, why add them? The remove link next to these clients will remove them from the list of clients you trust.
Read more
  • 0
  • 0
  • 4535

article-image-web-cms
Packt
23 Oct 2009
17 min read
Save for later

Web CMS

Packt
23 Oct 2009
17 min read
Let's get started. Do you want a CMS or a portal? We are evaluating a CMS for our Yoga Site. But you may want to build something else. Take a look again at the requirements. Do you need a lot of dynamic modules such as an event calendar, shopping cart, collaboration module, file downloads, social networking, and so on? Or you need modules for publishing and organizing content such as news, information, articles, and so on? Today's top-of-the-line Web CMSs can easily work as a portal. They either have a lot of built-in functionality or a wide range of plug-ins that extend their core features. Yet, there are solutions specifically made for web portals. You should evaluate them along with CMS software if your needs are more like a portal. On the other hand, if you want a simple corporate or personal web site, with some basic needs, you don't require a mammoth CMS. You can use a simple CMS that will not only fulfill your needs, but will also be easier to learn and maintain. Joomla! is a solid CMS. But it requires some experience to get used to it. For this article, let's first evaluate a simpler CMS. How do we know which CMS is simple? I think we can't go wrong with a CMS that's named "CMS Made Simple". Evaluating CMS Made Simple As the name suggests, CMS Made Simple (http://www.cmsmadesimple.org/) is an easy-to-learn and easy-to-maintain CMS. Here's an excerpt from its home page: If you are an experienced web developer, and know how to do the things you need to do, to get a site up with CMS Made Simple is just that, simple. For those with more advanced ambitions there are plenty of addons to download. And there is an excellent community always at your service. It's very easy to add content and addons wherever you want them to appear on the site. Design your website in whatever way or style you want and just load it into CMSMS to get it in the air. Easy as that! That makes things very clear. CMSMS seems to be simple for first-time users, and extensible for developers. Let's take CMSMS to a test drive. Time for action-managing content with CMS Made Simple Download and install CMS Made Simple. Alternatively, go to the demo a thttp://www.opensourcecms.com/. Log in to the administration section. Click on Content | Image Manager. Using the Upload File option, upload the Yoga Site logo. Click on Content | Pages option from the menu. You will see a hierarchical listing of current pages on the site. The list is easy to understand. Let's add a new page by clicking on the Add NewContent link above the list. The content addition screen is similar to a lot of other CMSs we have seen so far.There are options to enter page title, category, and so on. You can add page content using a large WYSIWYG editor. Notice that we can select a template for the page. We can also select a parent page.Since we want this page to appear at the root level, keep the Parent as none. Add some Yoga background information text. Format it using the editor as you see fit. There are two new options on this editor, which are indicated by the orange palmtree icons. These are two special options that CMSMS has added: first, to insert a menu; and second, to add a link to another page on the site. This is excellent. It saves us the hassle of remembering, or copying, links. Select a portion of text in the editor. Click on the orange palm icon with the link symbol on it. Select any page from the fly out menu. For now, we will link to the Home page. Click on the Insert/edit Image icon. Then click on the Browse icon next to the ImageURL field in the new window that appears. Select the logo we uploaded and insert it into content. Click on Submit to save the page. The Current Pages listing now shows our Background page. Let's bring it higher in the menu hierarchy. Click on the up arrow in the Move column on our page to push it higher. Do this until is at the second position—just after Home. That's all. We can click on the magnifying glass icon at the main menu bar's rightside to preview our site. Here's how it looks. What just happened? We set up the CMSMS and added some content to it. We wanted to use an image in ourcontent page. To make things simpler, we first uploaded an image. Then we went to the current pages listing. CMSMS shows all pages in the site in a hierarchical display. It's a simplefeature that makes a content administrator's life very easy. From there, we went on to createa new page. CMSMS has a WYSIWYG editor, like so many other CMSs we have seen till now. The content addition process is almost the same in most CMSs. Enter page title and related information,type in content, and you can easily format it using a WYSIWYG editor. We inserted the logo image uploaded earlier using this editor. CMSMS features extensions to the default WYSIWYG editor. These features demonstrate all of the thinking that's gone into making this software. The orange palm tree icon appearing on the WYSIWYG editor toolbar allowed us to insert a link to another page with a simple click. We could also insert a dynamic menu from within the editor if needed. Saving and previewing our site was equally easy. Notice how intuitive it is to add and manage content. CMS Made Simple lives up to its namein this process. It uses simple terms and workflow to accomplish tasks at hand. Check out the content administration process while you evaluate a CMS. After all, it's going to be your most commonly used feature! Hierarchies: How deep do you need them?What level of content hierarchies do you need? Are you happy with two levels? Do you like Joomla!'s categories -> sections -> content flow ? Or do you need to go even deeper? Most users will find two levels sufficient. But if you need more, find out if the CMS supports it. (Spoiler: Joomla! is only two-level deepby default.) Now that we have learned about the content management aspect of CMSMS, let's see how easily we can customize it. It has some interesting features we can use. Time for action-exploring customization options Look around the admin section. There are some interesting options. The third item in the Content menu is Global Content Blocks. Click on it. The name suggests that we can add content that appears on all pages of the site from there. A footer block is already defined. Our Yoga Site can get some revenue by selling interesting products. Let's create a block to promote some products on our site. Click on the Add Global Content Block link at the bottom. Let's use product as the name. Enter some text using the editor. Click on Submit to save. Our new content block will appear in the list. Select and copy Tag to Use this Block. Logically, we need to add this tag in a template. Select Layout | Templates from the main menu. If you recall, we are using the Left simple navigation + 1 column template. Click on the template name. This shows a template editor. Looking at this code we can make out the structure of a content page. Let's add the new content block tag after the main page content. Paste the tag just after the {* End relational links *} text. The tag is something like this. Save the template. Now preview the site. Our content block shows up after mainpage content as we wanted. Job done! What just happened? We used the global content block feature of CMSMS to insert a product promotion throughout our site. In the process, we learned about templates and also how we could modify them. Creating a global content block was similar to adding a new content page. We used the WYSIWYG editor to enter content block text. This gave us a special tag. If you know about PHP templates, you will have guessed that CMSMS uses Smarty templates and the tag was simply a custom tag in Smarty. Smarty Template EngineSmarty (http://www.smarty.net/) is the most popular template engine for the PHP programming language. Smarty allows keeping core PHP code and presentation/HTML code separate. Special tags are inserted in template files as placeholders for dynamic content. Visit http://www.smarty.net/crashcourse.php and http://www.packtpub.com/smarty/book for more. Next, we found the template our site was using. We could tell it by name, since the template shows up in a drop down in the add new pages screen as well. We opened the template and reviewed it. It was simple to understand—much like HTML. We inserted our product content block tag after the main content display. Then we saved it and previewed our site. Just as expected, the product promotion content showed up after main content of all pages. This shows how easy it is to add global content using CMSMS. But we also learned that global content blocks can help us manage promotions or commonly used content. Even if you don't go for CMS Made Simple, you can find a similar feature in the CMS of your choice. Simple features can make life easierCMS Made Simple's Global Content Block feature made it easy to run product promotions throughout a site. A simple feature like that can make the content administrator's life easier. Look out for such simple things that could make your job faster and easier in the CMS you evaluate. It's good time now to dive deeper into CMSMS. Go ahead and see whether it's the right choice for you. Have a go hero-is it right for you? CMS Made Simple (CMSMS) looks very promising. If we wanted to build a standard website with a photo gallery, newsletter, and so on, it is a perfect fit. Its code structure is understandable, the extending functionality is not too difficult. The default templates could be more appealing, but you can always create your own. The gentle learning curve of CMSMS is very impressive. The hierarchical display of pages,easy reordering, and simplistic content management approach are excellent. It's simple to figure out how things work. Yet CMSMS is a powerful system—remember how easily we could add a global content block? Doing something like that may need writing a plug-in or hacking source code in most other systems. It's the right time for you to see how it fits your needs. Take a while and evaluate the following: Does it meet your feature requirements? Does it have enough modules and extensions for your future needs? What does its web site say? Does it align with your vision and philosophy? Does it look good enough? Check out the forums and support structure. Do you see an active community? What are its system requirements? Do you have it all taken care of? If you are going to need customizations, do you (or your team) comfortably understand the code? We are done evaluating a simple CMS. Let us now look at the top two heavyweights in the Web CMS world—Drupal and Joomla!. Diving into Drupal Drupal (http://www.drupal.org) is a top open source Web CMS. Drupal has been around for years and has excellent architecture, code quality, and community support. The Drupal terminology can take time to sink in. But it can serve the most complicated content management needs. FastCompany and AOL's Corporate site work on Drupal:  Here is the About Drupal section on the Drupal web site. As you can see, Drupal can be used for almost all types of content management needs. The goal is to allow easy publishing and management of a wide variety of content. Let's try out Drupal. Let's understand how steep the learning curve really is, and why so many people swear by Drupal. Time for action-putting Drupal to the test Download and install Drupal. Installing Drupal involves downloading the latest stable release, extracting and uploading files to your server, setting up a database, and then following the instructions in a web installer. Refer to http://drupal.org/getting-started/ if you need help. Log in as the administrator. As you log in, you see a link to Create Content. This tells you that you can either create a page (simple content page) or a story (content with comments). We want to create a simple content page without any comments. So click on Page. In Drupal, viewing a page and editing a page are almost the same. You log in to Drupal and see site content in a preview mode. Depending on your rights, you will see links to edit content and manage other options. This shows the Create Page screen. There is a title but no WYSIWYG editor. Yes, Drupal does not come with a WYSIWYG text editor by default. You have to install an extension module for this. Let's go ahead and do that first. Go to the Drupal web site. Search for WYSIWYG in downloads. Find TinyMCE in the list. TinyMCE is the WYSIWYG editor we have seen in most other CMSs. Download the latest TinyMCE module for Drupal—compatible with your version of Drupal. The download does not include the actual TinyMCE editor. It only includes hooks tomake the editor work with Drupal. Go to the TinyMCE web site http://tinymce.moxiecode.com/download.php. Download the latest version. Create a new folder called modules in the sites/all/ folder of Drupal. This is theplace to store all custom modules. Extract the TinyMCE Drupal module here. It should create a folder named tinymcewithin the modules folder. Extract the TinyMCE editor within this folder. This creates a subfolder called tinymce within sites/all/modules/tinymce. Make sure the files are in the correct folders. Here's how your structure will look: Log in to Drupal if you are not already logged in. Go toAdminister | Site building | Modules. If all went well so far, at the end of the list of modules, you will find TinyMCE. Check the box next to it and click on Save Configuration to enable it. We need to perform two more steps before we can test this. Go to Administer |Site configuration | TinyMCE. It will prompt you that you don't have any profiles created. Create a new profile. Keep it enabled by default. Go to Administer | User management | Permissions. You will get this link from theTinyMCE configuration page too. Allow authenticated users to access tinymce. Then save permissions. We are now ready to test. Go to the Create Content | Page link. Super! The shiny WYSIWYG editor is now functional! It shows editing controls belowthe text area (all the other CMSs we saw so far show the controls above). Go ahead and add some content. Make sure to check Full HTML in Input Format.Save the page. You will see the content we entered right after you save it. Congratulations! What just happened? We deserve congratulations. After installing Drupal, we spotted that it did not come with a WYSIWYG editor. That's a bit of a setback. Drupal claims to be lightweight, but it should come with a nice editor, right? There are reasons for not including an editor by default. Drupal can be used for a variety of needs, and different WYSIWYG editors provide different features. The reason for not including any editor is to allow you to use the one that you feel is the best. Drupal is about a strong core and flexibility. At the same time, not getting a WYSIWYG editor by default was an opportunity. It was our opportunity to see how easy it was to add a plug-in to Drupal. We went to the Drupal site and found the TinyMCE module. The description of the module mentioned that the module is only a hook to TinyMCE. We need to download TinyMCE separately. We did that too. Hooks are another strength of Drupal. They are an easy way to develop extensions for Drupal. An additional function of modules is to ensure that we download a version compatible with Drupal's version. Mismatched Drupal and module versions create problems. We created a new directory within sites/all. This is the directory in which all custom modules/extensions should be stored. We extracted the module and TinyMCE ZIP files. We then logged on to the Drupal administration panel. Drupal had detected the module. We enabled it and configured it. The configuration process was multi step. Drupal has a very good access privilege system, but that made the configuration process longer. We not only had to enable the module, but also enable it for users. We also configured how it should show up, and in which sections. These are superb features for power users. Once all this was done, we could see a WYSIWYG editor in the content creation page. We used it and created a new page in Drupal. Here are the lessons we learned: Don't assume a feature in the CMS. Verify if that CMS has what you need. Drupal's module installation and configuration process is multistep and may require some looking around. Read the installation instructions of the plug-in. You will make fewer mistakes that way. Drupal is lightweight and is packed with a lot of power. But it has a learning curve of its own. With those important lessons in our mind, let's look around Drupal and figure out our way. Have a go hero-figure out your way with Drupal We just saw what it takes to get a WYSIWYG editor working with Drupal. This was obviously not a simple plug-and-play setup! Drupal has its way of doing things. If you are planning to use Drupal, it's a good time to go deeper and figure your way out with Drupal. Try out the following: Create a book with three chapters. Create a mailing list and send out one newsletter. Configure permissions and users according to your requirements. What if you wanted to customize the homepage? How easily can you do this? (Warning: It's not a simple operation with most CMSs.) Choosing a CMS is very confusing!Evaluating and choosing a CMS can be very confusing. Don't worry if you feel lost and confused among all the CMSs and their features. The guiding factors should always be your requirements, not the CMS's features. Figure out who's going to use the CMS—developers or end users. Find out all you need: Do you need to allow customizing the homepage? Know your technology platform. Check the code quality of the CMS—bad code can gag you. Does your site need so many features? Is the CMS only good looking, or is it beauty with brains? Consider all this in your evaluation. Drupal code quality Drupal's code is very well-structured. It's easy to understand and extend it via the hooks mechanism. The Drupal team takes extreme care in producing good code. Take a look at the sample code here. If you like looking around code, go ahead and peek into Drupal. Even if you don't use Drupal as a CMS, you can learn more about programming best practices. Now let's do a quick review and see some interesting Joomla! features.
Read more
  • 0
  • 0
  • 2159
article-image-customizing-drupal-6-interface
Packt
23 Oct 2009
19 min read
Save for later

Customizing Drupal 6 Interface

Packt
23 Oct 2009
19 min read
There is quite a lot involved in coming up with an entirely fresh, pleasing, and distinct look for a site. There are lots of fiddly little bits to play around with, so you should be prepared to spend some time on this section after all, a site's look and feel is really the face you present to the community, and in turn, the face of the community presents to the outside world. Take some time to look at what is already out there. Many issues that you will encounter while designing a site have already been successfully dealt with by others, and not only by Drupal users of course. Also, don't be scared to treat your design as an ongoing process while it is never good to drastically change sites on a weekly basis, regular tweaking or upgrading of the interface can keep it modern and looking shiny new. Planning a Web-Based Interface The tenet form follows function is widely applied in many spheres of human knowledge. It is a well understood concept that states the way something is built or made must reflect the purpose it was made for. This is an exceptionally sensible thought, and applying it to the design of your site will provide a yardstick to measure how well you have designed it. That's not to say one site should look like every other site that performs the same function. In fact, if anything, you want to make it as distinctive as possible, without stepping over the bounds of what the target user will consider good taste or common sense. How do you do that? The trick is to relate what you have or do as a website with a specific target audience. Providing content that has appeal to both sexes of all ages across all nationalities, races, or religions implies that you should go with something that everyone can use. If anything, this might be a slightly flavourless site because you wouldn't want to marginalize any group of users by explicitly making the site bias towards another group. Luckily though, to some extent your target audience will be slightly easier to define than this, so you can generally make some concessions for a particular type of user. Visual Design There's no beating about the bush on this issue. Make the site appear as visually simple as possible without hiding any critical or useful information. By this, I mean don't be afraid to leave a fairly large list of items on a page if all the items on that list are useful, and will be (or are) used frequently. Hiding an important thing from users no matter how easy it appears to be to find it on other pages will frustrate them, and your popularity might suffer. How a site looks can also have a big impact on how users understand it to work. For example, if several different fonts apply to different links, then it is entirely likely that users will not think of clicking on one type of link or another because of the different font styles. Think about this yourself for a moment, and visualize whether or not you would spend time hovering the pointer over each and every type of different content in the hope that it was a link. This can be summed up as: Make sure your site is visually consistent, and that there are no style discrepancies from one page to the next. By the same token, reading a page of text where the links are given in the same font and style as the writing would effectively hide that functionality. There are quite a few so-called rules of visual design, which can be applied to your site. Some that might apply to you are: the rule of thirds, which states that things divided up into thirds either vertically or horizontally are more visually appealing than other designs; or the visual center rule, which states that the visual center of the page (where the eye is most attracted to) is just above and to the right of the actual center of the page. You may wish to visit the website A List Apart at http://www.alistapart.com/ that has plenty of useful articles on design for the Web, or try searching on Google for more information. Language Now this is a truly interesting part of a site's design, and the art of writing for the Web is a lot more subtle than just saying what you mean. The reason for this is that you are no longer writing simply for human consumption, but also for consumption by machines. Because machines can only follow a certain number of rules when interpreting a page, the concessions on the language used must be made by the writers (if they want their sites to feature highly on search engines). Before making your site's text highly optimized for searching, there are a few more fundamental things that are important to consider. First off, make sure your language is clear and concise. This is the most important; rather sacrifice racy, stylized copy for more mundane text if the mundane text is going to elucidate important points better. People have very short attention spans when it comes to reading Web copy so keep things to the point. Apart from the actual content of your language, the visual and structural appearance of the copy is also important. Use bold or larger fonts to emphasize headings or important points, and ensure that text is spaced out nicely to make the page easier on the eye, and therefore easier to read and understand. Images Working with images for the Web is very much an art. I don't mean this in the sense that generally one should be quite artistic in order to make nice pictures. I mean that actually managing and dealing with image files is itself an art. There is a lot of work to be done for the aspiring website owner with respect to attaining a pleasing and meaningful visual environment. This is because the Web is an environment that is most reliant on visual images to have an effect on users because sight and sound are the only two senses that are targeted by the Internet (for now). In order to have the freedom to manipulate images, you really need to use a reasonably powerful image editor. Gimp, http://www.gimp.org/, is an example of a good image-editing environment, but anything that allows you to save files in a variety of different formats and provides resizing capabilities should be sufficient. If you have to take digital photographs yourself, then ensure you make the photos as uniform as possible, with a background that doesn't distract from the object in question editing the images to remove the background altogether is probably best. There are several areas of concern when working with images, all of which need to be closely scrutinized in order to produce an integrated and pleasing visual environment: One of the biggest problems with images is that they take up a lot more space and bandwidth than text or code. For this reason, having an effective method for dealing with large images is required—simply squashing large images into thumbnails will slow everything down because the server still has to download the entire large file to the user's machine. One common mistake people make when dealing with images is not working on them early on in the process to make them as uniform in size and type as possible. If all the images are of one size and of the same dimension, then you are going to have things a lot easier than most. In fact, this should really be your aim before doing anything involving the site—make sure your images are all as uniform as a given situation allows. Deciding what type of image you actually want to use from the variety available can also be a bit of an issue because some image types take up more space than others, and some may not even be rendered properly in a browser. By and large, there are really only three image types that are most commonly used—GIF, PNG, and JPG. The intended use of an image can also be a big factor when deciding how to create, size, and format the file. For example, icons and logos should really be saved as PNG or GIF files, whereas photos and large or complex images should be saved in the JPG format due to how efficiently JPG handles complex images. Let's take a quick look at those here. GIF, or Graphics Interchange Format, is known for its compression and the fact that it can store and display multiple images. The major drawback to GIF is that images can only display up to 256 distinct colors. For photographic-quality images, this is a significant obstacle. However, you should use GIFs for: Images with a transparent background Animated graphics Smaller, less complex images requiring no more than 256 colors PNG, or Portable Network Graphics, is actually designed as a replacement for GIF files. In general, it can achieve greater file compression, give a wider range of color depth, and quite a bit more. PNG, unlike GIF files, does not support animations. You can use PNG files for anything that you would otherwise use GIFs for, with the exception of animations. IE6 will not render transparency in PNG images correctly, so be aware that this may affect what people think about your site having ugly shaded regions around images can make your site appear to be of poor quality when in fact it is an aspect of their dated browser that causes the problem. Incidentally, there is also an MNG format that allows for animations you might want to check that out as an alternative to animated GIFs. JPG, or JPEG (Joint Photographic Experts Group), should be used when presenting photo-realistic images. JPG can compress large images while retaining the overall photographic quality. JPG files can use any number of colors, and so it's a very convenient format for images that require a lot of color. JPG should be used for: Photographs Larger, complex images requiring more than 256 to display properly Be aware that JPG uses lossy compression, which means that in order to handleimages efficiently, the compression process loses quality. Before we begin an in-depth look at themes that are responsible for just about everything when it comes to your site's look-and-feel, we will take a glance at CSS. CSS The pages in a Drupal site obtain their style-related information from associated stylesheets that are held in their respective theme folders. Using stylesheets gives designers excellent, fine-grained control over the appearance of web pages, and can produce some great effects. The appearance of pretty much every aspect of the site can be controlled from CSS within a theme, and all that is needed is a little knowledge of fonts, colors, and stylesheet syntax. It will make life easier if you have a ready-made list of the type of things you should look at setting using the stylesheet. Here are the most common areas (defined by HTML elements) where stylesheets can be used to determine the look-and-feel of a site's: Background Text Font Color Images Border Margin Padding Lists Besides being able to change all these aspects of HTML, different effects can be applied depending on whether certain conditions, like a mouse hovering over the specified area, are met this will be demonstrated a little later on. You can also specify attributes for certain HTML tags that can then be used to apply styles to those specific tags instead of creating application-wide changes. For example, imagine one paragraph style with a class attribute set, like this: <p class="signature"></p> You could reference this type of paragraph in a stylesheet explicitly by saying something like: p.signature {color: green;} Analyzing this line highlights the structure of the standard style-sheet code block in the form of a: Selector: in this case p.signature Property: in this case color Delimiter: always : Value: in this case green Note that all the property/value pairs are contained within curly braces, and each is ended with a semi-colon. It is possible to specify many properties for each selector, and indeed we are able to specify several selectors to have the same properties. For example, the following block is taken from the garland stylesheet, style.css, and is used to provide all the header text within the theme with a similar look-and-feel by giving them all the same properties: h1, h2, h3, h4, h5, h6 {margin: 0;padding: 0;font-weight: normal;font-family: Helvetica, Arial, sans-serif;} In this instance, multiple selectors have been specified in a comma delimited list, with each selector given four properties to control the margin, padding, font-weight, and font-family of the header tags. It is important to realize that tags can be referenced using either the class attribute, or the id attribute, or both. For example, the following HTML: <p class="signature" id="unique-signature"></p> ...makes it possible for this tag to be referenced both as part of a class of tags all with the same property, or specifically by its unique id attribute. The distinction between the two is important because class gives broad sweeping powers to make changes to all tags within that class, and id gives fine-grained control over a tag with the unique id. This introduction to CSS has been very brief, and there are plenty of excellent resources available. If you would like to learn more about CSS (and it is highly recommended), then visit: CSS Discuss: http://css-discuss.incutio.com/ HTML Dog: http://www.htmldog.com/ We are ready to begin looking at… Themes The use of themes makes Drupal exceptionally flexible when it comes to working with the site's interface. Because the functionality of the site is by and large decoupled from the presentation of the site, it is quite easy to chop and change the look, without having to worry about affecting the functionality. This is obviously a very useful feature because it frees you up to experiment knowing that if worst comes to worst, you can reset the default settings and start from scratch. You can think of a theme as a template for your site that can be modified in order to achieve virtually any design criteria. Of course, different themes have wildly varying attributes; so it is important to find the theme that most closely resembles what you are looking for in order to reduce the amount of work needed to match it to your envisaged design. Also, different themes are implemented differently. Some themes use fixed layouts with tables, while others use div tags and CSS you should play around with a variety of themes in order to familiarize yourself with a few different ways of creating a web page. We only have space to cover one here, but the lessons learned are easily transferred to other templates with a bit of time and practice. Before we go ahead and look at an actual example, it is important to get an overview of how themes are put together in general. Theme Anatomy Some of you might have been wondering what on earth a theme engine is, and how both themes and theme engines relate to a Drupal site. The following two definitions should clear up a few things: Theme: A file or set of files that defines and controls the features of Drupal's web pages (ranging from what functionality to include within a page, to how individual page elements will be presented) using PHP, HTML, CSS and images. Theme engine: Provides PHP-based functionality to create your own unique theme, which in turn, gives excellent control over the all aspects of a Drupal site. Drupal ships with the PHPTemplate engine that is utilized by most themes. Not all theme engines are pure PHP-based. For example, there is a Smarty theme engine available in Drupal for use by people who are familiar with Smarty templates. Looking at how theme files are set up within Drupal hints at the overall process and structure of that theme. Bear in mind that there are several ways to create a working theme, and not all themes make use of template files, but in the case of the Drupal's default theme setup, we have the following: The left-hand column shows the folders contained within the themes directory. There are a number of standard themes, accompanied by the engines folder that houses a phptemplate.engine file, to handle the integration of templates into Drupal's theming system. Looking at the files present in the garland folder, notice that there are a number of PHPTemplate files suffixed by .tpl.php. These files make use of HTML and PHP code to modify Drupal's appearance the default versions of these files, which are the ones that would be used in the event a theme had not implemented its own, can be found in the relevant modules directory. For example, the default comment.tpl.php file is found in modules/comment, and the default page.tpl.php file is located, along with others, in the modules/system folder. Each template file focuses on its specific page element or page, with the noted exception of template.php that is used to override non-standard theme functions i.e. not block, box, comment, node or page. The theme folder also houses the stylesheets along with images, and in the case of the default theme, colors. What's interesting is the addition of the mandatory .info file (.info files were present in Drupal 5 modules, but are only mandatory in themes for Drupal 6) that contains information about the theme to allow Drupal to find and set a host of different parameters. Here are a few examples of the type of information that the .info file holds: Name - A human readable theme name Description—A description of the theme Core—The major version of Drupal that the theme is compatible with Regions—The block regions available to the theme Features—Enables or disables features available in the theme—for example, slogan or mission statement Stylesheets—Stipulate which stylesheets are to be used by the theme Scripts—Specify which scripts to include PHP—Define a minimum version of PHP for which the theme will work To see how .info files can be put to work, look closely at the Minnelli theme folder. Notice that this is in fact a sub-theme that contains only a few images and CSS files. A sub-theme shares its parents' code, but modifies parts of it to produce a new look, new functionality or both. Drupal allows us to create new sub-themes by creating a new folder within the parent theme (in this case, Garland), and providing, amongst other things, new CSS. This is not the only way to create a subtheme a subtheme does not have to be in a subdirectory of its parent theme, rather it can specify the base theme directive in its .info file, in order to extend the functionality of the specified base, or parent, theme. As an exercise, access the Minnelli .info file and confirm that it has been used to specify the Minnelli stylesheet. So far we have only looked at templated themes, but Drupal ships with a couple of CSS driven themes that do not rely on the PHPTemplate engine, or any other, at all. Look at the chameleon theme folder: Notice that while it still has the mandatory .info file, a few images, and stylesheets, it contains no .tpl.php files. Instead of the template system, it uses the chameleon.theme file that implements its own versions of Drupal's themeable functions to determine the theme's layout. In this case, the Marvin theme is a nice example of how all themes can have sub-themes in the same way as the template-driven theme we saw earlier. It should be noted that engine-less themes are not quite as easy to work with as engine-based themes, because any customization must be done in PHP rather than in template files. In a nutshell, Drupal provides a range of default themeable functions that expose Drupal's underlying data, such as content and information about that content. Themes can pick and choose which snippets of rendered content they want to override the most popular method being through the use of PHP template files in conjunction with style sheets and a .info file. Themes and sub-themes are easily created and modified provided that you have some knowledge of CSS and HTML PHP helps if you want to do something more complicated. That concludes our brief tour of how themes are put together in Drupal. Even if you are not yet ready to create your own theme, it should be clear that this system makes building a new theme fairly easy, provided one knows a bit about PHP. Here's the process: Create a new themes folder in the sites/default directory and add your new theme directory in there call it whatever you want, except for a theme name that is already in use. Copy the default template files (or files from any other theme you want to modify) across to the new theme directory, along with any other files that are applicable (such as CSS files). Modify the layout (this is where your PHP and HTML skills come in handy) and add some flavor with your own stylesheet. Rewrite the .info file to reflect the attributes and requirements of the new theme. Now, when it is time for you to begin doing a bit of theme development, bear in mind that there are many types of browser, and not all of them are created equal. What this means is that a page that is rendered nicely on one browser might look bad, or worse, not even function properly on another. For this reason, you should test your site using several different browsers! The Drupal help site has this to say about browsers: It is recommended you use the Firefox browser with developer toolbar and the 'view formatted source' extensions. You can obtain a copy of the Firefox browser at http://www.mozilla.com/firefox/ if you wish to use something other than Internet Explorer. Firefox can also be extended with Firebug, which is an extremely useful tool for client-side web debugging. For the purposes of this article, we are going to limit ourselves to the selection of a base theme that we will modify to provide us with the demo site's new interface. This means that, for now, you don't have to concern yourself with the intricacies of PHP.
Read more
  • 0
  • 0
  • 1041

article-image-joomla-and-database
Packt
23 Oct 2009
8 min read
Save for later

Joomla! and Database

Packt
23 Oct 2009
8 min read
The Core Database Much of the data we see in Joomla! is stored in the database. A base installation has over thirty tables. Some of these are related to core extensions and others to the inner workings of Joomla!. There is an official database schema, which describes the tables created during the installation. For more information, please refer to: http://dev.joomla.org/ component/option,com_jd-wiki/Itemid,31/id,guidelines:database/. A tabular description is available at: http://dev.joomla.org/downloads/Joomla15_DB-Schema.htm. We access the Joomla! database using the global JDatabase object. The JDatabase class is an abstract class, which is extended by different database drivers. There are currently only two database drivers included in the Joomla! core, MySQL and MySQLi. We access the global JDatabase object using JFactory: $db =& JFactory::getDBO(); Extending the Database When we create extensions, we generally want to store data in some form. If we are using the database, it is important to extend it in the correct way. Table Prefix All database tables have a prefix, normally jos_, which helps in using a single database for multiple Joomla! installations. When we write SQL queries, to accommodate the variable table prefix, we use a symbolic prefix that is substituted with the actual prefix at run time. Normally the symbolic prefix is #__, but we can specify an alternative prefix if we want to. Schema Conventions When we create tables for our extensions, we must follow some standard conventions. The most important of these is the name of the table. All tables must use the table prefix and should start with name of the extension. If the table is storing a specific entity, add the plural of the entity name to the end of the table name separated by an underscore. For example, an items table for the extension 'My Extension' would be called #__myExtension_items. Table field names should all be lowercase and use underscore word separators; you should avoid using underscores if they are not necessary. For example, you can name an email address field as email. If you had a primary and a secondary email field, you could call them email and email_secondary; there is no reason to name the primary email address email_primary. If you are using a primary key record ID, you should call the field id, make it of type integer auto_increment, and disallow null. Doing this will allow you to use the Joomla! framework more effectively. Common Fields We may use some common fields in our tables. Using these fields will enable us to take advantage of the Joomla! framework. Publishing We use publishing to determine whether to display data. Joomla! uses a special field called published, of type tinyint(1); 0 = not published, 1 = published. Hits If we want to keep track of the number of times a record has been viewed, we canuse the special field hits, of type integer and with the default value 0. Checking Out To prevent more than one user trying to edit one record at a time we can check out records (a form of software record locking). We use two fields to do this, checked_out and checked_out_time. checked_out, of type integer, holds the ID of the user that has checked out the record. checked_out_time, of type datetime, holds the date and time when the record was checked out. A null date and a user ID of 0 is recorded if the record is not checked out. Ordering We often want to allow administrators the ability to choose the order in which items appear. The ordering field, of type integer, can be used to number records sequentially to determine the order in which they are displayed. This field does not need to be unique and can be used in conjunction with WHERE clauses to form ordering groups. Parameter Fields We use a parameter field, a TEXT field normally named params, to store additional information about records; this is often used to store data that determines how a record will be displayed. The data held in these fields is encoded as INI strings (which we handle using the JParameter class). Before using a parameter field, we should carefully consider the data we intend to store in the field. Data should only be stored in a parameter field if all of the following criteria are true: Not used for sorting records Not used in searches Only exists for some records Not part of a database relationship Schema Example Imagine we have an extension called 'My Extension' and an entity called foobar. The name of the table is #__myextension_foobars. This schema describes the table: Field Datatype NOT NULL AUTO INC UNSIGNED DEFAULT id INTEGER X X X NULL content TEXT X       checked_out INTEGER X   X 0 checked_out_time DATETIME X     0000-00-00 00:00:00 params TEXT X       ordering INTEGER X   X 0 hits INTEGER X   X 0 published TINYINT(1) X   X 0 This table uses all of the common fields and uses an auto-incrementing primary keyID field. When we come to define our own tables we must ensure that we use thecorrect data types and NOT NULL, AUTO INC, UNSIGNED and DEFAULT values. The SQL displayed below will create the table described in the above schema: CREATE TABLE `#__myextension_foobars` ( `id` INTEGER UNSIGNED NOT NULL DEFAULT NULL AUTO_INCREMENT, `content` TEXT NOT NULL DEFAULT '', `checked_out` INTEGER UNSIGNED NOT NULL DEFAULT 0, `checked_out_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', `params` TEXT NOT NULL DEFAULT '', `ordering` INTEGER UNSIGNED NOT NULL DEFAULT 0, `hits` INTEGER UNSIGNED NOT NULL DEFAULT 0, `published` INTEGER UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY(`id`)) CHARACTER SET `utf8` COLLATE `utf8_general_ci`; Date Fields We regularly use datetime fields to record the date and time at which an action has taken place. When we use these fields, it is important that we are aware of the effect of time zones. All dates and times should be recorded in UTC+0 (GMT / Z). When we come to display dates and times we can use the JDate class. The JDate class allows us to easily parse dates, output them in different formats, and apply UTC time-zone offsets. For more information about time zones, please refer to http://www.timeanddate.com. We often use parsers before we display data to make the data safe or to apply formatting to the data. We need to be careful how we store data that is going to be parsed. If the data is ever going to be edited, we must store the data in its RAW state. If the data is going to be edited extremely rarely and if the parsing is reversible, we may want to consider building a 'reverse-parser'. This way we can store the data in its parsed format, eradicating the need for parsing when we view the data and reducing the load on the server. Another option available tous is to store the data in both formats. This way we only have to parse data when we save it. Dealing with Multilingual Requirements Unlike ASCII and ANSII, Unicode is a multi-byte character set; it uses more than eight bits (one byte) per character. When we use UTF-8 encoding, character byte lengths vary. Unfortunately, MySQL versions prior to 4.1.2 assume that characters are always eight bits (one byte), which poses some problems. To combat the issue when installing extensions we have the ability to define different SQL files for servers, that do and do not support UTF-8. In MySQL servers that do not support UTF-8, when we create fields, which define a character length, we are actually defining the length in bytes. Therefore, if we try to store UTF-8 characters that are longer than one byte, we may exceed the size of the field. To combat this, we increase the length of fields to try to accommodate UTF-8strings. For example, a varchar(20) field becomes a varchar(60) field. We triple the size of fields because, although UTF-8 characters can be more than three bytes, the majority of common characters are a maximum of three bytes. This poses another issue, if we use a varchar(100) field, scaling it up for a MySQL server, which does not support UTF-8, we would have to define it as a varchar(300) field. We cannot do this because varchar fields have a maximum size of 255. The next step is slightly more drastic. We must redefine the field type so as it will accommodate at least three hundred bytes. Therefore, a varchar(100) field becomes a text field. As an example, the core #__content table includes a field named title. For MySQL severs that support UTF-8, the field is defined as: `title` varchar(255) NOT NULL default '' For MySQL severs that do not support UTF-8, the field is defined as: `title` text NOT NULL default '' We should also be aware that using a version of MySQL that does not support UTF-8 would affect the MySQL string handling functions. For example ordering by a string field may yield unexpected results. While we can overcome this using postprocessing in our scripts using the JString class, the recommended resolution is to upgrade to the latest version of MySQL.
Read more
  • 0
  • 0
  • 1163

article-image-customizing-default-theme-drupal
Packt
23 Oct 2009
3 min read
Save for later

Customizing the Default Theme in Drupal

Packt
23 Oct 2009
3 min read
Let's look at the default theme (garland) and customize it. We can customize the following features: Color scheme, either based on a color set, or by changing the individual colors If certain elements, such as the logo, are displayed The logo The favicon Back in the Themes section of the Administer area, there is a configure link next to each theme; if we click this we are taken to the theme's configuration page. Although Doug ideally wants a new theme that is unique to his website, he also wants to have a look at a few different options for the default theme. In particular, he wants to add his company's logo to the website and try a number of red color schemes as those are his corporate colors. Color Scheme The color scheme settings are quite intuitive and easy to change. We can either: Select a color set Change each color by entering the hexadecimal color codes (the # followed by 6 characters) Select the colors from the color wheel To change a color using the color wheel, we need to click on the color type (base color, link color, etc.) to select it and then chose the general color from the wheel and the shade of the color from the square within. When we change the colors or color set, the preview window below the settings automatically updates to reflect the color change. The following color sets are available: Blue Lagoon (the default set) Ash Aquamarine Belgian Chocolate Bluemarine Citrus Blast Cold Day Greenbeam Meditarrano Mercury Nocturnal Olivia Pink Plastic Shiny Tomato Teal Top Custom Quite a number of these are red-based color schemes, let's look into them, they are: Belgian Chocolate Meditarrano Shiny Tomato Belgian Chocolate Color Set The Belgian Chocolate color set uses a dark red header with a gradient starting with black flowing into a dark red color. The page's background is a cream color and the main content area has a white background as illustrated by the picture below: Mediterrano Color Set The Mediterrano color set uses a lighter red color where the gradient in the header starts with a light orange color which then flows into a light red color. Similar to the Belgian Chocolate color scheme the background is cream in color with a white background for the content area. Shiny Tomato Color Set The Shiny Tomato color set has a gradient header that starts with deep red and flows into a bright red color. The page's background is light grey with white background for the main content area, reflecting a professional image. The Shiny Tomato color set uses a red scheme which is in Doug's logo and he feels this set is the most professional of the three and wants us to use that.  
Read more
  • 0
  • 0
  • 1085
article-image-planning-extensions-typo3
Packt
23 Oct 2009
8 min read
Save for later

Planning Extensions in TYPO3

Packt
23 Oct 2009
8 min read
Why is Planning Important? Most open source developers see planning as a boring task. Why plan if one can just go and code? The answer is as simple as the question: The "Go and code" approach does not let us create truly optimal code. Portions of code have to be changed while other portions are written. They often lead to redundant code or uninitialized variables, partially covered conditions, and wrong return results. Code gets a "do not touch" reputation because changing anything renders the whole project unstable. Often the code works, but the project is more a failure than a success because it cannot be extended or re-used. Another reason for planning is the ease of bug fixing and the costs associated with it. Open source developers often do not think about it until they start selling their services or work to commercial companies. As shown by recent studies, the cost of problem fixing grows rapidly toward the end of the project. The cost is minimal when development has not started yet, and the person in charge just collects requirements. When requirements are collected and a programmer (or a team of programmers) starts to think how to implement these requirements, a change of requirements, or fixing a problem in the requirements still does not cost much. But it may already be difficult for developers if they came to a certain implementation approach after reviewing requirements. Things become worse at the development stage. Imagine that the selected approach was wrong and it was uncovered close to the end of development. Lots of time is lost, and work may have to start from the beginning. Now imagine what happens if the project is released to the customer and the customer says that the outcome of the project does not work as expected (something was implemented differently (as compared to expectations), or something was not implemented at all). The cost of fixing is likely to be high and overshoot the budget. Next, imagine what would happen if problems occurred when a project went live. After reading the previous paragraph, some developers may ask how the situation applies to non-commercial development, as there is a false perception that there are no costs associated with it (at least, no direct costs). But, the costs exist! And often they are much more sensitive than financial costs. The cost in non-commercial development is reputation. If a developer's product does not work well or does not work at all or it has obvious flaws, the general opinion about the developer may become bad ("cannot trust his code"). Developers will also have troubles improving because often they do not understand what has gone wrong. But the answer is near. Do not rush! Plan it well! You may even think of something about the future code, and then start coding only when the picture is clear. Planning is an important part of software development. While freelancers can usually divide their time freely between planning and implementation, many corporate developers often do not have such freedom. And even worse, many managers still do not see planning as a necessary step in software development. This situation is well explained in The parable of the two programmers, which readers of this book are encouraged to read in full. When it comes to TYPO3, planning is more important than an average application. TYPO3 is very complex, and its implementation is also complex. Without planning, programmers will most likely have to change their already written code to fix unforeseen problems therefore, good planning for TYPO3 extensions is extremely important. But let us move on and see how to plan an extension. How to Plan There are several stages in planning. Typically, each stage answers one or more important questions about development. TYPO3 developers should think about at least three stages: Gathering requirements Implementation planning Documentation planning Of course, each project is unique and has other stages. But these three stages generally exist in every project. Gathering Requirements The first thing that a developer needs to know is what his/her extension will do. While it sounds pretty obvious, not many extension authors know exactly what functionality the extension has in the end. It evolves over time, and often the initial idea is completely different from the final implementation. Predictably, neither the original nor the final is done well. In the other case, when extension features are collected, though planned and implemented according to plan, they usually fit well together. So, the very first thing to do when creating an extension is to find out what that extension should do. This is called gathering requirements. For non-commercial extensions, gathering requirements simply means writing down what each extension should do. For example, for a news extension, it may be: Show list of news sorted by date Show list of latest news Show news archive Show only a small amount of text in news list view As we have seen, gathering requirements looks easier than it actually is. The process, however, may become more complex when an extension is developed for an external customer. Alan Cooper, in his famous About Face book, shows how users, architects, and developers see the same product. From the user's perspective, it looks like a perfect circle. An architect sees something closer to an octagon. A developer creates something that looks like a polygon with many segments connected at different degrees. These differences always exist and each participating party is interested in minimizing them. A developer must not be afraid of asking questions. The cleaner picture he/she has, the better he/she will understand the customer's requirements. Implementation Planning When the requirements are gathered, it is necessary to think which blocks an extension will have. It may be blocks responsible for data fetching, presentation, conversion, and so on. In the case of TYPO3 extension implementation, planning should result in a list of Frontend (FE) plugins, Backend (BE) modules, and standalone classes. The purpose of each plug-in, module, and/or class must be clear. When thinking of FE plugins, caching issues must be taken into account. While most of the output can be cached to improve TYPO3 performance, forms processing should not be cached. Some extensions completely prevent caching of the page when processing forms. But there is a better approach, a separate FE plug-in from the non-cached output. BE modules must take into account the ease of use. Standard BE navigation is not very flexible, and this must be taken into account when planning BE modules. Certain functionalities can be moved to separate classes. This includes common functions and any public APIs that an extension provides to the other extensions. Hooks or "user functions" are usually placed in separate classes depending on the functional zone or hooked class. Documentation Planning A good extension always comes with documentation. Documentation should also be planned. Typically, manuals for extensions are created using standard templates, which have standard sections defined. While this simplifies documentation writing for extension developers, they still have to plan what they will put into these sections. TYPO3-Specific Planning There are several planning issues specific to TYPO3. Developers must take care of them before the actual development. Extension Keys Each extension must have a unique key. Extension keys can be alphanumeric and contain underscore characters. It may not start with a digit, the letter u, or the test_ prefix. However, not every combination of these symbols makes a good extension key. An extension key must be descriptive but not too long. Having personal or company prefixes is not forbidden but is not recommended. Underscores should be avoided. Abbreviations should be avoided as well, because they often do not make sense for other users. Examples of good extension keys are: news comments usertracker loginbox Examples of bad extension keys are: news_extension mycorp_ustr myverygoodextensionthatdoesalotofthings mvgetdalot john_ext div2007 Database Structure Most TYPO3 extensions use a database to load and/or store their own data. Changing the data structure during application development may seriously slow down development, or may even cause damage to data if some data is already entered into the system. Therefore, it is extremely important to think about an extension's data structure well in advance. Such thinking requires knowledge about how TYPO3 database tables are organized. Tables in TYPO3 database must have certain structures to be properly managed by TYPO3. If a table does not fulfill TYPO3 requirements, users may see error messages in the BE (especially in the Web | List module), and data may become corrupted. Every record in every TYPO3 table belongs to a certain page inside TYPO3. TYPO3 has a way to identify which page the record belongs to.
Read more
  • 0
  • 0
  • 1074

article-image-layouts-ext-js
Packt
23 Oct 2009
9 min read
Save for later

Layouts in Ext JS

Packt
23 Oct 2009
9 min read
What are layouts, regions, and viewports? Ext uses Panels, which are the basis of most layouts. We have used some of these, such as FormPanel and GridPanel, already. A viewport is a special panel-like component that encloses the entire layout, fitting it into the whole visible area of our browser. For our first example, we are going to use a viewport with a border layout that will encapsulate many panels. A viewport has regions that are laid out in the same way as a compass, with North,South, East and West regions—the Center region represents what's left over in the middle. These directions tell the panels where to align themselves within the viewport and, if you use them, where the resizable borders are to be placed: The example we're creating will look like the following image, and combines many of the previous examples we have created: This layout is what's called a 'border' layout, which means that each region is separated by a somewhat three dimensional border bar that can be dragged to resize the regions. This example contains four panel regions: North: The toolbar West: A form Center: Grid in a tab panel East: A plain panel containing text Note that there is no 'South' panel in this example—not every region needs to be used in every layout. Our first layout Before we create our layout that uses only four regions let's go ahead and create a layout that utilizes all the regions, and then remove the South panel. We are going to create all of the regions as 'panels', which can be thought of as blank canvases to which we will add text, HTML, images, or even Ext JS widgets. var viewport = new Ext.Viewport({ layout: 'border', renderTo: Ext.getBody(), items: [{ region: 'north', xtype: 'panel', html: 'North' },{ region: 'west', xtype: 'panel', split: true, width: 200, html: 'West' },{ region: 'center', xtype: 'panel', html: 'Center' },{ region: 'east', xtype: 'panel', split: true, width: 200, html: 'East' },{ region: 'south', xtype: 'panel', html: 'South' }]}); Each region is defined as one of the four compass directions—East, West, North, and South. The remainder in the middle is called the center region, which will expand to fill all of the remaining space. Just to take up some blank space in each region and to give a visual indicator as to where the panels are, we defined an 'HTML' config that has just text. (This could also contain complex HTML if needed, but there are better ways to set the contents of panels which we will learn about soon). Ext JS provides an easy, cross-browser compatible, speedy way to get a reference to the body element, by using Ext.getBody(). If everything works out ok, you should see a browser that looks like this: Now we have a layout with all five regions defined. These regions can have other text widgets added into them, seamlessly, by using the xtype config. Alternatively they can be divided up separately into more nested regions—for instance, the center could be split horizontally to have its own South section. A 'Center' region must always be defined. If one is not defined, the layout will produce errors and appear as a jumbled set of boxes in the browser. Splitting the regions The dividers are set up for each panel by setting the split flag—the positioning of the dividers is determined automatically based on the region the panel is in. split: true For this page, we have set the West and East regions as 'split' regions. This, by default, makes the border into a resizing element for the user to change the size of that panel. I want options Typically, when a split is used, it's combined with a few other options that make the section more useful, such as width, minSize, and collapseMode. Here are some of the more commonly-used options: Option Value Description split true/false Boolean value that places a resizable bar between the sections collapsible true/false Boolean value that adds a button to the title bar which lets the user collapse the region with a single click collapseMode Only option is mini mode, or undefined for normal mode When set to 'mini', this adds a smaller collapse button that's located on the divider bar, in addition to the larger collapse button on title bar; the panel also collapses into a smaller space title String Title string placed in the title bar bodyStyle CSS CSS styles applied to the body element of the panel. minSize Pixels, ie: 200 The smallest size that the user can drag this panel to maxSize Pixels, ie: 250 The largest size that the user can drag this panel to margins In pixels: top, right, bottom, left, i.e.,: 3 0 3 3 Can be used to space the panel away from the edges or away from other panels; spacing is applied outside of the body of the panel cmargins In pixels: top, right, bottom, left, i.e.,: 3 0 3 3 Same idea as margins, but applies only when the panel is collapsed   Let's add a couple of these options to our west panel: { region: 'west', xtype: 'panel', split: true, collapsible: true, collapseMode: 'mini', title: 'Some Info', bodyStyle:'padding:5px;', width: 200, minSize: 200, html: 'West'} Adding these config options to our west panel would give us the following look: Expanding and collapsing a panel that does not have a width specified can produce rendering problems. Therefore, it's best to specify a width for panels—of course this is not needed for the center, as this panel automatically fills the remaining space. Tab panels With Ext JS, tab panels are also referred to as a "card" layout because they work much like a deck of cards where each card is layered directly above or below the others and can be moved to the top of the deck, to be visible. We also get pretty much the same functionality in our tab panel as a regular panel, including a title, toolbars, and all the other usual suspects (excluding tools). Adding a tab panel If the Ext JS component is a panel type component, for instance GridPanel andFormPanel, then we can add it directly to the layout using its xtype. Let's start by creating a tabPanel: { region: 'center', xtype: 'tabpanel', items: [{ title: 'Movie Grid', html: 'Center' }]} The items config is an array of objects that defines each of the tabs contained in this tabpanel. The title is the only option that's actually needed to give us a tab, and right now html is just being used as a placeholder, to give our empty tab some content. We will also need to add an activeTab config that is set to zero to our tab panel. This is the index of the tabs in the panel left to right starting with zero and counting up for each tab. This tells the tab panel at position zero to make itself active by default, otherwise, we would have no tabs displayed, resulting in a blank section until the user clicked a tab. { region: 'center', xtype: 'tabpanel', activeTab: 0, items: [{ title: 'Movie Grid', html: 'Center' }]} If we take a look at this in a browser, we should see a tab panel in the center section of our layout. Adding more tabs is as easy as adding more items into the items array. Each tab item is basically its own panel, which is shown or hidden, based on the tab title that has been clicked on the tab panel. { region: 'center', xtype: 'tabpanel', activeTab: 0, items: [{ title: 'Movie Grid', html: 'Center' },{ title: 'Movie Descriptions', html: 'Movie Info' }]} Both the Movie Grid and Movie Descriptions tabs are just plain panels right now. So let's add some more configuration options and widgets to them. Widgets everywhere Earlier, I mentioned that any type of panel widget could be added directly to a layout, just as we had done with the tabs. Let's explore this by adding another widget to our layout—the grid. Adding a grid into the tabpanel As we now have these tabs as part of our layout, let's start by adding a grid panel to one of the tabs. Adding the xtype config option to the grid config code will produce a grid that fills one entire tab: { region: 'center', xtype: 'tabpanel', activeTab: 0, items: [{ title: 'Movie Grid', xtype: 'gridpanel', store: store, autoExpandColumn: 'title', columns: // add column model //, view: // add grid view spec // },{ title: 'Movie Descriptions', html: 'Movie Info' }]} xtypes offer a quick way to instantiate a new component with minimal typing. This is sometimes referred to as 'lazy rendering' because the components sit around waiting to be displayed before they actually execute any code. This method can help conserve memory in your web application. As we are adding this grid to a tab—which is essentially just a panel—there are some things that we no longer need (like the renderTo option, width, height, and a frame).The size, title, and border for the grid are now handled by our tab panel. Now we should have a layout that looks like this: Accordions The accordion is a very useful layout that works somewhat like a tab panel, where we have multiple sections occupying the same space, with only one showing at a time. This type of layout is commonly used when we're lacking the horizontal space needed for a tab panel, but instead have more vertical space available. When one of the accordion panels is expanded, the others will collapse. Expanding and collapsing the panels can be done either by clicking the panel's title bar or by clicking the plus/minus icons along the rightmost side of the panel.    
Read more
  • 0
  • 0
  • 3574