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
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

7019 Articles
article-image-xpath-support-oracle-jdeveloper-xdk-11g
Packt
15 Oct 2009
11 min read
Save for later

XPath Support in Oracle JDeveloper - XDK 11g

Packt
15 Oct 2009
11 min read
With SAX and DOM APIs, node lists have to be iterated over to access a particular node. Another advantage of navigating an XML document with XPath is that an attribute node may be selected directly. With DOM and SAX APIs, an element node has to be selected before an element attribute can be selected. Here we will discuss XPath support in JDeveloper. What is XPath? XPath is a language for addressing an XML document's elements and attributes. As an example, say you receive an XML document that contains the details of a shipment and you want to retrieve the element/attribute values from the XML document. You don't just want to list the values of all the nodes, but also want to output the values of specific elements or attributes. In such a case, you would use XPath to retrieve the values of those elements and attributes. XPath constructs a hierarchical structure of an XML document, a tree of nodes, which is the XPath data model. The XPath data model consists of seven node types. The different types of nodes in the XPath data model are discussed in the following table: Node Type Description Root Node The root node is the root of the DOM tree. The document element (the root element) is a child of the root node. The root node also has the processing instructions and comments as child nodes. Element Node It represents an element in an XML document. The character data, elements, processing instruction, and comments within an element are the child nodes of the element node. Attribute Node It represents an attribute other than the valign="top"> Text Node The character data within an element is a text node. A text node has at least one character of data. A whitespace is also considered as a character of data.  By default, the ignorable whitespace after the end of an element and before the start of the following element is also a text node. The ignorable whitespace can be excluded from the DOM tree built by parsing an XML document. This can be done by setting the whitespace-preserving mode to false with the setPreserveWhitespace(boolean flag) method. Comment Node It represents a comment in an XML document, except the comments within the DOCTYPE declaration. Processing Instruction Node It represents a processing instruction in an XML document except the processing instruction within the DOCTYPE declaration. The XML declaration is not considered as a processing instruction node. Namespace Node It represents a namespace mapping, which consists of a . A namespace node consists of a namespace prefix (xsd in the example) and a namespace URI (http://www.w3.org/2001/XMLSchema in the example). Specific nodes including element, attribute, and text nodes may be accessed with XPath. XPath supports nodes in a namespace. Nodes in XPath are selected with an XPath expression. An expression is evaluated to yield an object of one of the following four types: node set, Boolean, number, or string. For an introduction on XPath refer to the W3C Recommendation for XPath (http://www.w3.org/TR/xpath). As a brief review, expression evaluation in XPath is performed with respect to a context node. The most commonly used type of expression in XPath is a location path . XPath defines two types of location paths: relative location paths and absolute location paths. A relative location path is defined with respect to a context node and consists of a sequence of one or more location steps separated by "/". A location step consists of an axis, a node test, and predicates. An example of a location step is: child::journal[position()=2] In the example, the child axis contains the child nodes of the context node. Node test is the journal node set, and predicate is the second node in the journal node set. An absolute location path is defined with respect to the root node, and starts with "/". The difference between a relative location path and an absolute location path is that a relative location path starts with a location step, and an absolute location path starts with "/". XPath in Oracle XDK 11g Oracle XML Developer's Kit 11g, which is included in JDeveloper, provides the DOMParser class to parse an XML document and construct a DOM structure of the XML document. An XMLDocument object represents the DOM structure of an XML document. An XMLDocument object may be retrieved from a DOMParser object after an XML document has been parsed. The XMLDocument class provides select methods to select nodes in an XML document with an XPath expression. In this article we shall parse an example XML document with the DOMParser class, obtain an XMLDocument object for the XML document, and select nodes from the document with the XMLDocument class select methods. The different select methods in theXMLDocument class are discussed in the following table: Method Name Description selectSingleNode(String XPathExpression) Selects a single node that matches an XPath expression. If more than one node matches the specified expression, the first node is selected. Use this method if you want to select the first node that matches an XPath expression. selectNodes(String XPathExpression) Selects a node list of nodes that match a specified XPath expression. Use this method if you want to select a collection of similar nodes. selectSingleNode(String XPathExpression, NSResolver resolver) Selects a single namespace node that matches a specified XPath expression. Use this method if the XML document has nodes in namespaces and you want to select the first node, which is in a namespace and matches an XPath expression. selectNodes(String XPathExpression, NSResolver resolver) Selects a node list of nodes that match a specified XPath expression. Use this method if you want to select a collection of similar nodes that are in a namespace. The example XML document that is parsed in this article has a namespace declaration for elements in the namespace with the prefix journal. For an introduction on namespaces in XML refer to the W3C Recommendation on Namespaces in XML 1.0 (http://www.w3.org/TR/REC-xml-names/). catalog.xml, the example XML document, is shown in the following listing: <?xml version="1.0" encoding="UTF-8"?><catalog title="Oracle Magazine" publisher="Oracle Publishing"><journal:journal journal_date="November-December 2008"> <journal:article journal_section="ORACLE DEVELOPER"> <title>Instant ODP.NET Deployment</title> <author>Mark A. Williams</author></journal:article><journal:article journal_section="COMMENT"> <title>Application Server Convergence</title> <author>David Baum</author> </journal:article></journal:journal><journal date="March-April 2008"> <article section="TECHNOLOGY"> <title>Oracle Database 11g Redux</title> <author>Tom Kyte</author> </article><article section="ORACLE DEVELOPER"> <title>Declarative Data Filtering</title> <author>Steve Muench</author> </article> </journal></catalog Setting the environment Create an application (called XPath, for example) and a project (called XPath) in JDeveloper. The XPath API will be demonstrated in a Java application. Therefore, create a Java class in the XPath project with File | New. In the New Gallery window select < >Categories | General and Items | Java Class. In the Create Java Class window, specify the class name (XPathParser, for example), the package name (xpath in the example application), and click on the OK button. To develop an application with XPath, add the required libraries to the project classpath. Select the project node in Application Navigator and select Tools | Project Properties. In the Project Properties window, select the Libraries and Classpath node. To add a library, select the Add Library button. Select the Oracle XML Parser v2 library. Click on the OK button in the Project Properties window. We also need to add an XML document that is to be parsed and navigated with XPath. To add an XML document, select File | New. In the New Gallery window, select Categories | General | XML and Items | XML Document. Click on the OK button. In the Create XML File window specify the file name catalog.xml in the File Name field, and click on the OK button. Copy the catalog.xml listing to the catalog.xml file in the Application Navigator. The directory structure of the XPath project is shown in the following illustration: XPath Search In this section, we shall select nodes from the example XML document, catalog.xml, with the XPath Search tool of JDeveloper 11g. The XPath Search tool consists of an Expression field for specifying an XPath expression. Specify an XPath expression and click on OK to select nodes matching the XPath expression. The XPath Search tool has the provision to search for nodes in a specific namespace. An XML namespace is a collection of element and attribute names that are identified by a URI reference. Namespaces are specified in an XML document using namespace declarations. A namespace declaration is an > To navigate catalog.xml with XPath, select catalog.xml in the Application Navigator and select Search | XPath Search. In the following subsections, we shall select example nodes using absolute location paths and relative location paths. Use a relative location path if the XML document is large and a specifi c node is required. Also, use a relative path if the node from which subnodes are to be selected and the relative location path are known. Use an absolute location path if the XML document is small, or if the relative location path is not known. The objective is to use minimum XPath navigation. Use the minimum number nodes to navigate in order to select the required node. Selecting nodes with absolute location paths Next, we shall demonstrate with various examples of selecting nodes using XPath. As an example, select all the title elements in catalog.xml. Specify the XPath expression for selecting the title elements in the Expression field of the Apply an XPath Expression on catalog.xml window. The XPath expression to select all title elements is /catalog/journal/article/title. Click on the OK button to select the title elements. The title elements get selected. Title elements from the journal:article elements in the journal namespace do not get selected because a namespace has not been applied to the XPath expression. As an other example, select the title element in the first article element using the XPath expression /catalog/journal/article[1]/title. We are not using namespaces yet. The XPath expression is specified in the Expression field. The title of the first article element gets selected as shown in the JDeveloper output: Attribute nodes may also be selected with XPath. Attributes are selected by using the "@" prefix. As an example, select the section attribute in the first article element in the journal element. The XPath expression for selecting the section attribute is /catalog/journal/article[1]/@section and is specified in the Expression field. Click on the OK button to select the section attribute. The attribute section gets outputted in JDeveloper. Selecting nodes with relative location paths In the previous examples, an absolute location is used to select nodes. Next, we shall demonstrate selecting an element with a relative location path. As an example, select the title of the first article element in the journal element. The relative location path for selecting the title element is child::catalog/journal/article[position()=1]/title. Specifying the axis as child and node test as catalog selects all the child nodes of the catalog node and is equivalent to an absolute location path that starts with /catalog. If the child nodes of the journal node were required to be selected, specify the node test as journal. Specify the XPath expression in the Expression field and click on the OK button. The title of the first article element in the journal element gets selected as shown here: Selecting namespace nodes XPath Search also has the provision to select elements and attributes in a namespace. To illustrate, select all the title elements in the journal element (that is, in the journal namespace) using the XPath expression /catalog/journal:journal/journal:article/title. First, add the namespaces of the elements and attributes to be selected in the Namespaces text area. Prefix and URI of namespaces are added with the Add button. Specify the prefix in the Prefix column, and the URI in the URI column. Multiple namespace mappings may be added. XPath expressions that select namespace nodes are similar to no-namespace expressions, except that the namespace prefixes are included in the expressions. Elements in the default namespace, which does not have a namespace prefix, are also considered to be in a namespace. Click on the OK button to select the nodes with XPath. The title elements in the journal element (in the journal namespace) get selected and outputted in JDeveloper. Attributes in a namespace may also be selected with XPath Search. As an example, select the section attributes in the journal namespace. Specify the XPath expression to select the section attributes in the Expression field and click on the OK button. Section attributes in the journal namespace get selected.
Read more
  • 0
  • 0
  • 5524

article-image-html-php-and-content-posting-drupal-6
Packt
15 Oct 2009
9 min read
Save for later

HTML, PHP, and Content Posting in Drupal 6

Packt
15 Oct 2009
9 min read
Input Formats and Filters It is necessary to stipulate the type of content we will be posting, in any given post. This is done through the use of the Input format setting that is displayed when posting content to the site—assuming the user in question has sufficient permissions to post different types of content. In order to control what is and is not allowed, head on over to the Input formats link under Site configuration. This will bring up a list of the currently defined input formats, like this: At the moment, you might be wondering why we need to go to all this trouble to decide whether people can add certain HTML tags to their content. The answer to this is that because both HTML and PHP are so powerful, it is not hard to subvert even fairly simple abilities for malicious purposes. For example, you might decide to allow users the ability to link to their homepages from their blogs. Using the ability to add a hyperlink to their postings, a malicious user could create a Trojan, virus or some other harmful content, and link to it from an innocuous and friendly looking piece of HTML like this: <p>Hi Friends! My <a href="link_to_trojan.exe">homepage</a> is a great place to meet and learn about my interests and hobbies. </p> This snippet writes out a short paragraph with a link, supposedly to the author's homepage. In reality, the hyperlink reference attribute points to a trojan, link_to_trojan.exe. That's just HTML! PHP can do a lot more damage—to the extent that if you don't have proper security or disaster-recovery policies in place, then it is possible that your site can be rendered useless or destroyed entirely. Security is the main reason why, as you may have noticed from the previous screenshot, anything other than Filtered HTML is unavailable for use by anyone except the administrator. By default, PHP is not even present, let alone disabled. When thinking about what permissions to allow, it is important to re-iterate the tenet: Never allow users more permissions than they require to complete their intended tasks! As they stand, you might not find the input formats to your liking, and so Drupal provides some functionality to modify them. Click on the configure link adjacent to the Filtered HTML option, and this will bring up the following page: The Edit tab provides the option to alter the Name property of the input format; the Roles section in this case cannot be changed, but as you will see when we come around to creating our own input format, roles can be assigned however you wish to allow certain users to make use of an input format, or not. The final section provides a checklist of the types of Filters to apply when using this input format. In this previous screenshot, all have been selected, and this causes the input format to apply the: HTML corrector – corrects any broken HTML within postings to prevent undesirable results in the rest of your page. HTML filter – determines whether or not to strip or remove unwanted HTML. Line break converter – Turns standard typed line breaks (i.e. whenever a poster clicks Enter) into standard HTML. URL filter – allows recognized links and email addresses to be clickable without having to write the HTML tags, manually. The line break converter is particularly useful for users because it means that they do not have to explicitly enter <br> or <p> HTML tags in order to display new lines or paragraph breaks—this can get tedious by the time you are writing your 400th blog entry. If this is disabled, unless the user has the ability to add the relevant HTML tags, the content may end up looking like this: Click on the Configure tab, at the top of the page, in order to begin working with the HTML filter. You should be presented with something like this: The URL filter option is really there to help protect the formatting and layout of your site. It is possible to have quite long URLs these days, and because URLs do not contain spaces, there is nowhere to naturally split them up. As a result, a browser might do some strange things to cater for the long string and whatever it is; this will make your site look odd. Decide how many characters the longest string should be and enter that number in the space provided. Remember that some content may appear in the sidebars, so you can't let it get too long if they is supposed to be a fixed width. The HTML filter section lets you specify whether to Strip disallowed tags, or escape them (Escape all tags causes any tags that are present in the post to be displayed as written). Remember that if all the tags are stripped from the content, you should enable the Line break converter so that users can at least paragraph their content properly. Which tags are to be stripped is decided in the Allowed HTML tags section, where a list of all the tags that are to be allowed can be entered—anything else gets handled appropriately. Selecting Display HTML help forces Drupal to provide HTML help for users posting content—try enabling and disabling this option and browsing to this relative URL in each case to see the difference: filter/tips. There is quite a bit of helpful information on HTML in the long filter tips; so take a moment to read over those. The filter tips can be reached whenever a user expands the Input format section of the content post and clicks on More information about formatting options at the bottom of that section. Finally, the Spam link deterrent is a useful tool if the site is being used to bombard members with links to unsanctioned (and often unsavory) products. Spammers will use anonymous accounts to post junk (assuming anonymous users are allowed to post content) and enabling this for anonymous posts is an effective way of breaking them. This is not the end of the story, because we also need to be able to create input formats in the event we require something that the default options can't cater for. For our example, there are several ways in which this can be done, but there are three main criteria that need to be satisfied before we can consider creating the page. We need to be able to: Upload image files and attach them to the post. Insert and display the image files within the body of the post. Use PHP in order to dynamically generate some of the content (this option is really only necessary to demonstrate how to embed PHP in a posting for future reference). There are several methods for displaying image files within posts. The one we will discuss here, does not require us to download and install any contribution modules, such as Img_assist. Instead, we will use HTML directly to achieve this, specifically, we use the <img> tag. Take a look at the previous screenshot that shows the configure page of the Filtered HTML input format. Notice that the <img> tag is not available for use. Let's create our own input format to cater for this, instead of modifying this default format. Before we do, first enable the PHP Filter module under Modules in Site building so that it can easily be used when the time comes. With that change saved, you will find that there is now an extra option to the Filters section of each input format configuration page: It's not a good idea to enable the PHP evaluator for either of the default options, but adding it to one of our own input formats will be ok to play with. Head on back to the main input formats page under Site configuration (notice that there is an additional input format available, called PHP code) and click on Add input format. This will bring up the same configuration type page we looked at earlier. It is easy to implement whatever new settings you want, based on how the input format is to be used. For our example, we need the ability to post images and make use of PHP scripts, so make the new input format as follows: As we will need to make use of some PHP code a bit later on, we have enabled the PHP evaluator option, as well as prevented the use of this format for anyone but ourselves—normally, you would create a format for a group of users who require the modified posting abilities, but in this case, we are simply demonstrating how to create a new input format; so this is fine for now. PHP should not be enabled for anyone other than yourself, or a highly trusted administrator who needs it to complete his or her work. Click Save configuration to add this new format to the list, and then click on the Configure tab to work on the HTML filter. The only change required between this input format and the default Filtered HTML, in terms of HTML, is the addition of the <img> and <div> tags, separated by a space in the Allowed HTML tags list, as follows: As things stand at the moment, you may run into problems with adding PHP code to any content postings. This is because some filters affect the function of others, and to be on the safe side, click on the Rearrange tab and set the PHP evaluator to execute first: Since the PHP evaluator's weight is the lowest, it is treated first, with all the others following suit. It's a safe bet that if you are getting unexpected results when using a certain type of filter, you need to come to this page and change the settings. We'll see a bit more about this, in a moment. Now, the PHP evaluator gets dibs on the content and can properly process any PHP. For the purposes of adding images and PHP to posts (as the primary user), this is all that is needed for now. Once satisfied with the settings save the changes. Before building the new page, it is probably most useful to have a short discourse on HTML, because it is a requirement if you are to attempt more complex postings.  
Read more
  • 0
  • 1
  • 20066

article-image-synchronous-communication-and-interaction-moodle-19-multimedia
Packt
14 Oct 2009
5 min read
Save for later

Synchronous Communication and Interaction with Moodle 1.9 Multimedia

Packt
14 Oct 2009
5 min read
These options can be helpful for distance education, providing new ways of communicating and interacting with our students (and between them) when we are not all in the same physical space. Because Moodle does not provide effective synchronous communication tools (the chat activity could overload the server), the aforementioned tools are presented as extensions that can support our courses, giving them a new level of interaction. In distance courses with considerable duration, such communication can be a motivation and a way of providing support to students when we are online at the same time. Communicating in real-time using text, audio, and video Google Chat is a service from Google that allows text, audio, and video chat amongst Google Mail users meaning, we'll need a Google account. The audio conversation is usually called Voice over IP (VoIP), but as bandwidth allowances increase, the use of video is becoming common. With this tool we can: Meet with colleagues or students, individually or in groups Participate in a distant event (for example, attend a conference) Conduct interviews Teach how to play an instrument (by using the webcam) Teach gestural language (by using the webcam) I find it really useful to use VoIP in distance courses, not only to give feedback to students and get to know them better, but also to create opportunities for students to interact with each other during group tasks outside of these tutor-students meeting times. A good time to use this application is in Module 10 – What's good music—a theme that fits well with an online debate about how to define quality criteria for music. Students will be required to work in groups and debate on what they think is good music and how it can be assessed. This discussion will be facilitated by using this tool. Chat and group chat The chat option is available in Google Mail, on the sidebar on the left. For a start, we can configure some settings, especially privacy settings, by going to Options | Chat settings…: In the section Auto-add suggested contacts, we should select the option Only allow people that I've explicitly approved to chat with me and see when I'm online option, as shown in the screenshot below: We can also disable chat history if we don't want to keep a record of our chat. There is another option during a chat to go "off record", meaning that if the chat history is on, this portion of the conversation (that takes place whilst this option is selected) will not be archived. We are now ready to start a chat. We can search for contacts in the same Google Mail Chat sidebar, using the search form that is available (Search, add or invite) and double-click on the name of the contact that is displayed, or in the Chat link of the pop-up window that is displayed: Because the chat is synchronous, it's obvious that the (two or more) people chatting must be online. We can check if a person is online or not by looking at the small icon next to the people we've located, or in our chat list. If they have a grey, round icon on the left of their name, they are offline (or invisible and don't want to be bothered). If the color is green (available), yellow (idle), or red (busy) it's possible to chat to them. In the pop-up, we can also add the person to the chat list below the search form. After starting the chat, a window similar to the one shown below opens in the lower-right corner of the Google Mail account, and we can start talking: When we are chatting with someone, we can click on the Video & More | Group Chat option to invite one or more friends to join the conversation: A new window will appear, in which we can chat with the participants. Note that if we click on the arrow in the blue bar at the top of our chat window, the window will pop-up from its position in the Google Mail window and we can access it as an independent window. If we paste a URL from a YouTube video into the chat window, a preview of the video will be integrated directly into our conversation, as shown in the screenshot below: Transferring files The easiest way to send files to participants for reading, or supporting discussion or commenting upon is either by using Google Mail, or by uploading them to Moodle or Google Docs and sharing these with the chat participants. This can be useful in many online discussions. Voice and video chat Chat, as we saw, is available by default in Google Mail, on the leftmost sidebar. To add audio and voice capabilities to this chat, we have to install a plug-in that is available at http://mail.google.com/videochat, for Windows and Mac users (again, sorry to Linux users). After installing this plug-in, we can start an audio or video conversation (only one-to-one). If our contacts have a camera or microphone, we can click on the Video & more option again, and the following two options will be available: In the case of voice chat, a call will be started, and we will also keep the text chat functionality: In the case of video chat, the same applies. In the upper area, a video of the person that we are chatting with will be displayed, and in the lower corner, if we have a webcam, our video will be displayed: Image source: Scmoewes (2005). Jimi. Retrieved March 30, 2009,from http://www.flickr.com/photos/cmoewes/30989105/ For distance courses or even in e-learning, Google chat is an option. But if we need more complex functionality, including audio conferencing and desktop sharing, there are other tools that are available. We will now look at one in particular, called Dimdim.
Read more
  • 0
  • 0
  • 1843

