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-vim-72-scripting
Packt
30 Apr 2010
9 min read
Save for later

Vim 7.2 Scripting

Packt
30 Apr 2010
9 min read
Scripting tips In this section, we will look at a few extra tips that can be handy when you create scripts for Vim. Some are simple code pieces you can add directly in your script, while others are good-to-know tips. Gvim or Vim? Some scripts have extra features when used in the GUI version of Vim (Gvim). This could be adding menus, toolbars, or other things that only work if you are using Gvim. So what do you do to check if the user runs the script in a console Vim or in Gvim? Vim has already prepared the information for you. You simply have to check if the feature gui_running is enabled. To do so, you use a function called has(), which returns 1 (true) if a given feature is supported / enabled and 0 (false), otherwise. An example could be: if has("gui_running") "execute gui-only commands here.endif This is all you need to do to check if a user has used Gvim or not. Note that it is not enough to check if the feature "gui" exists, because this will return true if your Vim is just compiled with GUI support—even if it is not using it. Look in :help 'feature-list' for a complete list of other features you can check with the has() function. Which operating system? If you have tried to work with multiple operating systems such as Microsoft Windows and Linux, you will surely know that there are many differences. This can be everything from where programs are placed, to which programs you have available and how access to files is restricted. Sometimes, this can also have an influence on how you construct your Vim script as you might have to call external programs, or use other functionality, specific for a certain operating system. Vim lets you check which operation system you are on, such that you can stop executing your script or make decisions about how to configure your script. This is done with the following piece of code: if has("win16") || has("win32") || has("win64")|| has("win95") " do windows things hereelseif has("unix") " do linux/unix things hereendif This example only shows how to check for Windows (all flavors available) and Linux / Unix. As Vim is available on a wide variety of platforms, you can of course also check for these. All of the operating systems can be found in: :help 'feature-list' Which version of Vim? Throughout the last decade or two, Vim has developed and been extended with a large list of functions. Sometimes, you want to use the newest functions in your script, as these are the best / easiest to use. But what about the users who have a version of Vim that is older than the one you use, and hence don't have access to the functions you use? You have three options: Don't care and let it be the user's own problem (not a good option). Check if the user uses an old version of Vim, and then stop executing the script if this is the case. Check if the user has too old a version of Vim, and then use alternative code. The first option is really not one I would recommend anyone to use, so please don't use it. The second option is acceptable, if you can't work around the problem in the old version of Vim. However, if it is possible to make an alternative solution for the older version of Vim, then this will be the most preferable option. So let's look at how you can check the version of Vim. Before we look at how to check the version, we have to take a look at how the version number is built. The number consists of three parts: Major number (for example, 7 for Vim version 7) Minor number (for example, 3 for Vim version 6.3) Patch number (for example, 123 for Vim 7.0.123) The first two numbers are the actual version number, but when minor features / patches are applied to a version of Vim, it is mostly only the patch number that is increased. It takes quite a bit of change to get the minor number to increase, and a major part of Vim should change in order to increase the major version number. Therefore, when you want to check which version of Vim the user is using, you do it for two versions—major and minor versions and patch number. The code for this could look like: if v:version >= 702 || v:version == 701 && has("patch123") " code here is only done for version 7.1 with patch 123 " and version 7.2 and aboveendif The first part of the if condition checks if our version of Vim is version 7.2 (notice that the minor version number is padded with 0 if less than 10) or above. If this is not the case, then it checks to see if we have a version 7.1 with patch 123. If patch version 124 or above is included, then you also have patch 123 automatically. Printing longer lines Vim was originally created for old text terminals where the length of lines was limited to a certain number of characters. Today, this old limitation shows up once in a while. One place where you meet this limitation of line length is when printing longer lines to the screen using the "echo" statement. Even though you use Vim in a window where there are more than the traditional 80 characters per line, Vim will still prompt you to press Enter after echoing lines longer than 80 characters. There is, however, a way to get around this, and make it possible to use the entire window width to echo on. Window width means the total number of columns in the Vim window minus a single character. So if your Vim window is wide enough to have 120 characters on each line, then the window width is 120-1 characters. By adding the following function to your script, you will be able to echo screen-wide long lines in Vim: " WideMsg() prints [long] message up to (&columns-1) lengthfunction! WideMsg(msg) let x=&ruler | let y=&showcmd set noruler noshowcmd redraw echo a:msg let &ruler=x | let &showcmd=yendfunction This function was originally proposed by the Vim script developer Yakov Lerner on the Vim online community site at http://www.vim.org. Now whenever you need to echo a long line of text in your script, instead of using the echo statement you simply use the function Widemsg(). An example could be: :call WideMsg("This should be a very long line of text") The length of a single line message is still limited, but now it is limited to the width of the Vim window instead of the traditional 80-1 characters. Debugging Vim scripts Sometimes things in your scripts do not work exactly as you expect them to. In these cases, it is always good to know how to debug your script. In this section, we will look at some of the methods you can use to find your error. Well-structured code often has fewer bugs and is also easier to debug. In Vim, there is a special mode to perform script debugging. Depending on what you want to debug, there are some different ways to start this mode. So let's look at some different cases. If Vim just throws some errors (by printing them at the bottom of the Vim window), but you are not really sure where it is or why it happens, then you might want to try to start Vim directly in debugging mode. This is done on the command line by invoking Vim with the -Dargument. vim -D somefile.txt The debugging mode is started when Vim starts to read the first vimrc file it loads (in most cases the global vimrc file where Vim is installed). We will look at what to do when you get into debug mode in a moment. Another case where you might want to get into debug mode is when you already know which function the error (most likely) is in, and hence, just want to debug that function. In that case you just open Vim as normal (load the script with the particular function if needed) and then use the following command: :debug call Myfunction() Here everything after the :debug is the functionality you want to debug. In this case, it is a simple call of the function Myfunction(), but it could just as well be any of the following: :debug read somefile.txt:debug nmap ,a :call Myfunction() <CR>:debug help :debug So let's look at what to do when we get into the debugging mode. When reaching the first line that it should debug, Vim breaks the loading and shows something like: Entering Debug mode. Type "cont" to continue.cmd: call MyFunction()> Now you are in the Vim script debugger and have some choices for what to make Vim do. If you are not familiar with debugging techniques, it might be a good idea to read up on this subject before starting to debug your scripts. The following commands are available in the debugger (shortcuts are in parentheses): cont (c): Continue running the scripts / commands as normal (no debugging) until the next breakpoint (more about this later). quit (q): Quit the debugging process without executing the last lines. interrupt (i): Stop the current process like quit, but go back to the debugger. step (s): Execute the next line of code and come back to the debugger when it is finished. If a line calls a function or sources a file, then it will step into the function / file. next (n): Execute the next command and come back to the debugger when it is finished. If used on a line with a function call, it does not go into the function but steps over it. finish (f): Continue executing the script without stopping on breakpoints. Go into debug mode when done.
Read more
  • 0
  • 0
  • 2417

article-image-installing-typo3-extensions
Packt
30 Apr 2010
2 min read
Save for later

Installing TYPO3 Extensions

Packt
30 Apr 2010
2 min read
TYPO3 is one of the most functional and powerful content management systems (CMS). Offering both functionality and expansiveness, TYPO3 is a relevant competitor for commercial solutions. One of the advantages of using TYPO3 is that this CMS has expandability possibilities that are called "extensions". Using these extensions, you can extend the TYPO3 functionality. You can manage shops, galleries, forums, or even a small community portal. You can download extensions from the TYPO3 extension repository (TER): http://typo3.org/extensions. *.t3x is the file format used for extension files. This package is partly compressed using GZIP and it contains the necessary files for the extension (SQL dump, tables, functions, templates, image resources, and so on). This site is a recommended easy way to search for appropriate and suitable extensions. Also, you can find an overview of the extension functionality and additional documentation. For easy extension installation, use its import through Extension Manager. In the extensions section, http://typo3.org/extensions, you'll find the following: New and updated: the latest updated or recently added extensions from the last 20 days—as per the claim on the repository. Popular: a list of the most downloaded extensions on TER. Full list: a complete list of extensions sorted by alphabet. Search: search the form to find an appropriate extension you need. A Search form is also provided in the section New and updated. All the extensions are sorted in groups according to their status: Reviewed extensions: extensions that are secure. These extensions don't affect the normal operation of the system and are qualitative. Alfa: early stage of extension development. Beta: early stage of extension development but operates partly. Stable: stable extension that can be used to provide page functionality. Test: test extension. These kinds of extensions are usually without functionality or are used for concept examples. Obsolete: extensions that are included in the TYPO3 core or are associated with other extensions. For our new shop, we need an eCommerce extension that provides product catalogue and functionality of a shopping cart. You can type shop or commerce in the search area and get a few versions of online shop extensions and those extensions that provide extra functionality to basic extensions. Note the most popular and downloaded online shop extensions: Shop System (tt_products) by Franz Holzinger Webformat Shop System (extendedshop) by Mauro Lorenzutti Commerce (commerce) by Ingo Schmitt, Volker Graubaum, and Thomas Hempel
Read more
  • 0
  • 0
  • 1806

article-image-using-aspnet-master-pages-your-mcms-applications
Packt
29 Apr 2010
6 min read
Save for later

Using ASP.NET Master Pages in your MCMS Applications

Packt
29 Apr 2010
6 min read
Overview and Benefits of Master Pages A master page includes common markup and one or more content placeholders. From this master page, new content pages can be created, which include content controls that are linked to the content placeholders in the master page. This provides an ideal way to separate common site branding, navigation, etc., from the actual content pages, and can significantly decrease duplication and markup errors. Master pages make working with template files a lot easier than before. You can add common markup and shared controls such as headers, footers, and navigation bars to master pages. Once a master page has been built, you can create MCMS template files based upon it. The template files will immediately adopt the look and feel defined in the master template. You can also mark certain regions of the master page to be customizable by introducing content placeholders (note that these are controls designed specifically for master pages and are not to be confused with MCMS placeholder controls). The space marked by content placeholders provides areas where you could add individual template markup as well as MCMS placeholder controls, as shown in the following diagram: Although at first glance both master pages and MCMS templates offer a way to standardize the look and feel of a site, their similarities end there. Don’t be mistaken into thinking that master pages take over the role of MCMS templates completely. A key difference between the two is that the use of master pages is reserved solely for site developers to ensure that template files created have a common look and feel. You can’t create a master page and expect authors to use it to create postings. In fact, master pages work alongside template files and offer a number of benefits to MCMS developers. Avoids duplication in MCMS Template files: Often MCMS templates contain common page layout code (usually an HTML table) along with navigation bars, headers, and footers (usually web user controls). This code has to be copied and pasted into each new template file after it is created or abstracted into user controls. In addition a change in the layout of this common code has to be applied to all template files. So, for example, an MCMS application with ten template files will duplicate this markup ten times. By placing this markup within a master page, this duplication can be removed. Separation of site-wide markup from template markup: One of the biggest drawbacks to MCMS is that the task of developing templates cannot be easily separated. It is a common requirement to separate the tasks of defining site branding, layout, and the development of controls such as navigation (performed by webmasters and programmers) from the task of designing template layouts (performed by business users). While master pages and Visual Studio 2005 do not address this completely due to MCMS’s inherent architecture, they offer a substantial improvement in this area. Avoids issues with MCMS Template File Visual Studio templates: The MCMS Project Item Templates have a number of issues, and do not fully embrace the Visual Studio 2005 project system. Although any web form can be MCMS ‘enabled’, master pages offer a more seamless development experience with less manual tweaks required. Visual Studio 2005 Designer support: One of the common problems with using user controls within template files in Visual Studio .NET is that the template design view doesn't provide an adequate experience for template developers. Visual Studio 2005 offers an improved design-view experience including rendering of user control content, and this is especially valuable when working with master pages. Experience of Master Pages: Just as MCMS is a great way to learn ASP.NET, MCMS SP2 is a great way to learn ASP.NET 2.0! In addition, master pages are a fundamental building block of future Web Content Management offerings from Microsoft. MCMS placeholder controls in the master page will work, but are not officially supported. As we will see in this article, master pages provide an ideal way to separate common site branding, navigation, etc., from the actual content pages, and can significantly decrease duplication and markup errors. The TropicalGreen Web Site Tropical Green is the fictitious gardening society upon which the article’s sample website is based. In the book, Building Websites with Microsoft Content Management Server from Packt Publishing (ISBN 1-904811-16-7), we built the Tropical Green website from scratch using ASP.NET 1.x. In this article series, we will attempt to rebuild parts of the website using MCMS SP2 and ASP.NET 2.0. While the code will be rewritten from the ground-up, we won’t start with a blank database. Instead, we’ll take a shortcut and import the TropicalGreen database objects from the TropicalGreen.sdo file available from the support section on Packt Publishing’s website (http://www.packtpub.com/support). Importing the TropicalGreen Site Deployment Object File Before we begin, let’s populate the database by importing objects using the Site Deployment Manager. Download the TropicalGreen.sdo file. Open Site Manager and log in with an MCMS administrator account. From the menu, select File | Package | Import…. In the Site Deployment Import dialog, click on the Browse… button. Navigate to the TropicalGreen_Final.sdo file downloaded earlier. In the Container Rules tab, set the following: Property Value When Adding Containers Use package container rights When Replacing Containers Keep destination container rights In the Rights Group tab, set the following: Property Value Select how Rights Groups are imported Import User Rights Groups Click on Import. The import confirmation dialog appears. Click on Continue. Creating a New MCMS Web Application To get started, let’s create a new MCMS web application using the project templates we created in the previous article. From Visual Studio, from the File Menu, choose New | Web Site. In the New Web Site dialog, select the MCMS SP2 Web Application icon in the My Templates section. Select HTTP in the Location list box. Enter http://localhost/TropicalGreen in the Location textbox, and click on OK. Our MCMS web application is created and opened in Visual Studio 2005.
Read more
  • 0
  • 0
  • 1606
