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-password-strength-checker-google-web-toolkit-and-ajax
Packt
23 Oct 2009
8 min read
Save for later

Password Strength Checker in Google Web Toolkit and AJAX

Packt
23 Oct 2009
8 min read
Password Strength Checker Visual cues are great way to inform the user of the status of things in the application. Message boxes and alerts are used much too often for this purpose, but they usually end up irritating the user. A much smoother and enjoyable user experience is provided by subtly indicating to the user the status as an application is used. In this section, we are going to create an application that indicates the strength of a typed password to the user by the use of colors and checkboxes. We are going to use check-boxes very differently than their normal usage. This is an example of using GWT widgets in new and different ways, and mixing and matching them to provide a great user experience. Time for Action—Creating the Checker In the current day and age, passwords are required for almost everything, and choosing secure passwords is very important. There are numerous criteria suggested for creating a password that is secure from most common password cracking exploits. These criteria run the gamut from creating 15 letter passwords with a certain number of lower case and numeric digits to creating passwords using random password generators. In our example application, we are going to create a password strength checker that is very simple, and only checks the number of letters in the password. A password string that contains less than five letters will be considered weak, while a password that contains between five and seven letters will be considered to be of medium strength. Any password containing more than seven letters will be considered as strong. The criteria were deliberately kept simple so that we can focus on creating the application without getting all tangled up in the actual password strength criteria. This will help us to understand the concepts and then you can extend it to use any password strength criteria that your application warrants. This example uses a service to get the password strength, but this could also be done all on the client without needing to use a server. 1. Create a new Java file named PasswordStrengthService.java in the com.packtpub.gwtbook.samples.client package. Define a PasswordStrengthService interface with one method to retrieve the strength of a password string provided as a parameter to the method: public interface PasswordStrengthService extends RemoteService{public int checkStrength(String password);} 2. Create the asynchronous version of this service definition interface in a new Java file named PasswordStrengthServiceAsync.java in the com.packtpub.gwtbook.samples.client package : public interface PasswordStrengthServiceAsync{public void checkStrength(String password, AsyncCallback callback);} 3. Create the implementation of our password strength service in a new Java file named PasswordStrengthServiceImpl.java in the com.packtpub.gwtbook.samples.server package. public class PasswordStrengthServiceImpl extendsRemoteServiceServlet implements PasswordStrengthService{private int STRONG = 9;private int MEDIUM = 6;private int WEAK = 3;public int checkStrength(String password){if (password.length() <= 4){return WEAK;}else if (password.length() < 8){return MEDIUM;}else{return STRONG;}}} 4. Now let's create the user interface for this application. Create a new Java file named PasswordStrengthPanel.java in the com.packtpub.gwtbook.samples.client.panels package that extends the com.packtpub.gwtbook.samples.client.panels.SamplePanel class. Create a text box for entering the password string an ArrayList named strengthPanel for holding the checkboxes that we will use for displaying the strength of the password. Also create the PasswordStrengthService object. public TextBox passwordText = new TextBox();final PasswordStrengthServiceAsync pwStrengthService =(PasswordStrengthServiceAsync)GWT.create(PasswordStrengthService.class);public ArrayList strength = new ArrayList(); 5. Add a private method for clearing all the checkboxes by setting their style to the default style. private void clearStrengthPanel(){for (Iterator iter = strength.iterator(); iter.hasNext();){((CheckBox) iter.next()).setStyleName(getPasswordStrengthStyle(0));}} 6. Add a private method that will return the CSS name, based on the password strength. This is a nice way for us to dynamically set the style for the checkbox, based on the strength. private String getPasswordStrengthStyle(int passwordStrength){if (passwordStrength == 3){return "pwStrength-Weak";}else if (passwordStrength == 6){return "pwStrength-Medium";}else if (passwordStrength == 9){return "pwStrength-Strong";}else{return "";}} 7. In the constructor for the PasswordStrengthPanel class, create a HorizontalPanel named strengthPanel, add nine checkboxes to it, and set its style. As mentioned before, the styles that we are using in the sample applications in this book are available in the file Samples.css, which is part of the source code distribution for this book. We also add these same checkboxes to the strength object, so that we can retrieve them later to set their state. These checkboxes will be used for displaying the password strength visually. Create a new VerticalPanel that we will use as the container for the widgets that we are adding to the user interface. Finally, create the service target and set its entry point. HorizontalPanel strengthPanel = new HorizontalPanel();strengthPanel.setStyleName("pwStrength-Panel");for (int i = 0; i < 9; i++){CheckBox singleBox = new CheckBox();strengthPanel.add(singleBox);strength.add(singleBox);}VerticalPanel workPanel = new VerticalPanel();ServiceDefTarget endpoint=(ServiceDefTarget) pwStrengthService;endpoint.setServiceEntryPoint(GWT.getModuleBaseURL() +"pwstrength"); 8. In the same constructor, set the style for the password text box, and add an event handler to listen for changes to the password box. passwordText.setStyleName("pwStrength-Textbox");passwordText.addKeyboardListener(new KeyboardListener(){public void onKeyDown(Widget sender, char keyCode, int modifiers){}public void onKeyPress(Widget sender, char keyCode, int modifiers){}public void onKeyUp(Widget sender, char keyCode,int modifiers){if (passwordText.getText().length() > 0){AsyncCallback callback = new AsyncCallback(){public void onSuccess(Object result){clearStrengthPanel();int checkedStrength = ((Integer) result).intValue();for (int i = 0; i < checkedStrength; i++){((CheckBox) strength.get(i)).setStyleName(getPasswordStrengthStyle(checkedStrength));}}public void onFailure(Throwable caught){Window.alert("Error calling the password strengthservice." + caught.getMessage());}};pwStrengthService.checkStrength(passwordText.getText(), callback);}else{clearStrengthPanel();}}}); 9. Finally, in the constructor, add the password text box and the strength panel to the work panel. Create a little info panel that displays descriptive text about this application, so that we can display this text when this sample is selected in the list of available samples in our Samples application. Add the info panel and the work panel to a dock panel, and initialize the widget. HorizontalPanel infoPanel = new HorizontalPanel();infoPanel.add(new HTML("<div class='infoProse'>Start typing a passwordstring. The strength of the password will bechecked and displayed below. Red indicates that thepassword is Weak, Orange indicates a Mediumstrength password and Green indicates a Strongpassword. The algorithm for checking the strengthis very basic and checks the length of the passwordstring.</div>"));workPanel.add(passwordText);workPanel.add(infoPanel);workPanel.add(strengthPanel);DockPanel workPane = new DockPanel();workPane.add(infoPanel, DockPanel.NORTH);workPane.add(workPanel, DockPanel.CENTER);workPane.setCellHeight(workPanel, "100%");workPane.setCellWidth(workPanel, "100%");initWidget(workPane); 10. Add the service to the module file for the Samples application—Samples.gwt.xml in the com.packtpub.gwtbook.samples package. <servlet path="/pwstrength" class="com.packtpub.gwtbook.samples.server.PasswordStrengthServiceImpl"/> Here is the user interface for the password strength checking application: Now start typing a password string to check its strength. Here is the password strength when you type a password string that is less than five characters: What Just Happened? The password strength service checks the size of the provided string and returns an integer value of three, six, or nine based on whether it is weak, medium, or strong. It makes this determination by using the criteria that if the password string is less than five characters in length, it is weak, and if it is more than five characters but not greater than seven characters, it is considered a medium strength password. Anything over seven characters is considered to be a strong password. The user interface consists of a text box for entering a password string and a panel containing nine checkboxes that visually displays the strength of the typed string as a password. An event handler is registered to listen for keyboard events generated by the password text box. Whenever the password text changes, which happens when we type into the field or change a character in the field, we communicate asynchronously with the password strength service and retrieve the strength of the given string as a password. The returned strength is displayed to the user in a visual fashion by the use of colors to symbolize the three different password strengths. The password strength is displayed in a compound widget that is created by adding nine checkboxes to a HorizontalPanel. The color of the checkboxes is changed using CSS depending on the strength of the password string. This process of combining the basic widgets provided by GWT into more complex widgets to build user interfaces is a common pattern in building GWT applications. It is possible to build quite intricate user interfaces in this way by utilizing the power of the GWT framework. Summary In the current day and age, passwords are required for almost everything, and choosing secure passwords is very important. In this article, we implemented a password strength checker in Google Web Toolkit (GWT) and AJAX. By going through the article, the reader can also get a general idea of implementing other interactive user forms.
Read more
  • 0
  • 0
  • 2090

article-image-table-and-database-operations-php
Packt
23 Oct 2009
8 min read
Save for later

Table and Database Operations in PHP

Packt
23 Oct 2009
8 min read
Various links that enable table operations have been put together on one sub-page of the Table view: Operations. Here is an overview of this sub-page: Table Maintenance During the lifetime of a table, it repeatedly gets modified, and so grows and shrinks. Outages may occur on the server, leaving some tables in a damaged state. Using the Operations sub-page, we can perform various operations, but not every operation is available for every table type: Check table: Scans all rows to verify that deleted links are correct. Also, a checksum is calculated to verify the integrity of the keys; we should get an 'OK' message if everything is all right. Analyze table: Analyzes and stores the key distribution; this will be used on subsequent JOIN operations to determine the order in which the tables should be joined. Repair table: Repairs any corrupted data for tables in the MyISAM and ARCHIVE engines. Note that the table might be so corrupted that we cannot even go into Table view for it! In such a case, refer to the Multi-Table Operations section for the procedure to repair it. Optimize table: This is useful when the table contains overheads. After massive deletions of rows or length changes for VARCHAR fields, lost bytes remain in the table. PhpMyAdmin warns us in various places (for example, in the Structure view) if it feels the table should be optimized. This operation is a kind of defragmentation for the table. In MySQL 4.x, this operation works only on tables in the MyISAM, Berkeley (BDB), and InnoDB engines. In MySQL 5.x, it works only on tables in the MyISAM, InnoDB, andARCHIVE engines. Flush table: This must be done when there have been lots of connection errors and the MySQL server blocks further connections. Flushing will clear some internal caches and allow normal operations to resume. Defragment table: Random insertions or deletions in an InnoDB table fragment its index. The table should be periodically defragmented for faster data retrieval. The operations are based on the underlying MySQL queries available—phpMyAdmin is only calling those queries. Changing Table Attributes Table attributes are the various properties of a table. This section discusses the settings for some of them. Table Type The first attribute we can change is called Table storage engine: This controls the whole behavior of the table: its location (on-disk or in-memory), the index structure, and whether it supports transactions and foreign keys. The drop-down list may vary depending on the table types supported by our MySQL server. Changing the table type may be a long operation if the number of rows is large. Table Comments This allows us to enter comments for the table. These comments will be shown at appropriate places (for example, in the left panel, next to the table name in the Table view and in the export file). Here is what the left panel looks like when the $cfg['ShowTooltip'] parameter is set to its default value of TRUE: The default value of $cfg['ShowTooltipAliasDB'] and $cfg['ShowTooltipAliasTB'] (FALSE) produces the behavior we have seen earlier: the true database and table names are displayed in the left panel and in the Database view for the Structure sub-page. Comments appear when the mouse pointer is moved over a table name. If one of these parameters is set toTRUE, the corresponding item (database names for DB and table names for TB) will be shown as the tooltip instead of the names. This time, the mouse-over shows the true name for the item. This is convenient when the real table names are not meaningful. There is another possibility for $cfg['ShowTooltipAliasTB']: the 'nested' value. Here is what happens if we use this feature: The true table name is displayed in the left panel. The table comment (for example project__) is interpreted as the project name and is displayed as such. Table Order When we Browse a table or execute a statement such as SELECT * from book, without specifying a sort order, MySQL uses the order in which the rows are physically stored. This table order can be changed with the Alter table order by dialog. We can choose any field, and the table will be reordered once on this field. We choose author_id in the example, and after we click Go, the table gets sorted on this field. Reordering is convenient if we know that we will be retrieving rows in this order most of the time. Moreover, if later we use an ORDER BY clause and the table is already physically sorted on this field, the performance should be higher. This default ordering will last as long as there are no changes in the table (no insertions, deletions, or updates). This is why phpMyAdmin shows the (singly) warning. After the sort has been done on author_id, books for author 1 will be displayed first, followed by the books for author 2, and so on. (We are talking about a default browsing of the table without explicit sorting.) We can also specify the sort order: Ascending or Descending. If we insert another row, describing a new book from author 1, and then click Browse, the book will not be displayed along with the other books for this author because the sort was done before the insertion. Table Options Other attributes that influence the table's behavior may be specified using the Table options dialog: The options are: pack_keys:Setting this attribute results in a smaller index; this can be read faster but takes more time to update. Available for the MyISAM storage engine. checksum: This makes MySQL compute a checksum for each row. This results in slower updates, but easier finding of corrupted tables. Available for MyISAM only. delay_key_write: This instructs MySQL not to write the index updates immediately but to queue them for later, which improves performance. Available for MyISAM only. auto-increment: This changes the auto-increment value. It is shown only if the table's primary key has the auto-increment attribute. Renaming, Moving, and Copying Tables The Rename operation is the easiest to understand: the table simply changes its name and stays in the same database. The Move operation (shown in the following screen) can manipulate a table in two ways: change its name and also the database in which it is stored Moving a table is not directly supported by MySQL, so phpMyAdmin has to create the table in the target database, copy the data, and then finally drop the source table. The Copy operation leaves the original table intact and copies its structure or data (or both) to another table, possibly in another database. Here, the book-copy table will be an exact copy of the book source table. After the copy, we will stay in the Table view for the book table unless we selected Switch to copied table. The Structure only copy is done to create a test table with the same structure. Appending Data to a Table The Copy dialog may also be used to append (add) data from one table to another. Both tables must have the same structure. This operation is achieved by entering the table to which we want to copy the data of the current table and choosing Data only. For example, we would want to append data when book data comes from various sources (various publishers), is stored in more than one table, and we want to aggregate all the data to one place. For MyISAM, a similar result can be obtained by using the MERGE storage engine (which is a collection of identical MyISAM tables), but if the table is InnoDB, we need to rely on phpMyAdmin's Copy feature. Multi-Table Operations In the Database view, there is a checkbox next to each table name and a drop-down menu under the table list. This enables us to quickly choose some tables and perform an operation on all those tables at once. Here we select the book-copy and the book tables, and choose the Check operation for these tables. We could also quickly select or deselect all the checkboxes with Check All/Uncheck All. Repairing an "in use" Table The multi-table mode is the only method (unless we know the exact SQL query to type) for repairing a corrupted table. Such tables may be shown with the in use flag in the database list. Users seeking help in the support forums for phpMyAdmin often receive this tip from experienced phpMyAdmin users. Database Operations The Operations tab in the Database view gives access to a panel that enables us to perform operations on a database taken as a whole. Renaming a Database Starting with phpMyAdmin 2.6.0, a Rename database dialog is available. Although this operation is not directly supported by MySQL, phpMyAdmin does it indirectly by creating a new database, renaming each table (thus sending it to the new database), and dropping the original database. Copying a Database Since phpMyAdmin 2.6.1, it is possible to do a complete copy of a database, even if MySQL itself does not support this operation natively. Summary In this article, we covered the operations we can perform on whole tables or databases. We also took a look at table maintenance operations for table repair and optimization, changing various table attributes, table movements, including renaming and moving to another database, and multi-table operations.
Read more
  • 0
  • 0
  • 4014