article-image-developing-wiki-seek-widget-using-javascript
Packt
14 Oct 2009
8 min read
Save for later

Developing Wiki Seek Widget Using Javascript

Packt
14 Oct 2009
8 min read
If you’re searching for details of a particular term in Google, you’re most probably going to see a link for relevant articles from wikipedia.org in the top 10 result list. Wikipedia, is the largest encyclopedia on the Internet, and contains huge collections of articles in many languages. The most significant feature of this encyclopedia is that it is a Wiki, so anybody can contribute to the knowledge base. A Wiki, (a new concept of web2.0), is a collection of web pages whose content can be created and changed by the visitor of the page with simplified mark-up language. Wikis are usually used as knowledge management systems on the web. Brief Introduction to Wikipedia Wikipedia has defined itself as : … a free, multilingual, open content encyclopedia project operated by the United States-based non-profit Wikimedia Foundation. Wikipedia is built upon an open source wiki package called MediaWiki. MediaWiki uses PHP as a server side scripting language and MySql as the database. Wikipedia uses MediaWiki’s wikitext format for editing the text, so the user (without any necessary  knowledge of HTML and CSS) can edit them easily. The Wikitext language (also called Wiki Markup) is a markup language which gives instruction on how outputted text will be displayed. It provides a simplified approach to writing pages in a wiki website. Different types of wiki software employ different styles of Wikitext language. For example, the Wikitext markup language has ways to hyperlink pages within the website but a number of different syntaxes are available for creating such links. Wikipedia was launched by Jimmy Wales and Larry Sanger in 2001 as a means of collecting and summarizing human knowledge in every major language. As of April 2008, Wikipedia had over 10 million articles in 253 languages. With so many articles, it is the largest encyclopedia ever assembled. Wikipedia articles are written collaboratively by volunteers, and any visitor can modify the content of article. Any modification must be accepted by the editors of Wikipedia otherwise the article will be reverted to the previous content. Along with popularity, Wikipedia is also criticized for systematic bias and inconsistency since the modifications must be cleared by the editors. Critics also argue that it’s open nature and the lack of proper sources for many articles makes it unreliable. Searching in Wikipedia To search for a particular article in Wikipedia, you can use the search box in the home page of wikipedia.org.Wikipedia classifies its articles in different sub-domains according to language; “en.wikipedia.org” contains articles in English language whereas “es.wikipedia.org” contains Spanish articles. Whenever you select “english” language in the dropdown box, the related articles will be searched over “en.wikipedia.org” and so on for the another language. You can also search the articles of Wikipedia from a remote server. For this, you have to send the language and search parameters to http://www.wikipedia.org/search-redirect.php via the GET method Creating a Wiki Seek Widget Up till now, we’ve looked at the background concept of Wikipedia. Now, let’s start building the widget. This widget contains a form with three components. A textbox where the visitors enters the search keyword, a dropdown list which contains the language of the article and finally a submit button to search the articles of Wikipedia. By the time we’re done, you should have a widget that looks like this: Concept for creating form Before looking at the JavaScript code, first let’s understand the architecture of the form with the parameters to be sent for searching Wikipedia. The request should be sent to http://www.wikipedia.org/search-redirect.php via the GET method. <form action="http://www.wikipedia.org/search-redirect.php" ></form> If you don’t specify the method attribute in the form, the form uses GET, which is the default method. After creating the form element, we need to add the textbox inside the above form with the name search because we’ve to send the search keyword in the name of search parameter. <input type="text" name="search" size="20" /> After adding the textbox for the search keyword, we need to add the dropdown list which contains the language of the article to search. The name of this dropdown-list should be language as we’ve to send the language code to the above URL in the language parameter. These language codes are two or three letter codes specified by ISO. ISO has assigned three letter language codes for most of the popular languages of the world. And, there are a few languages that are represented by two letter ISO codes. For example, eng and en are the three and two letter language code for English. Some of the article languages of Wikipedia don’t have ISO codes, and you have to find the value of the language parameter from Wikipedia. For example, articles in the Alemannisch language is als. Here is the HTML code for constructing a dropdown list in major languages : <select name="language"><option value="de" >Deutsch</option><option value="en" selected="selected">English</option><option value="es" >Español</option><option value="eo" >Esperanto</option><option value="fr" >Français</option><option value="it" >Italiano</option><option value="hu" >Magyar</option><option value="nl" >Nederlands</option></select> As you can see in the above dropdown list, English is the default language selected. Now, we just need to add a submit button in the above form to complete the form for searching the article in wikipedia. <input type="submit" name="go" value="Search" title="Search in wikipedia" /> Put all the HTML code together to create the form. JavaScript Code As we’ve already got the background concept of the HTML form, we just have to use the document.write() to output the HTML to the web browser. Here is the JavaScript code to create the Wiki Seek Widget : document.write('<div>');document.write('<form action="http://www.wikipedia.org/search-redirect.php" >');document.write('<input type="text" name="search" size="20" />');document.write('&nbsp;<select name="language">');document.write('<option value="de" >Deutsch</option>');document.write('<option value="en" selected="selected">English</option>');document.write('<option value="es" >Español</option>');document.write('<option value="eo" >Esperanto</option>');document.write('<option value="fr" >Français</option>');document.write('<option value="it" >Italiano</option>');document.write('<option value="hu" >Magyar</option>');document.write('<option value="nl" >Nederlands</option>');document.write('</select>');document.write('&nbsp;<input type="submit" name="go" value="Search" title="Search in wikipedia" />');document.write('</form>');document.write('</div>'); In the above code, I’ve used division (div) as the container for the HTML form. I’ve also saved the above code in a wiki_seek.js file. The above JavaScript code displays a non-stylish widget. To make a stylish widget, you can use style property in the input elements of the form. Using Wiki Seek widget To use this wiki seek widget we’ve to follow these steps: First of all, we need to upload the above wiki_seek.js to a web server so that it can be used by the client websites. Let’s suppose that is uploaded and placed in the URL : http://www.widget-server.com/wiki_seek.js Now, we can widget in any web pages by placing the following JavaScript Code in the website. <script type="text/javascript" language="javascript"src="http://www.widget-server.com/wiki_seek.js"></script> The Wiki Seek widget is displayed in any part of web page, where you place the above code.
Read more
  • 0
  • 0
  • 3687

