Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - CMS & E-Commerce

830 Articles
article-image-version-management-upk-35-part-2
Packt
18 Nov 2009
5 min read
Save for later

Version Management with UPK 3.5: Part 2

Packt
18 Nov 2009
5 min read
Restoring a deleted document In a client/server environment, content objects are never really deleted; they still exist on the server. Instead, they are removed from the Library folders so that they are not visible within the Library itself. However, they will appear in the Deleted documents view, from where developers can display and restore them. The only way they can be truly deleted is by the Administrator purging them. The advantage of this is that you can always (up until the point that the Administrator has purged it) "un-delete" a content object, if you realize that you deleted it by mistake. To restore (un-delete) a content object, carry out the following steps: From the Library screen, click on the drop-down button for the View field (which will normally indicate Details view) on the View toolbar, and select Deleted documents. A list of all of the content objects that have been deleted (but not purged) is displayed, as shown in the following screenshot: Right-click on the document that you want to restore, and select Restore from the context menu. This is the only option available on this context menu. The document is restored to the Library, and placed back in the folder it was originally deleted from. This location is also shown in the Original location column in the Deleted documents view. This will create another version in the version history for the content object—just as deleting it did. This is shown in the screenshot below: Exporting and importing content If you are working in a stand-alone environment and want to share your developed content with another user, you will need to export it from your Library so they can import it into their Library. If you are a developer working in a client/server environment, it is unlikely that you will need to export your content because all users will be able to access it in the same Library. However, even then there may be a need to export your content, for example: Your company may use a "staged" approach to implementation, whereby all content is developed in a Development library before being migrated to a more secure production environment If you are working with multiple libraries, then it is recommended that you always export/ import folders, and not simply Outline Elements and their contents. This will reduce the possibility of elements that appear in multiple outlines being overwritten on successive imports. You have developed content in one environment (for example, your personal stand-alone environment) and now want to bring it into your company's client/server environment You want to take a copy of everything you have done, as a personal back-up You want to export all of your content before upgrading to a new version of UPK and importing your content into the new version's Library Whatever the reason, UPK makes it easy to export content. In this section we'll look at just how to do this. You would not normally use this approach to export content for translation. Exporting content objects You can use the Export function to export content objects as an archive, publishing options, sound files, and content objects for localization. This section covers exporting content objects as an archive. You can export any type of content object to an archive: Modules, Sections, and Topics, as well as Web Pages and Packages. You can also export any of the objects in the System folder, such as Templates and Publishing Packages. To export a content object, carry out the following steps: In the Library, select on the content objects that you want to export. You can select a single object, or multiple objects of various types. You also have the option of selecting a folder and exporting all of the content within the folder. Select menu option Tools|Export|Documents. The Export dialog box is displayed, as shown in the following screenshot: Click on the Browse button next to the Export content to: field. The Save As dialog box is displayed, as shown below: Enter a suitable file name for your export file in the File name field. Note that UPK will automatically select a file type of Content archives (*.odarc) and add the file prefix .odarc (for OnDemand Archive. Note the reference to OnDemand even though the product is no longer called OnDemand!). Click on Save to confirm the destination folder and file. Back in the Export dialog box, under Selection Options, select whether you want to export only the specific content that you have selected (Export my selection), or the selected content and all related documents (Export my selection and related documents). Related documents are typically content objects such as web pages that are linked to the selected object(s). You can see a list of these objects by clicking the View related documents link. Depending on how you have organized your Library, you should normally export entire folders and their contents, not Outline Elements. Otherwise, you risk missing out objects that are not directly linked into the Outline, such as Packages. You also risk having broken links when you (re)import the content object(s). Click on Export. The selected content objects (and all related documents, if you chose that option) are exported to the specified file. While this is being done, a progress indicator is displayed for the object currently being exported, and the overall percentage complete. The export may be very quick, especially if you are only exporting one or two Topics so don't blink or you'll miss it. An example of the progress indicator is shown below: Once the export is complete, you are returned to the Library. As the content is exported to a single file, you can easily send the file to another Developer for importing into their UPK Library, save it to CD as a back-up, and so on. How to import content objects is described next.
Read more
  • 0
  • 0
  • 1673

article-image-keeping-extensions-secure-joomla-15-part-2
Packt
18 Nov 2009
15 min read
Save for later

Keeping Extensions Secure with Joomla! 1.5: Part 2

Packt
18 Nov 2009
15 min read
Making a directory path safe When we poke around in the server filesystem, we want to make sure that we know what we are doing. If we are dealing with directories, Joomla! provides us with some easy ways to make sure that those directories are being safely referenced. Failure to properly sanitize directory paths can lead to major security vulnerabilities. For example, if we were attempting to remove a directory, a security vulnerability could allow the deletion of the completely wrong resource! For more information about external control of paths, refer to CWE-73. A directory path is a URL to a directory. A directory path does not include a file. To safely manage a path to a file, refer to the next recipe, Making a path safe. How to do it... The static JFolder class, which is a part of the joomla.filesystem library, provides us with all sorts of useful methods for working with folders. To use the class, we must import it. jimport('joomla.filesystem.folder'); This bit is nice and easy. We use the JFolder::makeSafe() method and pass the name of the folder we want to sanitize. This method returns a string that can be used to interact safely with a folder. // make the directory path safe$safeDirPath = JFolder::makeSafe($unsafeDirPath); The one downside of JFolder::makeSafe() is that it assumes that the directory separators are correctly defined in the original string. For example, while running on a *nix system, if the string contained Windows-style backslashes instead of *nix style forward slashes, those slashes would be stripped. We can use the static JPath class to overcome this, as follows: // import JPath and JFolderjimport('joomla.filesystem.path');jimport('joomla.filesystem.folder');// clean the path$cleanDirPath = JPath::clean($unsafeDirPath);// make the directory path safe$safeDirPath = JFolder::makeSafe($cleanDirPath); This time we have included the JPath::clean() method prior to making the path safe. For more information about JPath, refer to the next recipe, Making a path safe. Directory separators The correct way to add directory separators in Joomla! is to use the DS constant. For example, the path to bar from foo is expressed as 'foo' . DS . 'bar'. How it works... What exactly does the JFolder::makeSafe() method do to guarantee that the directory path is safe? It strips out any characters or character sequences that are seen as posing potential security risks. The following list describes the characters that are considered safe: Alphanumeric (a-z, A-Z, and 0-9) Colon Dash Directory separators—the exact character sequence will depend on the environment Space Underscore The following table shows some examples of input and output strings from the JFolder::makeSafe() and JPath::clean() methods running on a Windows system (DS == ''). This is intended to show why using the two together can be preferable. If we choose to use the two together, order of usage is important. We should always use the JPath::clean() method first and the JFolder::makeSafe() method next. Although, as the fourth example shows, sometimes it can be worth cleaning a second time, which means clean, make safe, and clean.   Original   Clean   Safe   Clean and safe   foobar   foobar   foobar   foobar   //foo/bar   foobar   foobar   foobar   foo bar   foo bar   foo20bar   foo20bar   foo bar/..   foo bar..   foo bar   foo bar   /foo"   foo"   foodel   foodel   del *.*   del *.*       See also For information about safely dealing with files, refer to the previous recipe, Making a filename safe. For information about dealing with paths, please refer to the next recipe, Making a path safe. Making a path safe This recipe is similar to the previous two recipes, Making a filename safe and Making a directory path safe. This recipe differs in that it is for a complete path, normally to a file. There is a whole raft of security issues associated with processing paths. The following list identifies some of the more common issues we need to be aware of: CWE-22: Path traversal CWE-73: External control of filename or path CWE-98: Insufficient control of filename for include/require statement in PHP program (aka 'PHP file inclusion') CWE-434: Unrestricted file upload All of these vulnerabilities can have serious consequences, which should not be overlooked. For example, a malicious user could upload a destructively tailored script file and then execute it. Luckily, Joomla! provides us with some easy ways to reduce the risks associated with these potential weaknesses. Getting ready Before we delve into some of the complex ways of safely dealing with paths, let's start small. If we browse a basic installation of Joomla!, we will discover a large number of empty index.html files. These files prevent directory listings. Most web servers automatically generate directory listings if we visit a directory in which there are no index files. We should always add a copy of the empty index.html file to every directory in our extension. The use of empty index.html files provides a form of security through obscurity. This is only intended to be a very basic safeguard and should never be relied on for complete protection. For more information, refer to CWE-656. The second thing we should do is ensure that all of our PHP files can only be executed if the _JEXEC constant has been defined. This is used to make sure that the file has been executed from within Joomla!, that is, make sure it is not being used as a standalone script or is included from a script other than Joomla! // Check file executed from within Joomla!defined('_JEXEC') or die('Restricted access'); How to do it... If we are retrieving a path value from a request variable, we can use the PATH type. This type is not entirely what it seems, as a PATH type cannot be an absolute path and cannot reference hidden files and folders. This means it cannot start with any form of directory separator, as it would in a *nix environment, or a drive identifier, as it would in a Windows environment. It also means that none of the folder names or the optional filename can start with a period (a *nix hidden file/folder). If a value does not reach these criteria, the return value will be null. Therefore, it is very important to consider the suitability of the PATH type before opting to use it. // get the value of myPath from the request$myPath = JRequest::getVar('myPath', 'default', 'REQUEST', 'PATH'); On its own, the PATH type does not really constitute a security measure. For example, it does not protect against the path traversal CWE-22. Once we have our path variable, it is time to clean it. Cleaning is done in Joomla! using the static JPath class. Cleaning resolves any issues with directory separators. The exact process depends on the filesystem directory separator, for example a back or forward slash. The point is that if the directory separators in the string are incorrect, they are corrected as necessary. // import the JPath classjimport('joomla.filesystem.path');// clean $myPath$myPath = JPath::clean($myPath); Like the PATH type, a cleaned path does not really constitute a security measure. For example, it too does not protect against path traversal CWE-22. OK, we've heard enough about not constituting a security measure. Now it's time to overcome that problem. The static JPath class includes the JPath::check() method, which checks for path traversal and also that the path is within the Joomla! installation. The only constraint is that the method can only deal with absolute paths. Remember the PATH type used in JRequest can only cope with relative paths. Therefore, if we use the PATH type, we must convert it to an absolute path before using the JPath::check() method. // check for path traversal and snoopingJPath::check($myPath); The odd thing about this method is that we don't really do anything with the result! There is a very good reason for this. If the check fails, Joomla! will exit and display a suitable error message. In some instances, this may not be appropriate. Unfortunately, there is nothing we can do to prevent this. Therefore, if we want to avoid this we will have to check the path ourselves. Generally speaking, if a path fails the check, it is likely that an attack has been attempted. For that reason, exiting Joomla! is probably the most suitable response. However, the JPath::check() method does have one serious limitation. It only checks for snooping outside of the Joomla! root directory. We can manually check that we are only looking in a specified area in the Joomla! installation. // create path which must be the root of the directory$safePath = JPATH_COMPONENT . DS . 'safeFolder' . DS;// check for snooping outside of $safePathif (strpos($myPath, $safePath) !== 0) { JError::raiseError(20, 'Snooping out of bounds'); jexit();}// check for file traversaljimport('joomla.filesystem.path');JPath::check($directory); Essentially, this only ensures that the start of the $myPath string is equivalent to $safePath. We deal with failures in the same way as the JPath::check() method. Notice that we still use the JPath::check() method because we can still effectively use this method to check for file traversal. See also The previous two recipes, Making a filename safe and Making a directory path safe, discuss how to work safely with filenames and paths. We can also use filesystem permissions to secure files and folders. Safely retrieving request data Almost 99% of the time, security vulnerabilities in PHP applications such as Joomla! are caused by inadequate input parsing and validation CWE-20. We access request data in Joomla! using the static JRequest class. Built into this class is the ability to cast values to specific types and to mask data. We cannot rely solely on JRequest to ensure that incoming data is safe. This is where validation comes into play. Input data always has definable constraints. For example, we might define an entity identifier as a positive integer no less than 1 and no greater than 4294967295 (the maximum value for an unsigned MySQL INT). If we can define the constraints, we can also check that the input adheres to the constraints. Validating strings tend to be more complex. This is because strings are highly versatile and can contain many different characters. One thing we should always bear in mind when dealing with string validation is the effect of different character encodings. Joomla! 1.5 is UTF-8 compliant. UTF-8 is a Unicode variable-size multibyte character encoding that enables the encoding of many different alphabets and symbols that would otherwise be unavailable. As PHP is not UTF-8 aware, we should always use the static JString methods instead of the PHP string functions when dealing with UTF-8 strings. Getting ready Prior to doing anything, it is worth defining and documenting the boundaries of all the input that we use in our extension. This may include value ranges and formats. This can be a lengthy task, but it will help to ensure that our extension is secure. How to do it... The most important thing we must do when accessing request data is to use JRequest. Even if we just want the raw values, JRequest forms an important part of the Joomla! framework. Even before we get a chance to execute any code in our extension, JRequest will have already performed vital security work in an attempt to prevent global variable injection, CWE-471. So where do we begin? We start with the simple JRequest::getVar() method. This method is used to safely get at the request data. There are five parameters, of which only the first is required. The following example shows how we use the first three of these parameters: // gets the value of name$value = JRequest::getVar('nameOfVar');// gets the value of name,// if name is not specified returns defaultValue$value = JRequest::getVar('nameOfVar', 'defaultValue');// gets the value of name,// if name is not specified returns defaultValue// name is retrieved from the GET request data$value = JRequest::getVar('nameOfVar', 'defaultValue', 'GET'); The third parameter can be any of the following values:   Value Description COOKIE HTTP Cookies ENV Environment variables FILES Uploaded file details GET HTTP GET variables POST HTTP POST variables REQUEST Combination of GET, POST, and COOKIE; this is the default SERVER Server and environment variables In most instances, REQUEST (the default) should be sufficient. The only time we need to use GET and POST explicitly is when we are expecting a request to use a specific HTTP method. For added security, we can restrict a request to a certain HTTP method using the static JRequest::getMethod() method, as shown in the following example: if (JRequest::getMethod() != 'GET') { jexit('UNEXPECTED REQUEST METHOD');} There's more... The following two subsections discuss the last two parameters, $type and $mask. It is in the last two parameters where the security benefits of JRequest become very apparent. Casting Strictly speaking, casting is not an accurate description of the fourth JRequest::getVar() parameter. The types that we can cast to are not the types that we would use to describe a variable. For example, WORD is not a PHP or Joomla! type, but it is an available option. The following example extracts an integer representation of the GET request value, nameOfVar: // gets the value of nameOfVar,// if nameOfVar is not specified returns 0// name is retrieved from the GET request data// casts the return value as an integer$int = JRequest::getVar('nameOfVar', 0, 'GET', 'INT'); Hey presto! We have a safe value that we know is an integer. Had we not included the parameter to cast the value, we would not have been able to guarantee that $int was in fact an integer. Of course, we could have used the PHP intval() function or cast the value ourselves using (int). Not all of the types we can cast to are as simple as an integer; for example, ALNUM is used to strip non-alphanumeric characters from a string value. JRequest also provides alias methods that allow us to achieve the same thing, but with less code. For example, we can quickly extract an integer. The following example is the same as the previous example: $int = JRequest::getInt('nameOfVar', 0); The following table describes all of the types we can cast to using JRequest. Note that only the most commonly used types have alias methods. Type   Description   Alias   DEFAULT   Aggressive cleaning occurs to remove all detected code elements     ALNUM   Alphanumeric string; strips all non-ASCII letters and numbers     ARRAY   Force array cast     BASE64   Base64 string; strips all non Base64 characters, which is useful for passing encoded data in a URL, for example a return URL     BOOL or BOOLEAN   Force Boolean cast   getBool()   CMD   Command; strips all non-alphanumeric, underscore, period, and dash characters, which is ideal for values such as task   getCmd()   FLOAT or DOUBLE   Floating point number   getFloat()   INT or INTEGER   Whole number   getInt()   PATH   Filesystem path; used to identify a resource in a filesystem, for example the path to an image to use as a logo (relative paths only)     STRING   String; often used with a mask to clean the data   getString()   USERNAME   Username; strips characters unsuitable for use in a username, including non-printing characters (for example a backspace), angled brackets, double and single quotation marks, percent signs, and ampersands     WORD   Word; strips all non-alpha and underscore characters   getWord()     By default, the most aggressive mask is applied. This will remove code, such as HTML and JavaScript, from the data. The next section describes how we use masks. Masking strings The fifth JRequest::getVar() parameter defines a mask. Masks are used in JRequest to define what is and isn't allowed in a string value. By default no masking is applied, which means that very aggressive security measures are taken to ensure that the incoming data is as safe as possible. While this is useful, it is not always appropriate. For example, the core component com_content allows users to enter HTML data in an article. Without a mask, this information would be stripped from the request data. There are three constants we can use to easily define the mask we want to apply. These are JREQUEST_NOTRIM, JREQUEST_ALLOWRAW, and JREQUEST_ALLOWHTML. The following example shows how we can use these: // using getVar$string = JRequest::getVar('nameOfVar', 'default', 'REQUEST', 'STRING', JREQUEST_ALLOWRAW);// using getString alias$string = JRequest::getString('nameOfVar', 'default', 'REQUEST', JREQUEST_ALLOWRAW); The following examples show how the output varies depending on the mask that we apply: # Original input value 1 <p>Paragraph <a onClick="alert('foobar');">link</a></p> 2 CSS <link type="text/css", href="http://somewhere/nasty.css" /> 3 space at front of input 4 &ltp&gtPara&lt/p&gt # Output value (No mask) 1 Paragraph link 2 CSS 3 space at front of input 4 &ltp&gtPara&lt/p&gt    
Read more
  • 0
  • 0
  • 829