article-image-minilang-and-ofbiz
Packt
23 Oct 2009
11 min read
Save for later

Minilang and OFBiz

Packt
23 Oct 2009
11 min read
What is Minilang? The syntax of Minilang is simply well formed XML. Developers write XML that obeys a defined schema, this XML is then parsed by the framework and commands are executed accordingly. It is similar in concept to the Gang of Four Interpreter Pattern. We can therefore consider Minilang's XML elements to be "commands". Minilang is usually written in a simple method's XML file, which is specified at the top of the document like this: xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/ simple-methods.xsd"> Although Minilang's primary use is to code services and events, concepts from Minilang are also used to prepare data for screen widgets. Much of the simplicity of Minilang arises from the fact that variables are magically there for us to use. They do not have to be explicitly obtained, they are placed in the environment and we can take them as we wish. Should we wish to create a Map, we just use it, the framework will take care of its creation. For example: <set field="tempMap.fieldOne" from-field="parameters.fieldOne"/> will set the value of the fieldOne parameter to tempMap. If tempMap has already been used and is available, this will be added. If not, the Map will be created and the value added to the key fieldOne. Tools to Code XML Minilang is coded in XML and before it can be successfully parsed by the framework's XML parser, this XML must be well formed. Trying to code Minilang in a plain text editor like Notepad is not a wise move. Precious time can be wasted trying to discover a simple mistake such as a missing closing tag or a misspelled element. For this reason, before attempting to code Minilang services, make sure that you have installed some kind of XML editor and preferably one with an auto-complete feature. The latest versions of Eclipse come packaged with one and XML files are automatically associated to use this editor. Alternatively there are many editors available to download of varying functionality and price. For example XML Buddy (http://www.xmlbuddy.com), oXygen XML Editor (http://www.oxygenxml.com), or the heavyweight Altova XMLSpy (http://www.altova.com) Defining a Simple Service Minilang services are referred to as "simple" services. They are defined and invoked in the same way as a Java service. They can be invoked by the control servlet from the controller.xml file or from code in the same way as a Java service. In the following example we will write a simple service that removes Planet Reviews from the database by deleting the records. First open the file ${component:learning}widgetLearningForms.xml and find the PlanetReviews Form Widget. This widget displays a list of all reviews that are in the database. Inside this Form Widget, immediately under the update field element add: <field name="delete"><hyperlink target="RemovePlanetReview?reviewId=${reviewId}" description="Delete"/></field> Our list will now also include another column showing us a hyperlink we can click, although clicking it now will cause an error. We have not added the request-map to handle this request in the controller.xml. It will be added a little later. Defining the Simple Service In the file ${component:learning}servicedefservices.xml add a new service definition: <service name="learningRemovePlanetReview" engine="simple" location="org/ofbiz/learning/learning/LearningServices.xml" invoke="removePlanetReview"> <description>Service to remove a planet review</description> <attribute name="reviewId" type="String" mode="IN" optional="false"/> </service> Note that the engine type is simple. It is a common practice to group service definitions into their own XML file according to behavior. For instance, we may see that all services to do with Order Returns are in a file called services_returns.xml. So long as we add the <service-resource> element to the parent component's ofbiz-component.xml file and let the system know that this service definition file needs to be loaded, we can structure our service definitions sensibly and avoid huge definition files. It is not a common practice, however, to group service definitions by type. The type is abstracted from the rest of the system. When the service is invoked, the invoker doesn't care what type of service it is. It could be Java, it could be a simple service, it doesn't matter. All that matters is that the correct parameters are passed into the service and the correct parameters are passed out. For this reason, simple service definitions are found in the same XML files as Java service definitions. Writing the Simple Method Simple Method XML files belong in the component's script folder. In the root of ${component:learning} create the nested directory structure scriptorgofbizlearninglearning and in the final directory create a new file called LearningServices.xml. Before we add anything to this file we must make sure that the script directory is on the classpath. Open the file ${component:learning}ofbiz-component.xml and if it is not already there add <classpath type="dir" location="script"/> immediately underneath the other classpath elements. The location specified in the service definition can now be resolved. In our newly created file LearningServices.xml add the following code: <simple-methods xsi:noNamespaceSchemaLocation="http://www.ofbiz.org/dtds/ simple-methods.xsd"> <simple-method method-name="removePlantetReview" short-description="Delete a Planet Review"> <entity-one entity-name="PlanetReview" value-name="lookedUpValue"/> <remove-value value-name="lookedUpValue"/> </simple-method> </simple-methods> Finally all that is left is to add the request-map to the controller.xml: <request-map uri="RemovePlanetReview"> <security auth="true" https="true"/> <event type="service" invoke="learningRemovePlanetReview"/> <response name="success" type="view" value="ListPlanetReviews"/> <response name="error" type="view" value="ListPlanetReviews"/> </request-map> Since we have added a new service definition OFBiz must be restarted. A compilation is not needed. Restart and fire an http request ListPlanetReviews to webapp learning: Selecting Delete will delete this PlanetReview record from the database. Let's take a closer look at the line of code in the simple service that performs the lookup of the record that is to be deleted. <entity-one entity-name="PlanetReview" value-name="lookedUpValue"/> This command will perform a lookup on the PlanetReview entity. Since the command is <entity-one> the lookup criteria must be the primary key. This code is equivalent in Java to: GenericValue lookedUpValue = delegator.findByPrimaryKey ("PlanetReview", UtilMisc.toMap("reviewId", reviewId)); Already we can see that Minilang is less complicated. And this is before we take into account that the Java code above is greatly simplified, ignoring the fact that the delegator had to be taken from the DispatchContext, the reviewId had to be explicitly taken from the context Map and the method call had to be wrapped in a try/catch block. In Minilang, when there is a look up like this, the context is checked for a parameter with the same name as the primary key for this field, as specified in the entity definition for PlanetReview. If there is one, and we know there is since we have declared a compulsory parameter reviewId in the service definition, then the framework will automatically take it from the context. We do not need to do anything else. Simple Events We can call Minilang events, in the same way that we called Java events from the controller.xml. Just as Minilang services are referred to as simple services, the event handler for Minilang events is called "simple". Tell the control servlet how to handle simple events by adding a new <handler> element to the learning component's controller.xml file, immediately under the other <handler> elements: <handler name="simple" type="request" class="org.ofbiz.webapp.event.SimpleEventHandler"/> A common reason for calling simple events would be to perform the preparation and validation on a set of parameters that are passed in from an XHTML form. Don't forget that when an event is called in this way, the HttpServletRequest object is passed in! In the case of the Java events, it is passed in as a parameter. For simple events, it is added to the context, but is nonetheless still available for us to take things from, or add things onto. In the same location as our LearningServices.xml file (${component:learning} scriptorgofbizlearninglearning) create a new file called LearningEvents.xml. To this file add one <simple-method> element inside a <simple-methods> tag: <simple-methods xsi:noNamespaceSchemaLocation="http://www.ofbiz.org/dtds/ simple-methods.xsd"> <simple-method method-name="simpleEventTest" short-description="Testing a simple Event"> <log level="info" message="Called the Event: simpleEventTest"/> </simple-method> </simple-methods> Finally, we need to add a request-map to the controller from where this event will be invoked: <request-map uri="SimpleEventTest"> <security auth=true»https=true/> <event type=»simple»path=»org/ofbiz/learning/learning/ LearningEvents.xml»invoke=»simpleEventTest»/> <response name=»success»type=»view»value=»SimplestScreen»/> <response name=»error»type=»view»value=»SimplestScreen»/> </request-map> Notice our simple method doesn't actually do anything other than leave a message in the logs. It is with these messages that we can debug through Minilang. Validating and Converting Fields We have now met the Simple Methods Mini-Language, which is responsible for general processing to perform simple and repetitive tasks as services or events. Validation and conversion of parameters are dealt with by another type of Minilang—the Simple Map Processor. The Simple Map Processor takes values from the context Map and moves them into another Map converting them and performing validation checks en-route. Generally, Simple Map Processors will prepare the parameters passed into a simple event from an HTML form or query string. As such, the input parameters will usually be of type String. Other object types can be validated or converted using the Simple Map Processor including: BigDecimals, Doubles, Floats, Longs, Integers, Dates, Times, java.sql.Timestamps, and Booleans. The Simple Map Processors are, like simple methods, coded in XML and they adhere to the same schema (simple-methods.xsd). Open this file up again and search for The Simple Map Processor Section. The naming convention for XML files containing Simple Map Processors is to end the name of the file with MapProcs.xml (For example, LearningMapProcs.xml) and they reside in the same directory as the Simple Services and Events. One of the best examples of validation and conversion already existing in the code is to be found in the PaymentMapProcs.xml file in ${component:accounting}scriptorgofbizaccountingpayment. Open this file and find the simple-map-processor named createCreditCard. Here we can see that immediately, the field expireDate is created from the two parameters expMonth and expYear with a "/" placed in between (example, 09/2012): <make-in-string field="expireDate"> <in-field field="expMonth"/> <constant>/</constant> <in-field field="expYear"/> </make-in-string> Towards the end of the <simple-map-processor> this expireDate field is then copied into the returning Map and validated using isDateAfterToday. If the expiration date is not after today, then the card has expired and instead, a fail-message is returned. <process field="expireDate"> <copy/> <validate-method method="isDateAfterToday"> <fail-message message="The expiration date is before today"/> </validate-method> </process> The <validate-method> element uses a method called isDateAfterToday. This method is in fact a Java static method found in the class org.ofbiz.base.util.UtilValidate. We have already been using one of the OFBiz utility classes, UtilMisc, namely the toMap function, to create for us Maps from key-value pairs passed in as parameters. OFBiz provides a huge number of incredibly useful utility methods, ranging from validation, date preparation, and caching tools to String encryption and more. The framework will automatically allow Minilang access to this class. By adding a bespoke validation method into this class and recompiling, you will be able to call it from the <validate-method> in Minilang, from anywhere in your application.
Read more
  • 0
  • 0
  • 1602
Visually different images

article-image-user-access-control-drupal-6
Packt
23 Oct 2009
16 min read
Save for later

User Access Control in Drupal 6