article-image-implementing-document-management-alfresco-3-part2
Packt
14 Oct 2009
4 min read
Save for later

Implementing Document Management in Alfresco 3- part2

Packt
14 Oct 2009
4 min read
Library services Library services are common document management functions for controlling the users through permissions, for creating multiple instances of a document(versioning), and for providing users with access into a document to make the changes (checking-in or checking-out). Versioning You might have more than one person who can edit a document. What if somebody edits a document and removes a useful piece of information? Well, you can make use of the versioning features of Alfresco to resolve such issues. Versioning allows the history of previous versions of a content to be kept. The content needs to be Versionable, in order for versions to be kept. You can enable versioning in four different ways: Individually: To enable versioning for an individual content object item, go to the View Details page and click on the Allow Versioning link. The next screenshot illustrates how to enable versioning on an individual content item. Using Smart Spaces: A business rule can be set for a space to allow versioning of all of the content or selected content within that space. By Type: By default, versioning is disabled for all of the content types in the Alfresco content model. Versioning can be enabled for a specific content type, irrespective of the location of the content. Globally: Alfresco can be configured globally to enable versioning for all content throughout the site. Enable versioning for sample file that you have already uploaded to the system. Go to the Intranet > Marketing Communications > Switch to open source ECM > 02_Drafts space and view the details of Alfresco_CIGNEX.doc file. Click on the Allow Versioning link to enable versioning, as shown in the following screenshot. You will immediately notice that a version with a version number of 1.0 is created. At the time of writing this article (Alfresco version 3.1), reverting back to an older version of the content is not supported. There is a plan to support this feature in future releases of Alfresco. The workaround is to download the older version and upload it again as the current version. For a checked out content, the version is updated when the content is checked in. The version number is incremented from the version number of the content object that was checked out. Auto Versioning Auto versioning can be enabled by editing the content properties and selecting the Auto Version checkbox. If auto versioning is enabled, then each Save of the content results in an incremented version number, when the content is edited directly from the repository. Each Update (upload) of the content also results in a new version (with an incremented version number) being created. If auto versioning is not enabled, then the version number is incremented only when the content is checked in. Check In and Check Out By using the versioning feature, you can ensure that all of the changes made to a document are saved. You might have more than one person who can edit a document. What if two people edit a document at once, and you get into a mess with two new versions? To resolve this issue, you'll need to use the library services. Library services provide the ability to check out a document, reserving it for one user to edit, while others can only access the document in read-only mode. Once the necessary changes have been made to the document, the user checks in the document, and can either replace the original, or create a new version of the original. Check Out locks the item and creates a working copy that can be edited (both the content and the details). Check In replaces the original item with the working copy, and releases the lock.
Read more
  • 0
  • 0
  • 1993

article-image-building-friend-networks-django-10
Packt
14 Oct 2009
6 min read
Save for later

Building Friend Networks with Django 1.0

