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
Explore 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 - Web Development

1802 Articles
article-image-converting-xml-pdf
Packt
23 Oct 2009
5 min read
Save for later

Converting XML to PDF

Packt
23 Oct 2009
5 min read
XML is the most suitable format for data exchange, but not for data presentation. Adobe's PDF and Microsoft Excel's spreadsheet are the commonly used formats for data presentation. If you receive an XML file containing data that needs to be included in a PDF or Excel spreadsheet file, you need to convert the XML file to the relevant format. Some of the commonly used XML-to-PDF conversion tools/APIs are discussed in the following table: Tool/API Description iText iText is a Java library for generating a PDF document. iText may be downloaded from http://www.lowagie.com/iText/. Stylus Studio XML Publisher XML Publisher is a report designer, which supports many data sources, including XML, to generate PDF reports. Stylus Studio XML Editor XML Editor supports XML conversion to PDF. Apache FOP The Apache project provides an open source FO processor called Apache FOP to render an XSL-FO document as a PDF document. We will discuss the Apache FOP processor in this chapter. XMLMill for Java XMLMill may be used to generate PDF documents from XML data combined with XSL and XSLT. XMLMill may be downloaded from http://www.xmlmill.com/. RenderX XEP RenderX provides an XSL-FO processor called XEP that may be used to generate a PDF document.   We can convert an XML file data to a PDF document using any of these tools/APIs in JDeveloper 11g. Here, we will use Apache FOP API. The XSL specification consists of two components: a language for transforming XML documents (XSLT), and XML syntax for specifying formatting objects (XSL-FO). Using XSL-FO, the layout, fonts, and representations of the data may be formatted. Apache FOP (Formatting Objects Processor) is a print formatter for converting XSL formatting objects (XSL-FO) to an output format such as PDF, PCL, PS, SVG, XML, Print, AWT, MIF, or TXT. In this  article, we will convert an XML document to PDF using XSL-FO and the FOP processor in Oracle JDeveloper 11g.The procedure to create a PDF document from an XML file using the Apache FOP processor in JDeveloper is as follows: Create an XML document. Create an XSL stylesheet. Convert the XML document to an XSL-FO document. Convert the XSL-FO document to a PDF file. Setting the environment We need to download the FOP JAR file fop-0.20.5-bin.zip (or a later version) from http://archive.apache.org/dist/xmlgraphics/fop/binaries/ and extract the ZIP file to a directory. To develop an XML-to-PDF conversion application, we need to create an application (ApacheFOP, for example) and a project (ApacheFOP for example) in JDeveloper. In the project add an XML document, catalog.xml, with File | New. In the New Gallery window select Categories | General | XML and Items | XML Document. Click on OK. In the Create XML File window specify a File Name, catalog.xml, and click on OK. A catalog.xml file gets added to the ApacheFOP project. Copy the following catalog.xml listing to catalog.xml: <?xml version="1.0" encoding="UTF-8"?><catalog title="Oracle Magazine" publisher="Oracle Publishing"> <journal edition="September-October 2008"> <article> <title>Share 2.0</title> <author>Alan Joch</author> </article> <article> <title>Restrictions Apply</title> <author>Alan Joch</author> </article> </journal> <journal edition="March-April 2008"> <article> <title>Oracle Database 11g Redux</title> <author>Tom Kyte</author> </article> <article> <title>Declarative Data Filtering</title> <author>Steve Muench</author> </article> </journal></catalog> We also need to add an XSL stylesheet to convert the XML document to an XSL-FO document. Create an XSL stylesheet with File | New. In the New Gallery window, select Categories | General | XML and Items | XSL Stylesheet. Click on OK. In the Create XSL File window specify a File Name (catalog.xsl) and click on OK. A catalog.xsl file gets added to the ApacheFOP project. To convert the XML document to an XSL-FO document and subsequently create a PDF file from the XSL-FO file, we need a Java application. Add a Java class,  XMLToPDF.java, with File | New. In the New Gallery window select Categories | General and Items | Java Class. Click on OK. In the Create Java Class window specify a class Name (XMLToPDF for example) and click on OK. A Java class gets added to the ApacheFOP project. The directory structure of the FOP application is shown in the following illustration: Next, add the FOP JAR files to the project. Select the project node (ApacheFOP node) and then Tools | Project Properties. In the Project Properties window, select Libraries and Classpath. Add the Oracle XML Parser v2 library with the  Add Library button. The JAR files required to develop an FOP application are listed in the following table: JAR File Description <FOP>/fop-0.20.5/build/fop.jar Apache FOP API <FOP>/fop-0.20.5/lib/batik.jar Graphics classes <FOP>/fop-0.20.5/lib/ avalon-framework-cvs-20020806.jar Logger classes <FOP>/fop-0.20.5/lib/ xercesImpl-2.2.1.jar The DOMParser and the SAXParser classes
Read more
  • 0
  • 0
  • 21099

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
  • 5632