Packt
23 Oct 2009
16 min read
Before we continue, it is worth pointing out that at the moment of adding the basic functionality you are more than likely using the administrative user (user number 1) for all the site's development needs. That is absolutely fine, but once the major changes to the site are completed, you should begin using a normal administrative user that has only the permissions required to complete your day-to-day tasks. The next section will highlight the general philosophy behind user access, which should make the reason for this clear. Planning an Access Policy When you think about how your site should work, focus in on what will be required of yourself, other community members, or even anonymous users. For instance: Will there be a team of moderators working to ensure that the content of the site conforms to the dictates of good taste and avoids material that is tantamount to hate speech, and so on? Will there be subject experts who are allowed to create and maintain their own content? How much will anonymous visitors be allowed to become involved, or will they be forced to merely window shop without being able to contribute? Some of you might feel that the site should grow organically with the community, and so you want to be extremely flexible in your approach. However, you can take it as given that Drupal's access policies are already flexible, given how easy it is to reconfigure, so it is good practice to start out with a sensible set of access rules, even if they are going to change over time. If you need to make modifications later, so be it, but at least there will be a coherent set of rules from the start. The first and foremost rule of security that can be applied directly to our situation is Grant a user permissions sufficient for completing the intended task, and no more! Our entire approach is going to be governed by this rule. With a bit of thought you should be able to see why this is so important. The last thing anyone wants is for an anonymous user to be able to modify the personal blog of a respected industry expert. This means that each type of user should have carefully controlled permissions that effectively block their ability to act outside the scope of their remit. One upshot of this is that it is better to create a larger number of specific roles, rather than create a generic role or two, and allow everyone to use those catch-all permissions. A role constitutes a number of permissions that define what actions any members of that role can and can't perform. We will explore roles in detail in the next section! Drupal gives us fine-grained control over what users can accomplish, and you should make good use of this facility. It may help to think of your access control using the following figure (this does not necessarily represent the actual roles on your site—it's just an example): The shaded region represents the total number of permissions available for the site. Contained within this set are the various roles that exist either by default, like the Anonymous users role, or those you create in order to cater for the different types of users the site will require—in this case, the Blog Writer users and Forum Moderator users roles. From the previous diagram you can see that the Anonymous users role has the smallest set of permissions because they have the smallest area of the total diagram. This set of permissions is totally encapsulated by the Forum Moderator users and Blog Writer users—meaning that forum moderators and blog writers can do everything an anonymous user does, and a whole lot more. Remember, it is not compulsory that forum moderators encapsulate all the permissions of the anonymous users. You can assign any permissions to any role—it's just that in this context it makes sense that a forum moderator should be able to do everything an anonymous user can and more. Of course, the blog writers have a slightly different remit. While they share some privileges in common with the forum administrators, they also have a few of their own. Your permissions as the primary or administrative user encompass the entire set, because there should be nothing that you cannot control. It is up to you to decide which roles are best for the site, but before attempting this it is important to ask: What are roles and how are they used in the first place? To answer this question, let's take a look at the practical side of things in more detail. Roles It may seem a bit odd that we are not beginning a practical look at access control with a discussion on users. After all, it is all about what users can and cannot do! The problem with immediately talking about users is that the focus of a single user is too narrow, and we can learn far more about controlling access by taking a more broad view using roles. Once we have learned everything there is to know about roles, actually working with users becomes a trivial matter. As mentioned, a user role in Drupal defines a set of rules that must be obeyed by all the users in that role. It may be helpful to think of a role as a character in a play. In a play, an actor must always be true to their character (in the same way a user must be faithful to their role in Drupal)—in other words, there is a defined way to behave and the character never deviates (no matter which actor portrays the character). Creating a role in Drupal is very easy. Click the User management link under Administer and select the Roles tab to bring up the following: As you can see, we have two roles already defined by default—the anonymous user and the authenticated user. It is not possible to change these, and so the Operations column is permanently set to locked. To begin with, the anonymous user (this is any user who is browsing the site without logging in) has very few permissions set, and you would more than likely want to keep it this way, despite the fact it is possible to give them any and all permissions. Similarly, the authenticated user, by default, has only a few more permissions than the anonymous user, and it is also sensible to keep these to a minimum. We will see in a little while how to go about deciding who should have which permissions. In order to add a new role, type in a name for the role and click Add role, and you're done. But what name do you want to add? That's the key question! If you are unsure about what name to use, then it is most likely you haven't defined the purpose of the role properly. To see how this is done, let's assume we require a forum moderator who will be a normal user in every way, except for the ability to work directly on the forums (to take some of the burden of responsibility off the administrator's hands) to create new topics, and to edit the content if necessary. To get the ball rolling, type in forum moderator and click Add role—actually, you might even want to be more specific and use something like conservation forum moderator if there will be teams of forum moderators—you get the general idea. Now the roles page should display the new role with the option to edit it, shown in the Operations column. Click edit role in order to change the name of the role or delete it completely. Alternatively, click edit permissions to deal with the permissions for this specific role (we discuss permissions in a moment so let's leave this for now). Our work is just beginning, because now we need to grant or deny the various permissions that the forum moderator role will need in order to successfully fulfill its purpose. New roles are not given any permission at all to begin with—this makes sense, because the last thing we want is to create a role only to find that it has the same permissions as the administrative user. Chances are you will need to add several roles depending on the needs of the site, so add at least a blogger user that can edit their own blog—we will need a few different types to play with later on. Let's move on and take a look at how to flesh out this new role by setting permissions. Permissions In order to work with permissions, click the Permissions link under User management and you should be presented with a screen much like the following (notice the new forum moderator role on the right-hand side of the page): As you can see, this page lists all of the available permissions down the left-hand column and allows you to enable or disable that permission by checking or un-checking boxes in the relevant column. It is easy enough to see that one traverses the list, selecting those permissions required for each role. What is not so easy is actually determining what should and shouldn't be enabled in the first place. Notice too that the permissions given in the list on the left-hand side pertain to specific modules. This means that if we change the site's setup by adding or removing modules, then we will also have to change the permissions on this page. Most times a module is added, you will need to ensure that the permissions are set as required for that module, because by default no permissions are granted. What else can we learn from the permissions page shown in the previous screenshot? Well, what does each permission precisely mean? There are quite a few verbs that allow for completely different actions. The following lists the more common, generic ones, although you might find one or two others crop up every now and then to cater for a specific module: administer: gives the user the ability to affect the function of a module. For example, granting administer rights to the locale module means that the user can add or remove languages, manage strings, and even export .po files. This permission should only ever be given to trusted users, and never to anonymous users. access: gives the user the ability to make use of a module without being able to affect it in any way. For example, granting access rights to the comment module allows a user to view comments without being able to delete, edit, or reply to them. create: gives the user the ability to create content of some sort. For example, granting rights to create stories allows users to do so, but does not also give them the ability to edit those stories. edit any/own: gives the user the ability to work with either anyone's content or specifically the content they have created—depending on whether edit any or edit own is selected. For example, granting edit own rights to the blog module means that the user can modify their own blogs at will. delete any/own: applies to content related modules such as Node and empowers users to remove either anyone's content or confine them to removing only content posted by themselves. For example, setting delete own blog entry allows users to take back any blog postings they may regret having published. There are also other module-specific permissions available, and it is recommended that you play around and understand any new permission(s) you set. Previously, assigning the edit own permission automatically provided the delete own permission. For added security, delete own permissions for individual core content types have been removed from all roles and should be assigned separately. How do we go about setting up the required permissions for the forum moderator user? If we look down the list of permissions shown on the Permission page, we see the following forum-related options (at the moment, the forum moderator permissions are those in the outermost column): Enabling these three options, and then testing out what new powers are made available, should quickly demonstrate that this is not quite what we want. If you are wondering how to actually test this out, you need to create a new user and then assign them to the forum moderator role. The following section on Users explains how to create new users and administer them properly. Jump ahead quickly and check that out so that you have a new user to work with if you are unsure how it is done. The following point might make your life a bit easier: Use two browsers to test out your site. The demo site's development machine has IE and Firefox. Keep one browser for the administrator and the other for anonymous or other users in order to test out changes. This will save you from having to log in and log out whenever testing new permissions. When testing out the new permissions one way or another, you will find that the forum moderator can access and work with all of the forums—assuming you have created any. However, notice that there are node module permissions available, which is quite interesting because most content in Drupal is actually a node. How will this affect the forum moderator? Disable the forum module permissions for the forum moderator user and then enable all the node options for the authenticated user before saving and logging out. Log back in as the forum administrator and it will be clear that despite having revoked the forum based options for this user, it is possible to post to or edit anything in the forum quite easily by selecting the Create content link in the main menu. Is this what you expected? It should be precisely what you expect because the forum moderator is an authenticated user, so they have acquired the permissions that came from the authenticated user. In addition, the forum posts are all nodes, and any authenticated user can add and edit nodes, so even though the forum moderator is not explicitly allowed to work with forums, through generic node permissions we get the same result: Defined roles are given the authenticated user permissions. Actually, the result is not entirely the same because the forum moderator can now also configure all the different types of content on the site, as well as edit any type of content including other people's blogs. This is most certainly undesirable, so log back in as the primary user and remove the node permissions (except the first one) from the authenticated user role. With that done, you can now spend some time building a fairly powerful and comprehensive role-based access control plan. As an addendum, you might find that despite having a goodly amount of control over who does what, there are some things that are not easily done without help from elsewhere. Users A single user account can be given as many or as few permissions as you like via the use of roles. Drupal users are not really anything unless they already have a role that defines the manner in which they can operate within the Drupal framework. Hence, we discussed roles first. Users can be created in two ways. The most common way is by registering on the site—if you haven't already, go ahead and register a new user on your site by clicking the Create new account link on the homepage just to test things out. Remember to supply a valid email address otherwise you won't be able to sign in properly. This will create an authenticated user, with any and all permissions that have been assigned to the authenticated user role. The second way is to use the administrative user to create a new user. In order to do so, log on as the administrative user and click on Users in User management under Administer. Select the Add user tab and follow the instructions on that page. For example, I created a new forum moderator user by ensuring that the relevant role was checked: You will need to supply Drupal with usernames, email addresses, and passwords. Once there are a couple of users to play around with, it's time to begin working with them. Administering Users The site's administrator is given complete access to the other users' account information. By clicking on the edit link shown to the right of each user account (under the Operations column heading) in the Users page under User management, it is possible to make any changes you require to a given user. Before we do though, it's worth noting that the administration page itself is fairly powerful in terms of being able to administer individual users or groups of users with relative ease: The upper box, Show only users where, allows you to specify several filter conditions to cut down the result set and make it more manageable. This will become more and more important as the site accumulates more and more users. Once the various filter options have been implemented, the Update options allow you to apply whatever changes are needed to the list of users selected (by checking the relevant checkbox next to their name). Having both broad, sweeping powers as well as fine-grained control over users is one of the most valuable facilities provided by Drupal, and you will no doubt become very familiar with this page in due course. Click on the edit link next to the forum moderator user and take a look at the Roles section. Notice that it is now possible to stipulate which roles this user belongs to. At present there are only two new roles to be assigned (yours might vary depending on which roles have been created on your setup): Whenever a user is added to another role, they obtain the combined permissions of these roles. With this in mind, you should go about delegating roles in the following fashion: Define the most basic user of the site by setting the anonymous user permissions. Set permissions for a basic authenticated user (i.e. any Tom, Dick or Harry that registers on your site). Create special roles by only adding the specific additional permissions that are required by that role, and no more. Don't re-assign permissions that the authenticated user already has. Create new users by combining whatever roles are required for their duties or needs.
Read more
  • 0
  • 0
  • 2786

article-image-designing-and-creating-database-tables-ruby-rails
Packt
23 Oct 2009
9 min read
Save for later

Designing and Creating Database Tables in Ruby on Rails

Packt
23 Oct 2009
9 min read
Background Information The User Management Module is created for a website called 'TaleWiki'. TaleWiki is a website about user submitted tales and stories, which can be added, modified, deleted, and published by the user, depending on the Role or Privileges the user has. Taking into consideration this small piece of information, we will design and create tables that will become the back-end for the User Management functionality. Designing the Tables To Design and to create tables, we need to understand the entities and their relationship, the schema corresponding to the entities, and then the table creation queries. If we go step-by-step, we can say that following are the steps in designing the tables for the User Management module: Designing the E-R model Deriving the Schema from the E-R model Creating the Tables from the Schema So, let us follow the steps. Designing the E-R Model To design the E-R model, let us first look at what we have understood about the data required by the functionalities, which we just discussed. It tells us that 'only the Users with a particular Role can access TaleWiki'. Now we can consider this as our 'problem statement' for our E-R model design. If you observe closely, the statement is vague. It doesn't tell about the particular Roles. However, for the E-R design, this will suffice as it clearly mentions the two main entities, if we use the E-R terminology. They are: User Role Let us look at the User entity. Now this entity represents a real-world user. It is not difficult to describe its attributes. Keeping a real-world user in mind and the functionalities discussed for managing a user, we can say that the User entity should have the following attributes: Id: It will identify the different users, and it will be unique. User name: The name which will be displayed with the submitted story. Password: The pass key with which the user will be authenticated. First name: The first name of the user. Last name: The last name of the user. The combination of the first and last name will be the real name of the user. Age: The age of the user. This will help in deciding whether or not the user is of required age which is 15. E-mail id: The email id of the user in which he/she would like to get emails from the administrator regarding the submissions. Country: To keep track of the 'geographic distribution' of users. Role: To know what privileges are granted for the user. The Role is required because the problem statement mentions "User with a particular Role". The entity diagram will be as follows: Next, let us look at the Role entity. Role, as already discussed, will represent the privileges a user can have. And as these privileges are static, the Role entity won't need to have the attribute to store the privileges. The important point about the static privileges that you have to keep in mind is that they will have to be programmatically checked against a user. In other words, the privileges are not present in the database and there can only be a small number of Roles with predefined privileges. Keeping this in mind, we can say that the Role entity will have the following attributes: Id: The unique identification number for the Role. Name: The name with which the id will be known and that will be displayed along with the user name. The entity diagram for Role entity will be as follows: We have completed two out of three steps in designing the E-R model. Next, we have to define how the User entity is related with the Role entity. From the problem statement we can say that a user will definitely have a Role. And the functionality for assigning the Role tells us that a user can have only one Role. So if we combine these two, we can say that 'A user will have only one Role but different users can have the same Role'. In simple terms, a Role—let us say normal user—can be applied to different users such as John, or Jane. However, the users John or Jane cannot be both normal user as well as administrator. In technical terms, we can say that a Role has a one-to-many relationship with the User entity and a User has a many-to-one relationship with a Role. Diagrammatically, it will be as follows: One piece of the puzzle is still left. If you remember there is one more entity called Story. We had found that each story had a submitter. The submitter is a user. So that means there is a relationship between the User and the Story entity. Now, a user, let us say, John or Jane, can submit many stories. However, the same story cannot be submitted by more than one user. On the basis of this we can say that a User has a many-to-one relationship with a Story and a Story has a many-to-one relationship with a User. According to the E-R diagram it will be as follows: The final E-R design including all the entities and the attributes will be as follows: That completes our E-R design step. Next, we will derive the schema from theE-R model. Deriving the Schema We have all we need to derive the schema for our purpose. While deriving a schema from an E-R model, it is always a good choice to start with the entities at the 'one' end of a 'one-to-many' relationship. In our case, it is the Role entity. As we did in the previous chapter, let us start by providing the details for each attribute of the Role entity. The following is the schema for the Role entity: Attribute Data type of the attribute Length of the acceptable value Id Integer 10 Name Varchar 25 >Next, let us look at the schema of the User entity. As it is at the 'many' end of the 'one-to-many' relationship, the Role attribute will be replaced by the Id of Role. The schema will be as follows: Attribute Data type of the attribute Length of the acceptable value Id Integer 10 User name Varchar 50 First name Varchar 50 Last name Varchar 50 Password Varchar 15 Age Integer 3 e-mail id Varchar 25 Country Varchar 20 Id of the Role Integer 10 Now, let us visit the Story entity. The attributes of the entity were: Id: This is the Primary key attribute as it can uniquely identify a story. Heading: The title of the story. Body text: The body of the story. Date of Submission: The day the user submitted the story. Source: The source from where the story was found. If it is written by the user himself/herself, the source will be the user's id. Genre: The category of the story. User: The user who submitted the story. Name of the attribute Data type of the attribute Length of the acceptable value Id Integer 10 Title Varchar 100 Body Text Varchar 1000 Date of Submission Date   Source Varchar 50 Status Varchar 15 Id of Genre Integer 10 Id of the User Integer 10 The schema has been derived and now we can move to the last part of the database design—creation of the tables. Creating the Tables Looking at the schema  required for tables in Ruby on Rails, here is the table creation statement for the Role schema: CREATE TABLE `roles` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`name` VARCHAR( 25 ) NOT NULL ,`description` VARCHAR( 100 ) NOT NULL) ENGINE = innodb; Next comes the table creation statement for the User schema. Note that here also we are following the one-to-many path, that is, the table at the 'one' end is created first. Whenever there is a one-to-many relationship between entities, you will have to create the table for the entity at the 'one' end. Otherwise you will not be able to create a foreign key reference in the table for the entity at the 'many' end, and if you try to create one, you will get an error (obviously). So here is the create table statement for the User schema: CREATE TABLE `users` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`user_name` VARCHAR( 50 ) NOT NULL ,`password` VARCHAR( 15 ) NOT NULL ,`first_name` VARCHAR( 50 ) NOT NULL ,`last_name` VARCHAR( 50 ) NOT NULL ,`age` INT( 3 ) NOT NULL ,`email` VARCHAR( 25 ) NOT NULL ,`country` VARCHAR( 20 ) NOT NULL ,`role_id` INT NOT NULL,CONSTRAINT `fk_users_roles` FOREIGN KEY (`role_id`) REFERENCES `role`( `id`) ON DELETE CASCADE) ENGINE = innodb; Next, let us create the table for Story, we will call it the 'tales' table, we will also add a foreign key reference to the users table in it. Here is the query for creating the table CREATE TABLE `tales` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,`title` VARCHAR( 100 ) NOT NULL,`body_text` TEXT NOT NULL,`submission_date` DATE NOT NULL,`source` VARCHAR( 50 ) NOT NULL,`status` VARCHAR( 15 ) NOT NULL,`genre_id` INT NOT NULL,`user_id` INT NOT NULL,CONSTRAINT `fk_tales_genres` FOREIGN KEY (`genre_id`) REFERENCES genres( `id`)) ENGINE = innodb; Next, we will make a reference to the users table after executing the above query, with the following query: ALTER TABLE `tales` ADD FOREIGN KEY ( `user_id` ) REFERENCES `users` (`id`) ON DELETE CASCADE ; That completes our task of creating the required tables and making necessary changes to the tales table. The effect of this change will be visible to you when we implement session management in the next chapter. And incidentally, it completes the 'designing the tables' section. Let us move onto the development of the user management functionality. Summary In this article, we learned how to design and create tables for a User Management Module in Ruby on Rails. We looked at designing the E-R model, deriving the schema from the E-R model and creating the tables from the schema.
Read more
  • 0
  • 0
  • 3995