Packt
14 Oct 2009
6 min read
An important aspect of socializing in our application is letting users to maintain their friend lists and browse through the bookmarks of their friends. So, in this section we will build a data model to maintain user relationships, and then program two views to enable users to manage their friends and browse their friends' bookmarks. Creating the friendship data model Let's start with the data model for the friends feature. When a user adds another user as a friend, we need to maintain both users in one object. Therefore, the Friendship data model will consist of two references to the User objects involved in the friendship. Create this model by opening the bookmarks/models.py file and inserting the following code in it: class Friendship(models.Model): from_friend = models.ForeignKey( User, related_name='friend_set' ) to_friend = models.ForeignKey( User, related_name='to_friend_set' ) def __unicode__(self): return u'%s, %s' % ( self.from_friend.username, self.to_friend.username ) class Meta: unique_together = (('to_friend', 'from_friend'), ) The Friendship data model starts with defining two fields that are User objects: from_friend and to_friend. from_friend is the user who added to_friend as a friend. As you can see, we passed a keyword argument called related_name to both the fields. The reason for this is that both fields are foreign keys that refer back to the User data model. This will cause Django to try to create two attributes called friendship_set in each User object, which would result in a name conflict. To avoid this problem, we provide a specific name for each attribute. Consequently, each User object will contain two new attributes: user.friend_set, which contains the friends of this user and user.to_friend_set, which contains the users who added this user as a friend. Throughout this article, we will only use the friend_set attribute, but the other one is there in case you need it . Next, we defined a __unicode__ method in our data model. This method is useful for debugging. Finally, we defined a class called Meta. This class may be used to specify various options related to the data model. Some of the commonly used options are: db_table: This is the name of the table to use for the model. This is useful when the table name generated by Django is a reserved keyword in SQL, or when you want to avoid conflicts if a table with the same name already exists in the database. ordering: This is a list of field names. It declares how objects are ordered when retrieving a list of objects. A column name may be preceded by a minus sign to change the sorting order from ascending to descending. permissions: This lets you declare custom permissions for the data model in addition to add, change, and delete permissions. Permissions should be a list of two-tuples, where each two-tuple should consist of a permission codename and a human-readable name for that permission. For example, you can define a new permission for listing friend bookmarks by using the following Meta class: class Meta: permissions = ( ('can_list_friend_bookmarks', 'Can list friend bookmarks'), ) unique_together: A list of field names that must be unique together. We used the unique_together option here to ensure that a Friendship object is added only once for a particular relationship. There cannot be two Friendship objects with equal to_friend and from_friend fields. This is equivalent to the following SQL declaration: UNIQUE ("from_friend", "to_friend") If you check the SQL generated by Django for this model, you will find something similar to this in the code. After entering the data model code into the bookmarks/models.py file, run the following command to create its corresponding table in the database: $ python manage.py syncdb Now let's experiment with the new model and see how to store and retrieve relations of friendship. Run the interactive console using the following command: $ python manage.py shell Next, retrieve some User objects and build relationships between them (but make sure that you have at least three users in the database): >>> from bookmarks.models import *>>> from django.contrib.auth.models import User>>> user1 = User.objects.get(id=1)>>> user2 = User.objects.get(id=2)>>> user3 = User.objects.get(id=3)>>> friendship1 = Friendship(from_friend=user1, to_friend=user2)>>> friendship1.save()>>> friendship2 = Friendship(from_friend=user1, to_friend=user3)>>> friendship2.save() Now, user2 and user3 are both friends of user1. To retrieve the list of Friendship objects associated with user1, use: >>> user1.friend_set.all()[<Friendship: user1, user2>, <Friendship: user1, user3>] (The actual usernames in output were replaced with user1, user2, and user3 for clarity.) As you may have already noticed, the attribute is named friend_set because we called it so using the related_name option when we created the Friendship model. Next, let's see one way to retrieve the User objects of user1's friends: >>> [friendship.to_friend for friendship in user1.friend_set.all()][<User: user2>, <User: user3>] The last line of code uses a Python feature called "list" comprehension to build the list of User objects. This feature allows us to build a list by iterating through another list. Here, we built the User list by iterating over a list of Friendship objects. If this syntax looks unfamiliar, please refer to the List Comprehension section in the Python tutorial. Notice that user1 has user2 as a friend, but the opposite is not true. >>> user2.friend_set.all() [] In other words, the Friendship model works only in one direction. To add user1 as a friend of user2, we need to construct another Friendship object. >>> friendship3 = Friendship(from_friend=user2, to_friend=user1)>>> friendship3.save()>>> user2.friend_set.all() [<Friendship: user2, user1>] By reversing the arguments passed to the Friendship constructor, we built a relationship in the other way. Now user1 is a friend of user2 and vice-versa. Experiment more with the model to make sure that you understand how it works. Once you feel comfortable with it, move to the next section, where we will write views to utilize the data model. Things will only get more exciting from now on!
Read more
  • 0
  • 0
  • 9485
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 €18.99/month. Cancel anytime
article-image-testing-your-jboss-drools-business-rules-using-unit-testing
Packt
14 Oct 2009
5 min read
Save for later

Testing your JBoss Drools Business Rules using Unit Testing

Packt
14 Oct 2009
5 min read
What is unit testing? A good enterprise computer system should be built as if it was made of Lego bricks. Your rules are only a piece of the puzzle. You'll need to go back to the Lego box to get pieces that talk to the database, make web pages, talk to other systems that you may have in your company (or organization), and so on. Just as Lego bricks can be taken apart and put together in many different ways, the components in a well-designed system should be reusable in many different systems. Before you use any of these components (or 'bricks') in your system, you will want to be sure that they work. For Lego bricks this is easy—you can just make sure that none of the studs are broken. For components this is a bit harder—often, you can neither see them, nor do you have any idea whether their inputs and outputs are correct. Unit testing makes sure that all of the component pieces of your application work, before you even assemble them. You can unit test manually, but just like FIT requirements testing, you're going to 'forget' to do it sooner or later. Fortunately, there is a tool to automate your unit tests known as Junit (for Java; there are also versions for many other languages, such as .Net). Like Drools and FIT, Junit is open source. Therefore, we can use it on our project without much difficulty. Junit is integrated into the JBoss IDE and is also pretty much an industry standard, so it's easy to find more information on it. A good starting point is the project's home page at http://www.Junit.org. The following points can help you to decide when to use unit testing, and when to use the other forms of testing that we talked about: If you're most comfortable using Guvnor, then use the test scenarios within Guvnor. As you'll see shortly, they're very close to unit tests. If the majority of your work involves detailing and signing off against the requirement documents, then you should consider using FIT for Rules. If you're most comfortable using Java, or some other programming language, then you're probably using (J)unit tests already—and we can apply these unit tests to rule testing. In reality, your testing is likely to be a mix of two or three of these options. Why unit test? An important point to note is that you've already carried out unit testing in the rules that we wrote earlier. OK, it was manual unit testing, but we still checked that our block of rules produced the outcome that we expected. All we're talking about here is automating the process. Unit testing also has the advantage of documenting the code because it gives a working example of how to call the rules. It also makes your rules and code more reusable. You've just proved (in your unit test) that you can call your code on a standalone basis, which is an important first step for somebody else to be able to use it again in the future. You do want your rules to be reused, don't you? Unit testing the Chocolate Shipments sample As luck would have it, our Chocolate Shipments example also contains a unit test. This is called DroolsUnitTest.java, and it can be found in the test/java/net/firstpartners/chap7 folder. Running the Junit test is similar to running the samples. In the JBoss IDE Navigator or package explorer, we select DroolsUnitTest.java, right-click on it, and then select Run as | Junit test from the shortcut menu. All being well, you should see some messages appear on the console. We're going to ignore the console messages; after all, we're meant to be automating our testing, not manually reading the console. The really interesting bit should appear in the IDE— the Junit test result, similar to the screenshot shown below. If everything is OK, we should see the green bar displayed—success! We've run only one unit test, so the output is fairly simple. From top to bottom we have: the time it took to run the test; the number of errors and failures (both zero—we'll explain the difference shortly, but having none of them is a good thing), the green bar (success!), and a summary of the unit tests that we've just run (DroolsUnitTest). If you were running this test prior to deploying to production, all you need to know is that the green bar means that everything is working as intended. It's a lot easier than inspecting the code line by line. However, as this is the first time that we're using a unit test, we're going to step through the tests line by line. A lot of our Junit test is similar to MultipleRulesExample.java. For example, the unit test uses the same RuleRunner file to load and call the rules. In addition, the Junit test also has some automated checks (asserts) that give us the green bar when they pass, which we saw in the previous screenshot.
Read more
  • 0
  • 0
  • 7608

article-image-managing-posts-wordpress-plugin
Packt
14 Oct 2009
8 min read
Save for later

Managing Posts with WordPress Plugin