Visually different images

article-image-flash-video-encoding-skinning-and-components-wordpress
Packt
26 Apr 2010
6 min read
Save for later

Flash Video Encoding, Skinning and Components in Wordpress

Packt
26 Apr 2010
6 min read
Encoding with the Adobe Media Encoder If you have a video file, such as an MOV or MP4 file that you want to display as a SWF on the Web, simply encode (or compress) the video file into an FLV. With Flash CS4, you use the Adobe Media Encoder to do this. It can be accessed directly or through Flash's import video function. If you are using an earlier version of Flash, encoding is still possible, and the process is similar. Getting ready Make sure that you have a video file that is compatible with the Adobe Media Encoder. If you do not have a file to use, by all means, use the short.mov file. This file is a clip of the full length summer.mp4 file from www.archive.org that is listed on that website as being in the Public Domain. Use the MOV file because it is a short file, so the time it takes the encoder to render the video will be shorter. This is good for the purposes of learning and practicing. Also, do not worry if you cannot hear any of the sounds. There is nothing wrong with the speakers on your computer. This file does not have audio. How to do it... Open the Adobe Media Encoder: Click on the Add button. Navigate to the file you want to encode, such as short.move, and click on Choose/OK. It is now listed in the queue: Click on the down arrow under Format to select into which file format you will encode the video. Choose FLV | F4V if not already selected. Click on the down arrow under Preset to choose one of the preset export setting options. The default of FLV - Same As Source (Flash 8 and Higher) is generally fine. If you have fewer standard video needs, make a different choice based on your needs. Also, there is an option to Edit Export Settings as well as a Settings button if you want to make your own decisions. See the Edit Export Settings section for more on that. Click on the file name under Output File to select the destination of your encoded file. You can also change the file name. Click on Start Queue, and the encoding process will begin. If you are encoding a long video, you might want to go take a walk or get a cup of tea. For short.mov, just sit tight. It should only take a minute or two to encode. Once encoding is complete, the FLV is saved in the location you chose under the Output File section. There is also a check mark under the encoder's Status section. Now, you can do what you want with the file. For instance, you can take it into Flash and import it into an SWF. How it works... The Adobe Media Encoder encodes the selected video file into the FLV format. It is similar to taking a Photoshop file or a TIFF and compressing either of them into a JPG. The process is simply more involved because the data is more complex. There's more... The Adobe Media Encoder has many options and capabilities. Among these is a wealth of export settings that can be edited to suit your needs. Also available to you is the ability to not only encode multiple files in one sitting but also to duplicate and remove files in your queue. Edit Export Settings With your file selected in the encoder, click on the Settings button. This gives you the Export Settings dialog box: As you can see, it has a lot of options. Only some of the myriad of options will be discussed below. At the top left of the dialog box are two buttons: Source and Output. Source shows the video file you have selected. Output shows a preview of the encoded version of the file. On the bottom/middle left of the Export Settings dialog box, you can address the timeline. You are able to clip the movie if you want to export only part of it; and you can set up cue points. To clip the movie, do the following: Drag the playback head back and forth to manually preview the movie. This helps you find the section you want to keep. Drag the in and out point triangles back and forth to isolate the section you want to keep. The triangle on the left is the in point, and the one on the right is the out point. Everything between the two triangles will be encoded. The timer keeps track of time in milliseconds. The right side of the dialog box allows you to change the desired file format; save your own preset with the button that looks like a computer disk circa 1996. You can also change the file name of the encoded video and choose if you are exporting only video, only audio, or both. The Summary section gives you just that, a summary of your choices thus far. The bottom right section gives you options for putting on a blur filter under the Filter tab and changing the format as applicable under the Format tab. The Video tab lets you choose which Codec to use to encode the video. On2 VP6 is usually the best choice. Stick with that one. It is more advanced, gives better quality, and allows you to encode an Alpha Channel if you have one to encode. Alpha Channels, areas of transparency in video (i.e., green screen), cannot be set up in Flash. They must be set up in a video editing program such as Premiere Pro or Final Cut Pro. The encoder can only honor them, not generate them. If you need to resize your video, check the box for Resize Video, and change the values as needed. If you want to constrain the proportions of your video, leave the chain whole. Frame rate can also be changed here. Generally, it is in your best interest to leave the video set to the same frame rate it was shot in. Same as source is a good choice. For Bitrate Settings, the defaults are usually pretty good. If you want higher quality and can take the additional file size, you can change Encoding Passes to Two. For Advanced Settings, you can change overall quality by selecting either Quality for Speed, Good, or Best. It all depends on your needs. For Audio, if you have it incorporated into your video file, choose Stereo. It sounds better. The only reason to go with Mono is if you have little sound, if it is a video of a talking head, or if your file size needs to be as small as possible. For Bitrate Settings for audio, 128 kb per second is good. Again, only turn this lower if the audio is overly simple, not important, or your file size dictates it. Faster bitrate/higher number gives you better quality sound. When you are finished making changes, click on OK. This gets you back to the encoder. Proceed from here as needed.
Read more
  • 0
  • 0
  • 1493

article-image-database-interaction-codeigniter-17
Packt
26 Apr 2010
4 min read
Save for later

Database Interaction with Codeigniter 1.7

Packt
26 Apr 2010
4 min read
(Read more interesting articles on CodeIgniter 1.7 Professional Development here.) Loading the library Loading the Database library is slightly different from loading other libraries. This is because it is large and resides in a different folder, unlike the other libraries. $this->load->database(); Performing simple queries Let's dive straight in by starting with the simple stuff. CodeIgniter gives us a function that we can pass a SQL Query to, and the query will be run on the database. Here's how it works: $this->db->query('PUT YOUR SQL HERE'); This function is incredibly simple to use; you simply use this function in place of any native PHP functions you would use to run queries. This function will return TRUE or FALSE for write queries, and will return a dataset for read queries. There is another function that you can use for very simple queries; this will only return TRUE or FALSE. It won't let you cache your query or run the query timer. In most cases you won't want to use this function. $this->db->simple_query('PUT YOUR SQL HERE'); The SQL code that you pass to these functions are database-dependent. Only Active Record queries are independent of any type of Database SQL. Returning values You can assign the function $this->db->query() to a variable. You can then run a number of helper functions on the variable in order to return the data in different formats. Take the following example: $query = $this->db->query('SELECT * FROM 'users''); Return a result object In this case, returning the result will return an array of objects, or an empty array if the query failed. You would usually use this function in a foreach loop. foreach($query->result() as $row){ echo $row->username; echo $row->email;} If your query does not return a result, the CodeIgniter User Guide encourages you to check for a failure before using this function. if($query->num_rows > 0){ foreach($query->result() as $row) { echo $row->username; echo $row->email; }} Returning a result array You are also able to return the result dataset as an array. Typically, you would use this function inside a foreach loop as well. foreach($query->result_array() as $row){ echo $row['username']; echo $row['email'];} Returning a row object If your query is only expected to return a single result, you should return the row by using the following function. The row is returned as an object. if($query->num_rows() > 0){$row = $query->row();echo $row->username;echo $row->email;} You can return a specific row by passing the row number as a digit in the first parameter. $query->row(2); Returning a row array You can return a row as an array, if you prefer. The function is used in the same way as the previous example. if($query->num_rows() > 0){ $row = $query->row_array(); echo $row['username']; echo $row['email'];} You can return a numbered row by passing the digit to the first parameter, also. $query->row_array(2); Result helper functions Besides the helper function that helps to return the dataset in different ways, there are some other more generalized helper functions. Number of rows returned Used in the same way as the other helper functions, this will return the total number of rows returned from a query. Take the following example: echo $query->num_rows(); Number of fields returned Just like the previous function, this will return the number of fields returned by your query. echo $query->num_fields(); Free result This function will remove the resource ID associated with your query, and free the associated memory. PHP will usually do this by default, although when using many queries you may wish to use this to free up memory space. $query->free_result();
Read more
  • 0
  • 0
  • 1981

article-image-form-validation-codeigniter-17
Packt
26 Apr 2010
8 min read
Save for later

Form Validation with Codeigniter 1.7

Packt
26 Apr 2010
8 min read
Form validation is an important part of any application. Take a look at your favorite web application, notice that there are many forms in these web apps, and it is important that they be secure. It is also important that you have rules that should be adhered to; this also helps to keep a layer of security. In this article by Adam Griffiths, author of CodeIgniter 1.7 Professional Development, you will: Learn how the form validation process works Build a contact form Apply validation rules to the form's input fields Use callbacks to create your own rules We will cover database interaction seperately. (Read more interesting articles on CodeIgniter 1.7 Professional Development here.) Why should I validate my forms? The answer to this question is simple: security. If you simply left your forms bare, with no validation, and then stored this information directly in a database, you are liable to attack. People can simply place in some SQL code and can see a dump of a part or all of your database. By using form validation and creating rules, you will disallow most, if not all, of these practices from occurring. By having set validation rules you can limit the types of data being allowed in your forms. Best of all, the Form Validation Library makes it easy to re-populate your form fields and to show individual errors for each field, making the overall end user experience better; which can mean a lot in an environment with many forms. Even if you are building a contact form, it is a good idea to validate your forms to stop people abusing your form. Using the Form Validation Library In this article, we'll go over a Contact Form and how to use the Form Validation Library methods for validation. The form validation process The Form Validation processes are different for the developers and for users. Read on to see how the user interacts with the forms, as well as how the developer will create the forms. The user's process A form is displayed to the user, who then fills it in and submits it. The Form Validation Library then checks the form against any rules that the developer has set. If an error occurs the library returns these errors and they are shown against the form with the fields re-populated. This process proceeds until a valid form is submitted. The development process You create a form, along with a dynamic value from a form helper function—this will re-populate the data if needed. You will also display individual or global errors in the form view file. You set validation rules, which must be adhered to. Then you check to see if the validation process has been run, and if it has not, you load the form view file. Contact form We validate the form data using the Form Validation Library to complete tasks such as checking for empty fields, validating the e-mail, and then send the e-mail off. All of the code shown should be in the index() function of your email controller. Loading the assets We need to load two libraries for our contact form: the Form Validation Library and the Email class. We can do this in one line, by passing an array to the load->library function. $this->load->library(array('email', 'form_validation')); We also need to load two helpers: the email helper and the form helper. We will do this in the same way as we loaded the two libraries in the previous line of code. $this->load->helper(array('email', 'form')); Setting the rules The next step in using the Form Validation Library is to set the rules for the form. These rules are set and must be adhered to. The way we set rules is by using the set_rules() function of the Form Validation Library. We use the function as follows: $this->form_validation-> set_rules('field_name', 'human_name', 'rules'); As you can see, the function accepts three parameters. The first is the name of the form field that you wish to set the rule for. The second parameter is the name that you wish to be assigned to this, for humans to read. The final parameter is where you pass any validation rules. List of validation rules The following rules are readily available for use: required matches[field_name] min_length[x] max_length[x] exact_length[x] alpha alpha_numeric alpha_dash numeric integer is_natural is_natural_no_zero valid_email valid_emails valid_ip valid_base64 As you can see, some of these rules have a single parameter. The rule matches[] will return TRUE if the field matches the field name passed to it. The min_length[], max_length[], and exact_length[] rules will take an integer as a parameter and check if the minimum length, maximum length respectively, or exact length matches the rule. The rules with no parameters are pretty much self-explanatory. You are able to use more than one rule, simply separate rules with a vertical bar '|' and they will cascade. These rules can also be called as discrete functions. You may also use any native PHP function that accepts one parameter as a rule. $this->form_validation->required($string);$this->form_validation->is_array($string); // native PHP // function as a rule Prepping data We can also use various prepping functions to prep the data before we apply rules to it. Here's a list of the prepping rules that we can perform: xss_clean prep_for_form prep_url strip_image_tags encode_php_tags The first function listed is xss_clean. This basically strips out any code and unwanted characters, and replaces them with HTML entities. The function prep_for_form will convert special characters so that HTML data can be shown in a form without breaking it. The function prep_url will simply add http:// to a URL, if it is missing. The function strip_image_tags will remove image tags, leaving the RAW image URL. The function encode_php_tags will convert PHP tags into entities. You may also use any native PHP function that accepts one parameter as a rule. The rules Now that we know how to set rules and what the rules we can use are, we can go ahead and set the rules necessary for our form. All fields should be required, and the e-mail field should be validated to ensure that the e-mail address is correctly formatted. We also want to run all of the data through the XSS filter. $this->form_validation-> set_rules('name', 'Name', 'required|xss_clean');$this->form_validation-> set_rules('email', 'Email Address', 'required|valid_email|xss_clean');$this->form_validation-> set_rules('subject', 'Subject', 'required|xss_clean');$this->form_validation->set_rules('message', 'Message', 'required|xss_clean'); Check the validation process Instead of checking one of the form field's POST value to check if the form has been submitted, we simply check to see if the Form Validation Library has run. We do this by using the following code: if($this->form_validation->run() === FALSE){ // load the contact form}else // send the email} It's fairly simple: if the Form Validation Library hasn't processed a form, we display the form to the user; if the library has processed a form and there are no errors, we'll send the e-mail off. Sending the email As you'll notice, everything is the same as how we got the field data earlier. $name = $this->input->post('name');$email = $this->input->post('email');$subject = $this->input->post('subject');$message = $this->input->post('message'); $this->email->from($email, $name);$this->email->to('[email protected]'); $this->email->subject($subject);$this->email->message($message); $this->email->send(); Final controller code Here is the entirety of our controller code: <?phpclass Email extends Controller{function Email(){parent::Controller();} // function Email()function index(){$this->load->library(array('email', 'form_validation'));$this->load->helper(array('email', 'form'));$this->form_validation->set_rules('name', 'Name', 'required|xss_clean');$this->form_validation->set_rules('email', 'Email Address','required|valid_email|xss_clean');$this->form_validation->set_rules('subject', 'Subject', 'required|xss_clean');$this->form_validation->set_rules('message', 'Message', 'required|xss_clean');if($this->form_validation->run() == FALSE){$this->load->view('email'); // load the contact form}else{$name = $this->input->post('name');$email = $this->input->post('email');$subject = $this->input->post('subject');$message = $this->input->post('message');$this->email->from($email, $name);$this->email->to('[email protected]');$this->email->subject($subject);$this->email->message($message);$this->email->send();}} // function index()} // class Email extends Controller?>
Read more
  • 0
  • 0
  • 3486
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-customizing-kubrik-wordpress
Packt
19 Apr 2010
5 min read
Save for later