article-image-implementing-calendar-control-yahoo-user-interface-yui
Packt
23 Oct 2009
10 min read
Save for later

Implementing a Calendar Control in the Yahoo User Interface (YUI)

Packt
23 Oct 2009
10 min read
The Basic Calendar Class The most basic type of calendar is the single-panel Calendar which is created with the YAHOO.widget.Calendar class. To display a calendar, an HTML element is required to act as a container for the calendar. The screenshot shows a basic Calendar control: The constructor can then be called specifying, at the very least the id of the container element as an argument. You can also specify the id of the Calendar object as an argument, as well as an optional third argument that can accept a literal object containing various configuration properties. The configuration object is defined within curly braces within the class constructor. It contains a range of configuration properties and keys that can be used to control different Calendar attributes such as its title, a comma-delimited range of pre-selected dates, or a close button shown on the calendar. There are a large number of methods defined in the basic Calendar class; some of these are private methods that are used internally by the Calendar object to do certain things and which you normally wouldn't need to use yourself. Some of the more useful public methods include: Initialization methods including init, initEvents, and initStyles which initialize either the calendar itself or the built-in custom events and style constants of the calendar. A method for determining whether a date is outside of the current month: isDateOOM. Navigation methods such as nextMonth, nextYear, previousMonth, and previousYear that can be used to programmatically change the month or year displayed in the current panel. Operational methods such as addMonths, addYears, subtractMonths, and subtractYears which are used to change the month and year shown in the current panel by the specified number of months or years. The render method is used to draw the calendar on the page and is called in for every implementation of a calendar, after it has been configured. Without this method, no Calendar appears on the page. Two reset methods: reset which resets the Calendar to the month and year originally selected, and resetRenderers which resets the render stack of the calendar. Selection methods that select or deselect dates such as deselect, deselectAll, desellectCell, select, and selectCell. As you can see, there are many methods that you can call to take advantage of the advanced features of the calendar control. The CalendarGroup Class In addition to the basic calendar, you can also create a grouped calendar that displays two or more month panels at once using the YAHOO.widget.CalendarGroup class. The control automatically adjusts the Calendar's UI so that the navigation arrows are only displayed on the first and last calendar panels, and so that each panel has its own heading indicating which month it refers to. The CalendarGroup class contains additional built-in functionality for updating the calendar panels on display, automatically. If you have a two-panel calendar displaying, for example, January and February, clicking the right navigation arrow will move February to the left of the panel so that March will display as the right-hand panel. All of this is automatic and nothing needs to be configured by you. There are fewer methods in this class; some of those found in the basic Calendar class can also be found here, such as the navigation methods, selection methods, and some of the render methods. Native methods found only in the CalendarGroup class include: The subscribing methods sub and unsub, which subscribe or unsubscribe to custom events of each child calendar. Child functions such as the callChildFunction and setChildFunction methods which set and call functions within all child calendars in the calendar group. Implementing a Calendar To complete this example, the only tool other than the Yahoo User Interface (YUI) that you'll need is a basic text editor. Native support for the YUI is provided by some web authoring software packages, most notably Aptana, an open-source application that has been dubbed 'Dreamweaver Killer'. However, I always find that writing code manually while learning something is much more beneficial. It is very quick and easy to add the calendar, as the basic default implementations require very little configuration. It can be especially useful in forms where the visitor must enter a date. Checking that a date has been entered correctly and in the correct format takes valuable processing time, but using the YUI calendar means that dates are always exactly as you expect them to be. So far we've spent most of this article looking at a lot of the theoretical issues surrounding the library; I don't know about you, but I think it's definitely time to get on with some actual coding! The Initial HTML Page Our first example page contains a simple text field and an image, which once clicked will display the Calendar control on the page, thereby allowing for a date to be selected and added to the input. Begin with the following basic HTML page: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"><html lang="en"><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><title>YUI Calendar Control Example</title><link rel="stylesheet"type="text/css"href="yui/build/calendar/assets/skins/sam/calendar.css"><script type="text/javascript"src="yui/build/yahoo-dom-event/yahoo-dom-event.js"></script><script type="text/javascript"src="yui/build/calendar/calendar-min.js"></script><style type="text/css">input {margin:0px 10px 0px 10px;}</style></head><body class="yui-skin-sam"><div><label>Please enter your date of birth:</label><input type="text" name="dobfield" id="dobfield"><img id="calico" src="icons/cal.png"alt="Open the Calendar control"></div><div id="mycal"></div></body></html> We begin with a valid DOCTYPE declaration, a must in any web page. For validity, we can also add the lang attribute to the opening <html> tag and for good measure, enforce the utf-8 character set. Nothing so far is YUI-specific, but coding in this way every time is a good habit. We link to the stylesheet used to control the appearance of the calendar control, which is handled in this example by the sam skin within the <link> tag. Accordingly, we also need to add the appropriate class name to the <body> tag. Following this, we link to the required library files with <script> tags; the calendar control is relatively simple and requires just the YAHOO, Document Object Model (DOM), and Event components (using the aggregated yahoo-dom-event.js file for efficiency), as well as the underlying source file calendar-min.js. A brief <style> tag finishes the <head> section of the page with some CSS relevant to this particular example, and the <body> of the page at this stage contains just two <div> elements: the first holds a <label>, text field, and a calendar icon (which can be used to launch the control), while the second holds the calendar control. When viewed in a browser, the page at this point should appear like this: The calendar icon used in this example was taken, with gratitude from Mark Carson at http://markcarson.com. Beginning the Scripting We want the calendar to appear when the icon next to the text field is clicked, rather than it being displayed on the page-load, so the first thing we need to do is to set a listener for the click event on the image. Directly before closing </body> tag, add the following code: <script type="text/javascript">//create the namespace object for this exampleYAHOO.namespace("yuibook.calendar");//define the lauchCal function which creates the calendarYAHOO.yuibook.calendar.launchCal = function() {}//create calendar on page load YAHOO.util.Event.onDOMReady(YAHOO.yuibook.calendar.launchCal);</script> Let's look at each line of the above code. We first use the .namespace() method of the YAHOO utility to set up the namespace object used for this example. Next we define the anonymous launchCal function, which will hold all of the code that generates the calendar control. Then we use the .onDOMReady() method of the Event utility to execute the launchCal function when the DOM is in an usable state. We'll be looking at the DOM utility in much greater detail later in the book. Now we can add the extremely brief code that's required to actually produce the Calendar. Within the braces of our anonymous function, add the following code: //create the calendar object, specifying the containerVar myCal = new YAHOO.widget.Calendar("mycal");//draw the calendar on screenmyCal.render();//hide it again straight awaymyCal.hide(); This is all that we need to create the Calendar; we simply define myCal as a new Calendar object, specifying the underlying container HTML element as an argument of the constructor. Once we have a Calendar object, we can call the .render() method on it to create the calendar and display it on the page. No arguments are required for this method. Since we want the calendar to be displayed when its icon is clicked, we hide the calendar from view straight away. To display the calendar when the icon for it is clicked, we'll need one more anonymous function. Add the following code beneath the .hide() method: //define the showCal function which shows the calendarVar showCal = function() {//show the calendarmyCal.show();} Now we can attach a listener which detects the click event on the calendar icon: //attach listener for click event on calendar iconYAHOO.util.Event.addListener("calico", "click", showCal); Save the file that we've just created as calendar.html or similar in your yuisite directory. If you view it in your browser now and click the Calendar icon, you should see this: The calendar is automatically configured to display the current date, although this is something that can be changed using the configuration object mentioned earlier. If you use a DOM explorer to view the current DOM of a page with an open calendar on it, you'll see that a basic Calendar control is rendered as a table with eight rows and seven columns. The first row contains the images used to navigate between previous or forthcoming months and the title of the current month and year. The next row holds the two-letter representations of each of the different days of the week, and the rest of the rows hold the squares representing the individual days of the current month. The screenshot on the next page show some of the DOM representation of the Calendar control used in our example page: Now that we can call up the Calendar control by clicking on our Calendar icon, we need to customize it slightly. Unless the person completing the form is very young, they will need to navigate through a large number of calendar pages in order to find their date of birth. This is where the Calendar Navigator interface comes into play. We can easily enable this feature using a configuration object passed into the Calendar constructor. Alter your code so that it appears as follows: //create the calendar object, using container & config objectmyCal = new YAHOO.widget.Calendar("mycal", {navigator:true}); Clicking on the Month or Year label will now open an interface which allows your visitors to navigate directly to any given month and year: The configuration object can be used to set a range of calendar configuration properties including the original month and year displayed by the Calendar, the minimum and maximum dates available to the calendar, a title for the calendar, a close button, and various other properties.
Read more
  • 0
  • 0
  • 2603
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-business-blogging-technorati-state-blogosphere-2008
Packt
23 Oct 2009
4 min read
Save for later

Business Blogging On The Up - Technorati State of the Blogosphere 2008

Packt
23 Oct 2009
4 min read
The report also states that blogs are profitable, it says: The majority of bloggers we surveyed currently have advertising on their blogs. Among those with advertising, the mean annual investment in their blog is $1,800, but it’s paying off. The mean annual revenue is $6,000 with $75K+ in revenue for those with 100,000 or more unique visitors per month. It is interesting to note that the majority of bloggers now display advertising. One of the most encouraging statistics is that the proportion of people blogging about their jobs and on behalf of their business is now so high: About half of bloggers are professional bloggers — blogging is not necessarily their full-time job, but they blog about their industry or profession in an unofficial capacity. 12% of bloggers blog in an official capacity for their company. The amount of cross-over between the groups is also interesting. It shows that personal and business blogging can be successfully combined: More than half of professional and corporate bloggers are also personal bloggers. This could be on a separate blog, or they may blog about personal interests within their professional blog. Corporate bloggers: 69% are also personal bloggers 65% are professional bloggers Professional bloggers: 59% are also personal bloggers 17% are corporate bloggers It’s very encouraging to see the positive benefits being enjoyed by business and professional bloggers, with the majority of those surveyed reporting a positive impact as a result of their blog. Half of them say they are better known in their industry and a quarter see their blog as a useful résumé enhancement. Impact of blogging on professional life: Business bloggers also report that blogging has brought many unique opportunities that wouldn’t have otherwise been available. Taking part in an event, contributing to a print publication or even appearing on radio or TV are the kinds of things they are involved in, thanks to their blog. Have you been invited to any of the following as the result of your blog? Blogging is a time consuming activity. This is confirmed by the report which shows that a quarter of bloggers spend over 10 hours per week on their blog and nearly half spend 5 hours or more. Time spent blogging each week: As I mention in WordPress For Business Bloggers, many bloggers take on help to run their blog. This is particularly true for corporate or business bloggers, of whom nearly 20% have paid staff working for them. Blogs with higher Technorati authority are updated more frequently than those with less authority, as the report states: The Technorati Top 100 are prolific, with 43% posting ten times per day or more often. Only 8% post once a day or less frequently, compared to 13% of the next 500 bloggers, and 22% of the next 5000 bloggers. I highlight the importance of using tags in WordPress For Business Bloggers, and this is borne out by the data. Technorati top 100 bloggers are twice as likely to tag their posts. Percentage of bloggers who use tags: Promoting a blog well is key to its success and the report shows us the top traffic-building strategies used. These are particularly important for business bloggers, so all the techniques highlighted in the chart below are covered in WordPress For Business Bloggers, you’ll find many of them in Chapter 7, Supercharged Promotion: The vast majority of bloggers are tracking their site visitors and monthly page views, with Google Analytics being used by two thirds of them. Using Google Analytics with WordPress is covered in detail in the book, WordPress For Business Bloggers. Direct revenue generation is becoming an important aspect of blogging, with the majority of bloggers now displaying ads, affiliate marketing or other form of revenue generation (this subject is covered in detail in Chapter 10 of WordPress For Business Bloggers): The report data seems to suggest that the medium of blogging is gaining credibility and being taken more seriously as a source of information. 37% of bloggers have been quoted in the traditional media as a result of one of their posts. This is encouraging for business bloggers who use their blog as a PR tool. All in all, the State of the Blogosphere 2008 report makes encouraging reading for business bloggers as well as anyone who is thinking about starting a blog for their business. A blog can be a tremendously powerful tool for any business and using a top quality platform like WordPress makes running a blog extremely easy.  
Read more
  • 0
  • 0
  • 1076

article-image-third-party-video-hosting-drupal-websites
Packt
23 Oct 2009
7 min read
Save for later

Third-Party Video Hosting on Drupal Websites