Packt
14 Oct 2009
8 min read
Programming the Manage panel The Manage Posts screen can be changed to show extra columns, or remove unwanted columns in the listing. Let's say that we want to show the post type—Normal, Photo, or Link. Remember the custom field post-type that we added to our posts? We can use it now to differentiate post types. Time for action – Add post type column in the Manage panel We want to add a new column to the Manage panel, and we will call it Type. The value of the column will represent the post type—Normal, Photo, or Link. Expand the admin_menu() function to load the function to handle Manage Page hooks: add_submenu_page('post-new.php', __('Add URL',$this->plugin_domain) , __('URL', $this->plugin_domain) , 1 ,'add-url', array(&$this, 'display_form') );// handle Manage page hooksadd_action('load-edit.php', array(&$this, 'handle_load_edit') );} Add the hooks to the columns on the Manage screen: // Manage page hooksfunction handle_load_edit(){ // handle Manage screen functions add_filter('manage_posts_columns', array(&$this, 'handle_posts_columns')); add_action('manage_posts_custom_column', array(&$this, 'handle_posts_custom_column'), 10, 2);} Then implement the function to add a new Column, remove the author and replace the date with our date format: // Handle Column headerfunction handle_posts_columns($columns){ // add 'type' column $columns['type'] = __('Type',$this->plugin_domain); return $columns;} For date key replacement, we need an extra function:     function array_change_key_name( $orig, $new, &$array ){ foreach ( $array as $k => $v ) $return[ ( $k === $orig ) ? $new : $k ] = $v; return ( array ) $return;} And finally, insert a function to handle the display of information in that column: // Handle Type column displayfunction handle_posts_custom_column($column_name, $id){ // 'type' column handling based on post type if( $column_name == 'type' ) { $type=get_post_meta($id, 'post-type', true); echo $type ? $type : __('Normal',$this->plugin_domain); }} Don't forget to add the Manage page to the list of localized pages: // pages where our plugin needs translation$local_pages=array('plugins.php', 'post-new.php', 'edit.php');if (in_array($pagenow, $local_pages)) As a result, we now have a new column that displays the post type using information from a post custom field. What just happened? We have used the load-edit.php action to specify that we want our hooks to be assigned only on the Manage Posts page (edit.php). This is similar to the optimization we did when we loaded the localization files. The handle_posts_columns is a filter that accepts the columns as a parameter and allows you to insert a new column: function handle_posts_columns($columns){ $columns['type'] = __('Type',$this->plugin_domain); return $columns;} You are also able to remove a column. This example would remove the Author column: unset($columns['author']); To handle information display in that column, we use the handle_posts_custom_column action. The action is called for each entry (post), whenever an unknown column is encountered. WordPress passes the name of the column and current post ID as parameters. That allows us to extract the post type from a custom field: function handle_posts_custom_column($column_name, $id){ if( $column_name == 'type' ) { $type=get_post_meta($id, 'post-type', true); It also allows us to print it out: echo $type ? $type : __('Normal',$this->plugin_domain); }} Modifying an existing column We can also modify an existing column. Let's say we want to change the way Date is displayed. Here are the changes we would make to the code: // Handle Column headerfunction handle_posts_columns($columns){ // add 'type' column $columns['type'] = __('Type',$this->plugin_domain); // remove 'author' column //unset($columns['author']); // change 'date' column $columns = $this->array_change_key_name( 'date', 'date_new', $columns ); return $columns;}// Handle Type column displayfunction handle_posts_custom_column($column_name, $id){ // 'type' column handling based on post type if( $column_name == 'type' ) { $type=get_post_meta($id, 'post-type', true); echo $type ? $type : __('Normal',$this->plugin_domain); } // new date column handling if( $column_name == 'date_new' ) { the_time('Y-m-d <br > g:i:s a'); } }function array_change_key_name( $orig, $new, &$array ){ foreach ( $array as $k => $v ) $return[ ( $k === $orig ) ? $new : $k ] = $v; return ( array ) $return;} The example replaces the date column with our own date_new column and uses it to display the date with our preferred formatting. Manage screen search filter WordPress allows us to show all the posts by date and category, but what if we want to show all the posts depending on post type? No problem! We can add a new filter select box straight to the Manage panel. Time for action – Add a search filter box Let's start by adding two more hooks to the handle_load_edit() function. The restrict_manage_posts function draws the search box and the posts_where alters the database query to select only the posts of the type we want to show. // Manage page hooksfunction handle_load_edit(){ // handle Manage screen functions add_filter('manage_posts_columns', array(&$this, 'handle_posts_columns')); add_action('manage_posts_custom_column', array(&$this, 'handle_posts_custom_column'), 10, 2); // handle search box filter add_filter('posts_where', array(&$this, 'handle_posts_where')); add_action('restrict_manage_posts', array(&$this, 'handle_restrict_manage_posts'));} Let's write the corresponding function to draw the select box: // Handle select box for Manage pagefunction handle_restrict_manage_posts(){ ?> <select name="post_type" id="post_type" class="postform"> <option value="0">View all types</option> <option value="normal" <?php if( $_GET['post_type']=='normal') echo 'selected="selected"' ?>><?php _e ('Normal',$this->plugin_domain); ?></option> <option value="photo" <?php if( $_GET['post_type']=='photo') echo 'selected="selected"' ?>><?php _e ('Photo',$this->plugin_domain); ?></option> <option value="link" <?php if( $_GET['post_type']=='link') echo 'selected="selected"' ?>><?php _e ('Link',$this->plugin_domain); ?></option> </select> <?php} And finally, we need a function that will change the query to retrieve only the posts of the selected type: // Handle query for Manage pagefunction handle_posts_where($where){ global $wpdb; if( $_GET['post_type'] == 'photo' ) { $where .= " AND ID IN (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='post-type' AND metavalue='".__ ('Photo',$this->plugin_domain)."' )"; } else if( $_GET['post_type'] == 'link' ) { $where .= " AND ID IN (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='post-type' AND metavalue='".__ ('Link',$this->plugin_domain)."' )"; } else if( $_GET['post_type'] == 'normal' ) { $where .= " AND ID NOT IN (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='post-type' )"; } return $where;} What just happened? We have added a new select box to the header of the Manage panel. It allows us to filter the post types we want to show. We added the box using the restrict_manage_posts action that is triggered at the end of the Manage panel header and allows us to insert HTML code, which we used to draw a select box. To actually perform the filtering, we use the posts_where filter, which is run when a query is made to fetch the posts from the database. if( $_GET['post_type'] == 'photo' ){ $where .= " AND ID IN (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='post-type' AND metavalue='".__ ('Photo',$this->plugin_domain)."' )"; If a photo is selected, we inspect the WordPress database postmeta table and select posts that have the post-type key with the value, Photo. At this point, we have a functional plugin. What we can do further to improve it is to add user permissions checks, so that only those users allowed to write posts and upload files are allowed to use it. Quick referencemanage_posts_columns($columns): This acts as a filter for adding/removing columns in the Manage Posts panel. Similarly, we use the function, manage_pages_columns for the Manage Pages panel.manage_posts_custom_column($column, $post_id): This acts as an action to display information for the given column and post. Alternatively, manage_pages_custom_column for Manage Pages panel.posts_where($where): This acts as a filter for the where clause in the query that gets the posts.restrict_manage_posts: This acts as an action that runs at the end of the Manage panel header and allows you to insert HTML.
Read more
  • 0
  • 0
  • 3365

article-image-anatomy-typo3-extension
Packt
14 Oct 2009
8 min read
Save for later

Anatomy of TYPO3 Extension

Packt
14 Oct 2009
8 min read
TYPO3 Extension Categories All TYPO3 extensions are classified into several predefined categories. These categories do not actually differentiate the extensions. They are more like hints for users about extension functionality. Often, it is difficult for the developer to decide which category an extension should belong to. The same extension can provide PHP code that fits into many categories. An extension can contain Frontend (FE) plugins, Backend (BE) modules, static data, and services, all at once. While it is not always the best solution to make such a monster extension, sometimes it is necessary. In this case, the extension author should choose the category that best fits the extension's purpose. For example, if an extension provides a reservation system for website visitors, it is probably FE related, even if it includes a BE module for viewing registrations. If an extension provides a service to log in users, it is most likely a service extension, even if it logs in FE users. It will be easier to decide where the extension fits after we review all the extension categories in this article. Choosing a category for an extension is mandatory. While the TYPO3 Extension Manager can still display extensions without a proper category, this may change and such extensions may be removed from TER (TYPO3 Extension Repository) in the future. The extension category is visible in several places. Firstly, extensions are sorted and grouped by category in the Extension Manager. Secondly, when an extension is clicked in the Extension Manager, its category is displayed in the extension details. If an extension's category is changed from one to another, it does not affect extension functionality. The Extension Manager will show the extension in a different category. So, categories are truly just hints for the user. They do not have any significant meaning in TYPO3. So, why do we care and talk about them? We do so because it is one of those things that make a good extension. If an extension developer starts making a new extension, they should do it properly from the very beginning. And one of the first things to do properly is to decide where an extension belongs. So, let's look into the various extension categories in more detail. Category: Frontend Extensions that belong to the Frontend category provide functionality related to the FE. It does not mean that they generate website output. Typically, extensions from the FE category extend FE functionality in other ways. For example, they can transform links from standard /index.php?id=12345 to /news/new-typo3-bookis-out.htm. Or, they can filter output and clean it up, compress, add or remove HTML comments, and so on. Often, these extensions use one or more hooks in the FE classes. For example, TSFE has hooks to process submitted data, or to post‑filter content (and many others). Examples of FE extensions are source_optimization and realurl. Category: Frontend plugins Frontend plugins is possibly the most popular extension category. Extensions from this category typically generate content for the website. They provide new content objects, or extend existing types of content objects. Typical examples of extensions from the Frontend plugins category are tt_news, comments, ratings, etc. Category: Backend Extensions from the Backend category provide additional functionality for TYPO3 Backend. Often, they are not seen inside TYPO3 BE, but they still do some work. Examples of such extensions are various debugging extensions (such as rlmp_ filedevlog) and extensions that add or change the pop-up menu in the BE (such as extra_page_cm_options system extension). This category is rarely used because extensions belonging to it are very special. Category: Backend module Extensions from this category provide additional modules for TYPO3 BE. Typical examples are system extensions such as beuser (provides Tools | Users module) or tstemplate (provides Web | Template module). Category: Services Services extend core TYPO3 functionality. Most known and most popular service extensions are authentication services. TYPO3 Extension Repository contains extensions to authenticate TYPO3 users over phpBB, vBulletine, or LDAP user databases. Services are somewhat special and will not be covered in this article. Extension developers who are interested in the development of services should consult appropriate documentation on the typo3.org website. Category: Examples Extensions from this category provide examples. There are not many, and are typically meant for beginners or for those who want to learn a specific feature of TYPO3, or features that another TYPO3 extension provides. Category: Templates Extensions from this category provide templates. Most often, they have preformatted HTML and CSS files in order to use them with the templateautoparser extension or map with TemplaVoila. Sometimes, they also contain TypoScript templates, for example, tmpl_andreas01 and tmpl_andreas09 extensions. Once installed, they provide pre‑mapped TemplaVoila templates for any website, making it easy to have a website up and running within minutes. Category: Documentation Documentation extensions provide TYPO3 documentation. Normally, TYPO3 extensions contain documentation within themselves, though sometimes, a document is too big to be shipped with extensions. In such cases, it is stored separately. There is an unofficial convention to start an extension key for such extensions with the doc_ prefix (that is, doc_indexed_search). Category: Miscellaneous Everything else that does not fit into any other category goes here; typical examples are skins. But do not put your extension here if you just cannot decide where it fits. In all probability, it should go into one of the other categories, not into Miscellaneous. Extension Files TYPO3 extensions consist of several files. Some of these files have predefined names, and serve a predefined purpose. Others provide code or data but also follow certain naming conventions. We will review all the predefined files in this article and see what purpose they serve. We will look into the files according to their logical grouping. While reading this section, you can take any extension from the typo3conf/ext/ directory at your TYPO3 installation and check the contents of each discussed file. Some files may be missing if the extension does not use them. There is only one file which is mandatory for any TYPO3 extension, ext_emconf.php. We will start examining files starting from this one. Common Files All files from this group have predefined names, and TYPO3 expects to find certain information in them. Hacking these files to serve another purpose or to have a different format usually results in incompatibility with other extensions or TYPO3 itself. While it may work in one installation, it may fail in others. So, avoid doing anything non-standard with these files. ext_emconf.php This is the only required file for any TYPO3 extension. And this is the only file that should be modified with great care. If it is corrupt, TYPO3 will not load any extension. This file contains information on the TYPO3 Extension Manager. This information tells the Extension Manager what the extension does, provides, requires, and conflicts with. It also contains a checksum for each file in the extension. This checksum is updated automatically when the extension is sent to TER (TYPO3 Extension Repository). The server administrator can easily check if anyone has hijacked the extension files by looking into the extension details in the Extension Manager. The modified files are shown in red. Here is a tip. If you (as an extension developer) send your own extension directly to the customer (bypassing TER upload), or plan to use it on your own server, always update the ext_emconf.php file using the Backup/Delete function of the Extension Manager. This will ensure that TYPO3 shows up-to-date data in the Extension Manager. Here is an example of a ext_emconf.php file from the smoothuploader extension: <?php ############################################################# # Extension Manager/Repository config file for ext: ↵ # "smoothuploader" # Auto generated 29-02-2008 12:36 # Manual updates: # Only the data in the array - anything else is removed by ↵ # next write. # "version" and "dependencies" must not be touched! ############################################################# $EM_CONF[$_EXTKEY] = array( 'title' => 'SmoothGallery Uploader', 'description' => 'Uploads images to SmoothGallery', 'category' => 'plugin', 'author' => 'Dmitry Dulepov [Netcreators]', 'author_email' => 'dmitry@typo3.org', 'shy' => '', 'dependencies' => 'rgsmoothgallery', 'conflicts' => '', 'priority' => '', 'module' => '', 'state' => 'beta', 'internal' => '', 'uploadfolder' => 0, 'createDirs' => '', 'modify_tables' => 'tx_rgsmoothgallery_image', 'clearCacheOnLoad' => 0, 'lockType' => '', 'author_company' => 'Netcreators BV', 'version' => '0.3.0', 'constraints' => array( 'depends' => array( 'rgsmoothgallery' => '1.1.1-', ), 'conflicts' => array( ), 'suggests' => array( ), ), '_md5_values_when_last_written' => 'a:12:{s:9:...;}', 'suggests' => array( ), ); ?> The variable _md5_values_when_last_written is shortened in the listing above.
Read more
  • 0
  • 0
  • 3221

