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

How-To Tutorials

7018 Articles
article-image-polygon-modeling-handgun-using-blender-3d-249-part-1
Packt
30 Nov 2009
3 min read
Save for later

Polygon Modeling of a Handgun using Blender 3D 2.49: Part 1

Packt
30 Nov 2009
3 min read
With the base model created, we will be able to analyze the shape of our model and evaluate the next steps of the project. We can even decide to make changes to the project because new ideas may appear when we see the object in 3D rather than in 2D. Starting with a background image The first step to start the modeling is to add the reference image as the background of the Blender 3D view. To do that, we can go to the View menu in the 3D view and choose Background Image. The background image in Blender appears only when we are at an orthogonal or Camera view. The background image is a simple black and white drawing of the weapon, but it will be a great reference for modeling. Before we go any further, it's important to point out a few things about the Background Image menu. We can make some adjustments to the image if it doesn't fit our Blender view: Use: With this button turned on, we will use the image as a background. If you want to hide the image, just turn it off and the image will disappear. Blend: The blend slider will control the transparency of the image. If you feel that the image is actually blocking your view of the whole model, making it a bit transparent may help. Size: As the name says, we can control the scale of the image. X and Y offset: With this option, we will be able to move the image in the X or Y axis to place it in a specific location. After clicking on the Use button, just hit the load button and choose the image to be used as a reference. Since you don't have the image used in this example, visit the Packt web site and download the project files from Support. If you've never used a reference image in Blender, it is important to note that the reference images appear only in 3D view when we are using the orthographic view or the camera view mode. It works only in the top, right, left, front, and other orthographic views. If you hit 5 and change the view to perspective, the image will disappear. By using the middle mouse button or the scroll to rotate the view, the image disappears. However, it's still there and we can see the image again by changing the view to an orthogonal or camera view. Make the image more transparent by using the Blend control. It will help in focusing on the model instead of the image. A value of 0.25 will be enough to help in the modeling without causing confusion.
Read more
  • 0
  • 0
  • 3319

article-image-customizing-headers-and-footers-ms-office-live-small-business
Packt
30 Nov 2009
13 min read
Save for later

Customizing Headers and Footers with MS Office Live Small Business

Packt
30 Nov 2009
13 min read
Although a website is just a collection of web pages, the collection is not random. A central theme ties the web pages together with common elements such as branding, logo, layout, and formatting. On really large websites, the interweaving of these elements can be quite complex. Each of Google's websites, for example, has its distinct identity and yet you can identify it as a "Google website". It takes a small army of designers and illustrators to achieve such a "Similar But Distinct" identity. But it's fairly easy to establish a unifying theme for the web pages of a small website, such as yours. And you can do it all by yourself; a common header and footer is all that's usually necessary. Naturally, it would make immense sense if you could design a template for headers and footers once and use it on all of your web pages. A template isn't all that revolutionary a concept. You've probably built a template in your word processor for your letterhead or for a boilerplate, for example. Many widely-used applications save you the trouble of repetitive formatting by allowing you to make templates. Therefore, it shouldn't come as a great surprise to you that you can build page templates in Office Live Small Business as well. A web page template in Office Live Small Business has two components: information and design. The information component consists of the text and images that are specific to your website, such as your company name, logo, slogan, copyright notice, and so on. The design component deals with choosing the right font, colors, background pictures, and other such visual elements. Once you configure the necessary settings, you'll have a shell, so to say, which will appear around the content on your web pages. Choosing a title for your website A website's title is usually the name of the business it represents. My little company is called Acxede, for example. Therefore, it's logical that my site's title mimics my company's name. Now, there's only so much real estate available on a web page for the title. Because Acxede happens to be a short name, it can fit into most page layouts. But if your business is incorporated as Anthony Donaldson's Vacuum Cleaner Sales, Service, and Rentals Incorporated, this scheme of things breaks down. What do you do then? A good rule of thumb is to echo whatever name is on your business card. Unless your business card is the size of a postcard, you'd have shortened the name to something like Anthony Donaldson Inc. Use that as your site's title. People often want to set their domain name as their site's title. Because my company is called Acxede, it would, of course, be terrific to have acxede.com as my domain name. And I do. Unfortunately, not everyone is that lucky. More likely than not, the domain name you want is already taken. Let's say that you're Sam and you own a deli called, naturally, Sam's Deli. Everyone just calls it "Sam's". It wouldn't be unreasonable for you to want the domain name sams.com. The trouble is that Sam's Publishing has already snapped it up. Okay, so how about samsdeli.com? Nope. Another Sam owns it. So you're forced to settle for a domain name that doesn't echo the name of your business; something like samsfreshfood.com, perhaps. Nevertheless, your website's title should still say "Sam's Deli" because that's the name of your business, no matter what domain name you ultimately settle on. Now that you know more about setting a website's title than you ever wanted to, let's get around to doing the honors. Time for action – setting the site title Pull down the Design Site menu from the Page Manager toolbar and select Design site. A new window opens, displaying the Microsoft Office Live Small Business Web Design Tool web page with Site Designer as the active tab. Click on the Header button on the ribbon. The Customize Header dialog opens. Replace the text Welcome to my site in the gray box in the Site Title section with your site's title. I'm going to set it as The Office Live Guide for the site that I'm building—this article's companion site. Pull down the select options for the font face just above the title. You'll see a choice of seven fonts: Arial, Courier New, Georgia, Tahoma, Times New Roman, Trebuchet MS, and Verdana. Why only seven? After all, Microsoft Word seems to have a hundred. The reason is that in the Web's architecture, the task of displaying a given font is delegated to your browser. Not every browser can display every font. If a browser can't display a font that you've specified, it displays one that it thinks is right. Such a substitution might distort your web page. But these seven fonts are, more or less, the least common denominator; most browsers support them. Therefore, the chances of your web pages being distorted are quite slim if you choose one of these seven. So which of these seven should you choose? Follow this two step process: If one of the fonts in the list looks like the font on your letterhead or the sign above your office, choose that one. Not even close? Choose either Georgia or Verdana. Most fonts, such as Arial or Times New Roman, came to computer displays from the world of print. They were designed to look good on paper. Making a font look good on paper is relatively easy because text is printed on paper in very high resolution. On a monitor, however, pixels of resolution are at a premium. Besides, the resolution can vary from monitor to monitor. Therefore, text will look better onscreen if you use fonts that are designed specifically for monitors rather than using fonts that are grandfathered from the print world. Georgia and Verdana are designed specifically for monitors and so they're the ideal candidates for the text on your web pages. Set the font you've chosen. I've set it to Georgia. Next, pull down the adjacent select options for the font size. You'll see a choice of seven font sizes. They're conveniently numbered from 1 to 7. Size 1 is the smallest and size 7 is the largest. For some inexplicable reason, people often choose a size that's either too big or too small. I recommend size 5 for the title. That's just about right for most websites built with Office Live Small Business. One thing you've got to remember, though, is that: Thou shalt use Georgia or Verdana in size 5 for your site's title is not the eleventh commandment. I've suggested these settings because, in my experience, they are just about right for most websites built with Office Live Small Business. They make the header appear proportionate to the text on the web pages. But, they may not be right for your site if its title or slogan is either too long or too short. Come back and experiment with the font face or size of the header elements if your pages look out-of-whack after you finish building your website. Set the font size you've chosen. I've set it to 5. Although you can choose a color for the title. The choice of color depends on other layout options as well. Although you can make the title bold, italicize it, or underline it, you'd do well by avoiding the temptation. Depending on a combination of factors such as the font face, font size, and resolution of a visitor's monitor, these special effects can make the text quite difficult to read. The last thing you want to do is to inadvertently make the title of your site unreadable. Your Customize Header dialog should now look something like this: Keep the window open; you might as well set a slogan for your website while you're there. What just happened? You just took the first baby steps towards building your website! Agreed, all you did was set the site title—not exactly the kind of stuff that you'd write home about, but it's a fine start nevertheless. Your site's title and slogan, which you'll set in the following section, play an important role in helping people find your site from search engines. Choosing a slogan for your website An Office Live Small Business website's slogan is really just its tagline; so I'll use the terms interchangeably. Successful businesses use catchy taglines to reinforce their brands. What comes to mind when you hear "Just do it!"? Nike. How about "Don't Leave Home Without It"? American Express. And "Eat Fresh"? Subway, of course. See? People subconsciously associate taglines with brands or products. Come to think of it, the whole point of building your website is to reinforce your brand. Naturally, a good tagline will go a long way towards achieving your goal. While a tagline sounds like a no-brainer, not every business has one. If you don't, you're not alone. After all, you can't spend a few million dollars to come up with one the way Nike, American Express, and Subway probably did. But if you happen to have one, it's a good idea to immortalize it on your website. And if you don't, now's the time to scratch the creative side of your brain and think of one. But don't despair if you can't. You may be able to substitute a description of your business for the tagline with good effect. If you've shortened Anthony Donaldson's Vacuum Cleaner Sales, Service, and Rentals Incorporated, to Anthony Donaldson Inc., your tagline can be Vacuum Cleaner Sales, Service, and Rentals, or something to that effect. It may not be as potent as Nike's tagline, but at least it tells people what Anthony Donaldson does for a living. Time for action – setting the site slogan Replace the text Add your site slogan here! in the gray box in the Site Slogan section with your site slogan. I'm going to set it to Build your own website in a day! Pull down the select options for the font face just above the title and set it to the font you've chosen. I'm setting it to Georgia again. Next, pull down the adjacent select options for the font size and set it to 4. Why 4? I didn't pull the number 4 out of a hat. I chose it because size 4 is a size smaller than size 5, the size of my site's title. If your Site Title is set to a size other than five, choose one size smaller than the size of your site's title. As with the Site Title, don't select a color for your Site Slogan. And stay away from the B, I, and U buttons as well. Your Customize Header dialog should now look something like this: Click the OK button at the bottom of the Customize Header dialog. It closes and you arrive back at the Site Designer. Click the View button in Site Designer. You'll be using the View button, and the Save button next to it, quite often. When I want you to click the Save button, I'll simply tell you to save your work. If I want you to click the View button, I'll tell you to preview your website. Whenever I refer to these buttons, directly or indirectly, you now know where to find them. A pop-up message asks you whether you want to save your changes. Click OK. A preview of your site comes up in a new browser window. Notice that the site now displays the new title and slogan, as shown in the following screenshot: After you've admired your handiwork long enough, close the preview window and return to Site Designer. What just happened? You added a slogan to go along with your site's title. Why so much fuss about simply setting the title and slogan? In a word: findability. Findability? I didn't make that word up, by the way. Honest! Well-known web usability expert Jakob Nielsen did. A site is findable if it's easy to find; that is, it appears near the top of search engine results when a person searches for relevant terms. You can find great advice about building usable websites on Mr. Nielsen's website at http://www.useit.com Search engines attach considerable importance to the title of a web page. It tells them what the page is all about. But that's not the only thing they look at. They also try to determine whether the text on the web page has anything to do with its title. Because the slogan appears on every page with the title, a strong correlation between the two and their correlation with the text on your web pages will determine your web page's ranking in search results. To put it mildly, if your site's title and slogan stink, so will its ranking in the search results! Therefore, don't take these settings lightly. If you don't put enough thought behind them, you risk relegating your web pages to obscurity. Have a go hero – experiment with the site title and site slogan Although I handed down the edicts on setting the font face and the font size for the Site Title and the Site Slogan, by no means are my recommendations cast in stone. Although following my recommendations will save you a good deal of time and heartache, you'll do a disservice to yourself if you don't experiment on your own. Depending on how long your Site Title or Site Slogan is, you might find a better combination of these settings if you try out a few variations. Here are a few suggestions: If you've set your font to Georgia, you might want to try Verdana. How about Georgia for the Site Title and Verdana for the Site Slogan? Or vice-versa? Although I've recommended that you set the font size for your Site Slogan a size smaller than the font size for your Site Title, you might want to try a font size two sizes smaller than the size for your Site Title, especially if you've set different fonts for the title and the slogan. Verdana is a wide font. If your site title or slogan has several wide letters like W and M, Verdana may not be the right choice. You might want to try a similar but narrower font, such as Arial. Try out a few variations and settle on one that you like the best. You might want to get an opinion from a friend or a co-worker. And remember, you can come back and play with these settings any time. Pop quiz 1 Which of the following attributes make your website more "findable"? Your site's header Your site's title Your site's font setting Your site's slogan The answer to this quiz is given at the end of this article.
Read more
  • 0
  • 0
  • 1886

article-image-skin-customization-jboss-richfaces-33
Packt
30 Nov 2009
5 min read
Save for later

Skin Customization in JBoss RichFaces 3.3