Packt
23 Oct 2009
7 min read
Third-Party Video Providers Many sites desiring video will choose to use a third-party video provider such as YouTube or Blip.TV. This reduces the bandwidth requirement from their server, is easy to include in their posts, and allows videos to be easily shared virtually by users across the Internet. The easiest way, without further configuration of a basic Drupal installation, for an administrator to include a third-party video is to simply paste the video's embedded code in a post. Most video providers will offer a snippet of HTML that may be copied from a particular video page, which will embed the video. However, this requires using a filter that will allow <object>, <embed>, and <param> tags. But since they open the door to attacks on the site, they should only be used by administrators and trusted editors. You could also use the Full HTML filter, but this is even more dangerous as allowing that filter to be generally used would open the site to cross-site scripting (XSS) attacks. First, you'll need to set up a filter that allows the tags. Add an input format at Administer | Site configuration | Input formats (at /admin/settings/filters/add). After naming the filter, check the role(s) you wish to give access to this filter such as edit role. Check HTML corrector, HTML filter, and Line break converter. After pressing Save configuration, click on the Configure tab. Using YouTube as an example, an administrator would first need to upload a video to YouTube. This will require an account at YouTube, but they make it fairly painless for a user to jump in and contribute videos. You'll just need to follow their instructions: Once you have a video there, you will find the embedded code on the video page. You will need to click in the text field where that is provided, and copy the HTML for pasting on your own page: Next you will submit a node on your site such as from Node | Add | Page (at /node/add/page), and paste the embed code in the body for the node. You will need to enable either the new filter created earlier or Full HTML, as the embedded code will contain object and/or embedded tags, which would be filtered out by the default filter in Drupal. If you want editors to have the ability to select their filter, you will need to enable that ability for a role, and possibly set up a new filter depending on your needs. Also note that you will need to disable the TinyMCE Rich Text Editor when embedding video directly into content if the TinyMCE module is enabled on your site. After submitting, your video will appear in the content. As with any HTML embedded in your node body, you may manually place your video at any point within the content such as after the second paragraph or at the end of the node: Embedded Embedded Media Field Finally, we come to the alternative of hosting video from our own servers. Although using a module such as Media Mover combined with services such as Amazon S3 makes serving video a slightly easier task than it might have otherwise been, for most sites the bandwidth required for serving video is generally not a viable option. Additionally, sites may wish to take advantage of the viral opportunities of hosting video through a widely recognized provider such as YouTube or Blip.TV. There are several modules that provide some limited support for embedding third-party media, including both the Video and Asset modules. However, at the time of this writing, the most comprehensive and by far the easiest to configure and use is the Embedded Media Field, which includes the Embedded Video Field as part of its package. Install both of these modules and set up a new content type with an Embedded Video Field. You will need, of course, to have the CCK (Content) module installed as well. As with our other examples, you will first add your type from Administer | Content management | Content types | Add content type (at /admin/content/types/add), give it a name such as Video, and add the field from Administer | Content management | Content types | Video | Add field (at /admin/content/node-type/video/add_field). Before continuing, I must confess a bias here. I wrote the original Embedded Media Field module with assistance from Sam Tresler during DrupalCamp NYC in 2007, and rewrote it for a more solid and flexible API during OSCMS later that year. I am also indebted to Alex Urevick-Ackelsberg for his assistance in the ongoing maintenance and support. Without doing anything else, you may now add a new video from a provider by simply pasting its URL into the field. The module will then automatically parse and display the video appropriately. There are several settings on the following page that may be set, including allowed providers, video and thumbnail sizes, and whether the video plays automatically. You may leave the providers alone to allow content from any of them, or select only the providers you wish to allow editors and users to use The local checkbox is experimental at the time of this writing and may not actually be on the version you're reading. The module maintainers (myself included, of course) intend to hook into other APIs to provide better local video support without reinventing the wheel. That may or may not be ready by the time you read this book. The Custom URL provider is also used to experimentally support direct videos from any source available from an HTTP request, including your local server. It is not recommended for general use, as it would be easy to use that to unethically hotlink to videos from someone else's server. Hundreds of flying monkeys will hunt you down if you do that. Basically, always turn off support for that unless you have a specific (and moral) use for that feature. You can set video sizes in the next sections for full size and preview size video display. By default, videos will be displayed in full size. You can change the display to video preview or thumbnail at the display settings page, by browsing to Administer | Content management | Content types | Video | Display fields (at /admin/content/node-type/video/display). Videos will be forced to display at the size provided here, regardless of how they are offered by the provider. You can also determine if the video will autoplay or not. For instance, you might use a small video preview for teasers and a larger full-size video when viewing the node page, turning on the autoplay in that case. Finally, you may wish to use thumbnails, for instance when displaying a video as a teaser or when using views. Note that thumbnails are not yet supported for all video providers. Some providers do not offer an easy API to discover a particular video's thumbnail file. To learn if thumbnails are supported by a particular provider, go to Administer | Content management | Embedded Media Field Configuration (at /admin/content/emfield) and open the fieldset for Embedded Video Field. You will see the supported features for each provider within their particular fieldsets, where you may also disable them or enable unique settings. You may wish to provide for custom thumbnails, whether for providers lacking an automatic thumbnail or for any external video in general. For this purpose, the Embedded Custom Thumbnail module is included in the module's package. Just enable that module, and then check the Allow custom thumbnails for this field box on the type's administration screen We now have a full-featured video field in place, which is as easy to use as cut and paste. Summary Video is still a maturing media on the Internet. Much has happened as it has exploded onto sites across the world, and contributors to Drupal have made recent strides in supporting it. However, there is still much to be done to make it easier for administrators to support it. Also, although there are many new and traditional tools available such as Views and Embedded Media Field, these still require some setup to get working.
Read more
  • 0
  • 0
  • 1200

article-image-cooking-xml-oop
Packt
23 Oct 2009
9 min read
Save for later

Cooking XML with OOP

Packt
23 Oct 2009
9 min read
Formation of XML Let us look at the structure of a common XML document in case you are totally new to XML. If you are already familiar with XML, which we greatly recommend for this article, then it is not a section for you. Let's look at the following example, which represents a set of emails: <?xml version="1.0" encoding="ISO-8859-1" ?><emails> <email> <from>[email protected]</from> <to>[email protected]</to> <subject>there is no subject</subject> <body>is it a body? oh ya</body> </email></emails> So you see that XML documents do have a small declaration at the top which details the character set of the document. This is useful if you are storing Unicode texts. In XML, you must close the tags as you start it. (XML is more strict than HTML, you must follow the conventions.) Let's look at another example where there are some special symbols in the data: <?xml version="1.0" encoding="ISO-8859-1" ?><emails> <email> <from>[email protected]</from> <to>[email protected]</to> <subject>there is no subject</subject> <body><![CDATA[is it a body? oh ya, with some texts & symbols]]></body> </email></emails> This means you have to enclose all the strings containing special characters with CDATA. Again, each entity may have some attributes with it. For example consider the following XML where we describe the properties of a student: <student age= "17" class= "11" title= "Mr.">Ozniak</student> In the above example, there are three attributes to this student tag—age, class, and title. Using PHP we can easily manipulate them too. In the coming sections we will learn how to parse XML documents, or how to create XML documents on the fly. Introduction to SimpleXML In PHP4 there were two ways to parse XML documents, and these are also available in PHP5. One is parsing documents via SAX (which is a standard) and another one is DOM. But it takes quite a long time to parse XML documents using SAX and it also needs quite a long time for you to write the code. In PHP5 a new API has been introduced to easily parse XML documents. This was named SimpleXML API. Using SimpleXML API you can turn your XML documents into an array. Each node will be converted to an accessible form for easy parsing. Parsing Documents In this section we will learn how to parse basic XML documents using SimpleXML. Let's take a breath and start. $str = <<< END<emails> <email> <from>[email protected]</from> <to>[email protected]</to> <subject>there is no subject</subject> <body><![CDATA[is it a body? oh ya, with some texts & symbols]]></body> </email></emails>END;$sxml = simplexml_load_string($str);print_r($sxml);?> The output is like this: SimpleXMLElement Object( [email] => SimpleXMLElement Object ( [from] => [email protected] [to] => [email protected] [subject] => there is no subject [body] => SimpleXMLElement Object ( ) )) So now you can ask how to access each of these properties individually. You can access each of them like an object. For example, $sxml->email[0] returns the first email object. To access the from element under this email, you can use the following code like: echo $sxml->email[0]->from So, each object, unless available more than once, can be accessed just by its name. Otherwise you have to access them like a collection. For example, if you have multiple elements, you can access each of them using a foreach loop: foreach ($sxml->email as $email)echo $email->from; Accessing Attributes As we saw in the previous example, XML nodes may have attributes. Remember the example document with class, age, and title? Now you can easily access these attributes using SimpleXML API. Let's see the following example: <?$str = <<< END<emails> <email type="mime"> <from>[email protected]</from> <to>[email protected]</to> <subject>there is no subject</subject> <body><![CDATA[is it a body? oh ya, with some texts & symbols]]></body> </email></emails>END;$sxml = simplexml_load_string($str);foreach ($sxml->email as $email)echo $email['type'];?> This will display the text mime in the output window. So if you look carefully, you will understand that each node is accessible like properties of an object, and all attributes are accessed like keys of an array. SimpleXML makes XML parsing really fun. Parsing Flickr Feeds using SimpleXML How about adding some milk and sugar to your coffee? So far we have learned what SimpleXML API is and how to make use of it. It would be much better if we could see a practical example. In this example we will parse the Flickr feeds and display the pictures. Sounds cool? Let's do it. If you are interested what the Flickr public photo feed looks like, here is the content. The feed data is collected from http://www.flickr.com/services/feeds/photos_public.gne: <?xml version="1.0" encoding="utf-8" standalone="yes"?><feed > <title>Everyone's photos</title> <link rel="self" href="http://www.flickr.com/services/feeds/photos_public.gne" /> <link rel="alternate" type="text/html" href="http://www.flickr.com/photos/"/> <id>tag:flickr.com,2005:/photos/public</id> <icon>http://www.flickr.com/images/buddyicon.jpg</icon> <subtitle></subtitle> <updated>2007-07-18T12:44:52Z</updated> <generator uri="http://www.flickr.com/">Flickr</generator> <entry> <title>A-lounge 9.07_6</title> <link rel="alternate" type="text/html" href="http://www.flickr.com/photos/dimitranova/845455130/"/> <id>tag:flickr.com,2005:/photo/845455130</id> <published>2007-07-18T12:44:52Z</published> <updated>2007-07-18T12:44:52Z</updated> <dc:date.Taken>2007-07-09T14:22:55-08:00</dc:date.Taken> <content type="html">&lt;p&gt;&lt;a href=&quot;http://www.flickr.com/people/dimitranova/&quot; &gt;Dimitranova&lt;/a&gt; posted a photo:&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;http://www.flickr.com/photos/dimitranova/845455130/ &quot; title=&quot;A-lounge 9.07_6&quot;&gt;&lt;img src=&quot; http://farm2.static.flickr.com/1285/845455130_dce61d101f_m.jpg &quot; width=&quot;180&quot; height=&quot;240&quot; alt=&quot; A-lounge 9.07_6&quot; /&gt;&lt;/a&gt;&lt;/p&gt;</content> <author> <name>Dimitranova</name> <uri>http://www.flickr.com/people/dimitranova/</uri> </author> <link rel="license" type="text/html" href="deed.en-us" /> <link rel="enclosure" type="image/jpeg" href="http://farm2.static.flickr.com/1285/ 845455130_7ef3a3415d_o.jpg" /> </entry> <entry> <title>DSC00375</title> <link rel="alternate" type="text/html" href="http://www.flickr.com/photos/53395103@N00/845454986/"/> <id>tag:flickr.com,2005:/photo/845454986</id> <published>2007-07-18T12:44:50Z</published>...</entry></feed> Now we will extract the description from each entry and display it. Let's have some fun: <?$content = file_get_contents( "http://www.flickr.com/services/feeds/photos_public.gne ");$sx = simplexml_load_string($content);foreach ($sx->entry as $entry){ echo "<a href='{$entry->link['href']}'>".$entry->title."</a><br/>"; echo $entry->content."<br/>"; }?> This will create the following output. See, how easy SimpleXML is? The output of the above script is shown below: Managing CDATA Sections using SimpleXML As we said before, some symbols can't appear directly as a value of any node unless you enclose them using CDATA tag. For example, take a look at following example: <?$str = <<<EOT<data> <content>text & images </content></data>EOT;$s = simplexml_load_string($str);?> This will generate the following error: <br /><b>Warning</b>: simplexml_load_string() [<a href='function.simplexml-load-string'> function.simplexml-load-string</a>]: Entity: line 2: parser error : xmlParseEntityRef: no name in <b>C:OOP with PHP5Codesch8cdata.php</b> on line <b>10</b><br /><br /><b>Warning</b>: simplexml_load_string() [<a href='function.simplexml-load-string'> function.simplexml-load-string</a>]: &lt;content&gt;text &amp; images &lt;/content&gt; in <b>C:OOP with PHP5Codesch8cdata.php</b> on line <b>10</b><br /><br /><b>Warning</b>: simplexml_load_string() [<a href='function.simplexml-load-string'> function.simplexml-load-string</a>]: ^ in <b>C:OOP with PHP5Codesch8cdata.php</b> on line <b>10</b><br /> To avoid this problem we have to enclose using a CDATA tag. Let's rewrite it like this: <data> <content><![CDATA[text & images ]]></content></data> Now it will work perfectly. And you don't have to do any extra work for managing this CDATA section. <?$str = <<<EOT<data> <content><![CDATA[text & images ]]></content></data>EOT;$s = simplexml_load_string($str);echo $s->content;//print "text & images"?> However, prior to PHP5.1, you had to load this section as shown below: $s = simplexml_load_string($str,null,LIBXML_NOCDATA);
Read more
  • 0
  • 0
  • 1789

article-image-integrating-zen-cart-content-management-systems
Packt
23 Oct 2009
19 min read
Save for later

Integrating Zen Cart with Content Management Systems