Customizing Kubrik with Wordpress

Packt
19 Apr 2010
5 min read
Getting ready The first step is to make a list of the changes that you want to make. Here's what we've come up with: Increase width to 980px Increase font sizes in sidebar Use a graphic header We've picked 980px as our target width because this size is optimized for a 1024 screen resolution and works well in a grid layout. Several CSS adjustments will be necessary to realize this modification, as well as using an image editing program (we will be using Photoshop). How to do it... To increase the page width, the first step is to determine which entries in the CSS stylesheet are controlling the width. Using Firebug to inspect the page (as seen below), we find that the selector #page has a value of 760px for the width property. And #header has a width of 758px (less because there is a 1px left margin). The .narrowcolumn selector gives the main content column a width of 450px. And #sidebar has a width of 190px. Finally, #footer has a width of 760px. So, we will increase #page and #footer to 980px. #header we will increase to 978px. Let's apply all of the additional 220px width to .narrowcolumn. Taking note of the existing 45px left margin, our new value for the width property will be 700px. That means #sidebar width will remain at 190px, but the margin-left will need to be increased from 545px to 765px. Click on Appearance | Editor. In the right-hand column, below the Templates heading, click on style.css. Scroll past the section that says /* Begin Typography & Colors */, until you get to the section that says /* Begin Structure */. Make the following changes to the stylesheet (style.css), commenting as appropriate to document your changes. #page { background-color: white; margin: 20px auto; padding: 0; width: 980px; /* increased from 760px */ border: 1px solid #959596; }#header { background-color: #73a0c5; margin: 0 0 0 1px; padding: 0; height: 200px; width: 978px; /* increased from 758px */ }.narrowcolumn { float: left; padding: 0 0 20px 45px; margin: 0px 0 0; width: 700px; /* increased from 450px */ }#sidebar {margin-left:765px; /* increaseed from 545px */padding:20px 0 10px;width:190px;}#footer { padding: 0; margin: 0 auto; width: 980px; /* increased from 760px */ clear: both; } Adjustments via Photoshop We'll also need to use an image editing program to modify the three background images that create the rounded corners: kubrikbg-ltr.jpg, kubrickheader.jpg, and kubrickfooter.jpg. In this example, we modify kubrik-ltr.jpg (the background image for #page), a 760px image. Open up the image in Photoshop, select all, copy, create a new document (with a white or transparent background), and paste (Ctrl-A, Ctrl-C, Ctrl-N, Ctrl-V). Increase the canvas size (Image | Canvas Size) to 980px, keeping the image centered on the left-hand side by clicking on the left-pointing arrow. Select one half of the image with the Rectangular Marquee Tool, cut and paste. Use the Move Tool to drag the new layer to the right-hand side of the canvas. In this case, it does not matter if you can see the transparent background or if your selection was exactly one half the image. Since the middle of the image is simply a white background, we are really only concerned with the borders on the left and right. The following screenshot shows the background image cut in half and moved over: Save for Web and Devices, exporting as a jpg. Then, replace the existing kubrikbgltr.jpg with your modified version via FTP. The steps are similar for both kubrickheader.jpg and kubrickfooter.jpg. Increase the canvas size and copy/paste from the existing image to increase the image size without stretching or distortion. The only difference is that you need to copy and paste different parts of the image in order to preserve the background gradient and/or top and bottom borders. In order to complete our theme customization, the width of .widecolumn will need to be increased from 450px to 700px (and the 150px margin should be converted to a 45px margin, the same as .narrowcolumn). Also, the kubrikwide.jpg background image will need to be modified with an image editing program to increase the size from 760px to 980px. Then, the individual post view will look as good as the homepage. By following the same steps as above, you should now be prepared to make this final customization yourself. Our next goal is to increase the sizes of the sidebar fonts. Firebug helps us to pinpoint the relevant CSS. #sidebar h2 has a font-size of 1.2em (around line 123 of style.css). Let's change this to 1.75em. #sidebar has font-size of 1em. Let's increase this to 1.25em. To use a graphic in the header, open up kubrickheader.jpg in a new Photoshop document. Use the magic wand tool to select and delete the blue gradient with rounded corners. Now, use the rounded rectangle tool to insert your own custom header area. You can apply another gradient, if desired. We choose to apply a bevel and emboss texture to our grey rectangle. Then, to paste in some photos, decreasing their opacity to 50%. In a short time, we've been able to modify Kubrik by re-writing CSS and using an image-editing program. This is the most basic technique for theme modification. Here is the result:
Read more
  • 0
  • 0
  • 991

article-image-video-blogging-wordpress
Packt
16 Apr 2010
7 min read
Save for later

Video Blogging in Wordpress

Packt
16 Apr 2010
7 min read
Introduction Video is a major component of the Web today. Luckily, WordPress makes it easy to publish and share video. In this article, we will demonstrate ways of working with video in WordPress and in Flash. You will learn how to embed an .flv file, create an .xml video sitemap, and distribute your videos to sites such as YouTube and Blip. We will also show you how to set up Free WP Tube, a free video blogging theme that allows you to run a video web log (vlog). FLV Embed (Version 1.2.1) If you want to embed .flv files, use a Flash video player, and/or publish a video sitemap, this compact plugin does all three. The homepage is http://www.channel-ai.com/blog/plugins/flv-embed/. FLV Embed uses standards compliant, valid XHTML, and JavaScript. It is based on the JW FLV Media Player, whose homepage is http://www.longtailvideo.com/players/jw-flvplayer/ FLV Embed supports Google video sitemap generation, allowing you to describe, syndicate, and distribute your video content, facilitating indexing in Google video search. If a user is missing Flash or has disabled JavaScript, he or she is provided unobtrusive and appropriate on-screen instructions to correct the problem. Getting ready When a page with video loads, the player displays either the first frame of the video or a thumbnail (referred to as a poster image). The poster image is preferable, especially when a user is choosing between many videos—the first frame of a video may not offer the most representative or compelling description. Your poster image can be a poster or any image you like. Here is an example of our finished product: You will want to think about where you will upload the video files and poster images and,how you will name them. A good place might be wp-content/uploads/video. This plugin requires that you name your poster images the same as your video files. The default image type is jpg, but you can use any valid image file format. All your images must be in the same file format. A batch resize and rename utility is a useful tool. For PC, one free option is the Fast Stone Image Resizer, which you can download at http://www.faststone.org/FSResizerDetail.htm. How to do it... In your dashboard, navigate to Plugins | Add New. Search for "FLV Embed". Click on Install, then on Activate. Visit the plugin configuration panel at Settings | FLV Embed. In the Sitemap menu, check the first box to Enable sitemap feature and automatic custom field addition. FLV Embed will now be able to create your video sitemap by automatically adding a custom field each time you use FLV Embed to insert a video. In the Poster menu, check the box to Display poster image for embedded FLV movies. For both of the fields, Path to poster directory and Path to FLV directory, we suggest you leave these blank, and instead use absolute URLs. If you do use relative (site-specific) URLs, keep in mind that a trailing slash is required. An example is /wp-content/uploads/videos/. In the Player menu, you may want to change the colors or add your site logo as a linkable watermark to the video. Review all the Settings, and click on Save Changes. To embed an FLV file, use the following shortcode in HTML view: [flv:url width height]. For example, you could insert a YouTube video at 480 by 360 (using the absolute URL) like this: [flv:http://youtube.com/watch?v=fLV3MB3DpWN 480 360] A YouTube video cannot use a poster image because the file name of a jpg cannot contain a question mark. You can also insert an FLV that you have uploaded (using the relative path) like this: [flv:http://www.wordpressandflash.com/wp-content/uploads/video/swfobject_test.swf 480 360] Once you have inserted the video, FLV Embed automatically populates the FLV custom field with two URLs, as you can see below. The first is the location of the video, and the second is the location of the poster image: To use a custom poster image, upload any image to wp-content/uploads/video, and rename it to match the filename. You can also use an absolute URL if the poster image file is in another location—the filename must still match. To configure your video XML sitemap, visit the Video Sitemap Options menu by clicking on Settings | Video Sitemap. Here, you can get or modify the feed address. Our example is http://www.wordpressandflash.com/ videofeed.xml You can also adjust additional optional settings, and if you have made any changes to the settings or content and need to rebuild the sitemap or update your custom fields, you can do that here too. How it works... The video sitemap is an extension of the XML sitemap. A video sitemap allows you to publish and syndicate online video content, including descriptive metadata to tag your content for Google Video search. Adding details, such as a title and description, makes it easier for users who are searching to find a given piece of content. Your poster image will also be included as a clickable thumbnail image. The user will be directed to your website to see the video. If FLV Embed cannot automatically generate the XML file, you can simply copy the XML file from the demo and save it to your server. Make sure to set the file permissions to write (664 or 666) by context-clicking in your FTP client and modifying the File Attributes, as seen below: Then, make the appropriate changes to the Video sitemap filename field in the Video Sitemap Options menu, directing the plugin to the XML file you have prepared, and rebuild the sitemap. Here is what your finished feed will look like: There's more... The videofeed.xml file has a simple structure. The first three tags specify encoding, styling, and the video sitemap protocol: <?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl"href="http://www.wordpressandflash.com/wp-content/plugins/flv-embed/sitemap.xsl"?><urlset > Next, a <url> tag wraps each piece of content, which includes a <loc> tag (a link to the content on your site) and a <videogt; tag. The <videogt; tag contains additional tags that specify the video location, the video player location, the poster image location, a title, and description: <url> <loc>http://www.wordpressandflash.com/flv-embed/</loc> <video:video> <video:content_loc>http://www.wordpressandflash.com/wp-content/uploads/video/swfobject_test.swf</video:content_loc> <video:player_loc allow_embed="No">http://www.wordpressandflash.com/wp-content/plugins/flv-embed/flvplayer.swf?file=/wp-content/uploads/video/swfobject_test.swf</video:player_loc> <video:thumbnail_loc>http://www.wordpressandflash.com/wp-content/uploads/videos/swfobject_test.jpg</video:thumbna il_loc> <video:title><![CDATA[FLV Embed]]></video:title> <video:description><![CDATA[FLV Embed is a great plugin thatallows you to display FLV files &#8212; and most other video formats&#8212; in a compact Flash video player. Visit the homepage at:http://www.channel-ai.com/blog/plugins/flv-embed/. Check out thevideo sitemap!Get the latest Flash Player to see this player.[Javascript required to view Flash movie, please turn it [...]]]></video:description> </video:video></url></urlset> With this info, you can manually create a .xml video feed for any site, without a plugin. Commercial use? Commercial use does require a license. A free alternative for commercial use is the Hana FLV Player, whose homepage is http://www.neox.net/w/2008/05/25/hana-flv-playerwordpress-plugin/.
Read more
  • 0
  • 0
  • 2326

article-image-manipulation-dom-objects-using-firebug
Packt
16 Apr 2010
3 min read
Save for later

Manipulation of DOM Objects using Firebug