article-image-fundamentals-xhtml-mp-mobile-web-development
Packt
23 Oct 2009
7 min read
Save for later

Fundamentals of XHTML MP in Mobile Web Development

Packt
23 Oct 2009
7 min read
Fundamentals of XHTML MP Since XHTML MP is based on XHTML, certain syntactical rules must be followed. Making syntactical errors is a good way to learn a programming language, but so that you don't get frustrated with them, here are some rules you must follow with XHTML MP! Remember, HTML is very forgiving in terms of syntax, but make a small syntax error in XHTML MP and the browser may refuse to show your page! Overall, XHTML elements consist of a start tag—element name and its attributes, element content, and closing tag. The format is like: <element attribute="value">element content</element> XHTML Documents Must be Well Formed Since XHTML is based on XML, all XHTML documents must adhere to thebasic XML syntax and be well formed. The document must also have a DOCTYPE declaration. Tags Must be Closed! All open tags must be closed. Even if it is an empty tag like "<br>", it must be used in the self-closed form like "<br />". Note the extra space before the slash. It's not mandatory, but makes things work with some older browsers. If you can validate within your editor, make it a practice to do that. Also cultivate the habit of closing a tag that you start immediately—even before you put in the content. That will ensure you don't miss closing it later on! Elements Must be Properly Nested You cannot start a new paragraph until you complete the previous one. You must close tags to ensure correct nesting. Overlapping is not allowed. So the following is not valid in XHTML MP: <p><b>Pizzas are <i>good</b>.</i></p> It should be written as: <p><b>Pizzas are <i>good</i>.</b></p> Elements and Attributes Must be in Lowercase XHTML MP is case sensitive. And you must keep all the element tags and all their attributes in lowercase, although values and content can be in any case. Attribute Values Must be Enclosed within Quotes HTML allowed skipping the quotation marks around attribute values. This will not work with XHTML MP as all attribute values must be enclosed within quotes—either single or double. So this will not work: <div align=center>Let things be centered!</div> It must be written as: <div align="center">Let things be centered!</div> Attributes Cannot be Minimized Consider how you would do a drop down in HTML: <select> <option value="none">No toppings</option> <option value="cheese" selected>Extra Cheese</option> <option value="olive">Olive</option> <option value="capsicum">Capsicum</option> </select> The same drop down in XHTML is done as: <select> <option value="none">No toppings</option> <option value="cheese" selected="selected">Extra Cheese</option> <option value="olive">Olive</option> <option value="capsicum">Capsicum</option> </select> The "selected" attribute of the "option" element has only one possible value and, with HTML, you can minimize the attribute and specify only the attribute without its value. This is not allowed in XHTML, so you must specify the attribute as well as its value, enclosed in quotes. Another similar case is the "checked" attribute in check boxes. XHTML Entities Must be Handled Properly If you want to use an ampersand in your XHTML code, you must use it as &amp; and not just &. & is used as a starting character for HTML entities—e.g. &nbsp;, &quot;, &lt;, &gt; etc. Just using & to denote an ampersand confuses the XML parser and breaks it. Similarly, use proper HTML Entities instead of quotation marks, less than/greater than signs, and other such characters. You can refer to http://www.webstandards.org/learn/reference/charts/entities/ for more information on XHTML entities. Most Common HTML Elements are Supported The following table lists different modules in HTML and the elements within them that are supported in XHTML MP version 1.2. You can use this as a quick reference to check what's supported. Module Element Structure body, head, html, title Text abbr, acronym, address, blockquote, br, cite, code, dfn, div, em, h1, h2, h3, h4, h5, h6, kbd, p, pre, q, samp, span, strong, var Presentation b, big, hr, i, small Style Sheet style element and style attribute Hypertext a List dl, dt, dd, ol, ul, li Basic Forms form, input, label, select, option, textarea, fieldset, optgroup Basic Tables caption, table, td, th, tr Image img Object object, param Meta Information meta Link link Base base Legacy start attribute on ol, value attribute on li Most of these elements and their attributes work as in HTML. Table support in mobile browsers is flaky, so you should avoid tables or use them minimally. We will discuss specific issues of individual elements as we go further. XHTML MP Does Not Support Many WML Features If you have developed WAP applications, you would be interested in finding the differences between WML (Wireless Markup Language—the predecessor of XHTML MP) and XHTML MP; apart from the obvious syntactical differences. You need to understand this also while porting an existing WML-based application to XHTML MP. Most of WML is easily portable to XHTML MP, but some features require workarounds. Some features are not supported at all, so if you need them, you should use WML instead of XHTML MP. WML 1.x will be supported in any mobile device that conforms to XHTML MP standards. Here is a list of important WML features that are not available in XHTML MP: There is no metaphor of decks and cards. Everything is a page. This means you cannot pre-fetch content in different cards and show a card based on some action. With XHTML MP, you either have to make a new server request for getting new content, or use named anchors and link within the page. You could use the <do> tag in WML to program the left and right softkeys on the mobile device. Programming softkeys is not supported in XHTML MP; the alternative is to use accesskey attribute in the anchor tag (<a>) to specify a key shortcut for a link. WML also supports client-side scripting using WMLScript—a language similar to JavaScript. This is not supported in XHTML MP yet, but will come in near future in the form of ECMA Script Mobile Profile (ECMP). WML also supported client-side variables. This made it easier to process form data, validate them on the client side, and to reuse user-filled data across cards. This is not supported in XHTML MP. With XHTML MP, you have to submit a form with a submit button. WML allowed this on a link. WML also had a format attribute on the input tag—specifying the format in which input should be accepted. You need to use CSS to achieve this with XHTML MP. There are no timers in XHTML MP. This was a useful WML feature making it easier to activate certain things based on a timer. You can achieve a similar effect in XHTML MP using a meta refresh tag. The WML events ontimer, onenterbackward, onenterforward, and onpick are not available in XHTML MP. You can do a workaround for the ontimer event, but if you need others, you have to stick to using WML for development. XHTML MP also does not support the <u> tag, or align attribute on the <p> tag, and some other formatting options. All these effects can be achieved using CSS though. Summary In this article, we had a look at the fundamentals of XHTML MP and also at the grammar that must be followed for development with it. Next, we listed different modules in HTML and the elements within them that are supported in XHTML MP version 1.2. We finished the article by listing the important WML features that are not available in XHTML MP.
Read more
  • 0
  • 0
  • 3834

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
  • 2371

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
  • 3412