Packt
23 Oct 2009
19 min read
How to Integrate with CMS? While attempting integration of one CMS with another, some simple principles should be remembered. For all integration attempts, you have to consider the following aspects: Master-slave relationship: While integrating one CMS with the other, one of the applications act as the master and the other as the slave. If you integrate application A to application B, then application B will be considered as master. Master applications maintain authentication and sessions for both applications. While integrating Zen Cart with some other CMS, first consider whether Zen Cart will be the master or the slave. If you are integrating Zen Cart with an existing website, Zen Cart is going to be the slave. On the other hand, when you are adding blogging functionality to the Zen Cart shop by integrating WordPress with Zen Cart, Zen Cart is going to be the master. User and Group Management: One purpose of integrating two CMSs is to have a common user and group management system. Zen Cart integration may be tight, where both Zen Cart and an other CMS will use the same database for user and group management. On the other hand, loose integration will allow periodic or event-based synchronization of user or group databases. Tight integration becomes easier when both CMSs use the same type of user database. If the user databases are very different from each other, then tight integration may not be possible and some sort of fallback solution such as synchronizing the databases may be used. Visual integration: Users see the integration only through the visual integration. In fact, visual integration should be such that users will be unaware of integration attempt. While integrating the two CMSs, the visual template of the master should preferably be used for both CMSs. However, using a master's template system is difficult and a central template system should be developed which can be used for both applications. Now, we will see how to integrate Zen Cart with other CMSs. You will notice that at least one of the above-mentioned aspects is present in such integrations. Joomla!/Mambo If you are using Joomla!/Mambo and want e-commerce functionality, you have a number of choices. Among these, the best one is using the VirtueMart component. The VirtueMart component for Joomla!/Mambo is quite similar to Zen Cart or osCommerce. Only a few features of Zen Cart or osCommerce are missing in VirtueMart. However, if you still want to integrate Zen Cart into the existing Joomla!/Mambo website, you have two options-and neither is easier than the other: Use Zen Cart as a wrapper or, develop a component based on Zen Cart. Using Zen Cart as a wrapper is in its true sense not an integration. It runs separately and Joomla! provides a menu link. Clicking on this link will show Zen Cart in a wrapper window. If you are experienced with Joomla! or Mambo, you can figure out how a menu item can be added to show the application in a wrapper. However, adding a wrapper may appear to be an integration if you modify the Zen Cart template accordingly. As the Zen Cart shop appears in the wrapper, it would be wise not to use headers and sidebars in the Zen Cart template. Links to the categories and other menus can be provided in the headers. A separate login mechanism should also be provided in the Zen Cart template. Developing a bridge for Zen Cart and Joomla! is a hot topic in the Zen Cart forum. Users of both Joomla! and Zen Cart agree that integration or bridging of these two will be of great value. However, due to the framework of these two systems, developing such a bridge has some complexities and takes some time. Recently, a discussion on this topic has led to the development of such a bridge by the open-source enthusiasts. Please watch the following thread:http://tinyurl.com/65ypyu. Another possibility is JFusion plug-in for Joomla! (available at www.jfusion.org) which is a framework for integrating several forums to Joomla!. The developer of JFusion has proposed developing such a plug-in for Zen Cart as well. It is hoped that JFusion will be able to integrate Zen Cart to Joomla! soon. Drupal Drupal is a powerful CMS and is widely used. There are a wide range of modules available for Drupal and it is used for different types of websites. There are a great number of Drupal users who want to integrate Drupal and Zen Cart-as both are considered useful in their category. Until recently, there was no easy way to integrate Drupal and Zen Cart. Very recently, Zen Cart Integration module has been released as a development version. For now, it works on Drupal 5.x and Zen Cart 1.3.7. Once this module is installed and configured, you can create Zen Cart categories and products from Drupal. As other nodes, these products and categories will be displayed as nodes in Drupal. When visitors click on these products they see product details as a Drupal node, but when the product is added to cart, it redirects to the Zen Cart shop. This module also provides a single sign-on facility. For integrating Zen Cart into Drupal, download the module from http://drupal.org/project/zencart. Before we proceed with the integration of Drupal and Zen Cart, assume that you have installed Drupal and Zen Cart on the same server. Let us suppose, Drupal is installed in e:wwwdrupal57 directory and Zen Cart 1.3.7 is in e:wwwzc directory, and these two uses separate database on the same MySQL server. Follow these steps: Download and unzip Zen Cart integration module: For integrating Zen Cart into Drupal, download the module from http://drupal.org/project/zencart. On your computer, unzip the zencart-5.x-1.x-dev.tar.gz package. You will get a folder named zencart, under which there are some files and a subfolder named zencart. Copy files for Zen Cart: Inside the zencart subfolder you will find the includes folder. Copy this subfolder, that is /zencart/includes, to your Zen Cart installation directory, that is e:wwwzc. This will overwrite the e:wwwzcincludes directory, but will not overwrite any files. Once you have copied all the files in this folder, you are finished with Zen Cart. Install Zen Cart installation module in Drupal: Copy the zencart directory with all the files inside it, except the zencart subfolder, to Drupal's installation directory, that is e:wwwdrupal57. As an administrator in Drupal, you can install this module from Drupal's Administer | Site Building | Modules section. In the module list you will see the Zen Cart Integration module group. You will find the following modules in this group: Zencart-This is the main module for integrating Zen Cart shopping cart to Drupal. This is required by other modules in this group. Zencart Catalog-This module allows creation of Drupal nodes for Zen Cart products and categories. Zencart Category Node Hierarchy-This module depends on the Node Hierarchy module and organizes Zen Cart products and categories. Download the Node Hirarchy module from http://drupal.org/project/nodehierarchy and install it before enabling this module. To enable these modules, select checkboxes in Enabled column and click Save configuration button at the bottom of the list. Configure Zencart Integration module in Drupal: After enabling the modules, you can configure those from Administer | Site Configuration | Zencart Integration screen. The Zen Cart Status section will provide you information about your Zen Cart installation. The module will search and find the Zen Cart installation and show its version, path to Drupal installation and other information. The Zen Cart Settings section will give you the opportunity to mention the Zen Cart installation directory path. Type it into the Path to Zencart field. The Zen Cart Page Redirects section allows you to configure page redirects from the Zen Cart page to Drupal node. Zen Cart Catalog section allows you to configure redirect from the Zen Cart catalog items to Drupal. While using this integration module, you create Zen Cart catalog and products from Drupal. If you want to create these categories and products from inside Zen Cart and synchronize those with Drupal, then check Update product info on cron. This will synchronize product information both on Drupal and Zen Cart by running cron command on linux/unix. Checking Redirect Product Info Pages will automatically redirect visitors from the Zen Cart product info pages to equivalent Drupal nodes. Similarly, checking Redirect Category Listing Pages will automatically redirect visitors from the Zen Cart category pages to equivalent Drupal nodes. The Zen Cart Users section allows you to configure single sign-on options for Drupal and Zen Cart. If you want to allow Zen Cart existing customers to login to Drupal, then check the Allow Zen Cart Customers to login to Drupal checkbox. On the other hand, if you want to allow Drupal users to login to Zen Cart as customers, check Allow Drupal Users Customers to login to Zen Cart as Customers. Checking Allow Single Sign-On will allow users to login once and access both Drupal and Zen Cart.                                                                                                                                                                                                                                                                                                         The Zencart Integration screen has the following sections: Once you have configured these options, click the Save configuration button, or revert to defaults by clicking the Reset to defaults button. Create Content Type in Drupal for Zen Cart categories and products: If you have ever used Drupal, you know how to create content types in Drupal. You can add new content type from Administer | Content Management | Content types | Add content type. Now you will get a Zen Cart Catalog group. From this section you can define whether this type will be used as a Zen Cart product or category. You can also configure node hierarchy-ability to be parent or child (default is parent). In the Identification section, type a human readable name, for example Zen Cart Product, in the Name field. Then type a machine readable name of this content type, for example zc_product, in the Type field. Provide a description of this content type in the Description field. In the Submission Form section, provide a label for the title and body field, minimum number of words, and explanation or submission guidelines. Configure default options in the Workflow section. Finally, click the Save content type button. Create two content types&#x97;one for the Zen Cart category and another for the Zen Cart product. Add Category and Product in Drupal: You can create categories and products from Create Content section. In the list, click on Zen Cart Category. This will open Submit Zen Cart Category form. In this form, type the category name in Title field, type a description of this category in Body field. In the Node Hierarchy section, you can select a parent category. Check Category is Active to make this category visible. Configure other options like Menu settings, URL path settings, Publishing options, and so on and click the Submit button to create the category Similarly, you can create Zen Cart products by clicking on the Zen Cart Product content type. This will display the Submit Zen Cart Product form. Fill in the Submit Zen Cart Product form with appropriate information, such as product name, model, quantity in stock, tax class, base price, and so on. You can select its parent category in the Node Hierarchy section. Check the Create Menu option to make a menu item for this product. Configure other options like Menu settings, URL path settings, Publishing options, and so on and click the Submit button to create the product. Test Zen Cart Integration to and from Drupal: Now it is time to test whether the Drupal-Zen Cart integration is working or not. First, go to your Zen Cart shop, for example, http://localhost/zc. There you will find the categories and products you have added. Click on any of these, and you will be redirected to the respective Drupal node. Again, in the Drupal, click on a product link, type a quantity and click the Add to Cart button. That will redirect you to the Zen Cart shop's Your Shopping Cart Contents page. Similarly you can test single sign-on features by signing in to either Drupal or Zen Cart and trying to purchase items from these two shops. Gallery2 Gallery2 is a web-based software product that lets you manage photos on your own website. It creates a catalog of photos which visitors can view as thumbnails as well as in its original size. It has an intuitive interface to create and maintain albums. It can create thumbnails automatically and can be used for image resizing, rotation, ordering, captioning, searching, and some other functions. You can use Gallery2 to build a community site for sharing photos. You can create the community using Gallery2 and registered users can share their photographs by uploading their own photos. You need to integrate Gallery2 with Zen Cart if you want to sell photos from your photo gallery. Gallery2 has a great mechanism to integrate with Zen Cart. The Gallery2/Zen Cart integration module is available at the Gallery2 download site http://dakanji.com/g2stuff/zcg2-3_2_1a-full.zip. Using it, users can organize their photos and other multimedia files into Gallery2, and offer them for sale through Zen Cart. In integrating Gallery2 with Zen Cart, you have to configure Zen Cart first. Follow these steps for Zen Cart: Download the Gallery2/Zen Cart Integration module and extract it. Copy the zencart/includes folder into your Zen Cart installation directory. This directory contains some templates for Zen Cart. Copying these files will not overwrite any existing file. Login to your Zen Cart administration panel and create a new product category, such as Photographs. Photo items from Gallery2 will go to this category. Select Tools | Template Selection and choose one of the Gallery2 Integration templates provided. You can take a copy of the template folder (../includes/templates/pgxxx) and modify stylesheet.css. You can also modify these templates. Edit ../includes/languages/pgxxx/english.php if you want to change language strings or date formats. Replace ../includes/templates/pgxxx/images/logo.gif with your site's logo. Remember that for Gallery2/Zen Cart integration, both Zen Cart and Gallery2 data tables need to be in one database. In Gallery2, you need to make the following changes: Upload the module files in the gallery2/ directory to your Gallery2 installation's modules directory. In Gallery2 Site Administration, click on Plugins and find Zen Cart under the Commerce heading. Then click Install. After Installation, click Configure. Enter the entire server path to your Zen Cart installation, for example, /home/your_name/public_html/zencart/. Select the category you created in Zen Cart earlier (for example Photographs) from the drop-down menu. Click activate next to the Zen Cart listing on the module page. Refresh the page and click on the Zen Cart link under Admin Options to edit product details. Edit permissions for the individual items as you wish. The module will have assigned permissions to non-album items on activation. If you do not want to sell an item, you will need to disable that item in Zen Cart as the module adds all data items in your gallery to Zen Cart. You can add photograph items from Gallery2. Adding any item to the Gallery2 album will simply show that item in Zen Cart. You can add product options from Gallery2 by clicking on the Zen Cart link in your Gallery2 site administration menu. When you have installed the Gallery2/Zen Cart bridge, you will find a product type in Zen cart named Product-Gallery. All the items from Gallery2 need to be of this type. If you edit any item from Zen Cart and change the product type of any Gallery2 item, the link with the Gallery2 will be broken. Also, note that the Gallery2 bridge will co-exist with Zen Cart image handler and lightbox add-on for Zen Cart. These will handle product images for Zen Cart, whereas Gallery2 add-on only handles images added in Gallery2. You cannot assign the Main category in Zen Cart as the root product category for Gallery2. The category you are selecting in the Gallery2 bridge configuration must be a sub-category product. Once the configurations are done, you can see the photographs from Zen Cart. Visitors can also order photographs from Zen Cart. While you are in Gallery2, you can also place an order by clicking the add to cart link, which is redirected to Zen Cart. WordPress WordPress is an extremely powerful and widely used open-source blogging platform. It has a wide community of developers and users, and almost all kinds of plugins are available for it. Although there are some shopping cart plugins for WordPress, they are not full-blown shopping carts like Zen Cart or osCommerce. E-commerce plug-ins available for WordPress have limited features. Those who are running blogs using WordPress may want to integrate it with Zen Cart to provide e-commerce functionality to their blogs. In fact, there is a Zen Cart module for integrating these two. You can download that module from www.zen-cart.com. After downloading the plug-in WordPress on Zen Cart, you have to install it on the webserver. You can install the plug-in in two ways: first, in an environment where you have a working WordPress installation, and second, when you have not installed WordPress. WordPress and Zen Cart Installed in Separate Directories When you have an existing installation of WordPress, generally it will be in a separate directory from that of the Zen Cart installation. If your web document root directory is public_html, then the installation directories may be: /public_html/blog and /public_html/shop. Follow these procedures to install WordPress on Zen Cart plug-in: Step1: Install WordPress If you have not installed WordPress yet, then download the WordPress files from www.wordpress.org and unzip the files. Then, upload the files to your webserver's /public_html/blog directory. Now, change the permission of this directory to 777 and point your browser to http://yourdomain.com/blog/wp-admin/setup-config.php. The installation wizard for WordPress will be displayed. Follow the instructions on the wizard and give the necessary information. Once all of the information is given, WordPress will be installed. Step 2: Configure WordPress During installation, an administrative account will be created. Note the username and password for this account. Then, point your browser to http://yourdomain.com/blog/wp-admin/. The login page will be displayed. Type the username and password for the administrative account and click on the Login button. You will see the dashboard for administering WordPress. Go to Options | General. Now, change the Blog Address (URL) to Zen Cart's URL http://yourdomain.com/shop/. From the administration dashboard, go to Presentation | Themes and select WordPress Default 1.6. Step 3: Upload WordPress on Zen Cart When you unzip the WordPress on Zen Cart plug-in zip file, you will find that there is a directory called ZC_ROOT and WP_ROOT. Now, upload the contents of ZC_ROOT directory to Zen Cart's installation path on the server, that is, /public_html/shop/. Similarly, upload the contents of the WP_ROOT directory to WordPress' installation path, that is, /public_html/blog. Before uploading the contents of the ZC_ROOT directory, please change the name of the /ZC_ROOT/includes/templates/MY_TEMP/ directory to that of the template directory you are using for your Zen Cart shop Step 4: Edit WordPress File For older versions of WordPress, you may need to edit the /wp-include/template-loader.php file. Open the file in a text editor and replace all exit; with return;. However, you may not need this for the newer versions of WordPress. WordPress 2.3.1 can work without this modification. First, try without this modification. Step 5: Edit Zen Cart File You also need to edit another file in the Zen Cart installation. Open the /includes/extra_configures/wordpress-config.php file under the Zen Cart installation folder and find the following line: define ('ABSPATH','/var/www/vhost/example.com/public_html/blog/'); Type the appropriate WordPress path, that is, /home/username/public_html/blog/. The above line will look like this: define ('ABSPATH','/home/suhreed/public_html/blog/'); If you are trying it on Windows, you may need to put the absolute path, as in, e:/www/blog. Step 6: Configure Sideboxes from Layout Boxes Controller Once the file modifications have been done, login to the Zen Cart administration panel. Go to Tools | Layout Boxes Controller. The screen will notify you that some new sideboxes-wp_cats.php, wp_archives.php, wp_pages.php, wp_links.php, and wp_sidebar.php-have been found. To use these sidebars, click on the reset button at the bottom. To show these sideboxes on your Zen Cart shop, click on the sidebar and change its left/right column status.
Read more
  • 0
  • 0
  • 3131