Packt
16 Apr 2010
3 min read
Inspecting DOM The DOM inspector allows for full, in-place editing of our document structure, not just text nodes. In the DOM inspector, Firebug auto completes property value when we press the Tab key. The following are the steps to inspect an element under the DOM tab: Press Ctrl+Shift+C—the shortcut key to open Firebug in inspect mode. Let's move the mouse pointer over the HTML element that we want to inspect and click on that element. The HTML script of that element will be shown in Firebug's HTML tab. Right-clicking on the selected DOM element will open a context menu. Let's select the Inspect in DOM Tab option from the context menu. As soon as we do that, Firebug will take us to its DOM tab. Filtering properties, functions, and constants Many times we want to analyze whether a function written by us is associated with an HTML element. Firebug provides us an easy way to figure out whether an event, listener, function, property, or constants are associated with a particular element. The DOM tab is not only a tab but also a drop-down menu. When we click on the down arrow icon on the DOM tab, Firebug will show a drop-down list from which one can select the filtering options and inspect the element thoroughly. The following are the options provided by this menu: Show User-defined Properties Show User-defined Functions Show DOM Properties Show DOM Functions Show DOM Constants Refresh There are two kinds of objects and functions: Part of the standard DOM Part of our own JavaScript code Firebug can notify the difference, and shows us our own script-created objects and functions in bold at the top of the list. The text that is bold and green is a user-defined function. The text that is bold and black is a user-defined property. The text whose size is normal and is green in color is a DOM-defined function. The text whose size is normal and is black in color is a DOM-defined property. The upper case letters (capital letters) are the DOM constants. We can see the actual colored depiction in Firebug's DOM tab. In the following code, the onkeyup() event is a user-defined function for <input/> and calculatefactorial() is a user-defined function for the current window. To test this code, let's type the code in an HTML file, open it with Firefox, and enable Firebug by pressing the F12 key. Inspect the input element in the DOM. <html><head><script>function calculateFactorial(num,event){if(event.keyCode!=13){return;}var fact=1;for(i=1;i<=num;i++){fact*=i;}alert ("The Factorial of "+ num + " is: " +fact)}</script><title>code_6_1.html.html</title></head><body><font face="monospace">Enter a number to calculate its factorial<input type = "text" name="searchBox" onkeyup="calculateFactorial(this.value,event)"/></font></body></html> Intuitive DOM element summariesThere are many different kinds of DOM and JavaScript objects, and Firebug does its best to visually distinguish each, while providing as much information as possible. When appropriate, objects include brief summaries of their contents so that we can see what's there without having to click. Objects are color coded so that HTML elements, numbers, strings, functions, arrays, objects, and nulls are all easy to distinguish.
Read more
  • 0
  • 0
  • 2560

article-image-getting-started-development-environment-using-microsoft-content-management-server
Packt
15 Apr 2010
8 min read
Save for later

Getting Started with the Development Environment Using Microsoft Content Management Server

Packt
15 Apr 2010
8 min read
Visual Web Developer Websites The key difference between developing MCMS applications with Visual Studio .NET 2003 and Visual Studio 2005 is that ASP.NET applications (and therefore MCMS applications) are now built using the Visual Web Developer component of Visual Studio 2005. Visual Web Developer introduces a new "project system", which no longer uses the project (*.csproj) files and simply accesses web applications via HTTP or the file system. In Visual Studio .NET 2003, MCMS applications were created by choosing the MCMS Web Application project type. This project type was effectively a regular ASP.NET web application project with some modifications required by MCMS, such as additional references, the web authoring console, and modifications to the web.config. In Visual Studio 2005, developing web applications has been separated from developing other project types. The feature to develop a web application has been moved into the Visual Web Developer component. To reflect this design change, you are no longer using New Project but New Web Site from the File menu in Visual Studio 2005 to create a new website. Visual Studio 2005 ships with several website templates. The installation of the developer tools for MCMS extends the list of website templates with three additional templates: MCMS Empty Web Project, MCMS Web Application, and MCMS Web Service. These templates are actually modified versions of the similarly named standard templates shipped with Visual Studio 2005. Creating an MCMS Web Application Let's create an MCMS web application using Visual Studio 2005. Open Visual Studio 2005. From the File menu, choose New, followed by Web Site… In the New Web Site dialog, select the MCMS Web Application within the My Templates section. If the MCMS Web Application template does not appear in the My Templates section, the MCMS Visual Studio 2005 templates have not been correctly installed. Please refer to the Visual Studio Templates section of Article 1 for installation details. In the Location combo box, select HTTP, and in the textbox, enter http://localhost/mcmstest. MCMS applications have to be created using a local installation of IIS and do not support being created using the file system, which makes use of the built-in Visual Web Developer Web Server. Note that the New Web Site wizard will not prevent you from configuring an invalid website using the File System and Visual Web Developer Web Server. In the Language combo box (shown in the following figure), select Visual C#, and click on OK. If you wish, you can also choose VB.NET. The samples in this article series are all written in Visual C#. Visual Studio 2005 will create your project and initialize the MCMS Template Explorer. When it's done, you will be presented with an MCMS website with the basic foundation files. The MCMS Template Explorer within Visual Studio 2005 logs on to the MCMS repository using the credentials of the currently logged-on user. If this operation fails, check your MCMS Rights Groups configuration. The Template Explorer does not allow you to specify alternative credentials. Click on the MCMS Template Explorer tab at the bottom of the Solution Explorer, and note that the Template Gallery is accessible. If you don't see the Template Explorer, it is likely you didn't select HTTP in the Location combo box in step 4. You may also not see the Template Explorer if you are using a locale other than US English, in which case you need to install hotfix 914195 as detailed in Article 1. Click on the Solution Explorer tab at the bottom of the MCMS Template Explorer, and click on the Refresh button. Notice that unlike the web applications from ASP.NET 1.x days, the 'CMS' virtual directory is now part of the website. If you examine the contents of the website, its references, and web.config file, you will see that the necessary MCMS files and configuration changes have been added. Checking the Website Configuration Settings in IIS We can verify that Visual Studio 2005 has configured the MCMS application correctly by using the Internet Information Services snap-in. First, let's ensure that the mcmstest website is indeed running on ASP.NET 2.0. From the Start Menu click on Run, enter inetmgr in the Run textbox, and click on OK. In Internet Information Services, expand the tree view to display the mcmstest application. Right-click the mcmstest application and click on Properties. Click the ASP.NET tab and note that the ASP.NET version is correctly configured as 2.0.50727. When developing on Windows Server 2003, the Virtual Website root must run in the same worker process (that is Application Pool) as all MCMS applications so that the MCMS ISAPI Filter can work as expected. This filter cannot route requests across worker-process boundaries. In effect this means that all MCMS applications will share the same ASP.NET version, as ASP.NET does not support side-by-side execution of different versions inside the same worker process. This is not necessary with IIS on Windows XP as it does not use Worker Process Isolation mode. Next, we will check the authentication settings. For now, we will configure the website to use integrated Windows authentication. Only users with a domain or local user account will have access to the site. Later in Article 6 we will show alternative authentication methods such as Forms Authentication. Click on the Directory Security tab followed by the Edit... button, and note that the permissions are correctly inherited from the Virtual Web Site settings. In this example, we will use integrated Windows authentication. Note that we configured the Virtual Web Site to use Windows authentication in Article 1. Authentication methods can be configured on a per-application basis. Click on Cancel and close Internet Information Services. Developing MCMS Web Applications We are now ready to get started on developing our ASP.NET 2.0-based MCMS applications. There are a number of quirks with the MCMS web application templates, which we need to bear in mind during development. Switch back to Visual Studio 2005. In Solution Explorer, right-click on the website (http://localhost/mcmstest), and click on New Folder. Enter Templates as the folder name. Right-click on the Templates folder and click on Add New Item… In the Add New Item dialog, select the MCMS Template File item and enter Basic.aspx in the Name textbox. Click on Add. The new Basic.aspx template file is created and opened in Source View. Examine the contents of Basic.aspx. Correcting Basic.aspx Notice that the Basic.aspx file has a few problems. Some elements are highlighted by IntelliSense "squiggles", and if we attempt to build the website, a number of errors will prevent a successful build. Let's correct the Basic.aspx template file. In the CodeFile attribute of the Page directive on line one, replace CodeFile="~/Basic.aspx.cs" with CodeFile="basic.aspx.cs" The MCMS Web Application New Item template doesn't recognize that our new template file has been created in a subdirectory, and therefore the CodeFile attribute is incorrect. New templates in the web root are not affected. From the Build menu, choose Build Web Site. Notice that the website now builds, but still includes a number of errors. Correct the DOCTYPE. On line 19, replace <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> with <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Correct the <html> element. On line 20, replace <html> with <html >. Delete the comments on lines 4 through 17. The comments within an inline ASP script block (<% %>) are unnecessary. Delete the <meta> tags on lines 10 through 13. <meta name="GENERATOR" content="Microsoft Visual Studio .NET 8.0"><meta name="CODE_LANGUAGE" content="C#"><meta name="vs_defaultClientScript" content="JavaScript"><meta name="vs_targetSchema"content="http://schemas.microsoft.com/intellisense/ie5"> These <meta> tags are unnecessary. Correct the WebControls Register directive. On line 2, replace: <%@ Register TagPrefix="cms" Namespace="MicrosoftContentManagement.WebControls" Assembly="Microsoft.ContentManagement.WebControls"%> with <%@ Register Assembly="Microsoft.ContentManagement.WebControls,Version=5.0.1200.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="Microsoft.ContentManagement.WebControls"TagPrefix="cms"%> The original Register directive is not correctly recognized by Visual Studio 2005, and prevents IntelliSense from including the cms tag prefix. From the Build menu, choose Build Web Site. Notice that the website now builds free of any errors and that the cms tag prefix is understood. Your template file should now be as follows: <%@ Page language="c#" AutoEventWireup="false" CodeFile="Basic.aspx.cs" Inherits="Basic.Basic"%><%@ Register Assembly="Microsoft.ContentManagement.WebControls,Version=5.0.1200.0, Culture=neutral, PublicKeyToken= 31bf3856ad364e35"Namespace="Microsoft.ContentManagement.WebControls"TagPrefix="cms"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html > <head> <title>Basic</title> <cms:RobotMetaTag runat="server"></cms:RobotMetaTag> </head> <body> <form id="Form1" method="post" runat="server"> </form> </body></html>
Read more
  • 0
  • 0
  • 1107
article-image-creating-tumblr-theme
Packt
15 Apr 2010
13 min read
Save for later

Creating a Tumblr Theme