article-image-roles-and-permissions-moodle-administration-part1
Packt
23 Oct 2009
1 min read
Save for later

Roles and Permissions in Moodle Administration: Part1

Packt
23 Oct 2009
1 min read
Lets get started. Moodle's PreDefined Roles Moodle comes with a number of predefined roles. These standard roles are suitable for some educational setups, but most institutions require modifications to the roles' system in order to tailor Moodle to their specific needs. Each role has permissions for a number of actions that can be carried out in Moodle. For example, an administrator and a course creator are able to create new courses, whereas all other roles are denied this right. Likewise, a teacher is allowed to moderate forums, whereas students are only allowed to contribute to them. Before we can actually do anything with roles, we need to understand the concept of contexts, which is dealt with next. Contexts Contexts are the areas in Moodle where roles can be assigned to users. A role can be assigned within different contexts. A user has a role in any given context, where a context can be a course, an activity module, a user, a block, or Moodle itself. Moodle comes with the following seven contexts that you will come across a lot in this article.
Read more
  • 0
  • 0
  • 3470
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 $19.99/month. Cancel anytime
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
  • 3721

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
  • 1466

article-image-users-profiles-and-connections-elgg
Packt
23 Oct 2009
8 min read
Save for later

Users, Profiles, and Connections in Elgg