article-image-expressionengine-creating-photo-gallery
Packt
23 Oct 2009
6 min read
Save for later

ExpressionEngine: Creating a Photo Gallery

Packt
23 Oct 2009
6 min read
Install the Photo Gallery Module The photo gallery in ExpressionEngine is considered a separate module, even though it is included with every personal or commercial ExpressionEngine license. Installing it is therefore very simple: Log into the control panel using http://localhost/admin.php or http://www.example.com/admin.php, and select Modules from the top of the screen. About a quarter of the way down the page, we can see the Photo Gallery module. In the far-right column is a link to install it. Click Install. We will see a message at the top of the screen indicating that the photo gallery module was installed. That's it! Setting Up Our Photo Gallery Now that we have installed the photo gallery module, we need to define some basic settings and then create categories that we can use to organize our photos. Define the Basic Settings Still in the Modules tab, the photo gallery module should now have become a clickable link. Click on the Photo Gallery. We are presented with a message that says There are no image galleries. Select to Create a New Gallery. We are now prompted for our Image Folder Name. For our photo galleries, we are going to create a folder for our photos inside the images folder that should already exist. Navigate to C:xampphtdocsimages (or /Applications/MAMP/htdocs/images if using MAMP on a Mac) or to the images folder on your web server, and create a new folder called photos. Inside that folder, we are going to create a specific subfolder for our toast gallery images. (This will keep our article photos separate from any other galleries we may wish to create). Call the new folder toast. If doing this on a web server, set the permissions of the toast folder to 777 (read, write, and execute for owner, group, and public). This will allow everyone to upload images to this folder. Back in ExpressionEngine, type in the name of the folder we just created (toast) and hit Submit. We are now prompted to name our template gallery. We will use the imaginative name of toastgallery so that it is distinguishable from any other galleries we may create in the future. This name is what will be used as the default URL to the gallery and will be used as the template group name for our gallery templates. Hit Submit. We are now prompted to update the preferences for our new gallery. Expand the General Configuration option and define a Photo Gallery Name and Short Name. We are going to use Toast Photos as a Photo Gallery Name and toastphotos as a Short Name. The short name is what will be used in our templates to reference this photo gallery Next, expand the Image Paths section. Here the Image Folder Name should be the same name as the folder we created earlier (in our case toast). For XAMPP users, the Server Path to Image Directory is going to be C:/xampp/htdocs/images/photos/toast, and the Full URL to Image Directory is going to be http://localhost/images/photos/toast. For MAMP users on a Mac or when using a web server, these paths are going to be different depending on your setup. Verify these settings for correctness, making adjustments as necessary. Whenever we upload an image into the image gallery, ExpressionEngine creates three copies of the image&#x97;a medium-sized and a thumbnail-sized version of the image, in addition to the original image. The thumbnail image is fairly small, so we are going to double the size of the thumbnail image. Expand the Thumbnail Resizing Preferences section, and instead of a Thumbnail Width of 100, choose a width of 200. Check the box (the one outside of the text box) and the height should update to 150. Hit Submit to save the settings so far. We will review the rest of the settings later. We have now created our first gallery. However, before we can start uploading photos, we need to create some categories. Create Categories For the purposes of our toast website, we are going to create categories based on the seasons: spring, summer, autumn, and winter. We are going to have separate subfolders for each of the categories; these are created automatically when we create the categories. To do this, first select Categories from the new menu that has appeared across the top of the screen. We will see a message that says No categories exist. Select Add a New Category. We are going to use a Category Name of Spring and a Description that describes the category&#x97;we will later display this description on our site. We are going to create a Category Folder of spring. Leave the Category Parent as None, and hit Submit. Select Add a New Category, and continue to add three more categories: summer, autumn, and winter in the same way. After we a re done with creating all the categories, use the up and down arrows to order the categories correctly. In our case, we need to move Autumn down so that it appears after Summer. We now have the beginnings of a photo gallery. Next, we will upload our first photos so that we can see how the gallery works. Upload Our First Photos To upload a photo to a photo gallery is pretty straightforward. The example photos we are working with can be downloaded from the Packtpub support page at http://www.packtpub.com/files/code/3797_Graphics.zip. To upload a photo, select New Entry from the menu within the photo gallery module. For the File Name, click the Browse...> button and browse to the photo spring1.jpg. We are going to give this an Entry Title of Spring Flower. For Date, we could either leave it as a default or enter the date that the photo was taken on. We are going to use a date of 2006-04-22. Click on the calendar icon to expand the view to include a calendar that can be easily navigated. We are going to use a Category of Spring and a Status of Open. Leave the box checked to Allow Comments, and write a Caption that describes the photo. The Views allows us to indicate how many times this image has been viewed&#x97;in this case we are going to leave it at 0. Hit Submit New Entry when everything is done. We are presented with a message that reads Your file has been successfully submitted, and the image now appears underneath the entry information. In the folder where our image is uploaded, three versions of the same image are made. There is the original file (spring1.jpg), a thumbnail of the original file (spring1_thumb.jpg), and a medium-sized version of the original file (spring1_medium.jpg). Now, click on New Entry and repeat the same steps to upload the rest of the photos, using appropriate categories and descriptions that describe the photos. There are four example photos for each season (for example, winter1.jpg, winter2.jpg, winter3.jpg, and winter4.jpg). Having a few example photos in each category will better demonstrate how the photo gallery works.
Read more
  • 0
  • 0
  • 2944

article-image-openid-ultimate-sign
Packt
23 Oct 2009
13 min read
Save for later

OpenID: The Ultimate Sign On

Packt
23 Oct 2009
13 min read
Introduction How many times have you walked away from some Internet forum because you could not remember your login ID or password, and just did not want to go through the tedium of registering again? Or gone back to re-register yourself only to forget you password the next day? Remembering all those login IDs and passwords is indeed an onerous task and one more registration for a new site seems like one too many. We have all tried to get around these problems by jotting down passwords on pieces of paper or sticking notes to our terminal – all potentially dangerous practices that defeat the very purpose of keeping a digital identity secure. If you had the choice of a single user ID and password combination – essentially a single digital identity – imagine how easy it might become to sign up or sign in to new sites. Suppose you could also host your own digital identity or get it hosted by third party providers who you could change at will, or create different identity profiles for different classes of sites, or choose when your User ID with a particular site should expire; suppose you could do all this and more in a free, non-proprietary, open standards based, extensible, community-driven framework (whew!) with Open Source libraries and helpful tutorials to get you on board, you would say: “OpenID”. To borrow a quote from the OpenID website openid.net: “OpenID is an open, decentralized, free framework for user-centric digital identity.” The Concept The concept itself is not new (and there are proprietary authentication frameworks already in existence). We are all aware of reference checks or identity documents where a reliable agency is asked to vouch for your credentials. A Passport or a Driver's License is a familiar example. Web sites, especially those that transact business, have digital certificates provided by a reliable Certification Authority so that they can prove to you, the site visitor, they are indeed who they claim to be. From here, it does not require a great stretch of imagination to appreciate that an individual netizen can have his or her own digital identity based on similar principles. This is how you get the show on the road. First, you need to get yourself a personal identity based on OpenID from one of the numerous OpenID providers[1] or some sites that provide an OpenID with membership. This personal identity comes in the form a URL or URI (essentially a web address that starts with http:// or https://) that is unique to you. When you need to sign up or sign in to a web site that accepts OpenID logins (look for the words 'OpenID' or the OpenID logo), you submit your OpenID URL. The web site then redirects you to the site of your ID provider where you authenticate yourself with your password and optionally choose the details – such as full name, e-mail ID, or nickname, or when your login ID should expire for a particular site – that you want to share with the requesting site and allow the authentication request to go through. You are then returned to the requesting site. That is all there is to it. You are authenticated! The requesting site will usually ask you to associate a nickname with your OpenID. It should be possible to register with and sign in to different sites using different nicknames – one for each site – but the same OpenID. But you may not want to overdo this lest you get into trouble trying to recall the right nickname for a particular site. Just Enough Detail This is not a technical how-to. For serious technical details, you can follow the excellent links in the References section. This is a basic guide to get you started with OpenID, to show you how flexible it is, and to give pointers to its technical intricacies. By the end of this article you should be able to create your own personal digital identities based on OpenID (or discover if you already have one – you just might!), and be able to use them effectively. In the following sections, I have used some real web sites as examples. These are only for the purpose of illustration and in no way shows any preference or endorsement. Getting Your OpenID The simplest and most direct way to get your personal OpenID is to go to a third party provider. But before that, the smart thing to do would be find out if you already have one. For instance, if you blog at wordpress.com, then http://yourblogname.wordpress.com is an OpenID already available to you. There are other sites[1], too, that automatically provide you an OpenID with membership. Yahoo! gives you an OpenID if you have an account with them; but it is not automatic and you need to sign up for it at http://openid.yahoo.com. Your OpenID at Yahoo! will be of the form https://me.yahoo.com/your-nickname. To get your third party hosted OpenID we will choose Verisignlab's Personal Identity Provider (PIP) site -- http://pip.verisignlabs.com/ as an example. You are of course free to decide and choose your own provider(s). The sign up form is a simple no-fuss affair with the minimum number of fields. (If you are tired of hearing 'third party', the reason for using the term will get clearer further on. For the purpose of this article, you, the owner of the OpenID are the first party, the web site that wants you authenticated is the second party, the OpenID provider being the third.) After replying to the confirmation e-mail you are ready to take on the wide world with your OpenID. If you gave your ID as 'johndoe' then you will get an OpenID like: http://johndoe.pip.verisignlabs.com. You can come back to the PIP site and update your profile; some sites request information such as full name or e-mail ID but you are always in control whether you want to pass on this information back to them. If you choose to have just one OpenID, then this is about as much as you would ever do to sign on to any OpenID enabled site. You can also create multiple OpenID's for yourself – remember what we said earlier about having multiple ID's to suite different classes of sites. Testing Your OpenID Now that we have our OpenID we will test it and in the process also see how a typical OpenID-based authentication works in practice. Use the testing form[7] in the References section and enter your OpenID URL that you want tested. When you are redirected to your PIP's site (we are sticking to our Verisign example), enter your password and also choose what information you want passed back to the requesting site before clicking “Allow” to let the authentication go through. Important tip: Enter your password only on the PIP's site and nowhere else! Be aware that this particular testing page may not work with all OpenIDs; that may not necessarily mean that the OpenID itself has a problem. Step-by-Step: Use your WordPress or Verisign OpenID For this tutorial part, we will take the example of http://www.propeller.com (a voting site among other things) that accepts OpenID sign ups and sign ins. For an OpenID we will use the URL of your WordPress blog – http://yourblogname.wordpress.com. You could also use your OpenID URL (the one you got from the Verisign example) and follow through. On the Propeller site, go to the sign up page. Look for the prominent OpenID logo. Type in your OpenID URL and click on the 'Verify ...' button. You are taken to the site of your PIP where you need to authenticate yourself.   If you used your Verisign OpenID, enter your password, complete the details you want to pass back to the requesting site (remember, we are trying to sign up with Propeller) and allow the authentication to go through. You are now back with the Propeller site. Just hang in there a moment as we check the flow for a Wordpress OpenID.   For a WordPress OpenID, you will get a screen instead that asks you to deliberately sign in to your WordPress account. Once you are signed in, you will see a hyperlink that prompts you to continue with the authentication request from Propeller.     Follow this link to a form that asks your permission to pass back information to Propeller such your nickname and e-mail ID. You can change both these fields if you wish and allow the authentication to go through.   Now you should be back at the Propeller site with a successful OpenID verification. The site will ask you to associate a nickname with your OpenID and a working e-mail to complete your registration process. This step is no different from a normal sign up process. Check your e-mail, click on the link provided therein, get back to the Propeller site, and click another link to complete the registration process. You are automatically signed in to Propeller. Sign out for the moment so that we can see how an OpenID sign in works. Go to the sign in page at Propeller. You will see a normal sign in and an OpenID sign in. We will use the OpenID one (of course!). Type in your OpenID URL and click on the “Sign in...” button. Complete the formalities on your PIP site (for Verisign you will get a sign in page; for Wordpress you will need to sign in first unless you are already signed in) and let the authentication go through. This time you are back on the Propeller site all signed in and ready to go. Note that your nickname appears correctly because your OpenID is associated with it. That is all there is to it. Easier done than said. Try this a couple of times and I bet it will feel easier than the remote control of your home entertainment system! Your Custom OpenID URL If you want a personalized OpenID URL and do not like the one provided by your PIP you can always use delegation to get what you want. To make your blog or personal home page as your OpenID URL, insert the following in the head portion (the part that falls between <head> and </head> on an HTML page) of your blog or any page that you own. This will only work with pages that you completely own and have control over their source. There is a Wordpress plug-in that gives delegating capability to your Wordpress.com blog but we will not go into that here. The first URL is your OpenID server. The second URL is your OpenID URL – either the one you host yourself or the one provided by a third party. The requesting site discovers your OpenID and correctly authenticates you. With this approach you can switch providers transparently. At the risk of repeating: test your new personalized URL before you start using it. Note that the 'openid.server' URL may vary depending on the PIP. To get the name of your PIP's OpenID server, use the testing service[7] which reports the correct URL for your PIP to use with the “openid.server” part your delegation mark up. <link rel="openid.server" href="http://pip.verisignlabs.com/server" /><link rel="openid.delegate" href="http://johndoe.pip.verisignlabs.com/" /> Rolling Your Own If you are paranoid about entrusting the management of your digital identity to another web site and also have the technical smarts to match, there are ways you can become your own PIP[5][6]. If you are tech-savvy then you cannot fail to appreciate the elegance of the OpenID architecture and the way it lets control stay where it should – with you. Account Management – Lite? OpenID makes life easier for site visitors. But what about the site and the domain administrators? If administrators decide to go the OpenID way[3], it lightens their load by taking away a major part of the chore of membership administration and authentication. As a bonus, it also potentially opens up a site to the entire community of net users that have OpenID's or are getting one. Security and Reliability As the wisecrack goes – if you want complete security, you should unplug from the Internet. On a serious note, there are some precautions you have to take while using OpenID and they are no different from the precautions you would take for any item associated with your identity, say your Passport or your credit card. Remember to enter your password only on the Identity Provider's site and nowhere else. Be alert to phishing. This explains why WordPress asks you to log in explicitly rather than take you directly to their authentication page. Never use your e-mail ID handle as your OpenID name but use a different one. Using OpenID has its flip side, too. Getting your OpenID from a provider potentially lays open your browsing habits to tracking. You can get around this by being your own PIP, delegating from your own domain, or creating a PIP profile under an alias. There is the possibility that your OpenID provider goes out of service or worse, out of business. It is thus important to choose a reliable identity provider. There are sites that allow you to associate multiple OpenIDs with your account and perhaps this can be a way forward to popularize OpenID and to allay any fears of getting locked in with a single vendor and getting locked out of your identity in the process. Your Call There are many sites today that are not OpenID-ready. There are some sites that allow only OpenID sign ons. However, if you see the elegance of the OpenID mechanism and the convenience it provides both site administrators and members, you might agree that its time has come. Get an OpenID if you do not have one. Convince your friends to get theirs. And if you run an online community or are a member of one, throw your weight around to ensure that your site also provides an OpenID sign on. References http://wiki.openid.net/OpenIDServers is a list of ID providers. http://blogs.zdnet.com/digitalID/?p=78 makes a strong case for OpenID. Read it to get a good perspective on the subject. http://www.plaxo.com/api/openid_recipe is a soup-to-nuts tutorial on how to enable your site for OpenID authentication or migrate to OpenID from your current site-specific authentication scheme. Check out http://www.openidenabled.com/php-openid/ if you are looking for software libraries to OpenID-enable your site. http://www.intertwingly.net/blog/2007/01/03/OpenID-for-non-SuperUsers is a crisp if intermediate-level how-to that lets you try out new things in the OpenID space. http://siege.org/projects/phpMyID/ shows you how you can run your own (yes, your own) PIP server. http://www.openidenabled.com/resources/openid-test/checkup is a link that helps you test your OpenID. Once you get your OpenID, you can submit it to the form on this URL and get yourself authenticated to see if everything works fine. Does not seem to work with Wordpress and Yahoo! OpenIDs as of this writing. http://www.openid.net is the OpenID site.   Read another article by Gurudutt Talgery Podcasting with Linux Command Line Tools and Audacity  
Read more
  • 0
  • 0
  • 4551