article-image-integrating-websphere-extreme-scale-data-grid-relational-database-part-2
Packt
18 Nov 2009
6 min read
Save for later

Integrating Websphere eXtreme Scale Data Grid with Relational Database: Part 2

Packt
18 Nov 2009
6 min read
Removal versus eviction Setting an eviction policy on a BackingMap makes more sense now that we're using a Loader. Imagine that our cache holds only a fraction of the total data stored in the database. Under heavy load, the cache is constantly asked to hold more and more data, but it operates at capacity. What happens when we ask the cache to hold on to one more payment? The BackingMap needs to remove some payments in order to make room for more. BackingMaps have three basic eviction policies: LRU (least-recently used), LFU (least-frequently used), and TTL (time-to-live). Each policy tells the BackingMap which objects should be removed in order to make room for more. In the event that an object is evicted from the cache, its status in the database is not changed. With eviction, objects enter and leave the cache due to cache misses and evictions innumerable times, and their presence in the database remains unchanged. The only thing that affects an object in the database is an explicit call to change (either persist or merge) or remove it as per our application. Removal means the object is removed from the cache, and the Loader executes the delete from SQL to delete the corresponding row(s) from the database. Your data is safe when using evictions. The cache simply provides a window into your data. A remove operation explicitly tells both ObjectGrid and the database to delete an object. Write-through and write-behind Getting back to the slow down due to the Loader configuration, by default, the Loader uses write-through behavior: Now we know the problem. Write-through behavior wraps a database transaction for every write! For every ObjectGrid transaction, we execute one database transaction. On the up side, every object assuredly reaches the database, provided it doesn't violate any relational constraints. Despite this harsh reaction to write-through behavior, it is essential for objects that absolutely must get to the database as fast as possible. The problem is that we hit the database for every write operation on every BackingMap. It would be nice not to incur the cost of a database transaction every time we write to the cache. Write-behind behavior gives us the help we need. Write-behind gives us the speed of an ObjectGrid transaction and the flexibility that comes with storing data in a database: Each ObjectGrid transaction is now separate from a database transaction. BackingMap now has two jobs. The first job is to store our objects as it always does. The second job is to send those objects to the JPAEntityLoader. The JPAEntityLoader then generates SQL statements to insert the data into a database. We configured each BackingMap with its own JPAEntityLoader. Each BackingMap requires its own Loader because each Loader is specific to a JPA entity class. The relationship between JPAEntityLoader and a JPA entity is established when the BackingMap is initialized. The jpaTxCallback we specified in the ObjectGrid configuration coordinates the transactions between ObjectGrid and a JPA EntityManager. In a write-through situation, our database transactions are only as large as our ObjectGrid transactions. Update one object in the BackingMap and one object is written to the database. With write-behind, our ObjectGrid transaction is complete, and our objects are put in a write-behind queue map. That queue map does not immediately synchronize with the database. It waits for some specified time or for some number of updates, to write out its contents to the database: We configure the database synchronization conditions with the setWriteBehind("time;conditions") method on a BackingMap instance. Programmatically the setWriteBehind method looks like this: BackingMap paymentMap = grid.getMap("Payment");paymentMap.setLoader(new JPAEntityLoader());paymentMap.setWriteBehind("T120;C5001"); The same configuration in XML looks like this: <backingMap name="Payment" writeBehind="T120;C5001"pluginCollectionRef="Payment" /> Enabling write-behind is as simple as that. The setWriteBehind method takes one string parameter, but it is actually a two-in-one. At first, the T part is the time in seconds between syncing with the database. Here, we set the payment BackingMap to wait two minutes between syncs. The C part indicates the number (count) of changes made to the BackingMap that triggers a database sync. Between these two parameters, the sync occurs on a whichever comes first basis. If two minutes elapse between syncs, and only 400 changes (persists, merges, or removals) have been put in the write-behind queue map, then those 400 changes are written out to the database. If only 30 seconds elapse, but we reach 5001 changes, then those changes will be written to the database. ObjectGrid does not guarantee that the sync will take place exactly when either of those conditions is met. The sync may happen a little bit before (116 seconds or 4998 changes) or a little bit later (123 seconds or 5005 changes). The sync will happen as close to those conditions as ObjectGrid can reasonably do it. The default value is "T300;C1000". This syncs a BackingMap to the database every five minutes, or 1000 changes to the BackingMap. This default is specified either with the string "T300;C1000" or with an empty string (" "). Omitting either part of the sync parameters is acceptable. The missing part will use the default value. Calling setWriteBehind("T60") has the BackingMap sync to the database every 60 seconds, or 1000 changes. Calling setWriteBehind("C500") syncs every five minutes, or 500 changes. Write-behind behavior is enabled if the setWriteBehind method is called with an empty string. If you do not want write-behind behavior on a BackingMap, then do not call the setWriteBehind method at all. A great feature of the write-behind behavior is that an object changed multiple times in the cache is only written in its final form to the database. If a payment object is changed in three different ObjectGrid transactions, the SQL produced by the JPAEntityLoader will reflect the object's final state before the sync. For example: entityManager.getTransaction().begin();Payment payment = createPayment(line, batch);entityManager.getTransaction().commit();some time later...entityManager.getTransaction().begin();payment.setAmount(new BigDecimal("44.95"));entityManager.getTransaction().commit();some time later...entityManager.getTransaction().begin();payment.setPaymentType(PaymentType.REAUTH);entityManager.getTransaction().commit(); With write-through behavior, this would produce the following SQL: insert into payment (id, amount, batch_id, card_id, payment_type) values (12345, 75.00, 31, 6087, 'AUTH');update payment set (id, amount, batch_id, card_id, payment_type) values (12345, 44.95, 31, 6087, 'AUTH') where id = 12345;update payment set (id, amount, batch_id, card_id, payment_type) values (12345, 44.95, 31, 6087, 'REAUTH') where id = 12345; Now that we're using write-behind, that same application behavior produces just one SQL statement: insert into payment (id, amount, batch_id, card_id, payment_type) values (12345, 44.95, 31, 6087, 'REAUTH');
Read more
  • 0
  • 0
  • 1112