article-image-creating-better-selling-experience-drupal-e-commerce
Packt
14 Oct 2009
5 min read
Save for later

Creating a Better Selling Experience with Drupal e-Commerce

Packt
14 Oct 2009
5 min read
Doug is an avid dinosaur and model enthusiast, and runs his own shop and museum selling model dinosaurs and offering information and facts on various dinosaurs. For the purpose of this article, we will create an e-commerce website named 'Doug's Dinos!' for Doug and his business. Making Things Easier Although Doug's store is relatively simple for his customers to use, it is missing three key features that would make their time on the website easier, these are: An overview of the shopping cart Search features Ability to auto-create user accounts At the moment, without a search feature the only way for users to find products is by manually browsing through the website and stumbling across a product they like. Adding a Shopping Cart We can add a shopping cart to our theme so that customers can continue browsing the website but still know how much is in their shopping cart, and easily get to it later. To add this block, we need to go to the Blocks section, which is under Site Building within the Administer area. Within the Blocks section, we need to ensure we have all our themes selected (or do this for each theme we are using) and then change the Region of the Shopping cart to the left sidebar. Once we click on the Save blocks button, the shopping cart block is displayed in our theme: Adding Search Capabilities Doug tested the website with a few friends and family members, and their main issue with it was the difficulty in finding products they wanted. The first thing we need to do is install the Search module, which is grouped under the Core - optional section of Modules in the Administer area. With the module installed, we now need to enable the Search feature from the Blocks section; otherwise the search box won't be displayed on the website. We can select this feature by going to Administer | Site Building | Blocks, then set it up in the same way as for the shopping cart and save the settings. We now have a search box on our website under the header but above the main menu! Let's try searching for one of our products, for instance T-Rex. Notice something? No results found! This seems quite strange as we have a product with T-Rex in the name, so why didn't we get any results? The reason for this is that Drupal has not yet been indexed. Drupal uses a cron job to create the index of the site. Without the indexing done Search options cannot work. The Search settings under Administer | Site configuration allow us to specify how many pages are indexed per "cron run" and allow us to set the site to be re-indexed. Cron JobsA cron job is a setting on your web host's server (if you have cPanel hosting, it is available under "crontab") that performs tasks at specific times. Drupal has a special page that performs various tasks; this can be called by a cron job so that it regularly opens the page and runs the tasks. This setting depends on having set up a cron job to periodically call the cron.php file. For more information on setting up cron jobs, you should contact your web host. Typically it involves a crontab setting in your hosting control panel such as cPanel. We can manually run the cron task, by opening the cron.php file in our web browser. In this case we just open: http://www.dougsdinos.com/cron.php. Once we have opened this page, let's try searching for T-Rex again. This time we will get some results! Customers will now be able to find products and other content on Doug's website much more easily! Auto-Creating User Accounts If a customer is not a user on our site, we can automatically create a user account for them once they have placed their order; this saves the inconvenience of using an anonymous purchase policy where the user has to log in or register, but it gives the user the added convenience of having their details saved for future orders. This is something Doug wants to enable to make things easier for regular customers on this site. The first thing we need to do is install the module. The module is called EC Useracc and is listed in the E-Commerce Uncategorized group of modules. Now under E-Commerce configuration we have a new option called User Account; let's take a look at it. This has the following settings: Confirmation e-mail Welcome mail Days to confirm expiry The Confirmation e-mail is to see if the customer wants to create a user account; this email expires after the number of days set in the Days to confirmation expiry setting has passed, and the Welcome mail is the email sent when the account is created. These emails can be configured on the Mail page. These settings don't actually enable the feature though; we have installed the module and looked at the global settings, but to actually get it to work we need to set how we would like each product to work in relation to this module. If we go to edit any product, there is a new section, which was not there previously, called User account provision; this is what we need to change. As Doug wants this feature enabled, we need to check the option Create an account for the user when this product is purchased. The other option, Block the user's account when this product expires, relates to using recurring billing in products (mainly non-tangible products i.e. services) such as a customer support contract or a magazine subscription.
Read more
  • 0
  • 0
  • 1455
article-image-creating-your-first-web-page-using-expressionengine-part-1
Packt
14 Oct 2009
8 min read
Save for later

Creating Your First Web Page Using ExpressionEngine: Part 1

Packt
14 Oct 2009
8 min read
Toast for Sale! To demonstrate the power of ExpressionEngine, we are going to use a fictitious business as an example throughout this article. Our website is in the business of selling toast (heated bread with melted butter) online. With this example, we will be able to explore many of the nuances of building a complete website with ExpressionEngine. Though unlikely that we would really want to sell toast over the internet, the concepts of our example should be transferable to any website. In this article, we want to introduce the world to our business, so we are going to create a 'News from the President' webpage. This will allow the President of our company to communicate to customers and investors the latest goings-on in his business. Inside the Control Panel When you first log into the control panel, there are lots of options. Let us take a quick tour of the control panel. First, we will need to log into ExpressionEngine. If you are using XAMPP to follow along with this article, go to http://localhost/admin.php or http://localhost/system/index.php to log in. It is assumed that you are using XAMPP with http://localhost/ addresses. If you are following along on an actual website, substitute http://localhost/ for your website domain (for example, http://www.example.com/). It is required to move the login page to the root of our website to mask the location of our system directory The first page we see is the CP Home. We can return to this page anytime by selecting CP Home from the menu at the top-right of the screen, above the main menu. In the left column, we have EllisLab News Feed. Below, we have Most Recent Weblog Entries as well as any Recent Comments or trackbacks visitors may have left. In our case, our site is brand new, so there will be no recent comments or trackbacks, and only 1 recent weblog entry (Getting Started with ExpressionEngine). Clicking on the link will take you directly to that entry. On the right, there is a Bulletin Board (a way for you to pass messages to other members of your control panel), the Site Statistics and a Notepad (we can write anything here, and it will be available every time we log-in). Across the top is the main menu bar, and at the top-right are links to your website (My Site), this page (CP Home), the ExpressionEngine user-guide (User Guide), and to log-out (Log-out). The Publish and Edit links in the main menu bar are where you can create new entries and edit existing entries. The Templates link is where we can create new templates and edit existing templates. We will spend most of our time in these sections. The Communicate tab is where we can manage bulk-emails to our website members. At this time we do not have any members to email (other than ourselves), but as our site grows larger, this feature can be a useful communication/marketing tool. Be careful to avoid sending unsolicited bulk emails (or spam) using this feature. In many countries, there are laws governing what can or cannot be done. In the United States, commercial emails must meet very specific guidelines set by the Federal Trade Commission (http://www.ftc.gov/spam/). The Modules tab is where we can manage all the modules that come with ExpressionEngine, as well as optional third-party modules that we may wish to install. We can download additional modules from http://expressionengine.com/downloads/addons/category/modules/. The My Account tab is where we can edit our login preferences, including our username and password. We can also edit the look and feel of the control panel home page from this screen, as well as send private messages to other members. Much of this page is irrelevant when we are the only member of the site (as we are right now). The Admin tab is where most of the configuration of ExpressionEngine takes place, and we will spend a lot of time here. By default, most of the ExpressionEngine settings are already properly set, but feel free to browse and explore all the options that are available. Full documentation on each of the options is available at http://expressionengine.com/docs/cp/admin/index.html. This concludes our brief tour of ExpressionEngine. Now we are going to delve into one of the most important parts of the control panel—templates. Templates and URLs The basic concept in ExpressionEngine is that of a template. Go to any ExpressionEngine-powered website and you will undoubtedly be looking at a template. Templates are what the outside world sees. At its most basic, a template in ExpressionEngine is a HTML (or CSS or JavaScript) file. If we wanted to, we could use a template exactly like a HTML file, without any problems. We could create an entire website without ever using any other part of ExpressionEngine. However, we can take templates a lot further than that. By using ExpressionEngine tags inside our templates, we can take advantage of all the features of ExpressionEngine and combine it with all the flexibility that HTML and CSS offers in terms of layout and design. We are not limited to pre-defined 'cookie-cutter' templates that have been carefully adapted to work with ExpressionEngine. This is why ExpressionEngine is very popular with website designers. On the flip side, this is also why there is such a learning curve with ExpressionEngine. There is no point-and-click interface to change the look and feel of your website; you have to have some experience with HTML to get the most out of it. Let us take a closer look at templates and how they relate to URLs: If you are not already logged in, log into ExpressionEngine at either http://localhost/admin.php or http://www.example.com/admin.php. Click on the Templates button on the top of the screen. Templates are stored in groups. There is no 'right' way to group templates—some sites have all their templates in a single group and other sites have lots of template groups. We are going to create a new template group for each section of our website. ExpressionEngine does come pre-installed with two template groups: the site template group and the search template group. As a new user, it is best not to delete these template groups in case you want to refer to them later. In the next screen we can give our template group a name; let us use toast. There is an option to Duplicate an Existing Template Group which copies all the templates from one template group into our new template group. This can be useful if we are creating one template group that will work very similarly to the one that we already created, but as this is our first template group, we are going to start from scratch. Checking the box Make the index template in this group your site's home page? means that visitors will see the toast website in place of the ExpressionEngine example site. If you are using the XAMPP test server, go ahead and check this box. Hit Submit to create the template group. We will be returned to the Template Management screen. A message will appear saying Template Group Created, and the new template will appear in the box of groups on the left-hand side. Left-click on the New Template group in the Choose Group box on the left-hand side. Each template group comes with an initial template, called index. Remembering that a template is like an HTML file, a template group is like a directory on our server. The index template is the equivalent of the index.html file—when a visitor visits our template group, the index template is displayed first. For that reason, the index template cannot be renamed or deleted. Let us edit the index template to see what it does. Click on the word index. A template is essentially just text (although it usually contains HTML, CSS, or ExpressionEngine code). When we first create a template, there is no text, and therefore all we see is an empty white box. Let us write something in the box to demonstrate how templates are seen by visitors. Type in a sentence and click Update and Finished. Just like HTML files and directories, templates and template groups relate directly to the URL that visitors see. In the URL http://www.example.com/index.php/toast/index, the index.php is what distinguishes this as an ExpressionEngine page. Then comes the template group name, in our case called toast. Finally, we have the template name, in this case index. Go to the previous URL (with or without the index.php as appropriate, for example, http://www.example.com/toast/index or http://localhost/toast/index) and the template we just edited should appear. Now try typing the template group without specifying which template to load. The index template is always returned. What happens if we do not specify the template group, and just go to our base domain (http://localhost/ or http://www.example.com/)? In this case, the toast template of the default template group is returned. The default template group is indicated on the templates screen with an * before the template group name and underneath the list of template groups.
Read more
  • 0
  • 0
  • 4529