article-image-microsoft-sql-server-2008-installation-made-easy
Packt
23 Oct 2009
3 min read
Save for later

Microsoft SQL Server 2008 - Installation Made Easy

Packt
23 Oct 2009
3 min read
(For more resources on Microsoft, see here.) Initial State of Computer Assuming you are working with the Windows XP OS, it will be advisable to create a restore point to which you can fall back should you fail to install and something goes wrong. You can set up a fall back position by going to Start | All Programs | Accessories | System Tools | System Restore. This allows you to comeback where you were before starting the install. The other thing that you should lookup is the suite of Microsoft software you already have on your computer that may interfere with the product you are installing. This can be reviewed following Start | Control Panel | Add and Remove Programs. SQL 2008 server requires IE 6.0 or higher version. It may be helpful to install this before embarking on installing the SQL 2008 Server. For the purpose of this article IE 7.0 was installed. It has appeared in some forum topics that SQL 2008 can exist side-by-side with SQL 2005 server. However in the present case SQL 2005 was completely removed. Sometimes even this removal is not quite an easy process if something is broken in the original install and requires you to reinstall and then uninstall. In the case of SQL Server 2008, there was an earlier version, "Katmai", installed but never used due to its inability to connect to the SQL Server Management Studio (Well, unless you remove the SQL 2005 client you cannot install SQL 2008 Client), a fact which came to light much later. 'Katmai' components were completely removed which required reinstalling the 'Katmai' followed by its complete removal. When you download the SQL 2008 and run the executable, it creates the folder, servers, containing a number of subfolders and files (dynamic link library files etc) that are used during the installation. Help can be accessed from servershelp1033s10ch_setup, an HTML file which provides a wealth of information regarding all aspects of installation including migration from an earlier version. From servesdefault.htm you can begin the installation which provides the required support using Prepare | Install | Other information navigational aid. After removing all the suggested components during this installation, the remaining Microsoft SQL Server related components on the computer are as shown in the Add and Remove Programs window in the next figure. The very first screen you will see when you click on the serverssetup.exe file is the SQL Server 2008 Setup where you need to agree with the licensing terms before proceeding. When you click on the Next button which displays the Installation Pre-requisites screen, you will be shown the pending items needed before you install SQL 2008 server. Click on the Install button after highlighting the pending item regarding setup support files in the right screen. SQL Server Installation Center This will take you to the SQL Server Installation Center screen as shown. It has a number of useful hyperlinks that you can come back to by repeating the above steps. Click on New Installation link. This Starts Install SQL Server 2008 Wizard for System Configuration Check. After a while when the checking is completed the following screen will be displayed. This timeall items have the status marked 'Passed'. In a previous attempt when the 'Katmai' items were still uninstalled,the Previous CTP Install Check did not succeed and it was corrected only after completely removing those items. Clicking on Next button takes you to screen where you need to select the features that you want to have installed as shown. The display shows Features Selection window after all items have been checked.
Read more
  • 0
  • 0
  • 3343
article-image-search-engines-coldfusion
Packt
23 Oct 2009
5 min read
Save for later

Search Engines in ColdFusion

Packt
23 Oct 2009
5 min read
Built-In Search Engine Verity comes in package with ColdFusion. One of the reasons why people pay for ColdFusion is the incredible power that comes with this tool. It should be noted that one of the most powerful standalone commercial search engines is this tool. Some of the biggest companies in the world have expanded internal services with the help of the Verity tool that we will learn about. We can see that in order to start, we must create collections. The building of search abilities is a three-step process. There is a standard ColdFusion tag to help us with each of these functions. Create collections Index the collections Search the collections These collections can contain information about web pages, binary documents, and can even work as a powerful way to search cached query result information. There are many document formats supported. In the real business world, the latest bleeding-edge solutions will still store a previous version. Archived and shared documents should be stored in appropriate formats and versions that can be searched. Creating a Collection The first thing is to make our collection. See the ColdFusion Administrator under Data & Services. Here, we will be able to add collections and edit existing collections. There is one default collection included in ColdFusion installations. This is the bookclub demonstration application data. We will be creating a collection of PDF documents for this lesson. We have placed a collection of ColdFusion, Flex, and some of the Fusion Authority Quarterly periodicals in a directory for indexing. Here is the information screen for adding the collection through the administrator. We choose to select the Enable Category Support option. Also, there are libraries available for multiple languages if that is appropriate in a collection. We now see that there is a new collection for our devdocs. There are four icons to work with this collection. They are, from right to left, index, optimize, purge, and remove actions. The Name link takes us to the index action. The collection gives us the number of actual documents present, and the size of the index file on the server. The screen will show the details of the index as to when it was last modified, and the language in which it is stored. It lists the categories, and also shows the actual path where the index is stored. Here is a code version of creating a collection that would achieve the same thing. This means that it is possible to create an entire administrative interface to manage collections. It is also possible to move from tags to objects, and wrap up all the functions in that style. <cfcollection action="create" collection="devdocs" path="c:ColdFusion8veritycollectionsdocuments" /> If we have categories in our collection, and we want to get a list of the categories, then the following code must be used: <cfcollection action="categoryList" collection="bookClub" name="myCats" /><cfdump var="#myCats#"> Indexing a Collection We can do this through the administration interface. But here, we will do it as shown in the the following screenshot. This is a limited directory that we have used as an example for searching. This is the result of the devdocs submitted above. This gave a result of 12 documents with a search collection of the size, 4,611 Kb. Now, we will look at how to do the same search using code and build the index outside the administrator interface. This will require the collection to be built before we try to index files into it. The creation of the collection can also be done inside the administration interface or in code. It should also be noted that ColdFusion includes a security called Sandbox Security. These three core tags for Verity searching among many others can be blocked if you find it better for your environment. Just consider what is actually getting indexed and what needs to be searched. Hopefully, documents will be secured correctly and it will not be an issue. When we are making an index, we have to make sure that we can either choose to use a recursive search or not. A recursive search means that all the subdirectories in a document or web page search will be included in our search. It should also be noted that the service will not work for indexing other websites. It is for indexing this server only. <cfindex name="myCats" action="refresh" collection="bookClub" recurse="true" type="path" extensions=".html .htm .cfm .cfml" key="c:inetpubwwwrootdocuments" urlpath="http://localhost/documents/" /> Your collection has been indexed. It is important to note that there is no output from this tag. So we need to put some text on the screen to make sure the person using the site can know that the task has been completed. If we want to index a single file rather than a whole directory path, we can do it with this code: <cfindex action="refresh" collection="bookClub" recurse="true" type="file" extensions=".pdf" key=" c:inetpubwwwrootdocumentsColdFusioncf8_devguide.pdf" urlpath="http://localhost/documents/ColdFusion" /> Your collection has been indexed.
Read more
  • 0
  • 0
  • 2076

article-image-setting-openvpn-x509-certificates
Packt
23 Oct 2009
6 min read
Save for later

Setting Up OpenVPN with X509 Certificates

Packt
23 Oct 2009
6 min read
Creating Certificates One method could be setting up tunnels using pre-shared keys with static encryption, however, X509 certificates provide a much better level of security than pre-shared keys do. There is, however, slightly more work to be done to set up and connect two systems with certificate-based authentication. The following five steps have to be accomplished: Create a CA certificate for your CA with which we will sign and revoke client certificates.      Create a key and a certificate request for the clients.      Sign the request using the CA certificate and thereby making it valid.      Provide keys and certificates to the VPN partners.      Change the OpenVPN configuration so that OpenVPN will use the certificates and keys, and restart OpenVPN. There are a number of ways to accomplish these steps. easy-rsa is a command-line tool that comes with OpenVPN, and exists both on Linux and Windows. On Windows systems you could create certificates by clicking on the batch files in the Windows Explorer, but starting the batch files at the command-line prompt should be the better solution. On Linux you type the full path of the scripts, which share the same name as on Windows, simply without the extension .bat. Certificate Generation on Windows XP with easy-rsa Open the Windows Explorer and change to the directory C:Program Files OpenVPNeasy-rsa. The Windows version of easy-rsa consists of thirteen files. On Linux systems you will have to check your package management tools to find the right path to the easy-rsa scripts. On Debian Linux you will find them in /usr/share/doc/openvpn/examples/easy-rsa/. You find there are eight batch files, four configuration files, and a README (which is actually not really helpful). However, we must now create a directory called keys, copy the files serial.start and index.txt.start into it, and rename them to serial and index.txt respectively. The keys and certificates created by easy-rsa will be stored in this directory. These files are used as a database for certificate generation. Now we let easy-rsa prepare the standard configuration for our certificates. Double-click on the file C:Program FilesOpenVPNeasy-rsainit-config.bat or start this batch file at a command-line prompt. It simply copies the template files vars.bat.sample to vars.bat and openssl.cnf.sample to openvpn.ssl. While the file openssl is a standard OpenSSL configuration, the file vars.bat contains variables used by OpenVPN's scripts to create our certificates, and needs some editing in the next step. Setting Variables—Editing vars.bat Right-click on the vars.bat file's icon and select from the menu. In this file, several parameters are set that are used by the certificate generation scripts later. The following table gives a quick overview of the entries in the file: Entry in vars.bat Function set HOME=%ProgramFiles%OpenVPN easy-rsa The path to the directory where easy-rsa resides. set KEY_CONFIG=openssl.cnf The name of the OpenSSL configuration file. set KEY_DIR=keys The path to the directory where the newly generated keys are stored-relative to $HOME as set above. set KEY_SIZE=1024 The length of the SSL key. This parameter should be increased to 2048. set KEY_COUNTRY=US set KEY_PROVINCE=CA set KEY_CITY=SanFrancisco set KEY_ORG=FortFunston set [email protected] These five values are used as suggestions whenever you start a script and generate certificates with the easy-rsa software. Only the entry KEY_SIZE must be changed (unless you don't care much about security), but setting the last five entries to your needs might be very helpful later. Every time we generate a certificate, easy-rsa will ask (among others) for these five parameters, and give a suggestion that could be accepted simply by pressing Enter. The better the default values set here in vars.bat fit our needs, the less typing work we will have later. I leave it up to you to change these settings here. The next step is easy. Run vars.bat to set the variables. Even though you could simply double-click on its explorer icon, I recommend that you run it in a shell window. Select the entry Run from Windows' main menu, type cmd.exe, and change to the easy-rsa directory by typing cd "C:Program FilesOpenVPNeasy-rsa" and pressing Enter. By doing so, we will proceed in exactly the same way as we would do on a Linux system (except for the .bat extensions). Creating the Diffie-Hellman Key Now it is time to create the keys that will be used for encryption, authentication, and key exchange. For the latter, a Diffie-Hellman key is used by OpenVPN. The Diffie-Hellman key agreement protocol enables two communication partners to exchange a secret key safely. No prior secrets or safe lines are needed; a special mathematical algorithm guarantees that only the two partners know the used shared key. If you would like to know exactly what this algebra is about, have a look at this website: http://www.rsasecurity.com/rsalabs/node.asp?id=2248. easy-rsa provides a script (batch) file that generates the key for you: C:Program FilesOpenVPNeasy-rsabuild-dh.bat. Start it by typing build-dh.bat. A Diffie-Hellman key is being generated. The batch file tells you, This is going to take a long time, which is only true if your system is really old or if you are not patient enough. However, on modern systems some minutes may be a time span horribly long! Building the Certificate Authority OK, now it's time to generate our first CA. Enter build-ca.bat. This script generates a self-signed certificate for a CA. Such a certificate can be used to create and sign client certificates and thereby authenticate other machines. Depending on the data you entered in your vars.bat file, build-ca.bat will suggest different default parameters during the process of generating this certificate. Five of the last seven lines are taken from the variables set in vars.bat. If you edited these parameters, a simple return will do here and the certificate for the CA is generated in the keys directory.
Read more
  • 0
  • 0
  • 3858