Packt
15 Apr 2010
13 min read
At this moment, surely, you must have heard something about Tumblr, but in case you haven't, we can summarize by telling it's a platform for microblogging. We can publish texts, audio, photos, quotes, links etc in a very easy way. As other users can follow our posts, comment on them or ask questions to us, Tumblr can be considered a great social tool. Apart from being very easy to use, we can also customize it's appearance, so it shares our business look and feel, or simply because we prefer some other appearance. Not only can we customize it's appearance, but also design our own customized themes; that's exactly what we are going to do in this article: What we have and what we want First steps, a basic html template Generating the Tumblr theme from our template Adding a bit of jQuery Keep with us and by the end of the article, you will learn how to create very interesting Tumblr themes, and use also them. What we have and what we want For this article, we are going to use my own account as an example. For now, I'm using a theme that looks this way: This is a great theme, very clean, centered on showing our content. The theme we are going to create is going to be very clean too, and also enough for us to see how we can create a template. Let's take a look at it: As you can see, it's a quite easy design; hope you like it too. Also, you can download the PSD if you wish, maybe it will help you follow the article. Well, once we know which design we want to use, our next step will be to generate a plain html template. First step, a basic html template A basic html template is a good place to start our theme, and that's where we are going to start. First the basic structure: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html ><head> <title>Our first theme</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> </head> <body id="theme"> <div id="container"> <div id="menu"> <a href="#" class="menu_link">About me</a> | <a href="#" class="menu_link">Archives</a> | <a href="#" class="menu_link">Random</a> | <a href="#" class="menu_link">Mobile</a> | <a href="#" class="menu_link">RSS</a> </div> <div id="right_col"> <div class="post"> <div class="post_type"> <div class="blue_box">Text</div> <a href="#" class="content_link">Permalink</a> </div> <div class="date"> <div class="blue_box">Mar 22</div> Posted at 7:54am </div> <div class="post_contents"> <h1>Codeigniter 1.7</h1> <p> <img src="sample_image.jpg" /> <br/> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean fermentum  vestibulum nisl vitae placerat. Praesent nec massa neque. Nam dictum commodo posuere. Sed vitae est risus. Nunc suscipit justo vitae mi faucibus cursus. Morbi eu arcu erat. Nam venenatis, urna non tempus pretium, felis nunc blandit risus, non elementum elit turpis in diam. Proin ullamcorper blandit lacinia. Nulla nibh metus, lacinia at luctus vel, tincidunt et mauris. Sed rutrum, felis in tincidunt porttitor, nulla nunc placerat elit, ac tempor magna arcu non nisi. Proin ac sagittis lorem. Morbi imperdiet consectetur ipsum, volutpat convallis arcu pulvinar in. Nulla eget quam elit, vitae molestie ligula. Praesent rhoncus diam id lorem sagittis consequat ac et magna. </p> <hr> </div> </div> </div> <div id="left_col"> <div id="description"> <h1>Jose Argudo's Blog!</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean fermentum vestibulum nisl vitae placerat. Praesent nec massa neque. Nam dictum commodo posuere. Sed vitae est risus. Nunc suscipit justo vitae mi faucibus cursus. Morbi eu arcu erat. Nam venenatis, urna non tempus pretium, felis nunc blandit risus, non elementum elit turpis in diam. </p> </div> <div class="banner"> <img src="codeigniter_book.gif" /> &nbsp;&nbsp; Check my Codeigniter book </div> </div> <div id="footer"> <div id="left_footer"> Jose Argudo´s Blog </div> <div id="right_footer"> <img src="arrow.gif" /> </div> </div> </div> </body></html> We have our basic html structure here, quite simple by now, all html without any styling as of now. Our next step will be to add some css to our basic page, which, by now, looks more or less this way: Some reset css will be useful here, I usually use Eric Meyer's one, which you can find here: http://meyerweb.com/eric/tools/css/reset/ We are going to place this code in the head section of our page, just like this: ... <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <style type="text/css" media="screen"> /* CSS reset from Eric Meyer */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } :focus { outline: 0; } ins { text-decoration: none; } del { text-decoration: line-through; } table { border-collapse: collapse; border-spacing: 0; } </style> We have included this css styles in our html file, instead of including it from an external source. Why have we done that? Mostly because we have no ftp access to our Tumblr account, also themes are not packed in a zip file and installed somehow. Soon we will be answering all these questions; for now, placing our css styles directly in our html is the best solution. Now that we have added our reset styles, we can start working in the theme own styles, let's see: /* Theme's own styles */ #theme{ font-family: arial, sans-serif; font-size: 12px; color: #333333; background-color: #F5F5F5; } #container{ width: 960px; margin: 20px auto; } #menu{ height: 22px; } #left_col{ float: left; width: 320px; } #right_col{ float: right; width: 630px; } #footer{ float: none; clear: both; height: 20px; } #description, .banner{ background-color: #0087C5; padding: 12px; color: #ffffff; margin-bottom: 5px; } #description h1{ font-size: 24px; margin-bottom: 15px; } #description p{ line-height: 18px; } .banner{ font-style: italic; font-size: 10px; } .post_type{ width: 54px; float: left; margin-left: 10px; } .date{ width: 54px; float: left; color: #0087C5; font-style: italic; font-size: 10px; } .post_contents{ margin-left: 10px; margin-bottom: 22px; width: 500px; float: right; } .blue_box{ height: 54px; background-color: #0087C5; color: #ffffff; font-size: 14px; padding: 6px; padding-bottom: 0px; margin-bottom: 10px; } .post_contents h1{ font-size: 18px; color: #0087C5; margin-bottom: 22px; } .post_contents img{ margin-bottom: 24px; } .post_contents p{ line-height: 18px; } hr{ height: 1px; color: #0087C5; border: 1px solid #0087C5; } a.content_link:link, a.content_link:visited{ color: #0087C5; font-style: italic; font-size: 10px; text-decoration: none; } a.content_link:hover{ text-decoration: underline; } #menu{ color: #0087C5; } a.menu_link:link, a.menu_link:visited, a:link, a:visited{ color: #0087C5; font-size: 12px; text-decoration: none; } a.menu_link:hover, a:hover{ text-decoration: underline; } #left_footer{ width: 332px; height: 20px; float: left; background-color: #0087C5; color: #ffffff; } #right_footer{ width: 43px; float: right; } .padd{ padding: 4px; } .clear{ clear: both; float: none; } With these styles our template will be looking very similar to our design, maybe later we will need some small changes, but that's not so important. With all this in place, we can start with the interesting work, the Tumblr part. Generating the Tumblr theme from our template Converting this template into a working Tumblr theme is not going to be that hard, mostly we will be using some special tags to determine where some specific contents will be placed. Tumblr uses two type of tags Variable tags Block tags But we will see that better by working with our theme, for example, our page title: <title>Our first theme</title> We will change that for this code: <title>{Title}</title> In bold, we can see a {Title} tag. This tag, when rendered will be substituted by the title of our blog, without any html tag. Easy, isn't it? Most of our work will be quite similar, we are going to see the main tags to use. One of our main work will be showing the posts, after all, our main objective is to show these posts. Tumblr divides posts into eight possible types: Text posts, with only text and html. Photo posts, with one photo and its description Photosets, for when you need to show more than one photo Quote, used when we want to quote other site or source Link to other sites or online resources Chat, interesting option, for showing conversation, where each line, separated be a carriage return, is show in a different color. Audio, from an uploaded or external source Video, similar to audio but with videos. In our html code, we have prepared a zone for showing posts: <div class="post"> <div class="date"> <div class="blue_box">Mar 22</div> Posted at 7:54am </div> <div class="post_type"> <div class="blue_box">Text</div> <a href="#" class="content_link">Permalink</a> </div> <div class="post_contents"> . . . <hr> </div> </div> <br class="clear" /><br/> Now we need to generate one of these post zone for each post type. It's important to note that this is absolutely necessary for the theme to be correct, all post type must be present in our code. Firstly, we need to define these tags: {block:Posts} … {/block:Posts} All the other types of posts will go into these tags, let's summarize it a bit: {block:Posts} {block:Text} Text posts will go inside these tags {/block:Text} {block:Photo} Photo posts will go inside these tags {/block:Photo} {block:Photoset} Photoset posts will go inside these tags {/block:Photoset} {block:Quote} Quote posts will go inside these tags {/block:Quote} {block:Link} Link posts will go inside these tags {/block:Link} {block:Chat} Chat posts will go inside these tags {/block:Chat} {block:Audio} Audio posts will go inside these tags {/block:Audio} {block:Video} Video posts will go inside these tags {/block:Video} {/block:Posts} Now, we will be working on each one of these blocks. Remember that we will be placing them between {block:Posts} … {/block:Posts}, so we will have more or less this code: <div id="right_col"> {block:Posts} All the other block types will go here {/block:Posts}</div> Text Posts We will start with this type of posts, I will put the code and after we take a look at the different options {block:Text} <div class="post"> <div class="date"> {block:Date} {block:NewDayDate} <div class="blue_box">{Month} {DayOfMonth}</div> Posted at {12Hour}{AmPm} {/block:NewDayDate} {block:SameDayDate} <div class="blue_box">{Month} {DayOfMonth}</div> Posted at {12Hour}{AmPm} {/block:SameDayDate} {/block:Date} </div> <div class="post_type"> <div class="blue_box">Text</div> <a href="{Permalink}" class="content_link">Permalink</a> </div> <div class="post_contents"> {block:Title} <h1>{Title}</h1> {/block:Title} <p> {Body} </p> <hr> </div> </div> <br class="clear" /><br/> {/block:Text} Here we have some interesting tags, let's talk a bit about them: {block:Date} — this will render the date, with the options we are defining inside. {block:NewDayDate} — this is used for showing the date, but it's only show for the first post of the day. {block:SameDayDate} — If we want to show the date in each post, we need to use this tag. {Month} — with this tag we will show the day of the post {DayOfMonth} — and with this other we will show the day {12Hour} — the hour in a 12 hour format {AmPm} — and the am or pm text, where applicable {Permalink} — we used this inside our link href in order to generate a permalink {block:Title} — the code inside these tags will only be shown if the article has a title. {Title} — this is the title of the post. {Body} — and the content of the same. Most of the options are in fact very self explanatory, and quite easy to use. The next blog types are similar, but with some differences. Photo Posts The code for photo posts is quite similar, let's take a look to it: {block:Photo} <div class="post"> //same as before <div class="post_contents"> <img src="{PhotoURL-500}" alt="{PhotoAlt}"/> <p> {block:Caption}{Caption}{/block:Caption} </p> <hr> </div> </div> <br class="clear" /><br/>{/block:Photo} As you can see, we have changed the title tag for caption tag, but the structure remains mostly the same. The other main difference is the img tag we have used: <img src="{PhotoURL-500}" alt="{PhotoAlt}"/> The {PhotoAlt} tag will show the alt attribute of the photo, if there's any. {PhotoURL-500} is the more important one, as it will create the url of the image, but for a photo equal or smaller to 500px width. There are other options for this tag, which are as follows: {PhotoURL-400} — just the same tag, but will create a url for a image equal or smaller to 400px. {PhotoURL-250} — a smaller image, this time of 250px. {PhotoURL-100} — just the same as before, but will make urls for images of 100px width or less. {PhotoURL-75sq} — this one is a bit different, as will make a url for a reduced, squared image of the post, of 75px. {PhotoURL-HighRes} — this last tag will create a url for the high resolution image.
Read more
  • 0
  • 0
  • 2604

article-image-users-roles-and-pages-dotnetnuke-5
Packt
14 Apr 2010
7 min read
Save for later

Users, Roles, and Pages in DotNetNuke 5

Packt
14 Apr 2010
7 min read
One of the most important aspects of running a DotNetNuke portal is trying to figure out how to administer the portal. From adding modules to working with users, it may take a while before you have mastered all the administration tasks associated with running a portal. DotNetNuke uses a few terms that may be unfamiliar at first. For example, the term "portal" can be used interchangeably with the more common term "site". Similarly, the terms "tab" and "page" may be used interchangeably within the context of DotNetNuke. Knowing that they are interchangeable will help to understand the topics that we will discuss. User accounts If you are used to working within a network environment, or have worked with different portals in the past, then you are probably comfortable with the term "users". For those of us who may not be very familiar with this term, can think of a website that you have registered with in the past. When the registration had been completed, a user account was provided to you. This account lets you return to the site and log in as a recognized user. Everything that takes place on your portal revolves around users and user accounts. Whether users are required to register in order to use your services (such as a member site) or only a few user accounts are required to manage the content, functionality, and layout of your site, you will need to understand how to create and manage user accounts. Let's start with a general description of a user, and then you will see how to create and manage your users. In order to work through the examples, you will need to bring up your portal and sign in as an administrator account, such as the one created during the initial portal installation. Who is a user? The simplest definition of a user is an individual who consumes the services that your portal provides. However, a user can take on many different roles, from a visitor who is just browsing (unregistered user) or a person who registers to gain access to your services (registered user), to a specialized member of the site such as a content editor, to the facilitator (administrator or host) who is responsible for the content, functionality, and design of your portal. The difference between an administrator account and a host (or super user) account will be explained later in detail. For now, we will focus on the administrator account that is associated with a single portal. Everything in DotNetNuke revolves around the user, so before we can do anything else, we need to learn a little about user accounts. Creating user accounts Creating user accounts Before you create user accounts, you should decide and configure how users will be able to register on the site. You can choose from the following four different types of registrations: None Private Public (default) Verified To set the registration type for your portal, go to the Site Settings link found in the ADMIN menu, as shown in the following screenshot: The User Registration section can be found under Advanced Settings | Security Settings, as shown in the next screenshot: Many sections within DotNetNuke may be collapsed or hidden by default. To view these sections, you will need to expand them by clicking the '+' in front of them. The type of registration you use depends on how you will be using your portal. The following table gives a brief explanation of the different User Registration types: Registration setting Description None Setting the user registration as None will remove the Register link from your portal. In this mode, users can only be added by the administrator or host users. Thanks to the new features in DotNetNuke 5, users who have been given the proper permissions can also manage user accounts. This allows the administrator or host users to delegate account management to other individuals with the proper access. If you plan to have all sections of your site available to everyone (including unregistered users), then selecting None as your registration option is a good choice. Private If you select Private, then the Register link will reappear. After users fi ll out the registration form, they will be informed that their request for registration will be reviewed by the administrator. The administrator will decide whom to give access to the site. Unless an administrator approves (authorizes in DNN terms) a user, they will not be able to log in. Public Public is the default registration for a DotNetNuke portal. When this is selected, the users will be able to register for yoursite by entering the required information. Once the registration form is fi lled out, they will be given access to the site and can log in without requiring any action on the part of an administrator. Verified If you select Verified as your registration option, then the users will be sent an e-mail with a verifi cation code, once they fi ll out the required information. This ensures that the e-mail address they enter in the registration process is valid. The fi rst time they sign in, they will be prompted for the verifi cation code. Alternatively, they can click on the Verification link in the e-mail sent to them. After they have been verifi ed, they will need to type in only their login name and password to gain access to the site. Please note that proper SMTP confi guration is required to ensure delivery of the verifi cation e-mails. Setting required registration fields The administrator has the ability to decide what information the user will be required to enter when registering. If you are logged in as an administrator, then you can accomplish this through a combination of User Settings and Profile Properties. A user who is given the appropriate permissions can also modify these settings; however, this requires a few additional configuration steps that we will not cover in this section. To manage the Profile Properties for your site, select the ADMIN | User Accounts link. The User Accounts section appears as shown in the following screenshot: In the preceding screen, select Manage Profile Properties, either by selecting the link at the bottom of the module container or by selecting the link in the Action menu—the menu that pops up when you point on the drop-down button adjacent to the module title, User Accounts (more information on Action menu is provided later). When you select this link, you will be redirected to a screen (see the next screenshot) that displays a list of the currently configured Profile Properties. You can manage some attributes of the Profile Properties from within this screen. For instance, you can delete a property by clicking on the 'X' icon in the second column. Alternatively, you can change the display order of the properties by clicking on one of the Dn or Up icons in the third and fourth columns. If you change the order this way, make sure you click the Apply Changes button at the bottom of the page to save any changes. Your changes will be lost if you leave this screen without clicking the Apply Changes button. If you want even more control, then you can edit a single property by clicking on the pencil icon in the first column. You will see this icon extensively in the DNN user interface. It allows you to Edit/Modify the item it is associated with. You can also add a new property by selecting the Add New Profile Property action from the Action menu. In either case, you will be redirected to another page, where you can enter information about the property. You will be redirected to the Add New Property Details page, as shown in the following screenshot: Note that if you are editing an existing property, the Property Name field cannot be changed, so make sure you get it right the first time. If you need to change the Property Name, then you will need to delete and recreate the property. Most of these fields are self explanatory, but we will describe a few of these fields.
Read more
  • 0
  • 0
  • 1490