Visually different images

article-image-processing-twitter-and-new-york-times-apis-aspnet-ajax-microsoft-cdn
Packt
18 Nov 2009
7 min read
Save for later

Processing Twitter and New York Times APIs with ASP.NET Ajax on Microsoft CDN

Packt
18 Nov 2009
7 min read
APIs (Application Programming Interface) are application-to-application programming interfaces that support harvesting information on the web using the known web standards. These APIs are provided by the entities who wish to expose parts of their resources that a third party can use. The APIs run transparent to the user and exposes just what they want to expose, with some providing access to material for public consumption with others giving access to resources based on authentication. In a sense they may be called a basic form of SAAS. Amazon.com, Google etc have exposed their APIs for some time. Twitter and New York Times have also exposed their API's which can be used to do some digging into the information contained in them, a kind of web mining. Many others such as Netflix have provided their own APIs described on their web sites. What is Twitter API? Twitter API is provided by the Social Networking and Micro-blogging service. Twitter API adheres to the web standards and one can talk to Twitter using HTTP. You can just about access anything on the Twitter web site. One example of creating a Microsoft SQL Server Report using Twitter API is available here - Tweets with Reporting Services, wherein the response from the Twitter API was in XML format. JSON (JavaScript Object Notation) is another format in which data is returned when an API call is made. In this article we will be looking at API call that returns a JSON response. Twitter exposes a large number methods through their API's such as API's for Search, Timeline, Status, User, Direct Message, Friendship and many more. As previously mentioned the responses will be in XML or JSON. Also while some APIs may take parameters others may not. The Twitter API used in this tutorial We will be looking at trends in Twitter API exposed by the url, http://search.twiiter.com/trends.format. We will be using the GET method and we will expect a JSON response. Since the volume of traffic may overwhelm, the calls that you can make to this in an hour are limited (also known as rate limiting) but not critical for the demo in this tutorial. Here is a typical call to the trends method on the Twitter API. Herein we will search for trends on the Twitter site and expect a response in JSON, if we use json instead of Format in the next URL address. Instead of:http://search.twitter.com/trends.Formattype-in, the following for URL address,http://search.twitter.com/trends.json When you plug the above in a web Brower you would get a response trends.json which you may save to your hard drive or, use it in any way you like. The next quoted text is what you get in response (note that this is what I got on Saturday 31, 2009 and what you get will be different), the content of the file trends.json you saved to your computer. Note that presently you get about top ten trends from this API call. {"as_of":"Sat, 31 Oct 2009 20:44:46 +0000","trends":[{"name":"Happy Halloween", "url":"http://search.twitter.com/search?q=%22Happy+Halloween%22+OR+%22Feliz+ Halloween%22"},{"name":"#nxzerosetechaves","url":"http://search.twitter.com/search?q=%23nxzerosetechaves"},{"name":"Danyl","url":"http://search.twitter.com/search?q=Danyl"},{"name":"#HappyHalloween","url":"http://search.twitter.com/search?q=%23HappyHalloween"},{"name":"#potterday","url":"http://search.twitter.com/search?q =%23potterday"},{"name":"X Factor","url":"http://search.twitter.com/search?q=%22X+ Factor%22"},{"name":"It's Halloween","url":"http://search.twitter.com/search?q=%22It %27s+Halloween%22+OR+%22Its+Halloween%22"},{"name":"Trick","url":"http://search.twitter.com/search?q=Trick+OR+%23trick"},{"name":"Paranormal Activity","url":"http://search.twitter.com/search?q=%22Paranormal+Activity%22"},{"name":"This Is It","url":"http://search.twitter.com/search?q=%22This+Is+It%22"}]} First of all what you see returned is a JSON object. If you are new to JSON review this article on my blog. The various elements that you see such as 'name', 'url' etc are fields in the response that are all described in the API documentation(look for Return Values). Some of the API calls can return a ton of information and you will have to know the API method so that you can correctly parse this data. Another thing you would notice is that the JSON object you get out is a nested object with many levels. You may need a JSON Parser to get a clearer picture of this nesting and I recommend using the online parser at this site. Using the above site, the JSON Object would appear as shown (only a portion is shown). New York Times API New York Times made available to the developers sometime in the middle of October 2008 APIs that can search New York Times for various kinds of information . Just like in Twitter there are a large number of APIs that you can use such as: Article Search; Best Sellers; Campaign Finance; Congress; and many others. Interested users can get on to this resource by signing up here requesting what APIs they would like to use. After signing up, New York Times would provide keys for the APIs that you want to access. It is important therefore, that the call should include the keys provided to you. For example, I received keys to access the following resources: Movie Reviews, Article Search, Best Sellers and Times Newswire. The key for the Movies Reviews API appears as shown here (the one shown here has been doctored and will not work). Movie Reviews API Key: b57378910b9fd80ecc73461547c93e8a:10:50673441 Using the New York Times API It is a valuable resource since you can get for example with the Article Search API access to more than 2.8 million articles from 1981. Using this is quite simple, just paste the URL shown below into the address box of your browser. Note that the key shown here is fake (but of correct format). http://api.nytimes.com/svc/search/v1/article?query=India&facets=publication_year&api-key=6c208890a4880093c30020be8fe17a40:0:50633441 This will display in the browser the JSON object that is returned as shown. You can use the previously mentioned site to parse it for more friendly display. {"facets" : {"publication_year" : [{"count" : 2724 , "term" : "2008"} , {"count" : 2345 , "term" : "2006"} , {"count" : 2311 , "term" : "2009"} , {"count" : 2282 , "term" : "2007"} , {"count" : 2144 , "term" : "2002"} ,{"count" : 2111 , "term" : "2001"} , {"count" : 1988 , "term" : "2005"} , {"count" : 1951 , "term" : "2004"} , {"count" : 1921 , "term" : "1985"} , {"count" : 1798 , "term" : "2003"} , {"count" : 1761 , "term" : "1999"} , {"count" : 1720 , "term" : "2000"} , {"count" : 1642 , "term" : "1998"} , {"count" : 1442 , "term" : "1984"} , {"count" : 1382 , "term" : "1986"}]} , "offset" : "0" , "results" : [{"body" : "BARSUR, India — At the edge of the Indravati River, hundreds of miles from the nearest international border, India effectively ends. Indian paramilitary officers point machine guns across the water. The dense jungles and mountains on the other side belong to Maoist rebels dedicated to overthrowing the government. "That is their liberated" , "byline" : "By JIM YARDLEY" , "date" : "20091101" , "title" : "Maoist Rebels Widen Deadly Reach Across India" , "url" : "http://www.nytimes.com/2009/11/01/world/asia /01maoist.html"} ,.........(there is more of this but abbreviated here) Response Format As you can see the responses to the API calls return JSON objects in general of the form shown belo w (this one is of the form returned by the Twiiter API). What we propose to do is to use jQuery's GetJSON() method to get the JSON Objects and use Microsoft AJAX JavaScript files to display the data on the web page. Both jQuery javascript files and Microsoft ASP.NET AJAX files are both available on the Microsoft ECN (CDN). The GetJSON() method as well as the Microsoft ASP.NET AJAX templates can be easily implemented in the Visual Studio 2008 IDE. Alternatively Microsoft AJAX can also be used to retrieve data from the web sites. In this article the GetJSON() method will be used. {"x":{"y":[{"a1":"b1", "c1":"d1"}, {"a2":"b2", "c2":"d2"}]},.... "f":"g",....}
Read more
  • 0
  • 0
  • 3220

article-image-integrating-websphere-extreme-scale-data-grid-relational-database-part-1
Packt
18 Nov 2009
10 min read
Save for later

Integrating Websphere eXtreme Scale Data Grid with Relational Database: Part 1