Packt
30 Nov 2009
5 min read
Skinnability Every RichFaces component gives the support for skinnability and it means that just by changing the skin, we change the look for all of the components. That's very good for giving our application a consistent look and not repeating the same CSS values for each component every time. RichFaces still uses CSS, but it also enhances it in order to make it simpler to manage and maintain. Customize skin parameters A skin file contains the basic settings (such as font, colors, and so on) that we'll use for all the components—just by changing those settings, we can customize the basic look and feel for the RichFaces framework. As you might know, RichFaces comes with some built-in skins (and other external plug 'n' skin ones)—you can start with those skins in order to create your own custom skin. The built-in skins are: Plain emeraldTown blueSky wine japanCherry ruby classic deepMarine The plug 'n' skin ones are: laguna darkX glassX The plug 'n' skin skins are packaged in external jar files (that you can download from the same location as that of the RichFaces framework) that must be added into the project in order to be able to use them. Remember that the skin used by the application can be set as context-param in the web.xml file: <context-param> <param-name>org.richfaces.SKIN</param-name> <param-value>emeraldTown</param-value></context-param> This is an example with the emeralTown skin set: If we change the skin to japanCherry, we have the following screenshot: That's without changing a single line of CSS or XHTML! Edit a basic skin Now let's start creating our own basic skin. In order to do that, we are going to reuse one of the built-in skin files and change it. You can find the skin files in the richfaces-impl-3.x.x.jar file inside the META-INF/skins directory. Let's open the file and then open, for example, the emeraldTown.skin.properties file that looks like this (yes, the skin file is a .properties file!): #ColorsheaderBackgroundColor=#005000headerGradientColor=#70BA70headerTextColor=#FFFFFFheaderWeightFont=boldgeneralBackgroundColor=#f1f1f1generalTextColor=#000000generalSizeFont=18pxgeneralFamilyFont=Arial, Verdana, sans-serifcontrolTextColor=#000000controlBackgroundColor=#ffffffadditionalBackgroundColor=#E2F6E2shadowBackgroundColor=#000000shadowOpacity=1panelBorderColor=#C0C0C0subBorderColor=#fffffftabBackgroundColor=#ADCDADtabDisabledTextColor=#67AA67trimColor=#BBECBBtipBackgroundColor=#FAE6B0tipBorderColor=#E5973EselectControlColor=#FF9409generalLinkColor=#43BD43hoverLinkColor=#FF9409visitedLinkColor=#43BD43# FontsheaderSizeFont=18pxheaderFamilyFont=Arial, Verdana, sans-seriftabSizeFont=11tabFamilyFont=Arial, Verdana, sans-serifbuttonSizeFont=18buttonFamilyFont=Arial, Verdana, sans-seriftableBackgroundColor=#FFFFFFtableFooterBackgroundColor=#cccccctableSubfooterBackgroundColor=#f1f1f1tableBorderColor=#C0C0C0tableBorderWidth=2px#Calendar colorscalendarWeekBackgroundColor=#f5f5f5calendarHolidaysBackgroundColor=#FFEBDAcalendarHolidaysTextColor=#FF7800calendarCurrentBackgroundColor=#FF7800calendarCurrentTextColor=#FFEBDAcalendarSpecBackgroundColor=#E2F6E2calendarSpecTextColor=#000000warningColor=#FFE6E6warningBackgroundColor=#FF0000editorBackgroundColor=#F1F1F1editBackgroundColor=#FEFFDA#GradientsgradientType=plain In order to test it, let's open our application project, create a file called mySkin.skin.properties inside the directory /resources/WEB-INF/, and add the above text. Then, let's open the build.xml file and edit it, and add the following code into the war target: <copy tofile="${war.dir}/WEB-INF/classes/mySkin.skin.properties"file="${basedir}/resources/WEB-INF/mySkin.skin.properties"overwrite="true"/> Also, as our application supports multiple skins, let's open the components.xml file and add support to it: <property name="defaultSkin">mySkin</property><property name="availableSkins"> <value>mySkin</value> <value>laguna</value> <value>darkX</value> <value>glassX</value> <value>blueSky</value> <value>classic</value> <value>ruby</value> <value>wine</value> <value>deepMarine</value> <value>emeraldTown</value> <value>japanCherry</value></property> If you just want to select the new skin as the fixed skin, you would just edit the web.xml file and select the new skin by inserting the name into the context parameter (as explained before). Just to make an (bad looking, but understandable) example, let's change some parameters in the skin file: #ColorsheaderBackgroundColor=#005000headerGradientColor=#70BA70headerTextColor=#FFFFFFheaderWeightFont=boldgeneralBackgroundColor=#f1f1f1generalTextColor=#000000generalSizeFont=18pxgeneralFamilyFont=Arial, Verdana, sans-serifcontrolTextColor=#000000controlBackgroundColor=#ffffffadditionalBackgroundColor=#E2F6E2shadowBackgroundColor=#000000shadowOpacity=1panelBorderColor=#C0C0C0subBorderColor=#fffffftabBackgroundColor=#ADCDADtabDisabledTextColor=#67AA67trimColor=#BBECBBtipBackgroundColor=#FAE6B0tipBorderColor=#E5973EselectControlColor=#FF9409generalLinkColor=#43BD43hoverLinkColor=#FF9409visitedLinkColor=#43BD43# FontsheaderSizeFont=18pxheaderFamilyFont=Arial, Verdana, sans-seriftabSizeFont=11tabFamilyFont=Arial, Verdana, sans-serifbuttonSizeFont=18buttonFamilyFont=Arial, Verdana, sans-seriftableBackgroundColor=#FFFFFFtableFooterBackgroundColor=#cccccctableSubfooterBackgroundColor=#f1f1f1tableBorderColor=#C0C0C0tableBorderWidth=2px#Calendar colorscalendarWeekBackgroundColor=#f5f5f5calendarHolidaysBackgroundColor=#FFEBDAcalendarHolidaysTextColor=#FF7800calendarCurrentBackgroundColor=#FF7800calendarCurrentTextColor=#FFEBDAcalendarSpecBackgroundColor=#E2F6E2calendarSpecTextColor=#000000warningColor=#FFE6E6warningBackgroundColor=#FF0000editorBackgroundColor=#F1F1F1editBackgroundColor=#FEFFDA#GradientsgradientType=plain Here is the screenshot of what happened with the new skin: How do I know which parameters to change? The official RichFaces Developer Guide contains, for every component, a table with the correspondences between the skin parameters and the CSS properties they are connected to.
Read more
  • 0
  • 0
  • 3920

article-image-ways-improve-performance-your-server-modsecurity-25
Packt
30 Nov 2009
13 min read
Save for later

Ways to improve performance of your server in ModSecurity 2.5