article-image-users-roles-and-pages-dotnetnuke-5-extension
Packt
14 Apr 2010
8 min read
Save for later

Users, Roles, and Pages in DotNetNuke 5- An Extension

Packt
14 Apr 2010
8 min read
Understanding DotNetNuke roles and role groups We just discussed how to add a user to your site. But are all users created equal? To understand how users are allowed to interact with the portal, we will need to take a look at what a role is and how it factors into the portal. There are plenty of real-world examples of roles we can look at. A police station, for example, can have sergeants, patrol cops, and detectives, and with each position come different responsibilities and privileges. In a police station, there are multiple people filling those positions (roles) with each of those belonging to the same position (role) sharing the same set of responsibilities and privileges. Roles in our portal work the same way. Roles are set up to divide the responsibilities needed to run your portal, as well as to provide different content to different groups of users of your portal. We want our portal to be easy for the administrators to manage. To do this, we will need to settle on the different user roles needed for our site. To determine this, we first need to decide on the different types of users who will access the portal. We will detail these user types in the following list: Administrator: The administrators will have very high security. They will be able to modify, delete, or move anything on the site. They will be able to add and delete users and control all security settings. (This role comes built-in with DotNetNuke.) The default administrator account is created during the creation of the portal. Home Page Admin: The home page admins will have the ability to modify only the information on the home page. They will be responsible for changing what users see when they first access your site. (We will be adding this role.) Forum Admin: The forum moderators will have the ability to monitor and modify posts in your forum. They will have the ability to approve or disapprove messages posted. (We will be adding this role.) Registered User: The registered users will be able to post messages in the forum and be able to access sections of the site set aside for registered users only. (This role comes built into DotNetNuke; however, we would need to provide the proper permissions to this role to perform the mentioned tasks.) Unauthenticated User: The unauthenticated user is the most basic of all the user types. Any person browsing your site will fall under this category, until they have successfully logged in to the site. This user type will be able to browse certain sections of your portal, but will be restricted from posting in the forum and will not be allowed in the Registered Users Only section. (This role comes built into DotNetNuke; however, we would need to provide the proper permissions to this role to perform the mentioned tasks.) Once you formulate the different user roles that will access the site, you will need to re strict users' access. For example, we only want the Home Page Admin to be able to edit items on the home page. To accomplish this, DotNetNuke uses role-based security. Role-based security allows you to give access to portions of your website based on what role the user belongs to. User-based security is also available per page or content section of the portal. However, the benefit of using a role-based security method is that you only have to define the access privileges for a role once. Then you just need to add users to that role and they will possess the privileges that the role defines. The following diagram gives you an idea of how this works: Looking at the diagram, we notice two things: Users can be assigned to more than one role More than one user can be assigned to a single role This gives us great flexibility when deciding on the authorization that users will possess in our portal. To create the roles we have detailed, sign in with an administrator account, and select ADMIN | Security Roles on the main menu or click the Roles link in the Common Tasks section of the control panel. This is available on the top of every DNN page for authorized users. You might need to click the double down arrows on the top-right of the page to maximize the panel. The Security Roles page appears as shown in the following screenshot: Notice that DotNetNuke comes with three roles already built into the system: the Administrators role (which we have been using), the Registered Users role, and the Subscribers role. Before we jump right into creating the role, let us first discuss the role group feature of DotNetNuke, as we will be using this feature when we create our roles. A role group is a collection of roles used, mainly, in large sites with a large number of roles, as a way of managing the roles more effectively. For the site we are building, the benefit of using role groups will be minimal. However, in order to demonstrate how to use them, we will create one for our administrative roles. While on the Security Roles page, click the Add New Role Group link located below the list of roles. This will present us with the Edit Role Group page containing two form fields. Once these fields are filled out, click the Update link at the bottom of this page. A Filer By Role Group drop-down list should now be displayed above the list of roles on the Security Roles page. If you select the Administrative Roles group that we just created, two noticeable things happen on this page. Firstly, the list of roles become empty as no roles are currently assigned to this role group. Secondly, an edit (pencil) icon and a delete (red cross X) icon now appear next to the drop-down list. These icons can be used to update or remove any custom role groups that exist on the site. These red 'X' icons are standard icons used throughout DotNetNuke to represent the ability to delete/remove items. Now that we have created our role group, we want to create the role for Home Page Admin. To do this, you again have two choices. Either select Add New Role from the dropdown in the upper left, or click on the Add New Role link. This will bring up the Edit Security Roles page, as shown in the next screenshot. We will use this page to create the Home Page Admin role that we need. The Basic Settings shown in the screenshot are as follows: Role Name: Make the name of your role short, but descriptive. The name should attempt to convey its purpose. Description: Here you may detail the responsibilities of the role. Role Group: Set this field to the Administrative Roles group that we created earlier. Public Role: Checking this will give registered users of your site the ability to sign up for this role themselves. We will be creating a Newsletter role and will demonstrate how this works when it is created. Auto Assignment: If this is checked, users will automatically be assigned to this role as soon as they register for your portal. CAUTION Do not check the Public Role and Auto Assignment checkboxes, unless you are sure. Checking these options would allow all users of the site to become members of the associated role, which would grant them the privileges assigned to the role. As we want to decide who will be able to modify our home page, we will leave both of these unchecked. To save the settings, click on the Update link. The Advanced Settings section allows you to set up a fee for certain security roles. We will not be configuring any of these settings for this particular exercise. However, we will briefly discuss how these settings can be used in Assigning security roles to users section. Now to complete the roles that we will require for Coffee Connections, we will add two more security roles The first role will be called Newsletter. We will be using this role to allow users to sign up for the newsletter we will be hosting at the Coffee Connections site. Set up the security role with the following information: Role Name: Newsletter Description: Allows users to register for the Coffee Connections Newsletter Role Group: Leave this as the default < Global Roles > as it is not going to be used to grant administrative rights to its members Public Role: Yes (checked) Auto Assignment: No (unchecked) Click on the Update link to save this role. The second role will be called Forum Admin. We will be using this role to administer the forums at the Coffee Connections site. Set up the security role with the following information: Role Name: Forum Admin Description: Allows user to administer Coffee Connections Forum Role Group: Administrative Roles Public Role: No (unchecked) Auto Assignment: No (unchecked)
Read more
  • 0
  • 1
  • 3881
article-image-programming-php-nuke
Packt
13 Apr 2010
27 min read
Save for later

Programming PHP-Nuke