Packt
18 Nov 2009
10 min read
As stated above there are three compelling reasons to integrate with a database backend. First, reporting tools do not have good data grid integration. Using CrystalReports and other reporting tools, don't work with data grids right now. Loading data from a data grid into a data warehouse with existing tools isn't possible either. The second reason we want to use a database with a data grid is when we have an extremely large data set. A data grid stores data in memory. Though much cheaper than in the past, system memory is still much more expensive than a typical magnetic hard disk. When dealing with extremely large data sets, we want to structure our data so that the most frequently used data is in the cache and less frequently used data is on the disk. The third compelling reason to use a database with a data grid is that our application may need to work with legacy applications that have been using relational databases for years. Our application may need to provide more data to them, or operate on data already in the legacy database in order to stay ahead of a processing load.In this article, we will explore some of the good and not-so-good uses of an in-memory data grid. We'll also look at integrating Websphere eXtreme Scale with relational databases. You're going where? Somewhere along the way, we all learned that software consists of algorithms and data. CPUs load instructions from our compiled algorithms, and those instructions operate on bits representing our data. The closer our data lives to the CPU, the faster our algorithm can use it. On the x86 CPU, the registers are the closest we can store data to the instructions executed by the CPU. CPU registers are also the smallest and most expensive data storage location. The amount of data storable in registers is fixed because the number and size of CPU registers is fixed. Typically, we don't directly interact with registers because their correct usage is important to our application performance. We let the compiler writers handle translating our algorithms into machine code. The machine code knows better than we do, and will use register storage far more effectively than we will most of the time. Less expensive, and about an order of magnitude slower, we have the Level 1 cache on a CPU (see below). The Level 1 cache holds significantly more data than the combined storage capacity of the CPU registers. Reading data from the Level 1 cache, and copying it to a register, is still very fast. The Level 1 cache on my laptop has two 32K instruction caches, and two 32K data caches. Still less expensive, and another order of magnitude slower, is the Level 2 cache. The Level 2 cache is typically much larger than Level 1 cache. I have 4MB of the Level 2 cache on my laptop. It still won't fit the contents of the Library of Congress into that 4MB, but that 4MB isn't a bad amount of data to keep near the CPU. Up another level, we come to the main system memory. Consumer level PCs come with 4GB RAM. A low-end server won't have any less than 8GB. At this point, we can safely store a large chunk of data, if not all of the data, used by an application. Once the application exits, its data is unloaded from the main memory, and all of the data is lost. In fact, once our data is evicted from any storage at or below this level, it is lost. Our data is ephemeral unless it is put onto some secondary storage. The unit of measurement for accessing data in a register, either Level 1 or 2 cache and main memory, is a nanosecond. Getting to secondary storage, we jump up an SI-prefix to a microsecond. Accessing data in the secondary storage cache is on the order of microseconds. If the data is not in cache, the access time is on the order of milliseconds. Accessing data on a hard drive platter is one million times slower than accessing that same data in main memory, and one billion times slower than accessing that data in a register. However, secondary storage is very cheap and holds millions of times more than primary storage. Data stored in secondary storage is durable. It doesn't disappear when the computer is reset after a crash. Our operation teams comfortably build secondary storage silos to store petabytes of data. We typically build our applications so the application server interacts with some relational database management system that sits in front of that storage silo. The network hop to communicate with the RDBMS is in the order of microseconds on a fast network, and milliseconds otherwise. Sharing data between applications has been done with the disk + network + database approach for a long time. It's become the traditional way to build applications. Load balancer in front, application servers or batch processes constantly communicating with a database to store data for the next process that needs it. As we see with computer architecture, we insert data where it fits. We squeeze it as close to the CPU as possible for better performance. If a data segment doesn't fit in one level, keep squeezing what fits into each higher storage level. That leaves us with a lot of unused memory and disk space in an application deployment. Storing data in the memory is preferable to storing it on a hard drive. Memory segmentation in a deployment has made it difficult to store useful amounts of data at a few milliseconds distance. We just use a massive, but slow, database instead. Where does an IMDG fit? We've used ObjectGrid to store all of our data so far. This diagram should look pretty familiar by now: Because we're only using the ObjectGrid APIs, our data is stored in-memory. It is not persisted to disk. If our ObjectGrid servers crash, then our data is in jeopardy (we haven't covered replication yet). One way to get our data into a persistent store is to mark up our classes with some ORM framework like JPA. We can use the JPA API to persist, update, and remove our objects from a database after we perform the same operations on them using the ObjectMap or Entity APIs. The onus is on the application developer to keep both cache and database in sync: If you take this approach, then all of the effort would be for naught. Websphere eXtreme Scale provides functionality to integrate with an ORM framework, or any data store, through Loaders. A Loader is a BackingMap plugin that tells ObjectGrid how to transform an object into the desired output form. Typically, we'll use a Loader with an ORM specification like JPA. Websphere eXtreme Scale comes with a few different Loaders out of the box, but we can always write our own. A Loader works in the background, transforming operations on objects into some output, whether it's file output or SQL queries. A Loader plugs into a BackingMap in an ObjectGrid server instance, or in a local ObjectGrid instance. A Loader does not plug into a client-side BackingMap, though we can override Loader settings on a client-side BackingMap. While the Loader runs in the background, we interact with an ObjectGrid instance. We use the ObjectMap API for objects with zero or simple relationships, and the Entity API for objects with more complex relationships. The Loader handles all of the details in transforming an object into something that can integrate with external data stores: Why is storing our data in a database so important? Haven't we seen how much faster Websphere eXtreme Scale is than an RDBMS? Shouldn't all of our data be stored in in-memory? An in-memory data grid is good for certain things. There are plenty of things that a traditional RDBMS is good at that any IMDG just doesn't support. An obvious issue is that memory is significantly more expensive than hard drives. 8GB of server grade memory costs thousands of dollars. 8GB of server grade disk space costs pennies. Even though the disk is slower than memory, we can store a lot more data on it. An IMDG shines where a sizeable portion of frequently-changing data can be cached so that all clients see the same data. The IMDG provides orders of magnitude with better latency, read, and write speeds than any RDBMS. But we need to be aware that, for large data sets, an entire data set may not fit in a typical IMDG. If we focus on the frequently-changing data that must be available to all clients, then using the IMDG makes sense. Imagine a deployment with 10 servers, each with 64GB of memory. Let's say that of the 64GB, we can use 50GB for ObjectGrid. For a 1TB data set, we can store 50% of it in cache. That's great! As the data set grows to 5TB, we can fit 10% in cache. That's not as good as 50%, but if it is the 10% of the data that is accessed most frequently, then we come out ahead. If that 10% of data has a lot of writes to it, then we come out ahead. Websphere eXtreme Scale gives us predictable, dynamic, and linear scalability. When our data set grows to 100TB, and the IMDG holds only 0.5% of the total data set, we can add more nodes to the IMDG and increase the total percentage of cacheable data (see below). It's important to note that this predictable scalability is immensely valuable. Predictable scalability makes capacity planning easier. It makes hardware procurement easier because you know what you need. Linear scalability provides a graceful way to grow a deployment as usage and data grow. You can rest easy knowing the limits of your application when it's using an IMDG. The IMDG also acts as a shock absorber in front of a database. We're going to explore some of the reasons why an IMDG makes a good shock absorber with the Loader functionality. There are plenty of other situations, some that we have already covered, where an IMDG is the correct tool for the job. There are also plenty of situations where an IMDG just doesn't fit. A traditional RDBMS has thousands of man-years of research, implementation tuning, and bug fixing already put into it. An RDBMS is well-understood and is easy to use in application development. There are standard APIs for interacting with them in almost any language: In-memory data grids don't have the supporting tools built around them that RDBMSs have. We can't plug CrystalReports into an ObjectGrid instance to get daily reports out of the data in the grid. Querying the grid is useful when we run simple queries, but fails when we need to run the query over the entire data set, or run a complex query. The query engine in Websphere eXtreme Scale is not as sophisticated as the query engine in an RDBMS. This also means the data we get from ad hoc queries is limited. Running ad hoc queries in the first place is more difficult. Even building an ad hoc query runner that interacts with an IMDG is of limited usefulness. An RDBMS is a wonderful cross-platform data store. Websphere eXtreme Scale is written in Java and only deals with Java objects. A simple way for an organization to share data between applications is in a plaintext database. We have standard APIs for database access in nearly every programming language. As long as we use the supported database driver and API, we will get the results as we expect, including ORM frameworks from other platforms like .NET and Rails. We could go on and on about why an RDBMS needs to be in place, but I think the point is clear. It's something we still need to make our software as useful as possible.
Read more
  • 0
  • 0
  • 1669

article-image-keeping-extensions-secure-joomla-15-part-1
Packt
18 Nov 2009
7 min read
Save for later

Keeping Extensions Secure with Joomla! 1.5: Part 1

Packt
18 Nov 2009
7 min read
Introduction There's no such thing as a completely secure system. No matter how many precautions we take and how many times we verify our design and implementation, we will never be able to guarantee that we have created a truly secure Joomla! extension. Why not? This is because it is not possible to be prepared for every potential vulnerability. Common Weakness Enumeration (CWE) is a project dedicated to generating a formal categorization and identification system of security vulnerabilities. CWE published a list of the top 25 security weaknesses, which were selected on the basis of their frequency and consequences. This list includes some of the most publicized security weaknesses, such as code injection (CWE-94) and XSS (CWE-79). When considering the security of our extensions, this list can prove useful. For information about common programming mistakes that lead to security vulnerabilities, refer to http://cwe.mitre.org/top25/. This article includes references to the CWE weaknesses. These references are in the form of CWE IDs, that is, CWE-n. For information about a weakness, simply Search By ID on the CWE web site. These references are intended to help us better understand the weaknesses, the risks associated with the weaknesses, how the risks can be reduced using the Joomla! framework, and the suggested CWE mitigations. Something we should consider is the ramifications of security flaws. Whichever way we look at this, the answer always involves financial loss. This is true even of non-profit organizations. If a web site is attacked and the attacker managed to completely obliterate all the data held on that web site, it will cost the owner's time to restore a backup or replace the data. OK, it may not seem like a financial loss because it's non profit. It is a wastage of time if the web site owner spends two hours to restore his or her data, as those two hours could have been used elsewhere. For commercial web sites, the potential for financial loss is far more obvious. If we use a bank as an example, a security flaw could enable an attacker to transfer money from the bank to his or her own (probably untraceable) account. In 2004, the Internet bank Cahoot suffered a security flaw enabling any existing customer access to other customers' accounts. Cahoot did not suffer any obvious financial loss from the security flaw and they claimed there was no risk of financial loss. However, the customers' confidence in Cahoot was inevitably lost. This loss of confidence and bad press will certainly have affected Cahoot in some way. For example, some potential customers may have decided to open an account with a rival bank because of concerns over how secure their savings would, or would not, be with Cahoot. For more information, refer to http://news.bbc.co.uk/1/hi/business/3984845.stm. From the perspective of an extension developer, we should reflect on our moral duty and our liability. Disclaimers, especially for commercial software, do not relinquish us of legal responsibility. We should always try to avoid any form of litigation, and I'm not suggesting that we run to Mexico or our closest safe haven. We should take a holistic approach to security. We need a complete view of how the system works and of the various elements that need to be secure. Security should be built into our extension from the requirements gathering stage through to the ongoing system maintenance. How we do that depends on how we are managing our project and what the security implications of our extension are. For example, a shopping cart component with credit card processing facilities will require far greater attention to security than a content plugin that converts the occurrences of :) to smiley face images. Irrespective of the way we choose to manage the risks of weaknesses, we should always document how we are circumventing security threats. Doing so will make it easier to maintain our extension without introducing vulnerabilities. Documentation also provides us with proof of prudent risk management, which can be useful should we ever be accused of failing to adequately manage the security risks associated with our software. This is all starting to sound like a lot of work! This brings us back to the ramifications of vulnerabilities. If on the one hand, it costs us one extra month of development time to produce a piece of near-secure software. And on the other hand, it costs us two months to patch a non-secure piece of software and an incalculable amount of damage to our reputation. It is clear which route we should favor! Packt Publishing offers a book that deals specifically with Joomla! security. For more information, refer to http://www.packtpub.com/joomla-web-security-guide/. Writing SQL safe queries SQL injection is probably the most high profile of all malicious web attacks. The effects of an SQL injection attack can be devastating and wide ranging. Whereas some of the more strategic attacks may simply be aimed at gaining access, others may intend on bringing about total disruption and even destruction. Some of the most prestigious organizations in the world have found themselves dealing with the effects of SQL injection attacks. For example, in August 2007 the United Nations web site was defaced as a result of an SQL injection vulnerability. More information can be found at http://news.bbc.co.uk/1/hi/technology/6943385.stm. Dealing with the effects of an SQL injection attack is one thing, but preventing them is quite another. This recipe explains how we can ensure that our queries are safe from attack by utilizing the Joomla! framework. For more information about SQL injection, refer to CWE-89. Getting ready The first thing we need is the database handler. There is nothing special here, just the usual Joomla! code as follows: $db =& JFactory::getDBO(); How to do it... There are two aspects of a query that require special attention: Identifiers and names Literal values The JDatabase::nameQuote() method is used to safely represent identifiers and names. We will start with an easy example, a name that consists of a single identifier. $name = $db->nameQuote('columnIdentifier'); We must take care when dealing with multiple-part names (that is, names that include more than one identifier separated by a period). If we attempt to do the same thing with the name tableIdentifier.columnIdentifier, we won't get the expected result! Instead, we would have to do the following: // prepare identifiers$tableIdentifier = $db->nameQuote('tableIdentifier');$columnIdentifier = $db->nameQuote('columnIdentifier');// create name$name = "$tableIdentifier.$columnIdentifier"; Avoid hardcoding encapsulation Instead of using the JDatabase::nameQuote() method, it can be tempting to do this: $sql = 'SELECT * FROM `#__foobar_groups` AS `group`'. This is OK as it works. But the query is now tightly coupled with the database system, making it difficult to employ an alternative database system. Now we will take a look at how to deal with literal values. Let's start with strings. In MySQL, strings are encapsulated in double or single quotes. This makes the process of dealing with strings seem extremely simple. Unfortunately, this would be an oversight. Strings can contain any character, including the type of quotes we use to encapsulate them. Therefore, it is also necessary to escape strings. We do all of this using the JDatabase::Quote() method as follows: $tableIdentifier = $db->nameQuote('tableIdentifier');$columnIdentifier = $db->nameQuote('columnIdentifier');$sql = "SELECT * FROM $tableIdentifier " . "WHERE $columnIdentifier " . ' = ' . $db->Quote("How's the recipebook going?"); The JDatabase::Quote() method essentially does the following. The exact output will depend on the database handler. However, most databases escape and encapsulate strings in pretty much the same way.   Original Quoted How's the recipebook going? 'How's the recipebook going?'
Read more
  • 0
  • 0
  • 958
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 €14.99/month. Cancel anytime
article-image-most-wanted-apache-myfaces-trinidad-12-tags-and-tag-attributes
Packt
18 Nov 2009
6 min read
Save for later