Packt
30 Nov 2009
13 min read
A typical HTTP request To get a better picture of the possible delay incurred when using a web application firewall, it helps to understand the anatomy of a typical HTTP request, and what processing time a typical web page download will incur. This will help us compare any added ModSecurity processing time to the overall time for the entire request. When a user visits a web page, his browser first connects to the server and downloads the main resource requested by the user (for example, an .html file). It then parses the downloaded file to discover any additional files, such as images or scripts, that it must download to be able to render the page. Therefore, from the point of view of a web browser, the following sequence of events happens for each file: Connect to web server. Request required file. Wait for server to start serving file. Download file. Each of these steps adds latency, or delay, to the request. A typical download time for a web page is on the order of hundreds of milliseconds per file for a home cable/DSL user. This can be slower or faster, depending on the speed of the connection and the geographical distance between the client and server. If ModSecurity adds any delay to the page request, it will be to the server processing time, or in other words the time from when the client has connected to the server to when the last byte of content has been sent out to the client. Another aspect that needs to be kept in mind is that ModSecurity will increase the memory usage of Apache. In what is probably the most common Apache configuration, known as "prefork", Apache starts one new child process for each active connection to the server. This means that the number of Apache instances increases and decreases depending on the number of client connections to the server.As the total memory usage of Apache depends on the number of child processes running and the memory usage of each child process, we should look at the way ModSecurity affects the memory usage of Apache. A real-world performance test In this section we will run a performance test on a real web server running Apache 2.2.8 on a Fedora Linux server (kernel 2.6.25). The server has an Intel Xeon 2.33 GHz dual-core processor and 2 GB of RAM. We will start out benchmarking the server when it is running just Apache without having ModSecurity enabled. We will then run our tests with ModSecurity enabled but without any rules loaded. Finally, we will test ModSecurity with a ruleset loaded so that we can draw conclusions about how the performance is affected. The rules we will be using come supplied with ModSecurity and are called the "core ruleset". The core ruleset The ModSecurity core ruleset contains over 120 rules and is shipped with the default ModSecurity source distribution (it's contained in the rules sub-directory). This ruleset is designed to provide "out of the box" protection against some of the most common web attacks used today. Here are some of the things that the core ruleset protects against: Suspicious HTTP requests (for example, missing User-Agent or Accept headers) SQL injection Cross-Site Scripting (XSS) Remote code injection File disclosure We will examine these methods of attack, but for now, let's use the core ruleset and examine how enabling it impacts the performance of your web service. Installing the core ruleset To install the core ruleset, create a new sub-directory named modsec under your Apache conf directory (the location will vary depending on your distribution). Then copy all the .conf files from the rules sub-directory of the source distribution to the new modsec directory: mkdir /etc/httpd/conf/modseccp/home/download/modsecurity-apache/rules/modsecurity_crs_*.conf /etc/httpd/conf/modsec Finally, enter the following line in your httpd.conf file and restart Apache to make it read the new rule files: # Enable ModSecurity core rulesetInclude conf/modsecurity/*.conf Putting the core rules in a separate directory makes it easy to disable them—all you have to do is comment out the above Include line in httpd.conf, restart Apache, and the rules will be disabled. Making sure it works The core ruleset contains a file named modsecurity_crs_10_config.conf. This file contains some of the basic configuration directives needed to turn on the rule engine and configure request and response body access. Since we have already configured these directives, we do not want this file to conflict with our existing configuration, and so we need to disable this. To do this, we simply need to rename the file so that it has a different extension as Apache only loads *.conf files with the Include directive we used above: $ mv modsecurity_crs_10_config.conf modsecurity_crs_10_config.conf.disabled Once we have restarted Apache, we can test that the core ruleset is loaded by attempting to access an URL that it should block. For example, try surfing to http://yourserver/ftp.exe and you should get the error message Method Not Implemented, ensuring that the core rules are loaded. Performance testing basics So what effect does loading the core ruleset have on web application response time and how do we measure this? We could measure the response time for a single request with and without the core ruleset loaded, but this wouldn't have any statistical significance—it could happen that just as one of the requests was being processed, the server started to execute a processor-intensive scheduled task, causing a delayed response time. The best way to compare the response times is to issue a large number of requests and look at the average time it takes for the server to respond. An excellent tool—and the one we are going to use to benchmark the server in the following tests—is called httperf. Written by David Mosberger of Hewlett Packard Research Labs, httperf allows you to simulate high workloads against a web server and obtain statistical data on the performance of the server. You can obtain the program at http://www.hpl.hp.com/research/linux/httperf/ where you'll also find a useful manual page in the PDF file format and a link to the research paper published together with the first version of the tool. Using httperf We'll run httperf with the options --hog (use as many TCP ports as needed), --uri/index.html (request the static web page index.html) and we'll use --num-conn 1000 (initiate a total of 1000 connections). We will be varying the number of requests per second (specified using --rate) to see how the server responds under different workloads. This is what the typical output from httperf looks like when run with the above options: $ ./httperf --hog --server=bytelayer.com --uri /index.html --num-conn1000 --rate 50Total: connections 1000 requests 1000 replies 1000 test-duration20.386 sConnection rate: 49.1 conn/s (20.4 ms/conn, <=30 concurrentconnections)Connection time [ms]: min 404.1 avg 408.2 max 591.3 median 404.5stddev 16.9Connection time [ms]: connect 102.3Connection length [replies/conn]: 1.000Request rate: 49.1 req/s (20.4 ms/req)Request size [B]: 95.0Reply rate [replies/s]: min 46.0 avg 49.0 max 50.0 stddev 2.0 (4samples)Reply time [ms]: response 103.1 transfer 202.9Reply size [B]: header 244.0 content 19531.0 footer 0.0 (total19775.0)Reply status: 1xx=0 2xx=1000 3xx=0 4xx=0 5xx=0CPU time [s]: user 2.37 system 17.14 (user 11.6% system 84.1% total95.7%)Net I/O: 951.9 KB/s (7.8*10^6 bps)Errors: total 0 client-timo 0 socket-timo 0 connrefused 0 connreset 0Errors: fd-unavail 0 addrunavail 0 ftab-full 0 other 0 The output shows us the number of TCP connections httperf initiated per second ("Connection rate"), the rate at which it requested files from the server ("Request rate"), and the actual reply rate that the server was able to provide ("Reply rate"). We also get statistics on the reply time—the "reply time – response" is the time taken from when the first byte of the request was sent to the server to when the first byte of the reply was received—in this case around 103 milliseconds. The transfer time is the time to receive the entire response from the server. The page we will be requesting in this case, index.html, is 20 KB in size which is a pretty average size for an HTML document. httperf requests the page one time per connection and doesn't follow any links in the page to download additional embedded content or script files, so the number of such links in the page is of no relevance to our test. Getting a baseline: Testing without ModSecurity When running benchmarking tests like this one, it's always important to get a baseline result so that you know the performance of your server when the component you're measuring is not involved. In our case, we will run the tests against the server when ModSecurity is disabled. This will allow us to tell which impact, if any, running with ModSecurity enabled has on the server. Response time The following chart shows the response time, in milliseconds, of the server when it is running without ModSecurity. The number of requests per second is on the horizontal axis: As we can see, the server consistently delivers response times of around 300 milliseconds until we reach about 75 requests per second. Above this, the response time starts increasing, and at around 500 requests per second the response time is almost a second per request. This data is what we will use for comparison purposes when looking at the response time of the server after we enable ModSecurity. Memory usage Finding the memory usage on a Linux system can be quite tricky. Simply running the Linux top utility and looking at the amount of free memory doesn't quite cut it, and the reason is that Linux tries to use almost all free memory as a disk cache. So even on a system with several gigabytes of memory and no memory-hungry processes, you might see a free memory count of only 50 MB or so. Another problem is that Apache uses many child processes, and to accurately measure the memory usage of Apache we need to sum the memory usage of each child process. What we need is a way to measure the memory usage of all the Apache child processes so that we can see how much memory the web server truly uses. To solve this, here is a small shell script that I have written that runs the ps command to find all the Apache processes. It then passes the PID of each Apache process to pmap to find the memory usage, and finally uses awk to extract the memory usage (in KB) for summation. The result is that the memory usage of Apache is printed to the terminal. The actual shell command is only one long line, but I've put it into a file called apache_mem.sh to make it easier to use: #!/bin/sh# apache_mem.sh# Calculate the Apache memory usageps -ef | grep httpd | grep ^apache | awk '{ print $2 }' | xargs pmap -x | grep 'total kB' | awk '{ print $3 }' | awk '{ sum += $1 } END { print sum }' Now, let's use this script to look at the memory usage of all of the Apache processes while we are running our performance test. The following graph shows the memory usage of Apache as the number of requests per second increases: Apache starts out consuming about 300 MB of memory. Memory usage grows steadily and at about 150 requests per second it starts climbing more rapidly. At 500 requests per second, the memory usage is over 2.4 GB—more than the amount of physical RAM of the server. The fact that this is possible is because of the virtual memory architecture that Linux (and all modern operating systems) use. When there is no more physical RAM available, the kernel starts swapping memory pages out to disk, which allows it to continue operating. However, since reading and writing to a hard drive is much slower than to memory, this starts slowing down the server significantly, as evidenced by the increase in response time seen in the previous graph. CPU usage In both of the tests above, the server's CPU usage was consistently around 1 to 2%, no matter what the request rate was. You might have expected a graph of CPU usage in the previous and subsequent tests, but while I measured the CPU usage in each test, it turned out to run at this low utilization rate for all tests, so a graph would not be very useful. Suffice it to say that in these tests, CPU usage was not a factor. ModSecurity without any loaded rules Now, let's enable ModSecurity—but without loading any rules—and see what happens to the response time and memory usage. Both SecRequestBodyAccess and SecResponseBodyAccess were set to On, so if there is any performance penalty associated with buffering requests and responses, we should see this now that we are running ModSecurity without any rules. The following graph shows the response time of Apache with ModSecurity enabled: We can see that the response time graph looks very similar to the response time graph we got when ModSecurity was disabled. The response time starts increasing at around 75 requests per second, and once we pass 350 requests per second, things really start going downhill. The memory usage graph is also almost identical to the previous one: Apache uses around 1.3 MB extra per child process when ModSecurity is loaded, which equals a total increase of memory usage of 26 MB for this particular setup. Compared to the total amount of memory Apache uses when the server is idle (around 300 MB) this equals an increase of about 10%. Mod Security with the core ruleset loaded Now for the really interesting test we'll run httperf against ModSecurity with the core ruleset loaded and look at what that does to the response time and memory usage. Response time The following graph shows the server response time with the core ruleset loaded: At first, the response time is around 340 ms, which is about 35 ms slower than in previous tests. Once the request rate gets above 50, the server response time starts deteriorating. As the request rates grows, the response time gets worse and worse, reaching a full 5 seconds at 100 requests per second. I have capped the graph at 100 requests per second, as the server performance has already deteriorated enough at this point to allow us to see the trend. We see that the point at which memory usage starts increasing has gone down from 75 to 50 requests per second now that we have enabled the core ruleset. This equals a reduction in the maximum number of requests per second the server can handle of 33%.
Read more
  • 0
  • 0
  • 20675

article-image-linux-e-mail-customizing-spamassassin
Packt
30 Nov 2009
8 min read
Save for later

Linux E-mail: Customizing SpamAssassin

Packt
30 Nov 2009
8 min read
SpamAssassin is very configurable. Almost every setting can be configured on a system-wide or user-specific basis. Reasons to customize If SpamAssassin is so good, then why configure it? Well, there are several reasons why it's worth improving spam filtering with SpamAssassin. SpamAssassin by default (that is, when installed but not customized) typically manages to detect over 80% of spam. After adding a few customizations, the detection rate can be greater than 95%. Everyone's spam is different and one user's spam might look like another user's ham. By trying to be general, SpamAssassin may fail to filter spam for every user. Some of the features of SpamAssassin are disabled by default. By enabling them, the spam recognition rate is increased. The following configuration options are discussed in this article: Altering the scores for rules: This allows rules to be disabled, poor rules to be given less weight, and better rules to be given a higher weight. Obtaining and using new rules: This can improve spam detection. Adding e-mail addresses to white and blacklists: This allows the e-mail from specified senders to always be treated as ham, no matter what the content is, or the opposite. Enabling SpamAssassin's Bayesian filter: This can increase filtering accuracy from 80% to 95% or more. Rules and scores The configuration files for standard, sitewide, and user-specific settings are saved in different directories as follows: Standard configuration settings are stored in /usr/share/spamassassin. Site-wide customizations and settings are stored in /etc/mail/spamassassin/. All files matching *.cf are examined by SpamAssassin. User-specific settings are stored in ~/.spamassassin/local.cf. The bulk of the standard configuration files is devoted to simple rules and their scores. A rule is typically a match for letters, numbers, or other printing characters. Rules are written using a technique called regular expressions, or regex for short. This is a shorthand method of specifying that certain combinations of characters will trigger the rule. A rule might try to detect a particular word, such as "Rolex", or it might look for particular words in certain orders, such as "buy Rolex online". The rules are stored in text files. Default files are stored in /usr/share/spamassassin. These are files that are shipped with SpamAssassin and may change with each release. It's best not to modify these files or place new files in this directory, as an upgrade to SpamAssassin will overwrite these files. Most of the rules that SpamAssassin uses, and the scores applied to each rule, are defined within files in this directory. The defaults can be overwritten by sitewide configuration files. These are placed in /etc/mail/spamassassin. SpamAssassin will read all files matching *.cf in this directory. Settings made here can overrule those in the default files. They can include defining new rules and new rule scores. User-specific customizations can be placed in the ~/.spamassassin/local.cf file. Settings made here can override sitewide settings defined in /etc/mail/spamassassin, and default settings in /usr/share/spamassassin/. New rules may be defined here, and scores for existing rules can be overridden. SpamAssassin first reads all the files in /usr/share/spamassassin in alphanumerical order; 10_misc.cf will be read before 23_bayes.cf. SpamAssassin then reads all the .cf files in /etc/mail/spamassassin/, again in alphanumeric order. Finally, SpamAssassin reads ~user/.spamassassin/user_prefs. If a rule or score is defined in two files, the setting in the last file read is used. This allows the administrator to override the defaults and a user to override the sitewide settings. Each line in a rules file can be blank or contain a comment or a command. The hash or pound (#) symbol is used for comments. Rules generally have three parts, the rule definition, a textual description, and the score or series of scores. Convention dictates that all rule scores for rules provided by SpamAssassin should be located together in a separate file. That file is /usr/share/spamassassin/50_scores.cf. Altering rule scores The simplest configuration change is to change a rule score. There are two reasons why this might be done: A rule is very good at detecting spam, but the rule has a low score. E-mails that fire the rule are not being detected as spam. A rule is acting on non spam. As a result, e-mails that fire the rule are wrongly being detected as spam. The rules that give a positive result when SpamAssassin is run are listed in the X-Spam-Status: header of the e-mail: X-Spam-Status: Yes, score=5.8 required=5.0 tests=BAYES_05,HTML_00_10,HTML_MESSAGE,MPART_ALT_DIFF autolearn=noversion=3.1.0-r54722 The rules applied to the e-mail are listed after tests=. If one continually appears in e-mail that should be marked as spam, but isn't, then the score for the rule should be increased. If a rule often fires in e-mail that is wrongly classified as spam, the score should be decreased. To find the current score, use the grep utility in all the locations where a score can be defined. grep score.*BAYES /usr/share/spamassassin/* /etc/mail/spamassassin/*~/.spamassassin/local.cf/etc/mail/spamassassin/local_scores.cf:score RULE_NAME 0 0 1.665 2.599/etc/mail/spamassassin/local_scores.cf: 4.34 In the previous example, the rule has a default score that is overridden in /etc/mail/spamassassin/local_scores.cf. The original score for the rule had four values. SpamAssassin changes the scores it uses, depending on whether network tests (for example, those that test open relays) are in use and whether the Bayesian Filter is in use. Four scores are listed, which are used in the following circumstances: //===INSERT TABLE 02=== If only one score is given, as overridden in /etc/mail/spamassassin/local_scores.cf, it is used in all circumstances. In the previous example, the system administrator has overridden the default score in /etc/mail/spamassassin/local_scores.cf with a single value in /etc/mail/spamassassin/local_scores.cf. To change this value for a particular user, their ~/.spamassassin/local.cf might read: score RULE_NAME 1.2 This changes the score used from 4.34, set in /etc/mail/spamassassin/local_scores.cf, to 1.2. To disable the rule entirely, the score can be set to zero. score RULE_NAME 0 Endless hours can be spent configuring rule scores. SpamAssassin includes tools to recalculate optimal rule scores, by examining existing e-mails, both spam and non spam. They are covered in detail in the book SpamAssassin published by Packt. Using other rulesets SpamAssassin has a large following, and the design of SpamAssassin has made it easy to add new rulesets, which are sets of rules and default scores for those rules. There are many different rulesets available. Most are based on a particular theme, for example finding the names of drugs often sold with spam or telephone numbers found in spam e-mails. Most custom rulesets are listed on the Custom Rulesets page of the SpamAssassin Wiki at http://wiki.apache.org/spamassassin/CustomRulesets. As the battle against spam is so aggressive, rulesets have been developed that may possibly be uploaded daily. SpamAssassin provides this ability with the sa-update utility. You can choose to use sa-update on a regular basis, or to download a particular ruleset and keep it, or to manually update the rulesets that you choose. To obtain the best results in filtering spam, use of sa-update is recommended. If you wish to install rulesets manually, the Wiki page gives a general description of each ruleset and a URL to download it. Once a ruleset has been chosen, we install it as follows: In a browser, follow the link on the SpamAssassin Wiki page. In most cases, the link will be to a file with a name matching *.cf, and a browser will open it as a text file. Save the file using the browser (normally, the File menu has a Save as option). Copy the file to /etc/mail/spamassassin—the rules will be automatically run if the file is placed in this location. Check that the file has scores in it, otherwise the rules will not be used. Monitor spam performance to ensure that legitimate e-mail is not being detected as spam. Adding rules to SpamAssassin will increase the memory used by SpamAssassin, and the time that it takes to process e-mails. It is best to be cautious and add new rulesets gradually, to ensure that the effect on the machine is understood. You may manually monitor the ruleset and update it on your system using the same process. If you choose to use sa-update, you should plan your use of it. sa-update can use several channels, which are basically sources of rulesets. By default, the channel updates.spamassassin.org is used; another popular channel is the OpenProtect channel, called saupdates.openprotect.com. To enable sa-update, it must be run regularly, for example via cron. Add a cron entry to your system calling the following commands, to update the base rulesets: sa-update If you use an additional channel, the command might look like: sa-update –channel saupdates.openprotect.com To protect against DNS poisoning and impersonation, SpamAssassin allows digital signing of rulesets. To use a signed ruleset, use the –gpgkey parameter to sa-update. The correct value to use with the –gpgkey parameter will be described in the SpamAssassin wiki page for the ruleset.
Read more
  • 0
  • 0
  • 3528

article-image-navigating-your-site-using-codeigniter-17-part-2
Packt
30 Nov 2009
9 min read
Save for later

Navigating Your Site using CodeIgniter 1.7: Part 2

Packt
30 Nov 2009
9 min read
Designing a better view At this stage, you might ask: Why are we going through so much effort to serve a simple HTML page? Why not put everything in one file? For a simple site, that's a valid point—but whoever heard of a simple site? One of the coolest things about CI is the way it helps us to develop a consistent structure. So, as we add to and develop our site, it is internally consistent, well laid out, and simple to maintain. At the start, we need to take these three common steps: Write a view page Write a stylesheet Update our config file to specify where the stylesheet is After this is done, we need to update our controller to accept parameters from the URL, and pass variables to the view. First, let's redesign our view and save it as testview.php, at /www/codeigniter/application/views/testview.php. <html><head><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0Strict//EN'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'><html ><title>Web test Site</title><link rel="stylesheet" type="text/css" href="<?php echo$base."/".$css;?>"></head><body><h1><?php echo $mytitle; ?> </h1><p class='test'> <?php echo $mytext; ?> </p></body></html> It's still mostly HTML, but notice the PHP "code islands" in the highlighted lines. You'll notice that the first bits of PHP code build a link to a stylesheet. Let's save a simple stylesheet as styles.css, at www/codeigniter/css/styles.css. It just says: h1{margin: 5px;padding-left: 10px;padding-right: 10px;background: #ffffff;color: blue;width: 100%;font-size: 36px;}.test{margin: 5px;padding-left: 10px;padding-right: 10px;background: #ffffff;color: red;width: 100%;font-size: 36px;} This gives us two styles to play with, and you'll see we've used both of them in the view. Firstly, let's add an entry to the config file: $config['css'] = 'css/styles.css'; This is simply to tell the name and address of the CSS file that we've just written to the site. But note that the link to the stylesheet is referenced at $base/$css: Where do those variables, $base and $css, get their values? And come to think of it, those variables $mytitle and $mytext at the end of the code? We need a new controller! Designing a better controller Now, we need a new controller. We'll call it Start and save it as start.php, at /www/codeigniter/application/controllers/start.php. This controller has to do several things: Call a view Provide the view with the base URL and the location of the CSS file we just wrote Provide the view with some data—it's expecting a title ($mytitle) and some text ($mytext) Lastly, accept a parameter from the user (that is using the URL request) In other words, we have to populate the variables in the view. So let's start with our Start controller. This is an OO class: <?phpclass Start extends Controller{var $base;var $css; Notice that here we've declared the $base and $css (the CSS filename) as variables or class properties. This saves us from having to redeclare them if we write more than one function in each class. But you can define and use them as local variables within one function, if you prefer. The constructor function now defines the properties we've declared, by looking them up in the config file. To do this, we use the syntax: $this->config->item('name_of_config_variable'); As in: function Start(){parent::Controller();$this->base = $this->config->item('base_url');$this->css = $this->config->item('css');} CI recovers whatever we entered in the config file against that name. Using this system, no matter how many controllers and functions we write, we'll have to change these fundamental variables only once. This is true even if our site becomes so popular that we have to move it to a bigger server. Getting parameters to a function Now, within the Start controller class, let's define the function that will actually do the work. function hello($name = 'Guest'){$data['css'] = $this->css;$data['base'] = $this->base;$data['mytitle'] = 'Welcome to this site';$data['mytext'] = "Hello, $name, now we're getting dynamic!";$this->load->view('testview', $data);} This function expects the parameter $name, but you can set a default value—myfunction($myvariable = 0), which it uses to build the string assigned to the $mytext variable. Well, as we just asked, where does that come from? In this case, it needs to come from the URL request, where it will be the third parameter. So, it comes through the HTTP request: http://127.0.0.1/codeigniter/start/hello/Jose This example code doesn't "clean" the passed variable Jose, or check it in any way. You might want to do this while writing the code. We'll look at how to check form inputs. Normally, variables passed by hyperlinks in this way are generated by your own site. A malicious user can easily add his or her own, just by sending a URL such as: http://www.mysite.com/index.php/start/hello/my_malicious_variable. So, you might want to check that the variables you receive are within the range you expect, before handling them. The last segment of the URL is passed to the function as a parameter. In fact, you can add more segments of extra parameters if you like, subject to the practical limits imposed by your browser. Let's recap on how CI handles URLs, since we've covered it all now: URL segment   What it does   http://www.mysite.com   The base URL that finds your site.   /index.php   Finds the CI router that sets about reading the rest of the URL and selecting the correct route into your site. If you have added the .htaccess file in the previous chapter, this part will not be visible, but will still work as supposed.   /start   The name of the controller that CI will call (If no name is set, CI will call whichever default controller you've specified).   /hello   The name of a function that CI will call, inside the selected controller (If no function is specified, it defaults to the index function, unless you've used _remap).   /Jose   CI passes this to the function as a variable.   If there is a further URL segment, for example, /bert   CI passes this to the function as the second variable. More variables   CI will pass further URL segments as consequent variables.   Passing data to a view Let's go back to the hello function: function hello($name){$data['css'] = $this->css;$data['base'] = $this->base;$data['mytitle'] = 'Welcome to this site';$data['mytext'] = "Hello, $name, now we're getting dynamic!";$this->load->view('testview', $data);} Notice how the hello() function first creates an array called $data, taking a mixture of object properties set up by the constructor and text. Then it loads the view by name, with the array it has just built as the second parameter. Behind the scenes, CI makes good use of another PHP function—extract(). This takes each value in the $data array and turns it into a new variable in its own right. So, the $data array that we've just defined is received by the view as a series of separate variables; $text (equal to "Hello, $name, now we're getting dynamic"), $css (equal to the value from the config file), and so on. In other words, when built, the $data array looks like this: Array([css] => 'mystyles.css';[base] => 'http://127.0.0.1/packt';[mytitle] => 'Welcome to this site';[mytext] => 'Hello, fred, now we're getting dynamic!';) But on its way to the view, it is unpacked, and the following variables are created in the view to correspond to each key/value pair in the array: $css = 'mystyles.css';$base = 'http://127.0.0.1/packt';$mytitle = 'Welcome to this site';$mytext = 'Hello, fred, now we're getting dynamic!';) Although you can only pass one variable to a view, you can pack a lot of information into it. Each value in the $data array can itself be another array, so you can pass pieces of information to the view in a tightly structured manner. Now navigate to http://127.0.0.1/codeigniter/start/hello/jose (note that the URL is different—it is looking for the start function we wrote in the index controller) and you'll see the result—a dynamic page written using MVC architecture. (well, VC at least! We haven't really used the M yet). You can see that the parameter jose is the last segment of the URL. It has been passed into the function, and then to the view. Please remember that your view must be written in parallel with your controller. If the view does not expect and make a place for a variable, it won't be displayed. If the view is expecting a variable to be set and it isn't, you are likely to get an error message (your view can of course accept variables conditionally). Also, a controller can use more than one view; this way we can separate our pages into sections such as the header, the menu, and so on. Each of these views can be nested one inside the other. Child views can even inherit variables passed by the controller to their parent view. Loading a view from inside another view is very easy; just put something like this PHP snippet in your HTML code: <body><div id="menu"><?php $this->load->view('menu'); ?> This way we can load a view inside a view, with all variables in the first one also available into the nested one.
Read more
  • 0
  • 0
  • 3765
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-navigating-your-site-using-codeigniter-17-part-1
Packt
30 Nov 2009
10 min read
Save for later

Navigating Your Site using CodeIgniter 1.7: Part 1

Packt
30 Nov 2009
10 min read
MVC:Model-View-Controller What's MVC all about? For sure at this time you are very curious about this. In short, MVC is an architectural pattern, a way of structuring our application. system application models views controllers As you can see there is a folder for each of the words (MVC); let's see what we can put into them: Models: The models represent our application data, be it in databases, in XML files or anywhere else. Also, interaction with databases is carried here. For example, models will allow us to fetch, modify, insert, and remove data from our database. All actions that require our application to talk to our database must be put in a model. Views: Files placed here are responsible for showing our data to the visitors to our site, or users of our application. No programming logic, no insert or update queries must be run here, though data access may occur in these files. They are here only to show the results of the other two. So we fetch the data in the model, and show it in the view. Now, what if we need to process the data, for example, putting it into an array? Then we do it in the controller; let's see how. Controllers: These act as a nexus between models and views, and programming logic occurs here. Take a look at this little diagram, in the left column we can see a "classical" way of doing things (a little outdated right now). We have a PHP file with SQL queries and HTML code in the same file and embedded into the HTML PHP logic. It may seem, at first glance, that this way it is easier and faster to program. But in this case the code gets messed faster and becomes cluttered with SQL queries, HTML, and PHP logic. Look at the right-side column—we have SQL queries in the Model, HTML and other graphic elements in the View, and PHP logic in the Controller. Doesn't that seem organized? The Controller calls and fetches data from the Model. It then loads the data and passes it to the Views, and sends the results to the user. Once we start working with this pattern we will feel how easy it is; it will keep our projects organized. If we need to come back to our project months after finishing it we will appreciate having made it in a structured fashion. No more of—Oh my God where did I put that query, where is that include file?—they will be in the model and the controller respectively. But, what happens if we want to put our queries in the controller? Well, CodeIgniter allows us to do so (though it is not recommended; if you can avoid, it is better to do so). Other frameworks force you to keep a particular structure, but with CI you can do programming in the way you want. Although it is recommended to keep to the structure, there will be times when we will need to do things the other way. With this structure we can accomplish two important things: Loose Coupling: Coupling is the degree by which the components of a system rely on each other. The less the components depend on each other, the more reusable and flexible the system becomes. Component Singularity: Singularity is the degree by which components have a narrow focus. In CI, each class and its functions are highly autonomous in order to allow maximum usefulness. But how does all this work? Now that we have seen how CI is structured, maybe you are asking yourself—how are the files in those three folders (models, views, controllers) working together? To answer this question we have another diagram, here it is: As you can see it's similar to the previous one, and a little summarized (but with a wider scope of things, this is how the MVC pattern works), but this time we can see some new elements, and if you look at it closely you will be able to distinguish the flow of data. Let's explain it, first of all there is a browser call to your site, then the index.php file in the root folder is called (because we removed it from the URL, using the .htaccess file, we don't see it). This file acts as a router and calls the controllers, as and when they are needed. The controllers, as they are called, come into action. Now, two things can happen: There is no need to fetch data from the database—in this case only the View is called, and loaded by the Controller. Then it is returned to the Browser for you or your visitors to see. There is the need to fetch some data from the database—in this case theController calls the Model, which in turn makes a query to the database. The database returns data to the Model, and the Model to the Controller. The Controller modifies the data in every necessary way. Then it loads the View, passing all necessary data to it, and the View is created and returned to the Browser again. Do not get confused with the first case; there will be times when you will need to create static pages. CI doesn't differentiate between static and dynamic pages. On those occasions simply don't create the Models. Now, return to our sample site to see how all this applies to it. Remember when we put the URL as http://127.0.0.1/codeigniter, CI's welcome screen appeared in our browser. Now try this URL http://127.0.0.1/codeigniter/welcome. You can also try using this URLhttp://127.0.0.1/codeigniter/index.php/welcome. In both cases the welcome screen appears in the browser. You maybe wondering, how CI knows, if you put http://127.0.0.1/codeigniter/, that it has to load the welcome controller. Don't worry, we will see that in a moment; for now, we will go on with our example: http://127.0.0.1/codeigniter/index.php/welcome A request coming to your web site's root is intercepted by the index.php file, which acts as a router. That is, it calls a controller—welcome controller—which then returns a view, just as in the previous diagram. But how does the controller do that? We are going to see how in the welcome controller. The welcome controller As we know the welcome controller is the default controller, configured in the routes.php file of the config directory and the code is at ./application/controllers/welcome.php. Here's what it says: <?php class Welcome extends Controller { function Welcome() { parent::Controller(); } function index() { $this->load->view('welcome_message'); } } /* End of file welcome.php */ /* Location: ./system/application/controllers/welcome.php */ From the second line you'll learn that this file is a class. Every controller inherits from an original Controller class, hence extends Controller. The next three lines make the constructor function. Within the class there are two functions or methods—Welcome() and index(). Though it is not necessary, naming controllers the same way as for tables is a good practice. For example, if I have a projects table I will create a projects controller. You can name your controllers the way you want, but naming them like the tables they represent keeps things organized. Also, getting used to this won't harm you, as other frameworks are stricter about this. Notice that CI uses the older PHP 4 convention for naming constructor functions, which is also acceptable by PHP 5—it doesn't require you to use PHP 5 and is happy with either version of the language. The constructor function is used to set up the class each time you instantiate it. We can obviate this and the controller will still work, and if we use it, it won't do any harm. Inside it we can put instructions to load other libraries or models, or definitions of class variables. So far the only thing inside the constructor is the parent::Controller(); statement. This is just a way of making sure that you inherit the functionality of the Controller class. If you want to understand the parent CI Controller class in detail, you can look at the file /www/CI_system/libraries/controller.php. One of the reassuring things about CI is that all the code is there for you to inspect, though you don't often need to. Working with views Let's go back to the incoming request for a moment. The router needs to know which controller and which function within that controller should handle the request. By default the index function is called if the function is not specified. So, when we put http://127.0.0.1/codeigniter/welcome/, the index function is called. If no error is shown, this function simply loads the view, ('welcome_message') using CI's loader function ($this->load->view). At this stage, it doesn't do anything cool with the view, such as passing dynamic information to it. That comes in later. The ('welcome_message') it wants to load, is in the views folder that you have just installed at /www/codeigniter/application/views/welcome_message.php. This particular view is only a simple HTML page, but it is saved as a PHP file because most views have PHP code in them (no point in doing all this if we're only going to serve up plain old static HTML). Here's the (slightly shortened) code for the view: <html> <head> <title>Welcome to CodeIgniter</title> <style type="text/css"> body { background-color: #fff; margin: 40px; font-family: Lucida Grande, Verdana, Sans-serif; font-size: 14px; color: #4F5155; } . . . . . more style information here . . . . </style> </head> <body> <h1>Welcome to CodeIgniter!</h1> <p>The page you are looking at is being generated dynamically by CodeIgniter. </p> <p>If you would like to edit this page you'll find it located at: </p> <code>system/application/views/welcome_message.php</code> <p>The corresponding controller for this page is found at:</p> <code>system/application/controllers/welcome.php</code> <p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>. </p> <p><br />Page rendered in {elapsed_time} seconds</p> </body> </html> As you can see, it consists entirely of HTML, with an embedded CSS stylesheet. In this simple example, the controller hasn't passed any variables to the view. Curious about—&ltp> &ltbr/> Page rendered in {elapsed_time} seconds </p>? Take a look at: http://codeigniter.com/user_guide/libraries/benchmark.html. You can name the views the way you want, and don't put the .php extension for them. You will have to specify the extension when loading them, for example: $this->load->view('welcome_message.html');
Read more
  • 0
  • 0
  • 2653

article-image-linux-e-mail-using-spamassassin
Packt
30 Nov 2009
8 min read
Save for later

Linux E-mail: Using SpamAssassin

Packt
30 Nov 2009
8 min read
Now that SpamAssassin is installed, we need to configure the system to use it. SpamAssassin can be used in many ways. It can be integrated into the MTA for maximum performance; it can run as a daemon or a simple script to avoid complexity; it can use separate settings for each user or use a single set of settings for all users; and it can be used for all accounts or just for the chosen ones. In this article, we will discuss using SpamAssassin in three ways. The first method is with Procmail. This is the simplest method to configure and is suitable for low-volume sites, for example, less than 10,000 e-mails a day. The second method is to use SpamAssassin as a daemon. This is more efficient, and can still be used with Procmail, if desired. The third method is to integrate SpamAssassin with a content filter such as amavisd. This offers performance advantages, but occasionally the content filter does not work with the latest release of SpamAssassin. Problems, if any, are usually resolved quickly. To help you get the most out of SpamAssassin, Packt Publishing has published SpamAssassin: A practical guide to integration and configuration, (ISBN 1-904811-12-4) by Alistair McDonald. Using SpamAssassin with Procmail Before we configure the system to use SpamAssassin, let's consider what SpamAssassin does. SpamAssassin is not an e-mail filter. A filter is something that changes the destination of an e-mail. SpamAssassin adds e-mail headers to an e-mail message to indicate if it is spam or not. Consider an e-mail with headers like this: Return-Path: <user@domain.com>X-Original-To: jdoe@localhostDelivered-To: jdoe@host.domain.comReceived: from localhost (localhost [127.0.0.1])by domain.com (Postfix) with ESMTP id 52A2CF2948for <jdoe@localhost>; Thu, 11 Nov 2004 03:39:42 +0000 (GMT)Received: from pop.ntlworld.com [62.253.162.50]by localhost with POP3 (fetchmail-6.2.5)for jdoe@localhost (single-drop); Thu, 11 Nov 2004 03:39:42 +0000(GMT)Message-ID: <D8F7B41C.4DDAFE7@anotherdomain.com>Date: Wed, 10 Nov 2004 17:54:14 -0800From: "stephen mellors" <gregory@anotherdomain.com>User-Agent: MIME-tools 5.503 (Entity 5.501)X-Accept-Language: en-usMIME-Version: 1.0To: "Jane Doe" <jdoe@domain.com>Subject: nearest pharmacy onlineContent-Type: text/plain;charset="us-ascii"Content-Transfer-Encoding: 7bit SpamAssassin will add header lines. X-Spam-Flag: YESX-Spam-Checker-Version: SpamAssassin 3.1.0-r54722 (2004-10-13) onhost.domain.comX-Spam-Level: *****X-Spam-Status: Yes, score=5.8 required=5.0 tests=BAYES_05,HTML_00_10,HTML_MESSAGE,MPART_ALT_DIFF autolearn=noversion=3.1.0-r54722 SpamAssassin doesn't change the destination of the e-mail, all it does is add headers that enable something else to change the destination of the e-mail. The best indication that an e-mail is spam is the X-Spam-Flag. If this is YES, SpamAssassin considers the mail to be spam and it can be filtered by Procmail. SpamAssassin also assigns a score to each e-mail—the higher the score, the more likely that the e-mail is spam. The threshold that determines if an e-mail is spam can be configured on a system-wide or per-user basis. The default of 5.0 is a sensible default if you are using an unmodified installation of SpamAssassin without any custom rulesets. Global procmailrc file Let's suppose that we want to check all incoming e-mail for spam using SpamAssassin. Commands in the /etc/procmailrc file are run for all users, so executing SpamAssassin here is ideal. The following simple recipe will run SpamAssassin for all users when placed in /etc/procmailrc: :0fw| /usr/bin/spamassassin To place all spam in an individual spam folder, ensure that the global/etc/procmailrc file has a line specifying a default destination. For example: DEFAULT=$HOME/.maildir/ If not, then add a line specifying DEFAULT. To filter spam into a folder, add a recipe similar to the following: * ^X-Spam-Flag: Yes.SPAM/new This assumes that each user has a folder called SPAM already configured. To place all the spam in a single, central folder, use an absolute path to the destination in the recipe: * ^X-Spam-Flag: Yes/var/spool/poss_spam This will place all spam in a single folder, which can be reviewed by the system administrator. As times, regular e-mail may occasionally be wrongly detected as spam, the folder should not be world-readable, which leads to a more generalized statement. SpamAssassin will be run under the system account used by Postfix. This means that the Bayesian database and the auto-whitelists and blacklists will be shared by all users. From a security point of view, it's important that the various databases that SpamAssassin creates are not world-writable. SpamAssassin stores user-specific files in the ~/.spamassassin/ directory. Here is a list of fi les that may be present for a user: //===INSERT TABLE 01=== Some of them may contain confidential data—for example, regular contacts will appear in the auto-whitelist files. Careful use of permissions will ensure that the files are not readable by regular user accounts. Using SpamAssassin on a per-user basis Perhaps some users don't receive spam, or there may be issues with users sharing whitelists and Bayesian databases. SpamAssassin can be run on an individual basis by moving the recipes to the ~/.procmailrc of specific users. This should increase the filtering performance for each user, but increases disk space usage for each user and requires setting up each individual user account by modifying its ~/.procmailrc. A typical user's .procmailrc might look like this: MAILDIR=$HOME/.maildir:0fw| /usr/bin/spamassassin:0* ^X-Spam-Flag: Yes.SPAM/cur As suggested, e-mail may sometimes be wrongly detected as spam. It's worthwhile reviewing spam to ensure that legitimate e-mails have not been wrongly classified. If the user receives a lot of spam, then wading through it all is time consuming, tedious, and error prone. Procmail can filter spam by checking the spam score written in the e-mail headers by SpamAssassin. The low-scoring spam (for example, scoring up to 9) can be placed in one folder called Probable_Spam, while higher scoring e-mails (which are more likely to be spam) can be placed a folder called Certain_Spam. To do this, we use the X-Spam-Level header, which SpamAssassin creates. This is simply the number of asterisks, related to the X-Spam-Level value. By moving e-mail with more than a certain number of asterisks to the Certain_Spam folder, the remaining spam is "Probable Spam". E-mail that is marked with X-Spam-Flag: NO, is obviously not spam. The following .procmailrc file will filter high scoring spam separately from low scoring spam and non spam: MAILDIR=$HOME/.maildir:0fw| /usr/bin/spamassassin:0* ^X-Spam-Level: **************.Certain_Spam/cur:0* ^X-Spam-FLAG: YES.Probable_Spam/cur Using SpamAssassin as a daemon with Postfix A daemon is a background process; one that waits for work, processes it, and then waits for more work. Using this approach actually improves performance (as long as there is sufficient memory) because responsiveness is improved—the program is always ready and waiting and does not have to be loaded each time spam tagging is required. To use SpamAssassin as a daemon, a user account should be added—it's dangerous to run any service as root. As root, enter the following commands to make a user and a group called spam: # groupadd spam# useradd -m -d /home/spam -g spam -s /bin/false spam# chmod 0700 /home/spam To configure Postfix to run SpamAssassin, use SpamAssassin as a daemon. The Postfix master.cf file must be changed. Edit the file and locate the line that begins with 'smtp inet'. Amend the line to add -o content_filter=spamd to the end. smtp inet n - n - - smtpd -o content_filter=spamd Add the following lines to the end of the file: spamd unix - n n - - pipeflags=R user=spam argv=/usr/bin/spamc-e /usr/sbin/sendmail -oi -f ${sender} ${recipient} If the text is spread across several lines, any continuing line must begin with spaces as shown. The changes to the file define a filter called spamd that runs the spamc client for each message and also specifies that the filter should be run whenever an e-mail is received via SMTP. On this line, spamd is the name of the filter and matches the name used in the content_filter line. The user= portion specifies the user context that should be used to run the command. The argv= portion describes the program that should be run. The other flags are used by Procmail and their presence is important. Using SpamAssassin with amavisd-new amavisd-new is an interface between MTAs and content checkers. Despite its name, amavisd-new is a well-established open source package that is well maintained. Content checkers scan e-mail for viruses and/or spam. amavisd-new is slightly different. Just like like spamd, it is written in Perl and runs as a daemon, but instead of accessing SpamAssassin via the spamc or spamassassin clients, it loads SpamAssassin into memory and accesses the SpamAssassin functions directly. It is therefore closely coupled to SpamAssassin and may need to be upgraded at the same time as SpamAssassin. Unlike other Perl-based applications and utilities, amavisd-new is not available from CPAN. However, it is available in source form and RPM form for many distributions of Linux, and is also available for debian-based repositories. Details of versions available are listed on http://www.ijs.si/software/amavisd/#download. We recommend that if the version of SpamAssassin that your distributor offers is up-to-date, then you should use their package of both SpamAssassin and amavisd.
Read more
  • 0
  • 0
  • 2551

article-image-text-search-your-database-or-solr
Packt
30 Nov 2009
6 min read
Save for later

Text Search, your Database or Solr

Packt
30 Nov 2009
6 min read
Text Search Features If you think that text search is just a basic thing and nothing more than returning results that matched words in a user query, then think again! There are many technical details that a good search implementation will give you control over to affect how well this fundamental capability works, like text analysis and relevancy ranking. But there are also a variety of ancillary features to look for that make a big difference such as result highlighting and faceting. Text analysis: This is the processing of the original text into indexed terms, and there's a lot to it. Being able to configure the tokenization of words could mean that searching for “Mac” will be found if the word “MacBook” is in the text. And then there's synonym processing so that users can search for similar words. You might want both a common language dictionary and also hand-picked ones for your data. There's the ability to smartly handle desired languages instead of the pervasive English. And then there's stemming which normalizes word variations so that for example “working” and “work” can be indexed the same. Yet another variation of text analysis is phonetic indexing to find words that sound-like the search query. Relevancy ranking: This is the logic behind ranking the search results that closest match the query. In Lucene/Solr, there are a variety of factors in an overall equation with the opportunity to adjust factors based on matching certain fields, certain documents, or using field values in a configurable equation. By comparison, the commercial Endeca platform allows configuration of a variety of matching rules that behaves more like a strict sort. Query features & syntax: From boolean logic to grouping to phrases to fuzzy-searches, to score boosting... there are a variety of queries that you might perform and combine. Many apps would prefer to hide this from users but some may wish to expose it for “advanced” searches. Result highlighting: Displaying a text snippet of a matched document containing the matched word in context is clearly very useful. We have all seen this in Google. Query spell correction (i.e. “did you mean”): Instead of unhelpfully returning no results (or very few), the search implementation should be able to try and suggest variation(s) of the search that will yield more results. This feature is customarily based on the actual indexed words and not a language dictionary. The variations might be based on the so-called edit-distance which is basically the number of alterations needed, or it might be based on phonetic matching. Faceted navigation: This is a must-have feature which enables search results to include aggregated values for designated fields that users can subsequently choose to filter the results on. It is commonly used on e-commerce sites to the left of the results to navigate products by various attributes like price ranges, vendors, etc. Term-suggest (AKA search auto-complete): As seen on Google, as you start typing a word in the search box, it suggests possible completions of the word. These are relevancy sorted and filtered to those that are also found with any words prior to the word you are typing. Sub-string indexing: In some cases, it is needed to match arbitrary sub-strings of words instead of being limited to complete words. Unlike what happens with an SQL like clause, the data is indexed in such a way for this to be quick. Geo-location search: Given the coordinates to a location on the globe with records containing such coordinates, you should be able to search for matching records from a user-specified coordinate. An extension to Solr allows a radial based search with appropriate ranking, but it is also straight-forward to box the search based on a latitude & longitude. Field/facet suggestions: The Endeca search platform can determine that your search query matches some field values used for faceting and then offer a convenient filter for them. For example, given a data set of employees, the search box could have a pop-up suggestion that the word in the search box matches a department code and then offer the choice of navigating to those matching records. This can be easier and faster than choosing facets to filter on, especially if there are a great number of facet-able fields. Solr doesn't have this feature but it would not be a stretch to implement it based on its existing foundation. Clustering: This is another aid to navigating search results besides faceting. Search result clustering will dynamically divide the results into multiple groups called clusters, based on statistical correlation of terms in common. It is a bit of an exotic feature, but is useful with lots of results with lots of text information and after any faceted navigation is done if applicable. So that's quite a list and there are other features you may find too. This should give you a list of features to look for in whatever you choose. Some features are obviously more important to you than others. How NOT to implement text search: the SQL “like” clause Perhaps “back in the day” you implemented search by simply adding like “%searchword%” in the where clause of your SQL (the author is guilty as charged!) But of course, this has serious problems such as: It is very slow, especially given a data set of decent size and any amount of load on the server. A database does a simple brute-force search. There is no concept of relevancy (e.g. a match score). A record simply matched or not. You are forced to sort on one of your columns. It is too literal. Even if the search is case insensitive, any extra punctuation can screw it up, or it may match parts of words when you only wanted to match whole words. So the bottom line is don't do it! There are smarter approaches to this problem. Probably, the only situation you would do this is if you had a particular database column holding a limited number of short values and you have it indexed. Searches should go quickly and it's very easy to implement this approach.
Read more
  • 0
  • 0
  • 3506

article-image-cissp-security-measures-access-control
Packt
27 Nov 2009
4 min read
Save for later

CISSP: Security Measures for Access Control

Packt
27 Nov 2009
4 min read
Knowledge requirements A candidate appearing for the CISSP exam should have knowledge in the following areas that relate to access control: Control access by applying concepts, methodologies, and techniques Identify, evaluate, and respond to access control attacks such as Brute force attack, dictionary, spoofing, denial of service, etc. Design, coordinate, and evaluate penetration test(s) Design, coordinate, and evaluate vulnerability test(s) The approach In accordance with the knowledge expected in the CISSP exam, this domain is broadly grouped under five sections as shown in the following diagram: Section 1: The Access Control domain consists of many concepts, methodologies, and some specific techniques that are used as best practices. This section coverssome of the basic concepts, access control models, and a few examples of access control techniques. Section 2: Authentication processes are critical for controlling access to facilities and systems. This section looks into important concepts that establish the relationship between access control mechanisms and authentication processes. Section 3: A system or facility becomes compromised primarily through unauthorized access either through the front door or the back door. We'll see some of the common and popular attacks on access control mechanisms, and also learn about the prevalent countermeasures to such attacks. Section 4: An IT system consists of an operating system software, applications, and embedded software in the devices to name a few. Vulnerabilities in such software are nothing but holes or errors. In this section we see some of the common vulnerabilities in IT systems, vulnerability assessment techniques, and vulnerability management principles. Section 5: Vulnerabilities are exploitable, in the sense that the IT systems can be compromised and unauthorized access can be gained by exploiting the vulnerabilities. Penetration testing or ethical hacking is an activity that tests the exploitability of vulnerabilities for gaining unauthorized access to an IT system. Today, we'll quickly review some of the important concepts in the Sections 1, 2,and 3. Access control concepts, methodologies, and techniques Controlling access to the information systems and the information processing facilities by means of administrative, physical, and technical safeguards is the primary goal of access control domain. Following topics provide insight into someof the important access control related concepts, methodologies, and techniques. Basic concepts One of the primary concepts in access control is to understand the subject and the object. A subject may be a person, a process, or a technology component that either seeks access or controls the access. For example, an employee trying to access his business email account is a subject. Similarly, the system that verifies the credentials such as username and password is also termed as a subject. An object can be a file, data, physical equipment, or premises which need controlled access. For example, the email stored in the mailbox is an object that a subject is trying to access. Controlling access to an object by a subject is the core requirement of an access control process and its associated mechanisms. In a nutshell, a subject either seeks or controls access to an object. An access control mechanism can be classified broadly into the following two types: If access to an object is controlled based on certain contextual parameters, such as location, time, sequence of responses, access history, and so on, then it is known as a context-dependent access control. In this type of control, the value of the asset being accessed is not a primary consideration. Providing the username and password combination followed by a challenge and response mechanism such as CAPTCHA, filtering the access based on MAC adresses in wireless connections, or a firewall filtering the data based on packet analysis are all examples of context-dependent access control mechanisms. Completely Automated Public Turing test to tell Computers and Humans Apart (CAPTCHA) is a challenge-response test to ensure that the input to an access control system is supplied by humans and not by machines. This mechanism is predominantly used by web sites to prevent Web Robots(WebBots) to access the controlled section of the web site by brute force methods The following is an example of CAPTCHA: If the access is provided based on the attributes or content of an object,then it is known as a content-dependent access control. In this type of control, the value and attributes of the content that is being accessed determines the control requirements. For example, hiding or showing menus in an application, views in databases, and access to confidential information are all content-dependent.
Read more
  • 0
  • 0
  • 10505
article-image-business-rules-management-bpm-and-soa
Packt
27 Nov 2009
13 min read
Save for later

Business Rules Management, BPM, and SOA

Packt
27 Nov 2009
13 min read
Introduction to Business Rules Management Let us start by understanding some key concepts around business rules. What are Business Rules? Business rules can be defined as the key decisions and policies of the business. Rules are virtually everywhere in an organization; an example is the rule in a bank to deny a loan for a customer if his or her annual income is less than $15,000. We can generally categorize business rules under the following categories: Business Policies: These are rules associated with general business policies of a company, for example, loan approval policies, escalation policies, and so on. Constraints: These are the rules which business has to keep in mind, and work within the scope of while going about their operations. Rules associated with regulatory requirements will fall under this category. Computation: These are the rules associated with decisions involving any calculations, for example, discounting rules, premium adjustments, and so on. Reasoning capabilities: These are the rules that apply logic and inference course of actions based on multiple criteria. For example, rules associated with the up-sell or cross-sell of products and services to customers based on their profile. Allocation Rules: There are some rules that are applicable in terms of determining the course of action for the process, based on information from the previous tasks. They also include rules that manage the receiving, assignment, routing, and tracking of work. Business Rules Anatomy To understand the anatomy of a business rule, we can divide a business rule primarily into the following four blocks: Definitions of Terms: This helps in providing a vocabulary for expressing the rules. Defining a term acts as the category for the rules. For example, customer, car, claims, and so on define the entities for the business. Facts: These are used to relate terms in definitions with each other. For example, a customer may apply for a claim. Constraints: These are the constraints, limitations, or controls on how an organization wants to use and update the data. For example, for opening an account, a customer's passport details or social security details are required. Inference: This basically applies to logical assertions such as 'if X, then Y' to a fact, and infers new facts. For example, if we have a single account validation rule (if an applicant is a defaulter, then the applicant is high-risk), and we know that Harry (the applicant) has defaulted earlier on his payments for other bank services, we can infer that Harry is a high-risk customer. Automating Business Rules As we discuss the externalization and automation of business rules, it's important to understand the distinction between implicit and explicit rules. An implicit rule can be viewed as a rule that is a part of a larger context within the system. It's like multiple rules that are implemented in traditional applications to implement decision logic, for example, assessing the risk level for a loan. Its implementation is usually part of the application it is being developed for, and is never considered beyond the scope of the application, perhaps to be re-used. So Typically, in the IT world, these implicit rules are embedded within the complex application code and spread across multiple systems, making it extremely difficult to introduce changes quickly, and without creating a domino effect across systems. Some of these issues can be resolved by implementing a Business Rules Management System (BRMS) in collaboration with the BPM system in place. This allows the decision logic, which is being used by the process during its execution, to be driven by a central repository where all the rules are stored and managed. This repository provides a way to abstract the decision logic from the applications, and helps in managing this logic centrally, allowing for better management and flexibility for change and re-use. Hence, these rules are explicit in nature. For the loan approval example, business rules such as these would traditionally be embedded in application code, and might appear in an application as follows: public boolean checkAnnualIncome(Customer customer){boolean declineLoan = false;int income = customer.getincome();if( income < 10000 ){declineLoan = true;}return declineLoan;} The above example shows that this rule is obviously difficult for the business users to understand. In today's world, with the need for an organization to be agile, (considering our previous example) the business has to wait for weeks before a small change can be implemented by IT. What is required is the ability of the business users to define and control their own rules, and to be able to get the changes out in the market faster. Business Rules Management and related technology tries to solve this problem. Automating Business Rules for Business Issues Automation of business rules via BRMS is ideal for use, where the following issues are being faced by an organization: Dynamism and Volatility: Companies need to repeatedly change business policies, procedures, and products to meet the market needs. In this case, the rules change very dynamically, and having a BRMS can help in implementing these changes faster, and reducing the time to market and cost of implementation. Time to Market: In this case, the organization might want a particular set of changes to be released quickly due to market pressure, or to gain a competitive advantage. So, Even though the rules are not changed very often, a delay in their implementation could lead to a serious business loss. In this case, the organization needs to have the ability to get these changes in quickly, without roadblocks, which can be addressed by a BRMS. Regulatory Compliance: Failure to comply with regulatory requirements such as Anti-Money Laundering (AML) laws can result in millions of dollars in fines, and legal issues for the organizations. To solve these issues, institutions can combine business rules with SOA to create an effective strategy for enforcing compliance. Business rules technology helps in implementing these rules quickly, and helps them to be kept up–to-date across an enterprise. Business Participation: There could be rules which might be better off being controlled and owned by the business users. In this case, a BRMS can expose certain rules to be managed and edited by selected business users, providing an easy to use interface. Rules related to product configuration, customer eligibility, discounts and so on, are some examples where business users can manage the rules, and change them as required by changing scenarios. Complexity: Some scenarios, such as complex product and service pricing, require extremely complex dependencies between several rules to implement the scenario logic. These kinds of rules are best suited for implementation inside a BRMS rather than a procedural language, as is being done traditionally. Telecom Fraud Management, for example, is an area where rules management is being used along with BAM to identify potential frauds. There are similar applications in credit card and banking industries. Consistency: Rules managed centrally provides a more consistent way of managing certain policies requiring re-use and consistency across the enterprise. This is especially true in cases where inconsistency was an issue due to multiple applications, databases, and different lines of businesses. Business Rules Management, BPM, and SOA Business Rules Management, BPM, and SOA share a synergistic relationship, especially, when used together to provide agility to an organization. The term 'Agility' can be defined as "the ability of an enterprise to sense and predict change in their environment and respond quickly, efficiently, and effectively to that change". Agility, requires the organization to be flexible enough in introducing change and in modifying their current operations, to achieve higher levels of performance or output. A process-driven approach to SOA allows business users to introduce changes to the process for faster execution, and with less cost. This value is amplified by using a Business Rules platform alongside process orchestration. If we look at the BPM reference architecture again, rules functionality features in various layers of the architecture, in the initial rules discovery phase, during process mapping, and in its orchestration in the SOA environment. Business Rules-related technologies have been in the market for a number of years now. However, with the acceptance of BPM and SOA as enablers for increasing an organization's agility, today's enterprises are increasingly looking at using rules management to externalize their rules. Business rules management helps automate decisions and apply policies within processes. Automation of these decisions requires determining the meaning of a given situation, and applying a business policy in response to this. Business rules platforms provide tools to define this 'reasoning' logic for use by either developers or business analysts, and business stakeholders. Organizations are looking at Business Rules Management to deploy rules related to policy decisions, work allocation, compliance and control, business exception management, and even data validation. For example, a major financial services company uses business rules to apply privacy and anti-fraud policies to all of its transactions. Even more, these Business Rules are being considered as an asset for an organization that should be managed centrally and re-used across departments and systems, instead of being hard-coded into an application. So, it is important to ensure that business rules have a place in your SOA. Carefully defining and exposing your rules as services will enable all of the applications and services within your architecture to have simple access to a common rules repository. From an SOA perspective, before beginning a business rules implementation, you should: Incorporate a business rules platform into your SOA: This would be a service-enabled repository of your business rules, where instead of data you would maintain and execute rulesets using a business rules engine. Create standards and best practices for developing business rules: To maximize benefits from your rules implementation, you should focus on developing common standards and best practices for discovery, design, development, and interfacing of your rules. Some of the best practices for writing and designing business rules are: Declarative: Business rules should be declared, and not stated as procedures as in coding. How a rule will be enforced should not be part of a rule definition. For example, "If the customer is a premium customer, offer him further 5% discount." Precise: It's easier for business rules definitions to be misinterpreted due to the use of natural language syntax by business. One business rule should be open to only one interpretation, and would need rephrasing if it was found to be ambiguous. Consistency and non-redundancy: Business rules should be consistent and not conflict other rules. Similarly, you should look out for business rules that are redundant. Business Focused and Owned: Business rules should be declared using the business vocabulary so that they can understood by relevant business stakeholders. Avoid using technical jargons in business rules. Also business rules are best left under the ownership of the business, community, as that is the source for the rules. Key Considerations for Selecting a BRMS The following are some key considerations when selecting a BRMS to work with BPM and SOA: Standards-based Integration capability: The ability to integrate with the SOA landscape using a service layer. Business User Interface: The ability to provide the capability for business users to access and modify business rules through a user-friendly interface. Rule Language: The ability to provide support for natural languages for easily expressing a complex set of rules. Performance: The ability to provide support for high-volume transactions for mission-critical applications, which is normally measured in terms of the number of rules processed per second. Rules Monitoring and Reporting: The ability to feature support for rules debugging, rules reporting, and real time monitoring of rules. Rules Repository: The ability to provide a centralized repository for storing all rule-specific artifacts. The repository should also support change management by storing different versions of rules, and providing audit capabilities. Key components of a BRMS—A Brief Look into Oracle Business Rules Typically, a BRMS will comprise four main components: Business UI: This is a user interface component for writing and editing business rules. Typically, it will be a web-based interface for business users to log in and access existing business rules, create new ones, and so on. Rules Development Environment: Developers will be working in this environment to convert business rules defined by business users into code that can be implemented in the business rules engine. This will be also an environment where the service layer for the rules will be defined and implemented for integration with other applications and SOA components. Rules Repository: This will be a centralized repository where all rules-related information will be stored. Rules Execution Engine: This is the heart of the rules management system and will be responsible for executing the business rules in the run time environment. In SOA terms, this component will receive request for rules processing from the business process orchestration environment, based on which, it will run appropriate rules and provide decision information that will be sent back to the orchestration layer. Oracle also provides a suite of components under its Oracle Business Rules product to support rules management and execution, which are as follows: Oracle Rule Author: Rule Author provides a web-based graphical authoring environment that enables the easy creation of business rules via a web browser. The application developer uses Rule Author to define a data model and an initial set of rules. The business analyst uses Rule Author either to work with the initial set of rules, or to modify and customize the initial set of rules according to business needs. Using Rule Author, a business analyst can create and customize rules with little or no assistance from a programmer. Rules Engine: This is the heart of the rules system and executes and manages rules in a proper and efficient manner. This allows inference-based rule execution, based on the very popular Rete algorithm. The Rete algorithm is an efficient pattern-matching algorithm used for rules and facts, and stores partially-matched results in a single network of nodes in current working memory, allowing the rules engine to avoid unnecessary rechecking when facts are deleted, added, or modified. Oracle's rules engine provides a data-driven forward-changing system. This means that the facts will determine which rules can be triggered. When a particular rule is triggered, based on pattern matching within a set of facts, the rule may further add new facts. The new facts are again run against the rules as an iterative process untill it reaches an end state. This allows rules to be interlinked and triggered in a cycle, also referred to as an inference cycle.The rules engine also provides a web service interface with its SOA environment using 'Decision Services', which is available in a JDeveloper environment during the coding of business processes in BPEL. This can also be used to make a web service call to rules running in the rules engine. It also exposes a Rules API, which is based on JSR 94, a runtime specification for rules engines to integrate business rules application with other applications in an organization. Rule Repository: A rule repository is the database that stores business rules. The Oracle rules repository allows rules to be grouped as rulesets, and make it part of the rules dictionary in a central repository. These dictionaries can be versioned for better governance. Oracle's rules repository supports a WebDAV (Web Distributed Authoring and Versioning) repository and a file repository. Rules SDK: This allows users to develop and integrate the Rules Repository in to a custom authoring environment. This component also allows the development of a customized UI for business users to access and update the Rules repository, if required.
Read more
  • 0
  • 0
  • 4156

article-image-hibernate-types
Packt
27 Nov 2009
3 min read
Save for later

Hibernate Types

Packt
27 Nov 2009
3 min read
Hibernate allows transparent persistence, which means the application is absolutely isolated from the underlying database storage format. Three players in the Hibernate scene implement this feature: Hibernate dialect, Hibernate types, and HQL. The Hibernate dialect allows us to use a range of different databases, supporting different, proprietary variants of SQL and column types. In addition, HQL allows us to query persisted objects, regardless of their relational persisted form in the database. Hibernate types are a representation of databases SQL types, provide an abstraction of the underlying database types, and prevent the application from getting involved with the actual database column types. They allow us to develop the application without worrying about the target database and the column types that the database supports. Instead, we get involved with mapping Java types to Hibernate types. The database dialect, as part of Hibernate, is responsible for transforming Java types to SQL types, based on the target database. This gives us the flexibility to change the database to one that may support different column types or SQL without changing the application code. Built-in types Hibernate includes a rich and powerful range of built-in types. These types satisfy most needs of a typical application, providing a bridge between basic Java types and common SQL types. Java types mapped with these types range from basic, simple types, such as long and int, to large and complex types, such as Blob and Clob. The following table categorizes Hibernate built-in types with corresponding Java and SQL types: Java Type Hibernate Type Name SQL Type Primitives Boolean or boolean boolean BIT true_false CHAR(1)('T'or'F') yes_no CHAR(1)('Y'or'N') Byte or byte byte TINYINT char or Character character CHAR double or Double double DOUBLE float or float float FLOAT int or Integer integer INTEGER long or Long long BIGINT short or Short short SMALLINT String java.lang.String string VARCHAR character CHAR(1) text CLOB Arbitrary Precision Numeric java.math.BigDecimal big_decimal NUMERIC Byte Array byte[] or Byte[] binary VARBINARY   Time and Date java.util.Date date DATE time TIME timestamp TIMESTAMP java.util.Calendar calendar TIMESTAMP calendar_date DATE java.sql.Date date DATE java.sql.Time time TIME java.sql.Timestamp timestamp TIMESTAMP Localization java.util.Locale locale VARCHAR java.util.TimeZone timezone java.util.Currency currency Class Names java.lang.Class class VARCHAR Any Serializable Object java.io.Serializable Serializable VARBINARY JDBC Large Objects java.sql.Blob blob BLOB java.sql.Clob clob CLOB
Read more
  • 0
  • 0
  • 3361

article-image-freebies-and-downloads-drupal-6-part-2
Packt
27 Nov 2009
3 min read
Save for later

Freebies and Downloads in Drupal 6: Part 2

Packt
27 Nov 2009
3 min read
Automatically generating PDF files for a page Good Eatin' Goal: Generate PDF files of our pages so that the users can automatically download the pages for printing, or for offline usage. Additional modules needed: Printer, email, and PDF (http://drupal.org/project/print). Basic steps As you continue to work on your web site, you will find that many users want access to your content, even if they aren't online. With the Printer, email, and PDF module, you can easily and automatically provide content in various formats for offline usage. To begin with, download and install the Printer, email, and PDF module. You can now configure the basic options for the module by selecting Site configuration and then Printer-friendly pages from the Administer menu. The general settings are accessed by clicking on the Settings tab. These settings are shown below, and include options to style the printable pages, and to determine whether or not URLs and comments are displayed on the page. You can also control how the page is opened, and also which logos are displayed on it. By expanding the Source URL section, you can cause the URL of the page to be included on the printed output. You can also optionally add the date and time when the page was generated to the printed output. The printable page (web page) configuration options include a variety of options to control how the links to the printable versions are displayed, as well as how the printable pages are displayed. We have modified the Printer-friendly page link to be in the Content corner rather than in the Links area. You can also optionally display the printable page in a new window and automatically call the print function, as needed. Opening the Advanced link options gives you additional options for how the link is displayed, and what pages it should be displayed on, as shown in the following screenshot: The Robots META tags section allows you to prevent search engines from indexing your printable version, which will help to ensure that visitors are directed only to your online content. This can also help prevent duplicate content penalties being imposed by search engines. To create PDFs, we need to install a third-party tool to handle the conversion. You can choose from either TCPDF or dompdf, which are available at the following locations: TCPDF: http://tcpdf.org dompdf: http://www.digitaljunkies.ca/dompdf/faq.php You can install and use either of these. You can also install both of them and switch between the two, while you evaluate which one will meet the needs of your site best. After you have installed TCPDF and/or dompdf, you can access the PDF tabbed page in the Printer-friendly pages configuration.
Read more
  • 0
  • 0
  • 1216
article-image-device-management-zenoss-core-network-and-system-monitoring-part-2
Packt
27 Nov 2009
9 min read
Save for later

Device Management in Zenoss Core Network and System Monitoring: Part 2

Packt
27 Nov 2009
9 min read
Model Devices When we talk about Zenoss, two related but different words often come up, monitoring and modeling. Monitoring refers to the availability of the device and answers the question, "Is the device accessible?" Modeling defines a relationship between devices and identifies the components available on a device, such as services, interfaces, and file systems. Zenoss models devices via SNMP, SSH, port scan, and telnet and gathers information via collector plug-ins. Each class has a default set of collector plug-ins that tells Zenoss how to model the devices assigned to the class. We can add or remove collector plug-ins at the device level for individual changes or at the class level for all the devices in the class. The collector plug-in names reflect the monitoring protocol they are used for. All the SNMP collectors contain "snmp" in the name. The SSH and telnet plug-in names contain "cmd," and the port scan plug-in contains "portscan" in the name. We'll step through modeling examples for SNMP, SSH, and port scan; however, we'll skip telnet because it's similar to SSH. SNMP Zenoss defaults to SNMP monitoring, and the monitored device needs to have SNMP installed and configured to work properly. Zenoss supports SNMP v1, v2c, and v3. The example commands used in this section to troubleshoot SNMP specify v1. Test SNMP If we're unsure of our SNMP setup, we can test it by running the snmpwalk command to retrieve the values of the MIB tree on the monitored device. We'll demonstrate both working and broken SNMP configurations on the MillRace network. From the Device List, select the device named Coyote. From the Device Status page menu, choose Run Commands > snmpwalk. A new window opens and we see the results of the snmpwalk command as shown in the following screenshot. Now we select the device Bobcat from the Device List view. Run the snmpwalk command from the Device Status page. This time, we receive a Timeout error, which indicates that we have a problem with SNMP on the device Bobcat as shown in the following screenshot. Assuming that SNMP is properly configured on the device and that the monitored device accepts traffic on port 161, we may need to update the device's community string. To update the community: Select the device from the Device List view. From the Device Status page menu, select More > zProperties. Find the Community field and enter the correct value. Save the changes. After updating the SNMP community string in the zProperties, we run the snmpwalk command again to see if we have fixed the problem. If we continue to encounter problems getting Zenoss to model a device with SNMP, we can try to narrow down the problem by running the following snmpwalk command from the monitored devices shell prompt: snmpwalk -v1 -c public localhost system Replace public with the correct community string. If the command is successful when using localhost, edit the snmpd configuration file. As root, edit /etc/default/snmpd or /etc/default/snmp and remove 127.0.0.1 from the following line: SNMPDPORTS = '-Lsd -Lf /dev/null -u snmp -I -smux -p /var/run/snmpd.pid 127.0.0.1' After editing the /etc/default/snmpd file, restart the snmpd service as root. For example: /etc/init.d/snmpd stop/etc/init.d/snmpd start Retest the snmpwalk command to confirm that SNMP is working correctly.Windows users can run wbemtest from the command line to test SNMP. Windows Considerations In order to collect information from WMI,regarding the Windows SNMP installation we need to configure the zProperties for the Windows device. Navigate to the Windows device and open the zProperties page by selecting the More > zProperties from the page menu. Scroll to the bottom of the page and make the following changes: Set zWinEventLog to true. Enter the Windows user's password in the zWinPassword field. Enter the user name with administrative rights in the zWinUser field in the following formats: .user for local user accounts DOMAINuser for domain user accounts Set zWMIMonitorIgnore to false. Save the changes, and Zenoss is ready to model the information on the Windows device. We can force a model by selecting Manage > Model Device from thepage menu. SNMP Collector Plug-ins The Collector Plug-ins assigned to the device determines how Zenoss models the device. Let's take a look at our example device Coyote and see what collectors are currently assigned. From the Device Status page for Coyote, select More > Collector Plug-ins from the page menu. A page showing the assigned collector plugi-ns displays in the left column of the page with an Add Fields link on the right. When we click on the Add Fields link, a column of unassigned plug-ins appears and the link name changes to Hide Fields as shown in the following screenshot. The plug-in names are intuitive in that the name suggests the type of information we expect to be modeling. For example, zenoss.snmp.IpServiceMap returns a list of active IP services on the device, such as HTTP. The Dell specif?i c plugi-ns retrieve more detailed information from Dell devices using OpenManage, and the HPplugi-ns provide more information about devices using Insight Management agents. To remove a plug-in from the assigned plug-in list, click on the "x" next to the plug-in name. To assign a plug-in, drag the plug-in name from available list to the assigned list. To see how our devices are affected, let's remove the zenoss.snmp.IpServiceMap and add zenoss.cmd.df. After we make the changes to the plug-ins for Coyote, scroll to the bottom of the page and click Save. Model Device Zenoss automatically models each device in our inventory every six hours, but we can manually force Zenoss to model the device. From the Device Status page, select Manage > Model Device from the page menu. Zenoss displays the results of the zenmodeler command in the window as shown in the following screenshot. Zenoss first determines which plugi-ns are available and then collects information based on those plug-ins. Notice that no cmd plug-ins are found, which means that the zenoss.cmd.df plug-in we added to Coyote will not be collected. After Zenoss models the device, we can review the device overview page to see what component types Zenoss discovered. IpService should not be listed. If we go back to the Collector Plug-ins page for Coyote, we can add the zenoss.snmp.IpService plug-in and then model the device again. Now, IpServices is displayed in the Component Type list as shown in the following screenshot. The Component Type list gets updated as part of the modeling process and so does the OS fields in the Device Information table (the greyed-out fields in the screen shot). If we enter values in these fields during the Add Device step, the values would be overwritten with the SNMP values. Our example made changes to the device level, which means that if we view the collector plug-ins for the /Server/Linux device class, the original plug-ins are specified. To view the plug-ins for the class: Select Devices from the navigation panel. Select Server from the sub-devices list. Select Linux from the sub-devices list. From the /Devices/Server/Linux page menu, select More > CollectorPlug-ins. Devices automatically inherit any changes we make to the class collector plug-ins the next time Zenoss models the devices. SSH Modeling If the monitored device does not support SNMP, or if we need to monitor a device behind a firewall, SSH provides an alternative to SNMP. Unlike SNMP, SSH needs the Zenoss Plug-ins installed on each monitored device and platform support is limited to Linux, Darwin, and FreeBSD. We also need to make sure that the monitored device has an SSH server installed so that the Zenoss system can log in and retrieve information. OpenSSH from openssh.com offers a good cross-platform SSH solution. The level of modeling provided by the Zenoss Plug-ins varies between platforms. For this reason, we may not achieve the same level of detail as we do with SNMP, but SSH modeling provides more detail than a port scan. To help us setup our SSH monitoring, Zenoss provides the /Server/Cmd class which is already configured with the command plug-ins we need to monitor via SSH. SSH Collector Plug-ins From the navigation panel, select Devices. Navigate to the /Server/Cmd class and click on the zProperties tab. Find the zCollectorPlug-ins field and click on the Edit link. A list of the assigned collector plug-ins is displayed as shown in the following screenshot. The important thing to note with the command collector plug-ins is the new level of specificity in the name. The zenoss.cmd.uname and zenoss.cmd.df plug-ins are common to all architectures, while the plug-ins with "linux" in the name work with Linux systems. Mac OS X platforms use the plug-ins with "darwin" in the name. If we did not have any any OS X systems to monitor, then we could remove allthe Darwin-based plug-ins from the /Server/Cmd class or, if we know that wedon't want to monitor the memory usage for any of our devices, we can removethat plug-in. We'll leave the collector plug-ins as they are for the /Server/Cmd class and change our test device Coyote to use SSH instead of SNMP. Zenoss Plug-ins Zenoss will monitor and retrieve some data using the SSH modeler even if we do not install the Zenoss plug-ins, but the device model will be incomplete. For example, file systems will be detected along with the size of each drive., but the usage statistics will not be reported. Zenoss also generates warning events if it cannot find the zenplugin.py command on the monitored system. The monitored system needs a Python environment installed. This can beinstalled using your distribution's package manager. If you have setuptoolsinstalled, you can install the Zenoss-Plug-ins package from the Cheese Shop (http://pypi.python.org/pypi/) with the following command as root: easy_install Zenoss-Plugins We can also build the Zenoss Plug-ins package from source: Download the Zenoss Plug-ins package from http://www.zenoss.com/download/. Extract the plug-in file. From the plug-in source directory, run the following commands as root: python setup.py build python setup.py install The setuptools procedure installs zenplugin.py to /usr/bin, which is important because we need to configure the device zProperties to look for the plug-ins in the correct location. To ensure that the plug-in file is working correctly, run the following command on the monitored device, which is Coyote in our example: zenplugin.py –list-plugins The command outputs the detected platform and the supported plug-ins as shown in the following screenshot.
Read more
  • 0
  • 0
  • 3930

article-image-codeigniter-17-and-objects
Packt
27 Nov 2009
9 min read
Save for later

CodeIgniter 1.7 and Objects

Packt
27 Nov 2009
9 min read
Objects confused us, when we started using CodeIgniter. Coming to CodeIgniter through PHP 4, which is a procedural language, and not an object-oriented (OO) language. We duly looked up objects and methods, properties and inheritance, and encapsulation, but our early attempts to write CI code were plagued by the error message "Call to a member function on a non-object". We saw it so often that we were thinking of having it printed on a T-shirt. To save the world from a lot of boring T-shirts, this article covers the way in which CI uses objects, and the different ways you can write and use your own objects. Incidentally, we've used "variables/properties", and "methods/functions" interchangeably, as CI and PHP often do. You write "functions" in your controllers, for instance, when an OO purist would call them "methods". You define class "variables" when the purist would call them "properties". Object-oriented programming We assume that you have basic knowledge of OOP. You may have learned it as an afterthought to "normal" PHP 4. PHP 4 is not an OO language, though some OO functionality has been stacked on to it. PHP 5 is much better, with an underlying engine that was written from the ground up with OO in mind. You can do most of the basics in PHP 4, and CI manages to do everything it needs internally in either language. The key thing to remember—when an OO program is running, there is always one current object (but only one). Objects may call each other or hand over control to each other, in which case the current object changes, but only one of them can be current at any time. The current object defines the scope, in other words, the variables (properties) and methods (functions) that are available to the program at that moment. So it's important to know and control the current object. PHP, being a mixture of functional and OO programming, also offers the possibility where no object is current. You can start off with a functional program, call an object, let it take charge for a while, and then return control to the program. Luckily, CI takes care of this for you. The CI super-object CI works by building one super-object—it runs the entire program as one big object, in order to eliminate scoping issues. When you start CI, a complex chain of events occurs. If you set your CI installation to create a log (in /codeigniter/application/config/config.php set $config['log_threshold'] = 4; value. This will generate a log file in /www/CI_system/logs/), you'll see something like this: 1 DEBUG - 2006-10-03 08:56:39 --> Config Class Initialized2 DEBUG - 2006-10-03 08:56:39 --> No URI present. Default controllerset.3 DEBUG - 2006-10-03 08:56:39 --> Router Class Initialized4 DEBUG - 2006-10-03 08:56:39 --> Output Class Initialized5 DEBUG - 2006-10-03 08:56:39 --> Input Class Initialized6 DEBUG - 2006-10-03 08:56:39 --> Global POST and COOKIE datasanitized7 DEBUG - 2006-10-03 08:56:39 --> URI Class Initialized8 DEBUG - 2006-10-03 08:56:39 --> Language Class Initialized9 DEBUG - 2006-10-03 08:56:39 --> Loader Class Initialized10 DEBUG - 2006-10-03 08:56:39 --> Controller Class Initialized11 DEBUG - 2006-10-03 08:56:39 --> Helpers loaded: security12 DEBUG - 2006-10-03 08:56:40 --> Scripts loaded: errors13 DEBUG - 2006-10-03 08:56:40 --> Scripts loaded: boilerplate14 DEBUG - 2006-10-03 08:56:40 --> Helpers loaded: url15 DEBUG - 2006-10-03 08:56:40 --> Database Driver Class Initialized16 DEBUG - 2006-10-03 08:56:40 --> Model Class Initialized At start up, that is, each time a page request is received over the Internet—CI goes through the same procedure. You can trace the log through the CI files: The index.php file receives a page request. The URL may indicate which controller is required, if not, CI has a default controller (line 2). The index.php file makes some basic checks and calls the codeigniter.php file (codeignitercodeigniter.php). require_once BASEPATH.'codeigniter/CodeIgniter'.EXT; The codeigniter.php file instantiates the Config, Router, Input, URL, and other such, classes (see lines 1, and 3 to 9). These are called the base classes—you rarely interact directly with them, but they underlie almost everything CI does. /** ------------------------------------------------------* Instantiate the base classes* ------------------------------------------------------*/$CFG =& load_class('Config');$URI =& load_class('URI');$RTR =& load_class('Router');$OUT =& load_class('Output'); The file codeigniter.php tests to see the version of PHP it is running on, and calls Base4 or Base5 (/codeigniter/Base4.php or codeigniter/Base5.php). if (floor(phpversion()) < 5){load_class('Loader', FALSE);require(BASEPATH.'codeigniter/Base4'.EXT);}else{require(BASEPATH.'codeigniter/Base5'.EXT);} The above snippet creates an object—one which ensures that a class has only one instance. Each has a public &get_instance() function. Note the &—this is assignment by reference. So, if you assign using &get_instance() method, it assigns to the single running instance of the class. In other words, it points to the same pigeonhole. So, instead of setting up lot of new objects, you start building one super-object, which contains everything related to the framework. function &get_instance(){return CI_Base::get_instance();} A security check, /** ------------------------------------------------------* Security check* ------------------------------------------------------** None of the functions in the app controller or the* loader class can be called via the URI, nor can* controller functions that begin with an underscore*/$class = $RTR->fetch_class();$method = $RTR->fetch_method();if ( !class_exists($class)OR $method == 'controller'OR strncmp($method, '_', 1) == 0OR in_array(strtolower($method), array_map('strtolower',get_class_methods('Controller')))){show_404("{$class}/{$method}");} The file, codeigniter.php instantiates the controller that was requested, or a default controller (line 10). The new class is called $CI. $CI = new $class(); The function specified in the URL (or a default) is then called and life, as we know it, starts to wake up and happen. Depending on what you wrote in your controller, CI will initialize the classes you need, and "include" functional scripts you asked for. So, in the log, the model class is initialized (line 16). The boilerplate script, which is also shown in the log (line 13), is the one we wrote to contain standard chunks of text. It's a .php file, saved in the folder called scripts. It's not a class—just a set of functions. If you were writing pure PHP you might use include or require to bring it into the namespace—CI needs to use its own load function to bring it into the super-object. The concept of namespace or scope is crucial here. When you declare a variable, array, object, and so on, PHP holds the variable name in its memory and assigns a further block of memory to hold its contents. However, problems might arise if you define two variables with the same name. (In a complex site, this is easily done.) For this reason, PHP has several set of rules. Some of them are as listed: Each function has its own namespace or scope, and variables defined within a function are usually local to it. Outside the function, they are meaningless. You can declare global variables, which are held in a special global namespace and are available throughout the program. Objects have their own namespaces—variables exist inside the object as long as the object exists, and can only be referenced by using the object. So, $variable, global $variable, and $this->variable are three different things. Remember, $variable and global $variable can't be used in the same scope. So, inside a function you will have to decide if you want to use $variable or global $variable. Particularly before OO, this could lead to all sort of confusions—you may have too many variables in your namespace (so that conflicting names overwrite each other). You may also find that some variables are just not accessible from whatever scope you happen to be. Copying by reference You may have noticed the function &get_instance() in the previous section. This is to ensure that, as the variables change, the variables of the original class also change. As assignment by reference can be confusing, so here's a short explanation. We're all familiar with simple copying in PHP: $one = 1;$two = $one;echo $two; The previous snippet produces 1, because $two is a copy of $one. However, suppose you reassign $one: $one = 1;$two = $one;$one = 5;echo $two; This code still produces $two = 1, because changes made to $one after assigning $two have not been reflected in $two. This was a one-off assignment of the value that happened to be in variable $one at that time, to a new variable $two. Once that is done, the two variables lead separate lives (in just the same way if we alter $two, $one doesn't change). In effect, PHP creates two pigeonholes—called $one and $two. A separate value lives in each. You may, on any occasion, make the values equal, but after that each does its own work. PHP also allows copying by reference. If you add just a simple & to line 2 of the snippet as shown: $one = 1;$two =& $one;$one = 5;echo $two; The code now echoes 5, the change we made to $one is reflected in $two. Changing the = to =& in the second line means that the assignment is "by reference". It looks as if there was only one pigeonhole, which has two names ($one<.i> and $two). Whatever happens to the contents of the pigeonhole is reflected in both $one and $two, as if they were just different names for the same variables. The principle works for objects as well as simple string variables. You can copy or clone an object using the = operator in PHP 4. Or you can clone keyword in PHP, in which case you make a simple one-off new copy, which then leads an independent life. You can also assign one to the other by reference, so the two objects point to each other. Any changes made to one will also happen to the other. Again, think of them as two different names for the same thing.
Read more
  • 0
  • 0
  • 2621
Modal Close icon
Modal Close icon