Packt
13 Apr 2010
27 min read
After a quick look at the file and folder structure of a module, we then begin creating a new module for PHP-Nuke. This module will allow items of content to be submitted for modules that do not support user-submitted content. In this article, we will code functionality for users to submit encyclopedia entries for administrator approval. However, this will not involve making any modifications to the Encyclopedia module, and can be extended to cover other modules as well. What Happens When a Page is Requested? Let's see what happens when a visitor wants to view an article on the site, and the process that PHP-Nuke goes through to construct the page containing this information. Viewing an article means that the visitor will be navigating to a page similar to this: http://localhost/nuke/modules.php?name=News&file=article&sid=1 The page requested by the visitor is modules.php, so let's have a look at that. Note that although there are many PHP files in the PHP-Nuke installation, there are only four files actually requested in the normal course of interaction with the site: index.php modules.php admin.php backend.php The other files in the PHP-Nuke installation are used by these files when required. Where Does PHP-Nuke Get Information From? PHP-Nuke is able to collect information about what module the visitor wants to see, what operation they want to perform, and details of the user from request variables coming from these places: The query string in the URL: The URL of the page holds information that tells PHP-Nuke which module to select, which part of the module to use, what item of content to show, and so on. The query string information is used to select the page from the system that needs to be shown to the visitor. Posted variables: When a user enters information in a form, and submits this back to the server, this information will be available to PHP-Nuke. This posted information is how PHP-Nuke gets input from the user to create items of content, enter terms to search for, and so on. Cookie variables: There is user account information stored in a cookie (and administrator account information if the user has such an account). This is used to identify the user, so they do not have to keep logging on every time they view a page or come to the site. When the user logs out, this information is deleted from the cookie. The information that PHP-Nuke gets from these sources has to be treated very carefully within the system. These sources are the only means through which visitors communicate with the site, and are also the channels through which hacks or attacks might be conducted on the site. The patches we applied in Article 2 while installing the system address precisely this issue, and they make sure that the data PHP-Nuke collects from a visitor is in exactly the right form for working with. Requesting a Page Once the modules.php page is requested, the first step followed is to include the mainfile.php file. This file does the following things: It checks and processes the request variables (namely the input to the application), to avoid possibly harmful tags, or other indicators of some form of SQL injection attack. It creates global variables for each request variable. It sets up a connection to the database. It gets the site configuration such as the site name, site logo, and so on, from the database. The mainfile.php file also contains a number of core functions such as checking if the user is logged in or is an administrator, choosing the blocks to display, and filtering text, among others. These will be used at different points in the creation of the page. After this file has been included, the next thing to happen in modules.php is that PHP-Nuke gets the requested module from the $name global variable, which corresponds to the name query string variable (as in modules.php?name=News), and checks if this module is active. If the module isn't active, and the visitor isn't an administrator, a 'Module Not Active' message is displayed, and the page output is done. If the module is active, then PHP-Nuke checks if the visitor has rights to access this module. PHP-Nuke checks to see if the access is restricted to a particular user group, and if so, is the user a member of that group? PHP-Nuke also checks if the module is for subscribers only, and if so, is the user a subscriber to the site? If the visitor doesn't have the right permissions to view the module, then a 'No Access' message is displayed, and the page output is done. If the module selected by the visitor is active, and they do have permission to view it, then PHP-Nuke can get on with passing control to that module. Control is passed to the selected module by attempting to include the index.php file in the folder of the selected module. However, if there is a file variable in the query string, then the file with that name is included instead. If these files can't be found, a 'Module Cannot Be Found' error is displayed to the visitor. Thus if the user requests a page like modules.php?name=News&file=article&sid=1, the article.php file in the News folder will be included by PHP-Nuke. If the user requests a page like modules.php?name=News&sid=1, then the index.php file in the News folder will be included. Attempting to request a page like modules.php?name=News&file=nosuchfile returns a page with a 'No such page' message, since there is no file called nosuchfile.php in the News folder. The 'No such page' message is generated by PHP-Nuke, since it's in control of the process. If the user has selected an active module for which they have view permission, and are requesting a page that is part of the module, then control passes to the module, and it's up to that module to do its work and create the page. We'll see how this works later in the article, but for now, our overview of how PHP-Nuke gets the page creation underway is complete. Seeing how PHP-Nuke works isn't particularly exciting, what is more exciting is seeing how we can extend the power of PHP-Nuke by creating new blocks and modules. Along the way, we'll see most of the components required for 'programming' with PHP-Nuke, and you'll get a good idea of how to go about your own development projects. Creating a Block Our development efforts begin with creating a File block. A File block is a PHP script that is stored in the blocks folder. It must have a filename of the form block-NAME.php, where NAME will be used by PHP-Nuke as the title for the block. The filename should not contain any spaces. The goal of a block is simple. It just has to create one variable, $content, that holds the content of the block. After that, the PHP-Nuke core will bring the theme into play to take care of displaying the block. The block we will create is a better version of the Dinosaur of the Day static HTML block we created in Article 4. The block will display the name of the Dinosaur of the Day, and a thumbnail image of the lucky lizard. However, on the next day, a different dinosaur will be chosen, and the block display will be updated. This is how the block works: We will create a database table to hold the date, the title of the dinosaur for that day, and a link to the thumbnail image of that dinosaur. We will create a text data file that will contain the name of a dinosaur and a link to its thumbnail image on each line. The data in this file will be the dinosaur pool from which the dinosaur of the day is chosen at random. When the block code is executed, it will look in the database table to see if there is any information for the current date. If there is, it will retrieve it and build the block output. If there is no information for the current date, the data from the text file will be loaded in. One of the entries in that file will be selected at random, and that data will be inserted into the database. This will become the Dinosaur of the Day. That data will then be used to create the block output. We will use the text file to hold the 'Dinosaur of the Day' candidates rather than a database table so that we do not have to create a separate administration feature to add these details. To add more dinosaurs to the list, we simply upload a new version of the text file. Make sure that you copy the dinosaur thumbnails from the code download into the imagesdinosaurstnails folder of your PHP-Nuke installation root. Time For Action—Creating the Database Table Open up phpMyAdmin in your web browser, and select the nuke database from the drop-down list in the left-hand panel. Click on the SQL tab, and enter the following code into the textbox, then click on Go. CREATE TABLE dinop_dinoportal_dotd (id INT( 10 ) NOT NULL AUTO_INCREMENT ,day VARCHAR( 16 ) NOT NULL ,title VARCHAR( 128 ) NOT NULL ,image VARCHAR( 250 ) NOT NULL ,PRIMARY KEY ( 'id' )) TYPE = MYISAM ; What Just Happened? We just created our database table. There is only one table needed, with a simple design. There are four fields in the table. The id field will hold an auto-incrementing unique numerical value and the other fields will hold the current date, the title of the dinosaur, and the link to the image of the dinosaur. Time For Action—Creating the Text File Open up your text editor, and enter the following: Tyrannosaurus Rex,images/dinosaurs/tnails/tyro.gifStegosaurus,images/dinosaurs/tnails/stego.gifTriceratops,images/dinosaurs/tnails/triceratops.gif Save this file as dotd_list.txt in the blocks folder. What Just Happened? The dotd_list.txt file will be the data source for choosing a new Dinosaur of the Day image. You will notice that we are storing the data here in the form 'name of the dinosaur', 'path to the image', so it will be easy to extract the information when we need it. Time For Action—Creating the Block Code Open up your text editor, and enter the following code into a blank file: <?phpif ( !defined('BLOCK_FILE') ){ Header("Location: ../index.php"); die();}global $prefix, $db;$today = date('d-m-Y');$sql = "SELECT * from ".$prefix."_dinoportal_dotd WHERE day='$today'";$result = $db->sql_query($sql);$content = "";$dino_title = "";$image = ""; $numrows = $db->sql_numrows($result); if ($numrows) { $row = $db->sql_fetchrow($result); $dino_title = $row['title']; $image = $row['image']; } else { $filename = "blocks/dotd_list.txt"; $possibles =@ file($filename); if ($possibles) { $choice = rand(1, count($possibles)); $imp = explode("," , $possibles[$choice-1]); $dino_title = $imp[0]; $image = $imp[1]; $sql = "INSERT INTO ".$prefix."_dinoportal_dotd(day,title,image) VALUES ('$today', '$dino_title', '$image')"; $result = $db->sql_query($sql); } $choice = rand(1, count($possibles)); $imp = explode("," , $possibles[$choice-1]); $dino_title = $imp[0]; $image = $imp[1]; }if ($dino_title){ $content = "Today's dinosaur is:<br><center><b>$dino_title</b><center><br>"; $content .= "<center><img src="$image" alt="$dino_title"></center><br>";}?> Save this file as block-DinosaurOfTheDay.php in the blocks folder of your PHP-Nuke installation. What Just Happened? We just entered the code for the Dinosaur of the Day block, and we'll step through it now. This first part of the code stops this file being requested directly by a visitor— the BLOCK_FILE constant is defined in mainfile.php, and without that constant being defined, the visitor would be redirected back to the homepage of the site. Block files are never requested directly by the visitor, they are included by PHP-Nuke. These first few lines of code are found in every block file: if ( !defined('BLOCK_FILE') ){ Header("Location: ../index.php"); die();} Now we can get started. First, we set ourselves to access some of the global variables of the application, and we will have our first look at the objects to access data from the database. The only global variables we need here are the ones for data access—$prefix, which holds the value of the database tables prefix, and $db, which is used to actually perform database operations. global $prefix, $db; Next, we grab today's date, formatted as digits like this 24-05-2005. $today = date('d-m-Y'); Now we set up the SQL statement to retrieve the information corresponding to this date from the database: $sql = "SELECT * from ".$prefix."_dinoportal_dotd WHERE day='$today'"; Now we execute the SQL statement: $result = $db->sql_query($sql); It is possible that there is no data corresponding to today's date, so we check the number of rows returned from this last query. If there are zero rows, there will be no information. $numrows = $db->sql_numrows($result); If there are some rows returned, we can start creating the block output. We use the sql_fetchrow() method to retrieve a row of data from the result of the query. This row is returned as an array, and we set some variables from the array. We'll only grab one row. If for some reason, there is more than one entry for today's date, we simply ignore the others. if ($numrows){ $row = $db->sql_fetchrow($result); $dino_title = $row['title']; $image = $row['image'];} Now we move on to the situation where there is no information for today's date, and we have to create it. The first thing we do is to read the contents of the dotd_list.txt file into an array—there will be one entry in the array for each line in the text file. However, we have to consider what will happen if there is some kind of problem reading the file. else{ $filename = "blocks/dotd_list.txt"; Note that the path to the file for the dodt_list.txt file is blocksdotd_list.txt. This may seem strange, since both this file and the block file are in the same blocks folder. However, PHP will be looking for this file from the executing script, which will be one of index.php, modules.php, or admin.php, all of which are outside the blocks folder. Thus we need to add the blocks folder in the path to the dotd_list.txt file. Now we try to grab the file itself: $possibles =@ file($filename); The file function opens the named file, and reads the input into an array called $possibles. The use of the @ character here will suppress any error messages—if there is a problem opening or reading the file, no untidy error messages will be displayed to the user, and execution can continue. Of course, if there is a problem reading the file then there will be a problem with $possibles. So we check this next—if there has been some problem reading the file then $possibles will be false: if ($possibles){ If there is something stored in $possibles, then this check will be passed, and we can proceed to choose one element from it at random. We choose a random number, between 1 and the number of lines in the text file. $choice = rand(1, count($possibles)); All we have to do now is choose that element from the array (we have to subtract one from the random number because the first element of the array is 0, rather than 1), and then split up that line to get at the title and the path to the image. $imp = explode("," , $possibles[$choice-1]);$dino_title = $imp[0];$image = $imp[1]; We split the line using the explode() function. The explode() function converts a string to an array by splitting it at certain characters. We will split the string at the ',' character, and we get an array with two entries. The first entry is the name of the dinosaur; the second is the path of the image. Now we have the details of our Dinosaur of the Day, we can add it to the database using an INSERT SQL statement. $sql = "INSERT INTO ".$prefix."_dinoportal_dotd(day,title,image) VALUES ('$today', '$dino_title', '$image')"; $result = $db->sql_query($sql); }} At this point, we should have a Dinosaur of the Day, one way or another, and so we can finalize the block output. However, we check the value of the $dino_title variable just in case there has been some problem either retrieving data or creating the new Dinosaur of the Day. If there has been a problem with either of these, there will be no value for the $dino_title variable, and if so, this code will ensure that the block content will remain empty, rather than producing some useless output. if ($dino_title){ $content = "Today's dinosaur is:<br><center><b>$dino_title</b><center><br>"; $content .= "<center><img src="$image" alt="$dino_title"></center><br>";} That's it, our block is complete! The key points of this block were the initial few lines that stopped the file from being requested directly, and this was also our first encounter with the data access code. Another thing to note from this example is the effort we made to ensure that the block output was only created if everything went smoothly. We suppressed errors when trying to read in a file, we checked that the reading of a file had actually given us some data, and then we didn't create any output if there was a problem with dino_title variable, which would be an indicator of some problem. All this means that if there is a problem, the visitor will not be confronted with lots of error messages, which could disturb the visitor and lead to a poor impression of your site, or even break the layout of the page, or reveal some information about your code that could be used against you. All that remains now is to set up this File block using the steps we saw in Article 4, and we are away! Data Access in PHP-Nuke In the code for creating the block we had a couple of lines with data access functions: $result = $db->sql_query($sql);$numrows = $db->sql_numrows($result);$row = $db->sql_fetchrow($result); PHP-Nuke uses a 'data abstraction layer', which means that you call functions against an object, which translates them into specific calls against the database of your choice. Generally, MySQL is the database used with PHP-Nuke, but you could choose another database server to power your site. A more pertinent advantage is that you don't need to use database-specific functions to access data in PHP-Nuke; you only need to learn about the functions of the data access object (You will still need to know some SQL to create queries that will be executed on the database). The code for the data access object is found in the file dbmysql.php. In fact, the db folder contains code for different types of database server, but this file is the one selected by default by PHP-Nuke for working with the MySQL database server. The data access object is a genuine object, that is, it's an instance of a class, sql_db in this case. Classes are one of the basics of object-oriented programming, but other than this instance PHP-Nuke does not make much use of object-oriented programming. A discussion of object-oriented programming in PHP is beyond the scope of this article series, and it won't particularly help here since PHP-Nuke makes so little use of it. All that we need to know is how to access the methods (functions) of the data access object. Object-oriented programming is covered in more detail in any book on PHP programming, and you can read an article about it at http://www.devarticles.com/c/a/PHP/Object-Oriented-Programming-in-PHP/. The data-access object provides a number of methods that you can use to execute a query, retrieve a row of data, check the number of rows returned by the query, or get the last inserted auto-increment field. Working with the object follows a similar process to the standard way of working with data in PHP using functions like mysql_query() or mysql_fetch_field(). To access data in PHP-Nuke, you will need two global variables, $prefix and $db. The $prefix variable holds the table prefix of the database tables, and this needs to be used in your SQL queries. The $db variable is the data access object itself. In our block example, we had these lines to create a SQL query and then execute it: $sql = "SELECT * from ".$prefix."_dinoportal_dotd WHERE day='$today'";$result = $db->sql_query($sql); Note the $db->sql_query() syntax. This syntax is used in PHP to call a method on an object, in this case the sql_query() method of the $db object. The sql_query() method executes an SQL query as its name suggests. You provide a string with the query that's to be executed as a parameter. Following the execution of a query, you can retrieve a row using the sql_fetchrow() method: $row = $db->sql_fetchrow($result); This method returns an array, and you can refer to the fields in the data using $row['fieldname'], as we do in the block example to get the title and image fields: $dino_title = $row['title'];$image = $row['image']; If you want to insert or update data, you need to create the relevant SQL query and then use the sql_query() function to do it: $sql = "INSERT INTO ".$prefix."_dinoportal_dotd(day,title,image) VALUES ('$today', '$dino_title', '$image')";$result = $db->sql_query($sql); This is only a small selection of the methods of the data access object. Another interesting one is the sql_nextid() method, which you can use after an INSERT statement to get the value of the last auto-increment field created. However, these are the methods that you will see the most of as you look around the code in PHP-Nuke. Module File and Folder Structure Before we get started creating a new module, let's have a look at the file structure of a typical module. A module is simply a collection of files (usually only PHP files) contained in a folder that goes in the modules folder in the root of the PHP-Nuke installation. The name of the folder is the name that PHP-Nuke will recognize the module by. However, we can't just place the files into the module folder in any order. There is an organization of files, subfolder names, and filenames that modules need to follow in order to function properly with PHP-Nuke. The image below shows the contents of the News module folder: We have already seen how PHP-Nuke switches between files in the module folder based on the value of the file query string variable. If there is no value for this variable, the index.php file of the module is used. Files that sit inside the module folder are the 'front-end' files, which will be used during a standard user's visit to the module. The code for the administration part of a module resides in the admin folder within the module folder. In earlier versions of PHP-Nuke (before 7.5), the administration code for any module would have to go into the admin folder (the one in the root of the PHP-Nuke installation), and would be mixed with the 'core' administration code. The decision to have a module's administration code contained within the module folder itself means that the module is much more self-contained, keeps people away from the core code itself, and generally makes the module easier to set up, install, and maintain. We'll see more about what is found in the admin folder when we create the administration area of our new module later in this article. We saw in Article 4 that the Language block allows you to change PHP-Nuke's user interface language. This ability to switch languages is something that has made PHP-Nuke so popular all around the world. This multi-language support is achieved by module developers avoiding coding any 'localizable' text into the module output. Localizable text is text that needs to be translated if a different interface language is selected. Instead of coding the text, PHP constants are used, with the values of the constants defined in a language file. The language files are found in the language folder of the module, and there is a separate language file for each language, each with a filename of the form lang-LANGUAGE.php. All PHP-Nuke needs to do is select the correct file based on the desired language. Creating a User Submissions Module Writing a new module allows you to extend PHP-Nuke to get it to do exactly what you want it to do. What we will do here is to create a general-purpose module that will allow users to submit content for modules that do not support user-submitted material. We'll call it UserSubmissions. It will work in the way the Submit News module works for stories: The user will submit the material through a form. The administrator will be notified of the new submission by email. The administrator will be able to see a list of the submitted material in the administration area, and can edit, delete, or approve the material to go into the database. The point of this module is that it does not touch the modules for which it allows the submission of content; everything will happen in the UserSubmissions module. In this article, we will only code in functionality for users to submit encyclopedia entries. It is straightforward to extend this to allow submissions for the Content module, or questions for the FAQ module. Conceptually what the module does is to: Present a form to the user similar to the one the administrator would use for entering an encyclopedia entry. Take the user's input and store it in a 'general' way in a single database table. After the administrator checks the input, the data is then stored in the encyclopedia's database tables using the same kind of code that the Encyclopedia module uses. We will see exactly what the 'general' way we store the data in is later. Basically, the module will take all the parts of the encyclopedia entry—the title, the text, the encyclopedia ID—and put them all together into one bundle, which can then be easily retrieved and broken out to form the individual pieces of data for the administrator to view, approve, or delete. Rather than presenting the development as a series of steps for you to follow, we will break the code up into various tasks, and then examine each piece of code or activity. You can type in the code as it is presented, although it is probably easiest to grab the example code for this module from the code download, and refer to it as we go. Module Development Steps The steps that we will follow to create the module are these: Create the module folder Create the database tables Code the front end (visitor view) of the module Adapt the code for multi-language support Set up module administration Code the administration area Rather unusually, we're going to start by coding the front end of the site. The reason this is unusual is that modules typically display some kind of data (that is what all the modules we have encountered in the article series do), and you would first need to enter this data into the database. This data is usually entered by the administrator, through the administration interface. With some example data in place, the front end of the site will be able to display it. It will be difficult to test the front end if it is supposed to display data and there is no data to display! This module does not require any existing data in the database to work. In fact, the data is entered by a standard visitor, and the administrator only has to look at this data, and edit or delete it. There is no facility in the administrator part of the module for the administrator to add new data into the module, which would rather defeat the point of this module! Thus we can start on the front end of the module quite happily. Let's start off with creating the module folder. Creating the Module Folder Create a new folder in the modules folder called UserSubmissions. This will be our module folder. Within this folder, create two new folders called admin and language. The admin folder will contain our administration code, and the language folder will contain the user interface language files. We create another folder, inside the admin folder, also called language. This folder will hold the language files for the module's administration interface. That's the first step out of the way, so let's move on to the database tables. Creating the Database Tables The module has only one database table. The table will be called <prefix>_usersubmissions. You can follow the same steps in phpMyAdmin as we did earlier for creating the block database table to create this table: CREATE TABLE dinop_usersubmissions ( id int(11) NOT NULL auto_increment, data text NOT NULL, parent_id int(11) NOT NULL default '0', type varchar(36) NOT NULL default '1', user_id int(11) NOT NULL default '0', date timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, title varchar(255) NOT NULL default '', user_name varchar(250) NOT NULL default '', PRIMARY KEY (id)) COMMENT='Table for holding user submitted content' ; Each row in this table will represent a single item of submitted content. The row will be identified by its id field. With only one table, you may be wondering how this module is going to be able to hold data from different modules. The answer is that the submitted data will be bundled up into a single object, then 'serialized' and stored in the data field. When the data is needed for viewing, it will be unbundled, and 'unserialized' back into a form that can be worked with. The 'title' of the submission will be stored in the title field. The type of module that we are storing data for will be held in the type field of the row. The details of the submitter will be stored in the user_id and user_name fields. We actually only use the user_name field in this version of the module, but we store both for future use. The date the item is submitted is held in the field called date. This field is a MySQL TIMESTAMP, and whenever a row is inserted, the current date and time will be inserted into the field automatically by the database, so we will not need to record the date and time ourselves. The final field is parent_id. Recall how an encyclopedia entry belongs to an Encyclopedia; a content page belongs to a Content category; a FAQ question belongs to a particular category, and so on. For each of these types of content, you needed to provide a 'parent' object that the content would belong to. That is where our parent_id field comes in. The ID of the parent object will be stored in this field. For an encyclopedia entry, this will be the ID of the chosen Encyclopedia.
Read more
  • 0
  • 0
  • 2045