Most Wanted Apache MyFaces Trinidad 1.2 Tags and Tag Attributes

Packt
18 Nov 2009
6 min read
Component library structure Trinidad's approach to web technology is comprehensive: Aimed at full control of all the bits and pieces that make up a web application, little should be left that needs to be added. So based on such a closed world, Trinidad presents itself with a wealth of components and tags that even include very basic XHTML tags as replacements for the real XHTML originals. This is no radical replacement approach, rather it enables Trinidad to remain in full control of mechanisms such as partial-page rendering (PPR, also generally known as Ajax) that otherwise would need to deal with potentially incompatible libraries externally. The following image provides an outline of Trinidad's structural package design: Trinidad is divided into the following two namespaces: tr: It is the usual tag library id that references Trinidad's core library tags. It's a large library of over 100 components ranging from layout components and navigational components, to special viewer components that all implicitly support skinning, partial-page rendering, popup dialogs, error or info messaging, and so on. trh: It is the usual tag library id that references Trinidad's XHTML support library tags, a small companion that offers alternatives for those XHTML tags that are usually applied to build XHTML structures, for example, XHTML tables. Let us take a closer look at both namespaces. The upcoming image shows the core API's hierarchical structure. The tags are backed by two types of Trinidad classes—UIX* classes that deal with the JSF component requirements to implement specific JSF lifecycle processing methods, and Core* classes that deal with the specific properties (getters or setters). Trinidad’s XHTML tag library namespace (trh) Two groups can be distinguished from the trh namespace. The first one deals with the definition of an XHTML page and provides the developer with the following tags: <trh:html>: It is used to define the whole XHTML page, analogous to <html> <trh:head>: It is used to define the header, analogous to <head> <trh:body>: It is used to define the main contents, analogous to <body> <trh:script>: It is used to define a JavaScript to be executed, analogous to <script> <trh:tableLayout>: It is used to define an XHTML table. <trh:rowLayout>: It is used to define an XHTML table line, analogous to <tr>; note that it can also be used to display an arbitrary line, particularly when elements need to be kept in one and the same line. Alternatively, it is particularly interesting to look at the tr namespace as it provides some less heavy structures free from table constructions, for instance panelGroupLayout with a layout set to vertical or a panelBorderLayout, both generating div structures instead. <trh:cellFormat>: It is used to define an XHTML table cell as part of an XHTML table. The attributes of each tag are defined in a most consistent, and thus recognizable way. By the way, there are also tags for the construction of framesets such as trh:frame in case anyone still wants to make use of framesets. However, before we deal with the attributes let us conclude this structural overview by a look at the organization of the functionality of the core tag library. Trinidad’s core tag library namespace (tr) The following groups can be functionally distinguished which is also reflected in the packages structure of Trinidad's API (all beginning with org.apache.myfaces.trinidad.component; which has been left out here to avoid repetition). Note that, for completeness, we will also include information on the pure Java side as well as information on the few components that stem from the trh namespace: Basic document composition tags from the core API: document, stylesheet, form, subform. poll also appears here although it is not a composition tag. Form input and display tags, components from the core.input API: inputText, inputDate, inputListOfValues, and so on. Command or navigation tags from core.nav that includes two tag types: One that is focused on command tags that assumes a given form, presupposing the use of form and display tags from the foregoing group—commandButton, commandLink, goButton, goLink, and so on. The other deals exclusively with navigation: navigationTree, navigationPane, breadCrumbs, and so on. Large input and output component tags from core.data, for example, table, tree, and treeTable components. Layout component tags from core.layout, for example, all the swing-like panel tags, such as panelBorderLayout, panelHorizontalLayout, panelAccordion, showDetail, showDetailItem, and so on. Basic output components from core.output that are almost always used in a web application, for example, messages, outputText, outputLabel, spacer, statusIndicator, and so on. Model objects from core.model devised for various tags ; they provide the corresponding view models for their tag viewer counterparts, for example, SortableModel, CollectionModel and RowKeySet for tr:table, ChildPropertyTreeModel for tr:tree and ChartModel for tr:chart. A couple of converter components from trinidad.convert equip JSF and Trinidad input components with powerful JSF conversion, that is, convertNumber and convertDateTime. Validator components from trinidad.validator equip JSF and Trinidad input components with powerful JSF validation such as range validation (validateDateTimeRange) and validation by regular expression match (validateRegExp). Events and event listeners from trinidad.event add new event types and listeners specific for Trinidad components such as those that support Trinidad's dialog framework, for example, commandButton to launch a popup dialogue using LaunchEvent, ReturnEvent, and ReturnListener. It provides only a few tags, but these can be very utile, for example, fileDownloadActionListener, resetActionListener, returnActionListener, and setActionListener. There is a lot more to be found on the pure Java API side that either surfaces indirectly on the tag library as attributes, or is used implicitly by the tags themselves. Furthermore, there are utility classes and context support classes—RequestContext being probably the most prominent one because it offers a lot of functionality, for example, PPR from the server side. The following figure illustrates the Java side of things (it shows what the structure of some of the classes behind core.input look like): The preceding figure is an outline of the core.input API hierarchy. Again, we can see the typical UIX* and Core* structure. Finally, let us take a closer look at the tag attributes.
Read more
  • 0
  • 0
  • 1316

article-image-joomla-flash-flashy-templates-headers-banners-and-tickers-part-2
Packt
18 Nov 2009
4 min read
Save for later

Joomla! with Flash: Flashy Templates, Headers, Banners, and Tickers: Part 2

Packt
18 Nov 2009
4 min read
Using Flash headers We have seen that one of the uses of Flash in Joomla! templates is as a header. By using a Flash animation in a site's header you can create some stunning effects. As we have already seen, while designing the template, we may embed Flash animation in the header region and control the layout using an appropriate CSS stylesheet. To embed such Flash animations like these, you can use the <object> </object> XHTML tag. We have seen its use in the previous section. An alternative to this is showing the Flash header at some module position. There are several extensions that can be used for showing Flash objects at a module position. We will be looking at some of them next. Using Flexheader3 Flexheader3 is a Joomla! 1.5-compatible extension for using Flash as headers in Joomla! sites. This is available for download for free at http://flexheader2.andrehotzler.de/en/download/folder/208-flexheader3.html. After downloading the package, install it from the Extensions | Install/Uninstall screen in Joomla! administration. Then click on Extensions | Module Manager. In the Module Manager screen, you will find the module named Flexheader3. Click on it and that shows the Module: [Edit] screen for the Flexheader3 module, as shown in the following screenshot: The Details section is similar to other modules from where you enable the module, select the module position to display this, select the order of display, and assign menus for which this module will be displayed. The module-specific settings are in the Parameters section. As you see, selecting the module position is crucial for this module. Most of the templates don't have a position to display the header using a module. Therefore, you may need to create a module position for displaying a Flash header. The following section shows you how to create a module position displaying a header. Creating a module position To create a module position in your template you need to edit at least two files. Browse to the /templates directory, and click on the name of the template that you want to modify. You need to edit two files in the template folder: index.php and templateDetails.xml. First, open the templateDetails.xml file in your text editor and find the <positions> tag. Under this, type the line highlighted in the following code so that the file looks like the following: <positions> <position>flexheader</position> <position>left</position> <position>user1</position> ... <position>right</position> <position>debug</position> </positions> Remember to type <position>flexheader</position> before ending </positions> tag. Placing it outside the <positions> </positions> block will make the template unusable. After modifying the templateDetails.xml file, open the index.php file in your text editor. Find out the code for including a header image in that template. Generally, this is done by inserting an image using the <img src=... /> tag. If you don't find such a tag, then look for <div id="header" ... > or something like that. In such cases, CSS is used to display the background image to the div element. Once you have found the code for showing the header image, replace it with the following code: <jdoc:include type="modules" name="flexheader" style="RAW" /> This line of code means that you are instructing to include modules designated for the flexheader position. When we assign the Flexheader3 module to this position, the contents of that module will be displayed in this position. Generally, this module will produce a code like the following in this position: <img src="/images/header.png" title="My header image" alt="Header image" style="width: 528px; height: 70px;" /> When changes to index.php are made, save those changes. We will be configuring the module to display a Flash header in this module position.
Read more
  • 0
  • 0
  • 1919

article-image-joomla-flash-flashy-templates-headers-banners-and-tickers-part-1
Packt
18 Nov 2009
4 min read
Save for later

Joomla! with Flash: Flashy Templates, Headers, Banners, and Tickers: Part 1