Packt
23 Oct 2009
8 min read
Connecting to Friends and Users I hope you're convinced how important friends are to a social network. Initially, you'll have to manually invite your friends over to join. I say initially, because membership on a social network is viral. Once your friends are registered members of your network, they can also bring in their own friends. This means that soon your friends would have invited their own friends as well. Chances are that you might not know these friends of your friends. So, Elgg not only allows you to invite friends from outside, but also connect with users already on the network. Let's understand these situations in real-life terms. You invite your friends over to a party with you at your new Star Trek themed club. That's what you'll do with Elgg, initially. So your friends like the place and next time around they bring in more friends from work. These friends of friends from work talk about your place with their friends and so on, until you're hosting a bunch of people in the club that you haven't ever met in your life. You overhear some people discussing Geordi La Forge, your favorite character from the show. You invite them over for drinks. That's connecting with users already on the network. So let's head on over to Elgg and invite some friends! Inviting Friends to Join There are two ways of inviting users to join your network. Either send them an email with a link to join the website, or let Elgg handle sending them emails. If you send them emails, you can include a direct link to the registration page. This link is also on the front page of your network, which every visitor will see. It asks visitors to register an account if they like what's on the network. Let Elgg Handle Registration This is the most popular method of inviting users to join the network. It's accessible not only to you, but also to your friends once they've registered with the network. To allow Elgg to send emails on your behalf, you'll have to be logged into Elgg. Once you login, click on the Your Network button on the top navigation bar. This will take you to a page, which links to tools that'll help you connect with others. The last link in this bar (Invite a Friend) does exactly what it says. When you click on this link, it'll explain to you some benefits of inviting friends over. The page has three fields; Their name: Enter the name of the friend you're sending the invitation to. Their email address: Very important. This is the address to where the invitation is sent. An optional message: Elgg sends an email composed using a template. If you want to add a personal message to Elgg's email, you can do so here. In the email, which Elgg sends on behalf of the network's administrator, that means you, it displays the optional message (if you've sent one), along with a link to the registration page. The invitation is valid for seven days, after which the registration link in the email isn't valid. When your friends click on the registration form, it asks them to enter their: Name: This is your friend's real name. When he arrives here by clicking the link in the email, this field already has the same name as the one in the email. Of course, your friend can choose to change it if he pleases. Username: The name your friend wants to use to log in to the network. Elgg automatically suggests one based on your friend's real name. Password: The last two fields ask your friend to enter (and then re-enter to confirm) a password. This is used along with the username to authenticate him on the system. Once your friends enter all the details and click on join, Elgg creates an account for them, logs them in, and dispatches a message to them containing the log in details for reference. Build a Profile The first thing a new user has to do on the network is to create his profile. If you haven't yet built up a profile yourself, now is a good time. To recap, your profile is your digital self. By filling in a form, Elgg helps you define yourself in terms that'll help other members find and connect to you. This is again where socializing using Elgg outscores socializing in real life. You can find people with similar tastes, likes, and dislikes, as soon as you enter the network. So let's steam ahead and create a digital you. The Various Profile Options Once you are logged into your Elgg network, select the Your Profile option from the top navigation-bar. In the page that opens, click the first link, Edit this profile. This opens up a form, divided into five tabs—Basic details, Location, Contact, Employment, and Education. Each tab helps you fill in details regarding that particular area. You don't necessarily have to fill in each and every detail. And you definitely don't have to fill them all in one go. Each tab has a Save your profile button at the end. When you press this button, Elgg updates your profile instantaneously. You can fill in as much detail as you want, and keep coming back to edit your profile, and append new information. Let's look at the various tabs: Basic details: Although filling information in any tab is optional, I'd advise you to fill in all details in this tab. This will make it easy, for you to find others, and for others to find you. The tab basically asks you to introduce yourself, list your interests, your likes, your dislikes, your goals in life, and your main skills. Location: This tab requests information that'll help members reach you physically. Fill in your street address, town, state, postal code, and country. Contact: Do you want members to contact you outside your Elgg network? This tab requests both physical as well as electronic means which members can use to get in touch with you. Physical details include your work, home, and mobile telephone number. Electronic details include your email address, your personal, and official websites. Elgg can also list information to help users connect to you on instant messenger. It supports ICQ, MSN, AIM, Skype, and Jabber. Employment: List your occupation, the industry, and company you work in, your job title, and description. Elgg also lets you list your career goals and suggests you do so to "let colleagues and potential employers know what you'd like to get out of your career. Education: Here you can specify your level of education, and which high school, university or college you attended, and the degree you hold. As you can clearly see, Elgg's profiling options are very diverse and detailed. Rather than serve the sole purpose of describing you to the visitors, the profile also helps you find new friends as well, as we'll see later in this article. What is FOAF? While filling the profile, you must have noticed an Upload a FOAF file area down at the bottom of all tabs. FOAF or Friend of a Friend is a project (http://www.foaf-project.org/) to help create "machine-readable pages that describe people, the links between them, and the things they create, and do". The FOAF file includes lots of details about you, and if you have already created a FOAF profile, Elgg can use that to pick out information describing you from in there. You can modify the information once it's imported into Elgg, if you feel the need to do so. The FOAF-a-Matic tool (http://www.ldodds.com/foaf/foaf-a-matic.en.html) is a simple Web-based program you can use to create a FOAF profile. A Face for Your Profile Once you have created your digital self, why not give it a face as well. The default Elgg picture with a question mark doesn't look like you! To upload your picture, head over to Your Profile and select the Change site picture link. From this page, click Browse to find and select the picture on your computer. Put in an optional description, and then choose to make it your default icon. When you click the Upload new icon button, Elgg will upload the picture. Once the upload completes, Elgg will display the picture. Click the Save button to replace Elgg's default icon with this picture.   Elgg will automatically resize your picture to fit into its small area. You should use a close-up of yourself, otherwise the picture will lose clarity when resizing. If you don't like the picture when it appears on the website, or you want to replace it with a new one, simply tick the Delete check-box associated with the picture you don't like. When you click Save, Elgg will revert to the default question-mark guy.
Read more
  • 0
  • 0
  • 4695

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
  • 1641
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
  • 5065

article-image-front-page-customization-moodle
Packt
23 Oct 2009
11 min read
Save for later

Front Page Customization in Moodle

Packt
23 Oct 2009
11 min read
Look and Feel: An Overview Moodle can be fully customized in terms of layout and branding. It has to be stressed that certain aspects of changing the look and feel require some design skills. While you as an administrator will be able to make most of the relevant adjustments, it might be necessary to get a professional designer involved, especially when it comes to styling. The two relevant components for customization are the Moodle front page and Moodle themes, though this article will focus only on Moodle front page. Before going into further details, let's try to understand which part is responsible for which element of the look and feel of your site. Have a look at the screenshot that would follow. It shows the front page of Moodle site after you are logged in as an administrator. It is not obvious which parts are driven by the Moodle theme and by the front page settings. The next table sheds some light on this: Element Settings Theme Other Logos - x - Logged-in information (location and font) - x - Language Drop Down - - x Site Administration block (position) x - - Available Courses block (position) x - - Available Courses block (content) - - x Course categories and Calendar block (position) x - - Course categories and Calendar block (icons, fonts, colors) - x - Footer text - x - Footer logo - x - Copyright statement - x -   While this list is by no means complete, it hopefully gives you an idea that the look and feel of your Moodle site is driven by a number of different elemen In short, the settings (mostly front page settings as well as a few related parameters) dictate what content users will see before and after they log on. The theme is responsible for the design scheme or branding, that is, the header and footer as well as colors, fonts, icons, and so on used throughout the site. Now let's move towards the core part of this article. Customizing Your Front Page The appearance of Moodle's front page changes after a user has logged in. The content and layout of the page before and after login can be customized to represent the identity of your organization. Look at the following screenshot. It is the same site that the preceding screenshot was taken from, but before a user has logged in. In this particular example, a Login block is shown on the left and the Course categories are displayed in the center, as opposed to the list of available courses. Front Page Settings To customize the front page, you either have to be logged in as Moodle administrator, or have front-page-related permissions in the Front Page context. From the Site Administration block, select Front Page | Front Page Settings. The screen showing all available parameters will be loaded displaying your current settings that are changeable. ts. Setting Description Full site name This is the name that appears in the browser's title bar. It is usually the full name of your organization, or the name of the dedicated course, or qualification the site is used for. Short name for site This is the name that appears as the first item in the breadcrumb trail. Front Page Description This description of the site will be displayed on the front page via the Site Description block. It can, therefore, only be displayed in the left or right column, never in the center of the front page. The description text is also picked up by the Google search engine spider, if allowed. Front Page Moodle can display up to four elements in the center column of the front page when not logged in. List of courses List of categories News items Combo list(categories and courses) The order of the elements is the same as the one chosen in the pull-down menus. Front page items when logged in Same as "Front Page", but used when logged in. Include a topic section If ticked, an additional topic section (just like the topic blocks in the center column of a topics-format course) appears on top of the front page's center column. It can contain any mix of resources or activities available in Moodle. It is very often used to provide information about the site. News items to show Number of news items that are displayed. Courses per page This is a threshold setting that is used when displaying courses within categories. If there are more courses in a category than specified, page navigation will be displayed at the top of the page. Also, when a combo list is used, course names are only displayed if the number is less than the specified threshold. For all other categories, only the number of courses is shown after the category name. Allow visible courses within hidden categories By default, courses in hidden categories are not shown unless the said setting is applied. Default frontpage role If logged-in users should be allowed to participate in front page activities, a default front page role should be set. The default is None.   Arranging Front Page Blocks To configure the left and right column areas with blocks, you have to turn on editing (using the Blocks editing on button). The menu includes blocks that are not available in courses such as Course/Site description and Main menu. Blocks are added to the front page in exactly the same way as in courses. To change their position, use the standard arrows. The Main Menu block allows you to add any installed Moodle resource or activity inside the block. For example, using labels and links to (internal or external) websites, you are able to create a menu-like structure on your front page. If the Include a topic section parameter has been selected in the Front Page settings, you have to edit the part and add any installed Moodle activity or resource. This topic section is usually used by organizations to add a welcome message to visitors, often accompanied by a picture or other multimedia content. Login From a Different Website The purpose of the Login block is for users to authenticate themselves by entering their username and password. It is possible to log into Moodle from a different website, maybe your organization's homepage, effectively avoiding the Login block. To implement this, you will have to add some HTML code on that page as shown: <form class="loginform" name="login" method="post" action="http://www.mysite.com/login/index.php">   <p>Username :     <input size="10" name="username" />   </p>   <p>Password :     <input size="10" name="password" type="password" />   </p>   <p>     <input name="Submit" value="Login" type="submit" />   </p></form> The form will pass the username and password to your Moodle system. You will have to replace www.mysite.com with your URL. This address has to be entered in the Alternate Login URL field at Users | Authentication | Manage authentication in the Site Administration block. Other Front Page Items The Moodle front page is treated as a standalone component in Moodle, and therefore has a top-level menu with a number of features that can all be accessed via the Front Page item in the Site Administration menu. Having now looked in detail at the front page settings, let's turn to examining the other available options. Front Page Roles The front page has its own context in which roles can be assigned to users. This allows a separate user to develop and maintain the front page without having access to any other elements in Moodle. Since the front page is treated as a course, a Teacher role is usually sufficient for this. Front Page Backup and Restore The front page has its own backup and restore facilities to back up and restore all elements of the front page including any content. The mechanism of performing backup and restore is the same as for course backups.   Front page backups are stored in the backupdata folder in the Site Files area, and can be accessed by anybody who is aware of the URL. It is therefore best to move the created ZIP files to a more secure location. Front Page Questions Since the Moodle front page is treated in the same way as a course, it also has its own question bank, which is used to store any questions used on front-page quizzes. For more information on quizzes and the question bank, go to the MoodleDocs at http://docs.moodle.org/en/Quiz . Site Files The files areas of all courses are separate from each other, that is, files in Moodle belong to a course and can only be accessed by users who have been granted appropriate rights. The difference between Site files and the files area of any other course is that files in Site files can be accessed without logging in. Files placed in this location are meant for the front page, but can be accessed from anywhere in the system. In fact, if the location is known, files can be even be accessed from outside Moodle. Make sure that in the Site files area, you only place files that are acceptable to be seen by users who are not authenticated on your Moodle system. Typical files to be placed in this area are any images you want to show on the front page (such as the logo of your organization) or any document that you want to be accessed (for example, the curriculum). However, it is also used for other files that are required to be accessible without access to a course, such as the Site Policy Agreement, which has to be accepted before starting Moodle. To access these publicly available Site files elsewhere (for example, as a resource within other courses), you have to copy the link location that has the format: http://mysite.com/file.php/1/file.doc. Allow Personalization via My Moodle By default, the same front page is displayed for all users on your Moodle system. To relax this restriction and to allow users to personalize their own front page, you have to activate the My Moodle feature via the Force users to use My Moodle setting in Appearance | My Moodle in the Site Administration block. Once enabled, Moodle creates a /my directory for each user (except administrators) at their first login, which is displayed instead of the main Moodle front page. It is a very flexible feature that is similar to a customizable dashboard, but requires some more disk space on your server. Once logged in, users will have the ability to edit their page by adding blocks to their My Moodle area. The center of the page will be populated by the main front page, for instance displaying a list of courses, that users cannot modify. Making Blocks Sticky There might be some blocks that you wish to "stick", that is, display on each My Moodle page, making them effectively compulsory blocks. For example, you might want to pin the Calendar block on the top right corner of each user's My Moodle page. To do this, go to Modules | Blocks | Sticky blocks in the Site Administration block and select My Moodle from the pull-down menu. You can now add any item from the pull-down menu in the Blocks block. If the block is single instance (that is, only one occurrence is allowed per page), the block will not be available for the user to choose from. If the user has already selected a particular block, a duplicate will appear on their site, which can be edited and deleted. To prevent users from editing their My Moodle pages, change the moodle/my: manageblocks capability in the Authenticated user role from Allow to Not set. The sticky block feature is also available for course pages. A course creator has the ability to add and position blocks inside a course unless they have been made sticky. Select the Course page item from the same menu to configure the sticky blocks for courses, as shown in the preceding screenshot. Summary After providing a general overview of look and feel elements in Moodle, the article covered front page customization. As mentioned earlier, the front page in Moodle is a course. This has advantages (you can do everything you can do in a course and a little bit more), but it also has certain limitations (you can only do what you can do in a course and might feel limited by this). However, some organizations are now using the Moodle front page as their homepage.
Read more
  • 0
  • 0
  • 17368

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>nowhere@notadomain.tld</from> <to>unknown@unknown.tld</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>nowhere@notadomain.tld</from> <to>unknown@unknown.tld</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>nowhere@notadomain.tld</from> <to>unknown@unknown.tld</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] => nowhere@notadomain.tld [to] => unknown@unknown.tld [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>nowhere@notadomain.tld</from> <to>unknown@unknown.tld</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
  • 2504
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—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
  • 3736

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—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—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—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
  • 3602
Modal Close icon
Modal Close icon