article-image-understanding-dotnetnuke-core-architecture-extension
Packt
06 Apr 2010
8 min read
Save for later

Understanding the DotNetNuke Core Architecture- An Extension

Packt
06 Apr 2010
8 min read
The global files The Global.asax.vb and Globals.vb files share similar names but the parts they play in DotNetNuke are vastly different. The Global.asax.vb is used by DotNetNuke to handle application-level events raised by the ASP.NET runtime. The Globals.vb file, on the other hand, is a public module (which is the same as a static class in C#) that contains global utility functions. Before we take a look at these fi les, we first want to look at what object is being passed around in these transactions. Global.asax.vb Much of the logic that used to reside in the Global.asax.vb fi le has now been abstracted to the HTTP modules. We will look into the code that remains. Application_Start When the fi rst request is made to your application (when the fi rst user accesses the portal), a pool of HttpApplication instances are created and the Application_Start event is fi red. This will (theoretically) fire just once and on the first HttpApplication object in the pool. When there is inactivity on your portal for a certain amount of time, the application (or application pool) will be recycled. When the pool is recycled, your application will restart (and this event will fi re again) when the next request is made for your application. As the new version of DotNetNuke uses the .NET website structure, you will find the Global.asax.vb fi le in the App_Code folder. In the Application_Start, we are loading all of the confi gured providers to ensure they are available to the rest of the framework when needed. These are performed in the Application_Start because we want them to be called only once. Private Sub Application_Start(ByVal Sender As Object, ByVal E AsEventArgs)If Config.GetSetting("ServerName") = "" ThenServerName = Server.MachineNameElseServerName = Config.GetSetting("ServerName")End IfComponentFactory.Container = New SimpleContainer()'Install most Providers as Singleton LifeStyleComponentFactory.InstallComponents _(New ProviderInstaller("data", GetType(DotNetNuke.Data.DataProvider)))ComponentFactory.InstallComponents _(New ProviderInstaller("caching", GeType(Services.Cache.CachingProvider)))ComponentFactory.InstallComponents _(New ProviderInstaller("logging", GetType(Services.Log.EventLog.LoggingProvider)))ComponentFactory.InstallComponents _(New ProviderInstaller("scheduling", GetType(Services.Scheduling.SchedulingProvider)))ComponentFactory.InstallComponents _(New ProviderInstaller("searchIndex", GetType(Services.Search.IndexingProvider)))ComponentFactory.InstallComponents _(New ProviderInstaller("searchDataStore", GetType(Services.Search.SearchDataStoreProvider)))ComponentFactory.InstallComponents_(New ProviderInstaller("friendlyUrl", GetType(Services.Url.FriendlyUrl.FriendlyUrlProvider)))ComponentFactory.InstallComponents _(New ProviderInstaller("members", GetType(DotNetNuke.Security.Membership.MembershipProvider)))ComponentFactory.InstallComponents _(New ProviderInstaller("roles", GetType(DotNetNuke.Security.Roles.RoleProvider)))ComponentFactory.InstallComponents _(New ProviderInstaller("profiles", GetType(DotNetNuke.Security.Profile.ProfileProvider)))ComponentFactory.InstallComponents _(New ProviderInstaller("permissions", GetType(DotNetNuke.Security.Permissions.PermissionProvider)))ComponentFactory.InstallComponents _(New ProviderInstaller("outputCaching", GetType(DotNetNuke.Services.OutputCache.OutputCachingProvider)))ComponentFactory.InstallComponents _(New ProviderInstaller("moduleCaching", GetType(DotNetNuke.Services.ModuleCache.ModuleCachingProvider)))Dim provider As DotNetNuke.Security.Permissions.PermissionProvider = _DotNetNuke.ComponentModel.ComponentFactory.GetComponent _(Of DotNetNuke.Security.Permissions.PermissionProvider)()If provider Is Nothing ThenComponentFactory.RegisterComponentInstance _(Of DotNetNuke.Security.Permissions.PermissionProvider) _(New DotNetNuke.Security.Permissions.PermissionProvider())End If'Install Navigation and Html Providers as NewInstanceLifestyle (ie a new instance is generated each time the type isrequested, as there are often multiple instances on the page)ComponentFactory.InstallComponents _(New ProviderInstaller("htmlEditor", _GetType(Modules.HTMLEditorProvider.HtmlEditorProvider), _ComponentLifeStyleType.Transient))ComponentFactory.InstallComponents _(New ProviderInstaller("navigationControl", _GetType(Modules.NavigationProvider.NavigationProvider), _ComponentLifeStyleType.Transient))End Sub In previous versions of DotNetNuke, there was a great deal happening in this method. However, this code has been moved into various methods inside of the Initialize class. This was done to support the integrated pipeline mode of IIS 7. If you would like to take a look at what is happening inside of the Initialize class, it can be found in the Common folder of the DotNetNuke.Library project. Examining Application_BeginRequest The Application_BeginRequest is called for each request made to your application. In other words, this will fi re every time a page (tab), or other web request handlers such as a web service or an ashx handler, is accessed in your portal. This section is used to implement the scheduler built into DotNetNuke. Starting in version 2.0, two items, "users online" and "site log", require recurring operations. Also in this method is the call to the Initialize.Init() method that was moved out of the Appli cation_Startup method as mentioned previously. You can fi nd out more about the scheduler by looking at the DotNetNuke Scheduler.pdf document (only if you download the documentation pack). Also note that, there is a host setting that defi nes the running mode of a scheduler, you can check for a scheduler run on every request to your portal, or run the scheduler in a timer mode. Private Sub Global_BeginRequest(ByVal sender As Object, _ByVal e As EventArgs) Handles Me.BeginRequestDim app As HttpApplication = CType(sender, HttpApplication)Dim Request As HttpRequest = app.RequestIf Request.Url.LocalPath.ToLower.EndsWith("scriptresource.axd") _OrElse Request.Url.LocalPath.ToLower.EndsWith("webresource.axd") _OrElse Request.Url.LocalPath.ToLower.EndsWith("gif") _OrElse Request.Url.LocalPath.ToLower.EndsWith("jpg") _OrElse Request.Url.LocalPath.ToLower.EndsWith("css") _OrElse Request.Url.LocalPath.ToLower.EndsWith("js") ThenExit SubEnd If' all of the logic which was previously in Application_Start' was moved to Init() in order to support IIS7 integrated pipelinemode' ( which no longer provides access to HTTP context withinApplication_Start )Initialize.Init(app)'run schedule if in Request modeInitialize.RunSchedule(Request)End Sub The Globals.vb file As part of the namespace-reorganization effort associated with DotNetNuke version 3.0, general utility functions, constants, and enumerations have all been placed in a public module (as just mentioned, module here refers to VB.NET module keyword, not a DotNetNuke module) named Globals . As items in a .NET module are inherently shared, you do not need to instantiate an object in order to use the functions found here. In this module, you will find not only global constants, as shown in the following code: Public Const glbRoleAllUsers As String = "-1"Public Const glbRoleSuperUser As String = "-2"Public Const glbRoleUnauthUser As String = "-3"Public Const glbRoleNothing As String = "-4"Public Const glbRoleAllUsersName As String = "All Users"Public Const glbRoleSuperUserName As String = "Superuser"Public Const glbRoleUnauthUserName As String ="Unauthenticated Users"Public Const glbDefaultPage As String = "Default.aspx"Public Const glbHostSkinFolder As String = "_default"Public Const glbDefaultControlPanel As String = "Admin/ControlPanel/IconBar.ascx"Public Const glbDefaultPane As String = "ContentPane"Public Const glbImageFileTypes As String = "jpg,jpeg,jpe,gif,bmp,png,swf"Public Const glbConfigFolder As String = "Config"Public Const glbAboutPage As String = "about.htm"Public Const glbDotNetNukeConfig As String = "DotNetNuke.config"Public Const glbSuperUserAppName As Integer = -1Public Const glbProtectedExtension As String = ".resources"Public Const glbEmailRegEx As String = "b[a-zA-Z0-9._%-+']+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}b"Public Const glbScriptFormat As String = "<script type=""text/javascript"" src=""{0}"" ></script>"   but a tremendous number of public functions to help you do everything, from retrieving the domain name, as shown: Public Function GetDomainName(ByVal Request As HttpRequest, ByValParsePortNumber As Boolean) As String to setting the focus on a page: Public Sub SetFormFocus(ByVal control As Control) This one file contains a wealth of information for the developer. As there are more than 3070 lines in the fi le and the methods are fairly straightforward, we will not be stepping through this code. The Globals.vb fi le can now be found in the DotNetNuke.Library project in the Common folder. Putting it all together We have spent some time looking at some of the major pieces that make up the core architecture. You might be asking yourself how all this works together. In this section, we will walk you through an overview version of what happens when a user requests a page on your portal. A shown in the preceding diagram, when a user requests any page on your portal, the HTTP Modules that have been declared in the web.config file are hooked into the pipeline. Typically, these modules use the Init method to attach event handlers to application events. The request then goes through the Global.asax page. As just mentioned, some of the events fi red here will be intercepted and processed by the HTTP modules, but the call to run the scheduler will happen in this fi le. Next, the page that was requested, Default.aspx, will be processed. As we stated at the beginning of this article, all requests are sent to the Default.aspx page and all the controls and skins needed for the page are created dynamically by reading the tabID from the requested URL. So let's begin by looking at the HTML for this page.
Read more
  • 0
  • 0
  • 1426