Packt
18 Nov 2009
4 min read
In this article, we will mainly focus on the visual design of our site. To acquire the information presented here, it is assumed that you have some basic understanding of Joomla!'s visual design including templates, components, module position, and so on. Adding Flash in templates If you are familiar with Joomla! templates, then you will understand that there are two ways to display Flash in a template: By hardcoded embedding of Flash items By dynamically loading Flash objects at module positions We have seen many modules that can display Flash objects. Therefore, in this section, we will be looking into the embedding of Flash objects within templates. It will also be helpful if we understand the structure of Joomla! templates. Generally templates for Joomla! include headers in Flash. Flash animations are included in the header area of a Joomla! template. Some templates include the mechanism to show images from a specific directory. For example, the template shown in the following screenshot, available for download at http://joomlatp.com/joomla-1.5-templates/Templates-has-flash-header.html, is designed to show a Flash header comprised of the images kept in a directory: The following sections briefly describe the structure of a Joomla! template and the ways to embed a Flash object in this template. Structure of a Joomla! template The look and feel of Joomla! is determined by templates. You can apply a template to the frontend as well as to the backend. Templates for the Joomla! frontend reside in the /templates directory of the Joomla! webroot, while those for the administration panel are found in the /administrator/templates directory. You can install multiple templates and apply one or more templates to the different sections. However, you must designate one default template for the site. To designate a default template, go to Extensions | Template Manager. Select the desired template and click on the Default button on the toolbar. For assigning a template to a specific section of the site, click on a template, except the default template, and then select the section or the menu item for which you want to assign the template from the Menu Assignment section. If you examine the directory structure of a Joomla! template, you will find at least the following subdirectories in the templates directory: Directory Description mx_joofree2 This is the main template directory. It contains some subdirectories and at least the following files under its root: index.php: This is the main file for a template. The basic structure of a Joomla! template is defined in this file. We will examine this file later. templateDetails.xml: This XML file defines the template by mentioning its designer, the different files bundled with it, the positions and parameters available, and so on. params.ini: This file contains the parameters and their default values. For example, a template may use several colors for theming, but users can select a preferred color as a parameter for this template, and that information is stored in this file. mx_joofree2/css This directory contains all the cascading stylesheets to be used for a Joomla! site. This directory will contain at least one stylesheet named template_css.css. It may also contain a stylesheet named template_ie6.css and other stylesheets. mx_joofree2/html This folder may contain some definitions for the custom rendering of certain parts of the site. For example, the mx_joofree2 template contains two files-module.php and pagination.php. These two files define custom module rendering and pagination for Joomla!. For more information on using HTML overrides, refer to http://docs.joomla.org/How_to_override_the_content_from_the_Joomla!_core. mx_joofree2/images This folder contains the images for the template. It may contain a logo image, a background image, and so on. It may also contain some subdirectories, for example, the mx_joofree2 template contains a subdirectory images/headers, where the header images for the template are stored.
Read more
  • 0
  • 0
  • 1940

article-image-joomla-flash-showing-maps-using-yos-ammap
Packt
18 Nov 2009
12 min read
Save for later

Joomla! with Flash: Showing maps using YOS amMap

Packt
18 Nov 2009
12 min read
Showing maps using YOS amMap Adding a map to your site may be a necessity in some cases. For example, you want to show the population of countries, or you want to show a world map to your students for teaching geography. Flash maps are always interesting as you can interact with them and can view them as you like. amMap provides tools for showing Flash maps. The amMap tool is ported as a Joomla! component by yOpensource, and the component is released with the name YOS amMap. This component has two versions—free and commercial. The commercial or pro version has some advanced features that are not available in the free version. The YOS amMap component, together with its module, allows you to display a map of the world, a region, or a country. You can choose the map to be displayed, which areas or countries are to be highlighted, and the way in which the viewers can control the map. Generally, maps displayed through the YOS amMap component can be zoomed, centered, or scrolled to left, right, top, or bottom. You can also specify a color in which a region or a country should be displayed. Installing and configuring YOS amMap To use YOS amMap with your Joomla! website, you must first download it from http://yopensource.com/en/component/remository/?func=fileinfo&id=3. After downloading and extracting the compressed package, you get the component and module packages. Install the component and module from the Extensions | Install/Uninstall screen. Once installed, you can administer the YOS amMap component from Components | YOS amMap. This shows the YOS amMap Control Panel, as shown in the following screenshot: YOS amMap Control Panel displays several icons through which you can configure and publish maps. The first thing you should do is to configure the global settings for amMap. In order to do this, click on the Parameters icon in the toolbar. Doing so brings up the dialog box, as shown in the following screenshot: In the Global Configuration section, you can enter a license key if you have purchased the commercial or the pro version of this component. For the free version, this is not needed. In this section, you can also configure the legal extensions of files that can be uploaded through this component, the maximum file size for uploads, the legal image extensions, and the allowed MIME types of all uploads. You can also specify whether the Flash uploader will be used or not. Once you have configured these fields, click on the Save button and return to YOS amMap Control Panel. Adding map files You can see the list of available maps by clicking on the Maps icon on the YOS amMap Control Panel screen or by clicking on Components | amMap | Maps. This shows the Maps Manager screen, as shown in the next screenshot. As you can see, the Maps Manager screen displays the list of available maps. By default, you find the world.swf, continents.swf, and world_with_antartica.swf map files. You will find some extra maps with the amMap bundle. You can also download the original amMap package from http://www.ammap.com/download. After downloading the ZIP package, extract it, and you will find many maps in the maps subfolder. Any map from this folder can be uploaded to the Joomla! site from the Maps Manager screen. Creating a map There are several steps for creating a map using YOS amMap. First we need to upload the package for the map. For example, if we want to display the map of the United States of America, then we need to upload the map template, the map data file, and the map settings file for the United States of America. To do this first upload the map template from the Maps Manager screen. You will find the map template for USA in the ammap/maps folder. Then we need to upload the data and the settings files. For doing so, click on the Upload link on the YOS amMap Control Panel screen. Then, in the Upload amMap screen, which is shown in the next screenshot, type the map's title (United States) in the Title field. Before clicking on the Browse button besides the Package File field, you first add the ammap_data.xml and the ammap_settings.xml files to a single ZIP file, unitedstates.zip. Now, click on the Browse button, and select this unitedstates.zip file. Then click on the Upload File & Install button. Once uploaded successfully, you see this map listed in the YOS amMap Manager screen, as shown in the next screenshot. You get this screen by clicking on the amMaps link on the toolbar. As you can see, the map that we have added is now listed in the YOS amMap Manager screen. However, the map is yet in an unpublished state, and we need to configure the map before publishing it. We need to configure its data and settings files, which are discussed in the following sections. Map data file The different regions of a map are identified by the map data file. This is an XML file and it defines the areas to be displayed on the map. The typical structure of a map data file can be understood by examining ammap_data.xml. The file has many comments that explain its structure. This file looks like as follows: <?xml version="1.0" encoding="UTF-8"?><map map_file="maps/world.swf" tl_long="-168.49" tl_lat="83.63" br_long="190.3" br_lat="-55.58" zoom_x="0%" zoom_y="0%" zoom="100%"><areas> <area title="AFGHANISTAN" mc_name="AF"></area> <area title="ALAND ISLANDS" mc_name="AX"></area> <area title="BANGLADESH" mc_name="BD"></area> <area title="BHUTAN" mc_name="BT"></area> <area title="CANADA" mc_name="CA"></area> <area title="UNITED ARAB EMIRATES" mc_name="AE"></area> <area title="UNITED KINGDOM" mc_name="GB"></area> <area title="UNITED STATES" mc_name="US"></area> <area title="borders" mc_name="borders" color="#FFFFFF" balloon="false"></area></areas><movies> <movie lat="51.3025" long="-0.0739" file="target" width="10" height="10" color="#CC0000" fixed_size="true" title="build-in movie usage example"></movie> <movie x="59.6667%" y="77.5%" file="icons/pin.swf" title="loaded movie usage example" text_box_width="250" text_box_height="140"> <description> <![CDATA[You can add description text here. This text will appear the user clicks on the movie. this description text can be html-formatted (for a list which html tags are supported, visit <u><a href="http://livedocs.adobe.com/flash/8/main/00001459.html">this page</a></u>. You can add descriptions to areas and labels too.]]> </description> </movie></movies><labels> <label x="0" y="50" width="100%" align="center" text_size="16" color="#FFFFFF"> <text><![CDATA[<b>World Map]]></text> <description><![CDATA[]]></description></label></labels><lines> <line long="-0.0739, -74" lat="51.3025, 40.43" arrow="end" width="1" alpha="40"></line> </lines></map> This code is a stripped-down version of the default ammap_data.xml file. Let us examine its structure and try to understand the meaning of each markup: <map> </map>: You define the map's structure using this markup. First, by using the map_file attribute, we declare the map file that should be used to display this map. This markup has some other attributes through which we declare the top and the left offset in longitude and latitude. We can also specify the zooming level using the zoom_x, zoom_y, and zoom attributes. <areas> </areas>: Areas are the regions or countries on a map. These are defined in the map. We only need to define the areas that we want to display. For example, in the sample, we have defined eight countries to be displayed and one straight line. Each area element has several attributes, among which you need to mention mc_name and title. You specify the area's name in mc_name, which is predefined in the map template. The title element will be displayed as the title of that map area. For example, <area mc_name="BD" title="Bangladesh"></area> means the areas marked as BD in the map template will be displayed with the title Bangladesh. In order to specify the mc_name element, you need to follow the map template designer's instructions. <movies> </movies>: Movies are some extra clips that can be displayed as a separate layer on the map. For example, to display the capital of each country, a movie clip could be displayed in the specified latitude and longitude. You can also display some other animations or text using a movie definition. <labels> </labels>: The <labels> markup contains the text to be displayed on the map. You can add any text on a map by defining a label element. To view and edit the map data file, ammap_data.xml, click on the map name on the YOS amMap Manager screen. This opens-up the amMap: [Edit] screen, as shown in the following screenshot: The amMap: [Edit] screen displays several configurations for the map. From the Details section you can change the map name, publish the map, and enable security. From the Design section you can view and edit the data and the settings files. Clicking on Data will show the data file. You can edit the data file from the online editor. As we want to display the map of USA, we will make the following changes on this screen: Select usa.swf in the Maps list. Change the data file as follows: <?xml version="1.0" encoding="UTF-8"?><map map_file="maps/usa.swf" zoom="100%" zoom_x="7.8%"zoom_y="0.18%"><areas> <area mc_name="AL" title="Alabama"/> <area mc_name="AK" title="Alaska"/> <area mc_name="AZ" title="Arizona"/> <area mc_name="AR" title="Arkansas"/> <area mc_name="CA" title="California"/> <area mc_name="CO" title="Colorado"/> <area mc_name="CT" title="Connecticut"/> <area mc_name="DE" title="Delaware"/> <area mc_name="DC" title="District of Columbia"/> <area mc_name="FL" title="Florida"/> <area mc_name="GA" title="Georgia"/> <area mc_name="HI" title="Hawaii"/> <area mc_name="ID" title="Idaho"/> <area mc_name="IL" title="Illinois"/> <area mc_name="IN" title="Indiana"/> <area mc_name="IA" title="Iowa"/> <area mc_name="KS" title="Kansas"/> <area mc_name="KY" title="Kentucky"/> <area mc_name="LA" title="Louisiana"/> <area mc_name="ME" title="Maine"/> <area mc_name="MD" title="Maryland"/> <area mc_name="MA" title="Massachusetts"/> <area mc_name="MI" title="Michigan"/> <area mc_name="MN" title="Minnesota"/> <area mc_name="MS" title="Mississippi"/> <area mc_name="MO" title="Missouri"/> <area mc_name="MT" title="Montana"/> <area mc_name="NE" title="Nebraska"/> <area mc_name="NV" title="Nevada"/> <area mc_name="NH" title="New Hampshire"/> <area mc_name="NJ" title="New Jersey"/> <area mc_name="NM" title="New Mexico"/> <area mc_name="NY" title="New York"/> <area mc_name="NC" title="North Carolina"/> <area mc_name="ND" title="North Dakota"/> <area mc_name="OH" title="Ohio"/> <area mc_name="OK" title="Oklahoma"/> <area mc_name="OR" title="Oregon"/> <area mc_name="PA" title="Pennsylvania"/> <area mc_name="RI" title="Rhode Island"/> <area mc_name="SC" title="South Carolina"/> <area mc_name="SD" title="South Dakota"/> <area mc_name="TN" title="Tennessee"/> <area mc_name="TX" title="Texas"/> <area mc_name="UT" title="Utah"/> <area mc_name="VT" title="Vermont"/> <area mc_name="VA" title="Virginia"/> <area mc_name="WA" title="Washington"/> <area mc_name="WV" title="West Virginia"/> <area mc_name="WI" title="Wisconsin"/><area mc_name="WY" title="Wyoming"/></areas><labels> <label x="0" y="60" width="100%" color="#FFFFFF" text_size="18"> <text>Map of the United States of America</text> </label></labels></map> As you can see, we have defined regions (states) on the map of USA, and towards the end of the file, we have added a label for the map. Select Yes for the Published field in the Details section. When you are done making these changes click on the Save button to save these changes. Now we will look into the map settings file. Map data files for countries are available with the amMap package. Thus, if you download amMap 2.5.1, you will get the map settings files for different countries. For example, the map data file for USA will be in the amMap_2.5.1/examples/_countries/usa folder.  
Read more
  • 0
  • 0
  • 3854