article-image-creating-administration-interface-django-10
Packt
14 Oct 2009
5 min read
Save for later

Creating an Administration Interface with Django 1.0

Packt
14 Oct 2009
5 min read
Activating the administration interface The administration interface comes as a Django application. To activate it, we will follow a simple procedure that is similar to enabling the user authentication system. The administration application is located in the django.contrib.admin package. So the first step is adding the path of this package to the INSTALLED_APPS variable. Open the settings.py file, locate INSTALLED_APPS, and edit it as follows: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.comments', 'django_bookmarks.bookmarks',) Next, run the following command to create the necessary tables for the administration application: $ python manage.py syncdb Now we need to make the administration interface accessible from within our site by adding URL entries for it. The admin application defines many views (as we will see later), so manually adding a separate entry for each view can become a tedious task. Therefore, the admin interface provides a shortcut for this. There is a single object that encapsulates all the admin views. To use it, open the urls.py file and edit it as follows: from django.contrib import adminadmin.autodiscover()urlpatterns = ('', [...] # Admin interface (r'^admin/(.*)', admin.site.root),) Here, we are importing the admin module, calling a method in it, and mapping all the URLs under the path ^admin/ to a view called admin.site.root. This will make the views of the administration interface accessible from within our project. One last thing remains before we see the administration page in action. We need to tell Django what models can be managed in the administration interface. This is done by creating a new file called the admin.py file in the bookmarks directory. Create the bookmarks/admin.py file and add the following code to it: from django.contrib import adminfrom bookmarks.models import *class LinkAdmin(admin.ModelAdmin): passadmin.site.register(Link, LinkAdmin) We created a class derived from the admin.ModelAdmin class and mapped it to the Link model using the admin.site.register method. This effectively tells Django to enable the Link model in the administration interface. The keyword pass means that the class is empty. Later, we will use this class to customize the administration page; so it won't remain empty. Do the same to the Bookmark, Tag, and SharedBookmark models and add it to the bookmarks/admin.py file. Now, create an empty admin class for each of them and register it. The User model is provided by Django and, therefore, we don't have control over it. But fortunately, it already has an Admin class so it's available in the administration interface by default. Next, launch the development server and direct your browser to http://127.0.0.1:8000/admin/. You will be greeted by a login page. The superuser account after writing the database model is the account that you have to use in order to log in: Next, you will see a list of the models that are available to the administration interface. As discussed earlier, only models that have admin classes in the bookmarks/admin.py file will appear on this page. If you click on a model name, you will get a list of the objects that are stored in the database under this model. You can use this page to view or edit a particular object, or to add a new one. The following figure shows the listing page for the Link model: The edit form is generated according to the fields that exist in the model. The Link form, for example, contains a single text field called Url. You can use this form to view and change the URL of a Link object. In addition, the form performs proper validation of fields before saving the object. So if you try to save a Link object with an invalid URL, you will receive an error message asking you to correct the field. The following figure shows a validation error when trying to save an invalid link: Fields are mapped to form widgets according to their type. For example, date fields are edited using a calendar widget, whereas foreign key fields are edited using a list widget, and so on. The following figure shows a calendar widget from the user edit page. Django uses it for date and time fields. As you may have noticed, the administration interface represents models by using the string returned by the __unicode__ method. It was indeed a good idea to replace the generic strings returned by the default __unicode__ method with more helpful ones. This greatly helps when working with the administration page, as well as with debugging. Experiment with the administration pages. Try to create, edit, and delete objects. Notice how changes made in the administration interface are immediately reflected on the live site. Also, the administration interface keeps a track of the actions that you make and lets you review the history of changes for each object. This section has covered most of what you need to know in order to use the administration interface provided by Django. This feature is actually one of the main advantages of using Django. You get a fully featured administration interface from writing only a few lines of code! Next, we will see how to tweak and customize the administration pages. As a bonus, we will learn more about the permissions system offered by Django.
Read more
  • 0
  • 0
  • 5044

article-image-managing-users-and-their-profiles-drupal-6-social-networking
Packt
14 Oct 2009
10 min read
Save for later

Managing Users and their Profiles in Drupal 6 Social Networking