article-image-joomla-15-blogging-and-rss-feeds
Packt
18 Nov 2009
7 min read
Save for later

Joomla! 1.5 Blogging and RSS Feeds

Packt
18 Nov 2009
7 min read
  Blogging is a great way to get more traffic to your site and communicate with the community interested in the same topics as you. Search engines such as Yahoo! and Google love blogs because of the fact that articles written in blogs are mostly up-to-date and they get the information about the update of a blog really fast using RSS Feeds and Pings. Articles posted on a blog with these two options in place can get into the search engine indexes within hours, sometimes even minutes. How is blogging good for SEO? Using a blog has some advantages that fair really well if you want to have more visibility in the search engines. We will be looking at some of those advantages and how they can affect your search engine rankings. I am not saying blogging is easy, but it is very rewarding. Creating fresh content Creating short articles about your favorite topic and publishing them on a regular basis is the best way to get into the search engine results pages faster. The number one thing about blogging is that you can write long articles or short articles. The combination of the two different formats won't break the flow of your site, unlike a normal web site, where you mostly write articles that are built with a certain length. You can also state an opinion about things that are going on in your community and write news items. All that in one web site without worrying too much about how to structure all the information. A structure is needed for SEO and Joomla! will force you to use the structure you have chosen for your site. Using Joomla! as a blog will make it easier for you as you will be using the categories created in advance to hold that information for you. Google and blog indexing If you set up a blog and start using the sites and services we will be looking at, like FeedBurner and Technorati, you will notice that the major search engines also use these services to index blog sites and find new posts really fast. Now Google even owns FeedBurner! You will not only syndicate your articles using options such as RSS Feeds, but you will also push your articles through Technorati, the number one site to show your blog to bloggers. Google has a special tool with some basic categorization in place for searching blogs; you can find it at http://blogsearch.google.com. One good thing about this blog search tools is that it will show you how "old" a blog post is. For example, under the title you will see a statement such as 10 hours ago just to prove how fast you can get an article indexed from a blog. Setting up Joomla! as a blog Joomla! was not built to be a blog in its basic form, unlike WordPress. However, Joomla! has a built-in layout function called Blog layout that can be used for sections and categories. RSS Feeds are also built in, but we need to put an extra component in place to get a commenting system. First things first, let's set up the basic structure of your Joomla! based blog. How to structure your blog section The first thing you need to do is to come up with a section name for your blog. You already have an extended keywords list, so it should not be difficult to set up a blog. In my example site I have set up a Section called Garden Pools Blog and the Alias I want to use is garden-pools. This alias is going to be included in the SEF URL and contains some of the keywords I want to target with the blog. Once that is ready, you need to create the main categories, which of course will be the main topics of your blog section. Choosing your blog categories Again you need to find the right keywords to put into your category names. The best thing you can do now is to focus on the topic you want to blog about. It is really essential that you think about these categories and name them the right way, or you will get into trouble later on. Once you know about the SEF URLs, you might find yourself in trouble if you have the same category names as in the main site. In my category for this blog I have used the category name Water Gardens, depending on my choice of URL construction in the sh404SEF component. It is possible that I may not use the same category name for the main topics of my site. If I were to use the same category name they both would get the URL http://www.cblandscapegardening/water-gardens/, leaving one of the categories not reachable. One workaround would be to change the alias of one of the categories, but that would still leave a duplicate title on your site which you would need to change. Google would show it as a possible duplicate title in its webmaster content analysis. You can prevent this by choosing your categories wisely. Therefore, it is important to think about these URL structures, when you start naming and creating the blog categories. Stay focused and limit yourself If you start naming the categories make sure you stay on the same blog topic and keep the terms as relevant as possible. Don't create too many categories as you are going to create a separate menu for the blog. Too many categories will fill your menu with a long list of topics, and the visitors will not be able to choose from this long list. It is also not a pretty sight to have such a long list in your sidebar. Limiting yourself to a smaller section of categories, which you want to connect your articles to, will help you to stay more relevant to the topic of your choice. Creating a blog menu Once you have set up your categories, it's time to create your blog menu. Start with creating a new menu and call it whatever you want to, give it a title like The Garden Blog as in my example site. To set this feature go to your administrator panel and choose Menus | Main Menu from the menu bar at the top. After that choose New. Make it short and to the point so that it is really easy to find it on your site. Go to the Extensions menu, choose Module Manager, and Publish the module in the location you want it to show on your site. The first thing you should do is create a link to the section in which you are going to put your blog posts, and change the Parameters(Basic) to match the layout you want:   #Leading is set to 1, which means one full length article to start with   #Intro is set the 6, so you have the introduction text (that is the text before the "read more" link) from six articles, getting a total of seven on the blog page   Columns is set to 1 to get a complete overview of the articles in a listing that is not broken into two columns after the first Intro article   #Links this is the number of links with the title of older articles that don't show on the blog page anymore After setting the Parameters(Basic) you need to set the Parameters(Advanced) as well:   Change the Category Order to Order and the Primary Order to Most recent first.   Make sure you have the Show a Feed Link set to Yes—only for this menu item. This option is set so that we can get a full RSS Feed over all the blog categories For a blog, you need to change some of the settings in the Parameters(Component):     For a blog you need to Show the Author Name, the Created Date and Time, the Show Navigation, and the Read more... Link   The Article Rating/Voting depends on you, for me its set to off, as I don't like the dotted rating icons. The commenting system will give your visitors the ability to share their thoughts about your article, rather than just rate them, unlike the rating system. You will learn more about such a commenting system later in this article.
Read more
  • 0
  • 0
  • 1559

article-image-make-spacecraft-fly-and-shoot-special-effects-using-blender-3d-249
Packt
18 Nov 2009
4 min read
Save for later

Make Spacecraft Fly and Shoot with Special Effects using Blender 3D 2.49

Packt
18 Nov 2009
4 min read
Blender particles In the last versions of Blender 3D, the particle system received a huge upgrade, making it more complex and powerful than before. This upgrade, however, made it necessary to create more parameters and options in order for the system to acts. What didn't change was the need for an object that works as emitter of the particles. The shape and look of this object will be directly related to the type of effects we want to create. Before we discuss the effects that we will be creating, let's look at how the particles work in Blender. To create any type of particle system, go to the Objects panel and find the Particles button. This is where we will set up and change our particles for a variety of effects. The first time we open this menu, nothing will be displayed. But, if we select a mesh object and press the Add New button, this object will immediately turn into a new emitter. When a new emitter is created, we have to choose the type of behavior this emitter has in the particle system. In the top-left part of the menu, we will find a selector that lets us choose the type of interaction of the emitter. These are the three types of emitters: Emitter: This is the standard type, which is a single object that emits particles according to the parameters and rules that we set up in the particles controls. Hair: Here, we have a type of particle emitter that creates particles as thin lines for representing hair and fur. Since this is more related to characters, we won't use this type of emitter in this book. Reactor: With this emitter, we can create particle systems that interact with each other. It works by setting up a particle system that interferes with the motion and changes the trajectories of other particles. In our projects, we will use only the emitter type. However, you can create indirect animations and use particles to interact with each other. For instance, if you want to create a set of asteroids that block the path of our spacecraft, we could create this type of animation easily with a reactor particle system. How particles work To create and use a particle system, we will look at the most important features and parameters of each menu and create some pre-systems to use later in this article for the spacecraft. To fully understand how particles work, we have to become familiar with the forces or parameters that control the look and feel of particles. For each of those parameters and forces, we have a corresponding menu in Blender. Here corresponding parameters that control the particle system: Quantity: This is a basic feature of any particle system that allows us to set up how many particles will be in the system. Life: As a particle system is based on animation parameters, we have to know from how many frames the particle will be visible in the 3D world. Mesh emitting: Our emitters are all meshes, and we have to determine from which part of those 3D objects the particles will be emitted. We have several options to choose from, such as vertices or parts of the objects delimited by vertex groups. Motion: If we set up our particle system and don't give it enough force to make the particles move, nothing will happen to the system. So, even more important than setting up the appearance of the particles is choosing the right forces for the initial velocity of the particles. Physics and forces: Along with the forces that we use in the motion option, we will also apply some force fields and deflectors to particles to simulate and change the trajectories of the objects based on physical reactions. Visualization: A standard particle system has only small dots as particles, but we can change the way particles look in a variety of ways. To create flares and special effects such as the ones we need, we can use mesh objects that have Halo effects and many more. Interaction: At the end of the particle life, we can use several types of actions and behaviors to control the destiny of a particle. Should it spawn a new particle or simply die when it hits a special object? These are the things we have to consider before we begin setting up the animation.
Read more
  • 0
  • 0
  • 2515

article-image-extending-joomla-blogging-and-rss
Packt
18 Nov 2009
5 min read
Save for later

Extending Joomla! Blogging and RSS

Packt
18 Nov 2009
5 min read
Using Google's FeedBurner for SEO The preferred choice for burning your feed was www.feedburner.com, and they were so good at it that Google bought FeedBurner. So now if you want to Burn your Feed you have to login to Google with your Gmail account. Once logged in, look for the service FeedBurner and click on it. You will find a small screen in the middle of the page that says: Here you can paste the link that you got after clicking on Feed Entries on your Joomla! site. That is the public RSS Feed link that is shown by your syndication module. Once you click on the Next button you have a lot of options to improve your blog feed. The first thing you have to do is to make sure you have a nice feed URL.   I wanted it to be TheGardenBlog, but it was already taken so I settled for TheCrazyBeezGardenBlog, which is also good. You can also adjust your Feed Title, if you think it will be better, this title will be shown in a RSS reader to identify your feed. Click on Next and there you are:   Are you done? No way, now we get to the best part of the FeedBurner by Google service. Choosing your FeedBurner options for optimal results The Google service has a lot of options in store that will improve our RSS visibility and provide us with some blogging features that Joomla! doesn't have. One of the most important services is the PingShot that we will be looking at later. Let's take small steps and see what we can configure to get the best of the best. First we will go through the option tabs and check what you should really use:   Analyze: This is where you will see how well you are doing looking at your feed reader's stats   Optimize: Here are two services you need to activate, BrowserFriendly and SmartFeed   Publicize: Most of your work will be done here with Email Subscriptions, PingShot, FeedCount, and NoIndex   Monetize: Only if you want AdSense advertisements into your Feeds   Troubleshootize: A great place to start if your feed doesn't work the way it should From the tabs mentioned, we will be looking more closely at some of the settings in the Optimize and Publicize tabs. Let's take a look at the Optimize tab settings:   BrowserFriendly: This makes your RSS Feed that comes out of Joomla! a lot better, because it turns the not-so-nice looking feeds into human viewable HTML pages. For this, compare the following two screenshots. And all you have to do is activate the service!   SmartFeed is all for your visitors, it will give them the choice of viewing your feed into their favorite feed reader. There are a lot of feed readers out there. If you activate this service you give your visitors an easy choice to import your feed with a single click. If they click on your RSS Feed button, they get a list of services to which, they can add your feed with just a click on the button. Now, let's take a look at the Publicize tab settings:   Email Subscriptions makes it really easy to offer an email subscription to your RSS Feed.After activation of this service, copy the code from the Subscription Form Code field, and paste it on your site in a HTML module. To create such a module, go to your administrator panel. Choose Extensions from the top menu, then choose Module Manager. Then click on New and choose Custom HTML, give it a Title, Position, and publish it after you paste the code. The subscription form and fields are now ready for use. You can also configure the time when you want those emails to be sent to your visitors using the Delivery Options setting.   PingShot: PingShot does something that Joomla! cannot, but is essential for a blog. It sends a ping after you publish your post to several services such as Technorati, My Yahoo, and Bloglines.Make sure you activate the other two and add up to five extra options. For example, Ping-o-matic which will ping several other services for you, and Newsgator, which is another good service. From the drop-down list you can add a few extra services of which Google Blog Search Pinging Service is one.The other choice of services is dependent on the niche you work in, but for me the following ones work great:      icerocket     Weblogs.Com     FeedBlitz     Syndic8         FeedCount: This is a well-known counter. You can show it on your site to let people know how many subscribers are there on your feed. Don't show the feed count until you have over a minimum of 100 subscribers. There is a psychological effect behind this tip.Nobody will subscribe to your feed if it shows that there are only 3 subscribers. The thought behind this is that it is probably not that interesting because there are few subscribers.If you get over 100 subscribers, start showing the count! With over 100 subscribers there must be value in that feed! If you reach that limit and show it you will see that the number of subscribers will soon start to grow faster than before.   NoIndex: This option makes sure that your own feed is not indexed and ranking higher than your pages. This means the feed from burner.com will not be indexed, because of that it is not possible to have it outrank your pages. If you don't use that option the feed itself has the possibility to outperform your pages (this is not likely, but I have seen it happen on some sites, although that was before Google bought FeedBurner).
Read more
  • 0
  • 0
  • 924
article-image-authentication-zendauth-zend-framework-18
Packt
18 Nov 2009
6 min read
Save for later

Authentication with Zend_Auth in Zend Framework 1.8

Packt
18 Nov 2009
6 min read
Let's get started. Authentication versus Authorization Before we go any further, we need to first look at what exactly authentication and authorization is, as they are often misunderstood. Authorization is the process of allowing someone or something to actually do something. For example, if I go into a data centre, then the security guards control my authorization to the data centre and would, for instance, not allow me access to the server room if I was just a visitor but would if I worked there as a system admin. Authentication is the process of confirming someone or something's identity. For example, when I go to into the data centre the security guards will ask me for my identity, which most probably would be a card with my name and photo on. They use this to authenticate my identity. These concepts are very important so make sure you understand the difference. This is how I remember them: Authorization: Can they do this?Authentication: Are they who they say they are? Authentication with Zend_Auth To provide our authentication layer, we are going to use Zend_Auth. It provides an easy way to authenticate a request, obtain a result, and then store the identity of that authentication request. Zend_Auth Zend_Auth has three main areas—authentication adapters, authentication results, and identity persistence. Authentication adapters Authentication adapters work in a similar way to database adapters. We configure the adapter and then pass it to the Zend_Auth instance, which then uses it to authenticate the request. The following concrete adapters are provided by default: HTTP Digest authentication HTTP Basic authentication Database Table authentication LDAP authentication OpenID authentication InfoCard authentication All of these adapters implement the Zend_Auth_Adapter_Interface, meaning we can create our own adapters by implementing this interface. Authentication results All authentication adapters return a Zend_Auth_Result instance, which stores the result of the authentication request. The stored data includes whether the authentication request was successful, an identity if the request was successful, and any failure messages, if unsuccessful. Identity persistence The default persistence used is the PHP session. It uses Zend_Session_Namespace to store the identity information in the Zend_Auth namespace. There is one other type of storage available named NonPersistent, which is used for HTTP authentication. We can also create our own storage by implementing the Zend_Auth_Storage_Interface. Authentication Service We are going to create an Authentication Service that will handle authentication requests. We are using a service to keep the authentication logic away from our User Model. Let's create this class now: application/modules/storefront/services/Authentication.phpclass Storefront_Service_Authentication{ protected $_authAdapter; protected $_userModel; protected $_auth; public function __construct(Storefront_Model_User $userModel = null) { $this->_userModel = null === $userModel ? new Storefront_Model_User() : $userModel; } public function authenticate($credentials) { $adapter = $this->getAuthAdapter($credentials); $auth = $this->getAuth(); $result = $auth->authenticate($adapter); if (!$result->isValid()) { return false; } $user = $this->_userModel ->getUserByEmail($credentials['email']); $auth->getStorage()->write($user); return true;}public function getAuth(){ if (null === $this->_auth) { $this->_auth = Zend_Auth::getInstance(); } return $this->_auth;}public function getIdentity(){ $auth = $this->getAuth(); if ($auth->hasIdentity()) { return $auth->getIdentity(); } return false;}public function clear(){ $this->getAuth()->clearIdentity();}public function setAuthAdapter(Zend_Auth_Adapter_Interface $adapter){ $this->_authAdapter = $adapter;}public function getAuthAdapter($values){ if (null === $this->_authAdapter) { $authAdapter = new Zend_Auth_Adapter_DbTable( Zend_Db_Table_Abstract::getDefaultAdapter(), 'user', 'email', 'passwd' ); $this->setAuthAdapter($authAdapter); $this->_authAdapter ->setIdentity($values['email']); $this->_authAdapter ->setCredential($values['passwd']); $this->_authAdapter ->setCredentialTreatment( 'SHA1(CONCAT(?,salt))' ); } return $this->_authAdapter; }} The Authentication Service contains the following methods: __constuct: Creates or sets the User Model instance authenticate: Processes the authentication request getAuth: Returns the Zend_Auth instance getIdentity: Returns the stored identity clear: Clears the identity (log out) setAuthAdapter: Sets the authentication adapter to use getAuthAdapter: Returns the authentication adapter The Service is really separated into three areas. They are getting the Zend_Auth instance, configuring the adapter, and authenticating the request using Zend_Auth and the Adapter. To get the Zend_Auth instance, we have the getAuth() method. This method retrieves the singleton Zend_Auth instance and sets it on the $_auth property. It is important to remember that Zend_Auth is a singleton class, meaning that there can only ever be one instance of it. To configure the adapter, we have the getAuthAdapter() method. By default, we are going to use the Zend_Auth_Adapter_DbTable adapter to authenticate the request. However, we can also override this by setting another adapter using the setAuthAdapter() method. This is useful for adding authenticate strategies and testing. The configuration of the DbTable adapter is important here, so let's have a look at that code: $authAdapter = new Zend_Auth_Adapter_DbTable( Zend_Db_Table_Abstract::getDefaultAdapter(), 'user', 'email', 'passwd', 'SHA1(CONCAT(?,salt))');$this->setAuthAdapter($authAdapter);$this->_authAdapter->setIdentity($values['email']);$this->_authAdapter->setCredential($values['passwd']); The Zend_Auth_Adapter_DbTable constructor accepts five parameters. They are database adapter, database table, table name, identity column, and credential treatment. For our adapter, we supply the default database adapter for our table classes using the getDefaultAdapter() method, the user table, the email column, the passwd column, and the encryption and salting SQL for the password. Once we have our configured adapter, we set the identity and credential properties. These will then be used during authentication. To authenticate the request, we use the authenticate method. $adapter = $this->getAuthAdapter($credentials);$auth = $this->getAuth();$result = $auth->authenticate($adapter);if (!$result->isValid()) { return false;}$user = $this->_userModel ->getUserByEmail($credentials['email']);$auth->getStorage()->write($user);return true; Here we first get the configured adapter, get the Zend_Auth instance, and then fetch the result using Zend_Auth's authenticate method, while passing in the configured adapter. We then check that the authentication request was successful using the isValid() method. At this point, we can also choose to handle different kinds of failures using the getCode() method. This will return one of the following constants: Zend_Auth_Result::SUCCESSZend_Auth_Result::FAILUREZend_Auth_Result::FAILURE_IDENTITY_NOT_FOUNDZend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUSZend_Auth_Result::FAILURE_CREDENTIAL_INVALIDZend_Auth_Result::FAILURE_UNCATEGORIZED By using these, we could switch and handle each error in a different way. However, for our purposes, this is not necessary. If the authentication request was successful, we then retrieve a Storefront_Resource_User_Item instance from the User Model and then write this object to Zend_Auth's persistence layer by getting the storage instance using  getStorage() and writing to it using write(). This will then store the user in the session so that we can retrieve the user information throughout the session. Our Authentication Service is now complete, and we can start using it to create a login system for the Storefront.
Read more
  • 0
  • 0
  • 1966

article-image-customizing-document-joomla-15-part-2
Packt
18 Nov 2009
3 min read
Save for later

Customizing the Document with Joomla! 1.5: Part 2

Packt
18 Nov 2009
3 min read
Creating a PDF in a component This recipe explains how to create a PDF view in a Joomla! MVC component. Adding PDF views is a relatively quick process, and it significantly improves the functionality of a component. Getting ready Like any other view format, we must create a new JView subclass to create a PDF view. This should be located in the corresponding view's folder and the file should be named view.pdf.php. For example, for the myview view in the mycomponent component, we create the components/com_mycomponent/views/myview/view.pdf.php file, in which we place the MycomponentViewMyview class, which extends JView. How to do it... The first thing we do is override the display() method in order to change the PDF document. We modify the document using the mutator methods. The first method changes the document title, this is the title normally shown in the title bar of the PDF viewer. $document->setTitle($title); The next method changes the filename. This is especially useful if the user is likely to save the file, as this will be the default name the user is prompted to save the file as. $document->setName($filename); The next method sets the document description, sometimes referred to as the subject. This should only be a very brief description of the document. $document->setDescription($description); The next method sets the document metadata. Currently, only keywords are supported. It is possible to set other metadata, but it will not be used in the document. $document->setMetaData('keywords', $keywords); So far, all of the methods do not print anything to the body of the PDF itself. The next method adds a common header to every page. Note that the header text itself is not formatted. $document->setHeader("My PDF Document TitlenMy Subtitle"); Lastly, we can add content to the main body of the PDF document. We achieve this in the normal way by simply outputting the content. echo 'This is my PDF! '; The outputted data can be formatted using some basic HTML tags. The following tags are supported: Type Tags Format <b>, <u>, <i>, <strong>, <em>, <sup>, <sub>, <small>, <font> Heading <h1>, <h2>, <h3>, <h4>, <h5>, <h6> Indentation <blockquote> Linked <a>, <img> List <ol>, <ul>, <li> Spacing <p>, <br>, <hr> Table <table>, <tr>, <td>, <th>
Read more
  • 0
  • 0
  • 1014