Packt
14 Oct 2009
10 min read
What are we going to do and why? Before we get started, let's have a closer look at what we will be doing, and why. Our users can interact with the web site, and they can have their own blog. Apart from this, there are very few provisions for the users to tell everyone else about themselves, and expand their profiles with something more personal. With a site like ours, it would be useful to know more about our users including: Their pet dinosaur's name Breed of dinosaur Their pet dinosaur's birthday The dinosaur's hobbies and so on Their web address (if they have one) Location / City / Area More information about the user themselves This can be added to user profiles using the Profile module, which is a core module within Drupal, and simply needs to be enabled and configured. Many web sites allow users to upload an image to be associated with their accounts, which could be either a small photo of themselves, or a small image known as an avatar. Drupal allows this, but it has some drawbacks which can be fixed using Gravatar. Gravatar is a social avatar service, whereby users set up their avatars, and other web sites automatically pick up their avatars by sending a request to the Gravatar service with the users' emails. This is convenient for our users, as it saves them having to upload their avatars to our site, and reduces the amount of data stored on our site as well as the data being sent and received from our site. This module needs to be downloaded, installed and configured for our users to make use of its features. With the upload module enabled, users can upload their own avatars directly to the site, if they choose to do so. This is because not all users would be members of Gravatar, nor would they all wish to sign up to a third-party service. With the rise in the number of web sites and social networks that users of the Internet are members of, having to log in to different web sites on a daily basis can put off users if they have to sign up to another web site. OpenID helps prevent this as users need to remember only one username and password. It works by allowing users to login by providing a web address, instead of their usernames and passwords. This web site is their identity with an OpenID provider (maybe it is their own web site or another social network—MySpace and other social networking web sites are OpenID providers). When they log in with these identities, they will be taken to these web sites to log in before being returned to our site. If they have already logged in into their OpenIDs, they will return to the web site as new users. More information on OpenID is available from http://openid.net/. This is a core module which just needs to be enabled. There are two important points to be noted about OpenID. Firstly, it is decentralized, which means log in details are not tied to a specific provider, and secondly, it is offered as an alternative log in method—users without an OpenID (or those who don't know they have an OpenID!) can still log in or sign up as normal. Users have their own blogs which they can use, but they are not personalized blogs. By installing the blog theme module, we can allow our users to select different themes for use in their blogs. This way, visitors to one particular user's blog (for example 'Bob') will see the theme that Bob chose. Once users get to know each other more, they become more interested in each other's posts and topics, and may wish to look up a specific user's posts and contributions. The Tracker module allows users to track one another's contributions to the site. This is a core module, which just needs to be enabled and set up. Now that we have a better idea of what we are going to do, let's get started! Install the modules To make things easier for us, let's install and enable all the relevant modules first. This saves us having to do this again and again at a later stage. The modules which we require are: Profile (a core module) Tracker (a core module) OpenID (a core module) Gravatars (http://drupal.org/project/gravatar) Blog Theme (http://drupal.org/project/blogtheme) We need to download the relevant modules (ensuring we download ones which are compatible with Drupal 6.x), and extract the ZIP files into the /sites/all/modules folder. As we have not downloaded and installed any new modules on our Drupal installation yet, we will need to create the folder modules within the /sites/all/ directory. The reason there are sites/all and a sites/default directories is because Drupal can support multiple web sites running off one installation, and this defines which modules are available to which of the installations. Core modules are located elsewhere, which is why we don't have a modules folder already in this location containing the core modules. Now all the modules just have to be enabled via the Site Building | Modules section of the Administration area. Users, roles, and permissions Let's have a more detailed look at users, roles, and permissions and also how they work. These are all areas of the administration area, within the User management section. The other options within this section (Access rules, Gravatar, Profiles and User settings) will be looked at later in this article. Users When a visitor signs up for our site, a user account is created for him/her. From the Users area, we can view a list of existing users, create new ones and edit them. Within the context of editing a user, not only can we edit their details, such as their usernames or passwords, but we can also suspend their user accounts or delete their user accounts permanently from our social network. We want our site to become popular, which means that we want to have lots of users. When we get lots of users, it will become more difficult to navigate through their list, and this is when searching, sorting, and filtering them come in handy—which is what we are going to look at now. For each user, the user list displays: The username The status of the user account (active or blocked) Roles associated with the account Length of time the user has been a member for The time passed since the user was last active on our site A link to edit the user Viewing / searching / sorting / filtering Clicking the username will take us to their user profile. We can sort the list of users by clicking the heading in any of the columns to sort the list by that column. One particular use of doing this is that we can see all blocked users, ????so we can quickly reactivate an account should we need to, or see who the newest members are. We can also filter the accounts displayed using the Show only users where panel. This allows us to filter the list based on whether the account is active or not, or against specific roles assigned to users. Creating a user At the top of the users page, we have the Add user link. This takes us to the new user page, where we are required to fill out the Username, E-mail address, Password, and Confirm Password again for the user. We can also opt to notify the users of their new accounts, which will send them an email informing them that they have a new account with the Dino Space social network. Editing To edit an account, we just need to click the edit link which corresponds to the account, which takes us to the edit page. We can edit the user's Username, E-mail address, Password, account Status and settings pertaining to modules, which give users additional settings too. Careful!If you edit these settings, the users may not be able to log in to their accounts. If you change a user's Username without his/her request, you should let him/her know through email. Suspending / blocking a user Within the edit page, we have an option entitled Status, which can be set to either Blocked or Active. This would allow us to block a user from accessing our site, for instance if they had been posting inappropriate material repeatedly, even after being contacted and asked to stop. Why block? Why not just delete?If we were to just delete a user who was posting inappropriate material, or doing something we didn't want, then he/she could just sign up again. Blocking the user prevents him/her from signing up with the same email address and username. Of course, he/she could sign up again with a different email address and a different username. But this helps us to keep things under control. Deleting a user At the bottom of the edit user screen, there are two buttons: Save and Delete. The Save button will confirm and save any changes made to the user's account, and the delete button will permanently remove the user from our social network. When to delete a userA user may request to be removed from the web site, in which case, we can use this feature. Roles Users are grouped into roles, which in turn have permissions assigned to them. By default, there are two roles within Drupal. These two roles are: anonymous users authenticated users These roles can be edited, but they can neither be renamed nor deleted. This is why the Operations column in the table below is locked. The anonymous user role is the role for any user who is not logged-in, and so the permissions associated with it are those which a guest user has. Whereas the role of an authenticated user suits all those users who are logged-in. Additional roles which are added can apply to any number of users. At this stage, we must select which users have which roles assigned to them. Users can change their roles and get more active within the network with features such as Organic Groups, but it is out of the scope of this article. Editing the permissions of a role allows us to select which permissions are granted to users who have that role assigned to their account. New roles are simply created by entering the name of a new role into the text box and then clicking the Add role button and selecting the permissions to be granted to those users. Permissions The Permissions section provides us with a grid view for roles and the permissions assigned to them. All the permissions which can be granted are listed down theside (for example, create blog entries) and the roles along the top. The use of this view, if we were to install a new module with new permissions related to it, is that we could easily update all of our roles to have the desired permissions directly from the grid view. The Save permissions link at the bottom of the page saves the changes made.
Read more
  • 0
  • 0
  • 3080
article-image-audio-fields-drupal
Packt
14 Oct 2009
5 min read
Save for later

Audio Fields in Drupal

Packt
14 Oct 2009
5 min read
FileField remixed If you haven't examined FileField, you'll have to do so by downloading the FileField module from http://drupal.org/project/filefield and enable it on the Modules administration page (by browsing to Administer | Site building | Modules, at /admin/build/modules). Now create a new content type named Album by going to Administer | Content management | Content types | Add content type (at /admin/content/types/add). We'll next add a FileField to this by editing the new Album type and selecting the Add field tab (at /admin/content/types/album/add_field). Call it Song, select the File for the Field type, press Continue, and press Continue again (leaving the Widget type as File Upload). In the Permitted upload file extensions, enter mp3 for now. If you wish, you may enter a new File path as well such as audio. Uploaded files would then be saved to that path. Note that you have access to the Token module's features here. So, for instance you may enter something like audio/[user-raw], which will replace [user-raw] with the username of the node's creator: Finally, select Unlimited for the Number of values, since we'll allow a single album to contain many songs. We'll also check the Required checkbox so that each album will hold at least one song. Finally, we will ensure that the Default listed value is Listed, and that we select the Enforce Default radio button for How should the list value be handled? This will force a node to always list files when displayed. We need to list our files, although we plan ultimately to control display of an album's songs in the player: Now we can add an album node with a few songs by going to Create content | Album (at /node/add/album). Uploading is simple. At this point, we only have a link displayed for our files. Our next task is to create an inline player for the audio. One possibility would be to override the theme function. However, we have other tools available that will make our job easier and even ensure cross-browser compatibility, better accessibility, and valid HTML: jQuery Media to the rescue The jQuery Media plug-in, written by Mike Alsup at http://www.malsup.com/jquery/media/, is a perfect solution. It will convert any link to media into the browser-specific code required for displaying the media. The jQuery Media module is a configurable wrapper for this plug-in. We'll also need a media player. For this exercise, we'll again use the JW FLV Media Player developed by Jeroen Wijering. This excellent player is free for non-commercial use, and has a very inexpensive licensing fee for other uses. First, download that player from http://jeroenwijering.com/ and install the player.swf file somewhere in your site's directory tree. If you install it in the site's www root folder, the module will work with little extra configuration. But you can install it in the files directory, your theme folder, or another convenient place if you need it for your environment. Just remember where you put it for future reference. Next, download and enable the jQuery Media module from http://drupal.org/project/jquery_media. You may wish to also install the jQ module from http://drupal.org/project/jq, which consolidates jQuery plug-ins installed on your site. The configuration is simple. You'll just need to enter the filepath of your media player, which can be different than the Flash Video player entered earlier, if desired. Go to the jQuery Media Administration page by browsing to Administer | Site configuration | jQuery Media Administration (at /admin/settings/jquery_media). Open the Default players (within Extra settings) and enter the filepath of your media player in the MP3 Player (mp3Player) text field: Now just check the Album box in Node types, and set the width and height within Default settings. In most cases, you would be done and the audio would be displayed automatically with no further configuration. However, we're assuming you plan to use this module in conjunction with videos, which may have already set a width and height. That means we'll need to do some more customization. Note: You do not need to do any of this, unless you have video and audio files on the site both using jQuery Media. We need to change the class of our field and add a new invocation script. However, we don't want to affect the class of our existing video files. So add the following somewhere in the phptemplate_preprocess_filefield_file function, creating that function if necessary. (If you haven't already done that, then create function phptemplate_preprocess_filefield_file(&$variables) in template.php. $node = node_load($file['nid']); if ($node->type == 'album') { $variables['classes'] = 'filefield-file-song'; if (module_exists('jquery_media')) { jquery_media_add(array('media class' => '.filefield-file-song a', 'media height' => 20, 'media width' => 200)); } } else { $variables['classes'] = 'filefield-file'; } Then you'll need to change a line in filefield_file.tpl.php. (If you haven't already created that file, create it in your theme directory, and copy the code from the theme_filefield_file function that is found in /sites/all/modules/filefield/filefield_formater.inc.) The original line in question reads as follows: return '<div class="filefield-file clear-block">'. $icon . l($file['filename'], $url) .'</div>'; However, we can rewrite that line to read: <div id="filefield-file-file-<?php print $id; ?>" class="filefield-file clear-block" <?php print $style; ?> > In either case, simply replace class="filefield-file clear-block" with class=" clear-block".
Read more
  • 0
  • 0
  • 1863

article-image-data-modeling-erwin
Packt
14 Oct 2009
3 min read
Save for later

Data Modeling with ERWin

Packt
14 Oct 2009
3 min read
Depending on your data modeling need and what you already have, there are two other ways to create a data model: Derive from an existing model and Reverse Engineer an existing database. Let’s start with creating a new model by clicking the Create model button. We’d like to create both logical and physical models, so select Logical/Physical. You can see in the Model Explorer that our new model gets Model_1 name, ERWin’s default name. Let’s rename our model to Packt Model. Confirm by looking at the Model Explorer that our model is renamed correctly. Next, we need to choose the ER notation. ERWin offers two notations: IDEF1X and IE. We’ll use IE for our logical and physical models. It’s a good practice during model development to save our work from time to time. Our model is still empty, so let’s next create a logical model in it. Logical Model Logical model in ERWin is basically ER model. An ER model consists of entities and their attributes, and their relationships. Let’s start by creating our first entity: CUSTOMER and its attributes. To add an entity, load (click) the Entity button on the toolbar, and drop it on the diagramming canvas by clicking your mouse on the canvas. Rename the entity’s default E/1 name to CUSTOMER by clicking on the name (E/1) and typing its new name over it. To add an attribute to an entity, right-click the entity and select Attributes. Click the New button. Type in our first attribute name (CUSTOMER_NO) over its name, and select Number as its data type, and then click OK. We want this attribute as the entity’s primary key, so check the Primary Key box. In the same way, add an attribute: CUSTOMER_NAME with a String data type. Our CUSTOMER entity now has two attributes as seen in its ER diagram. Notice that the CUSTOMER_NO attribute is at the key area, the upper part of the entity box; while the CUSTOMER_NAME is in the common attribute area, the bottom part. Similarly, add the rest of the entities and their attributes in our model. When you’re done, we’ll have six entities in our ER diagram. Our entities are not related yet. To rearrange the entities in the diagram, you can move around the entities by clicking and dragging them.
Read more
  • 0
  • 0
  • 4017
Modal Close icon
Modal Close icon