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

How-To Tutorials - CMS & E-Commerce

830 Articles
article-image-drupal-7-themes-creating-dynamic-css-styling
Packt
05 Jul 2011
7 min read
Save for later

Drupal 7 Themes: Creating Dynamic CSS Styling

Packt
05 Jul 2011
7 min read
Drupal 7 Themes Create new themes for your Drupal 7 site with a clean layout and powerful CSS styling The reader would benefit by referring the previous article on Dynamic Theming In addition to creating templates that are displayed conditionally, the Drupal system also enables you to apply CSS selectively. Drupal creates unique identifiers for various elements of the system and you can use those identifiers to create specific CSS selectors. As a result, you can provide styling that responds to the presence (or absence) of specific conditions on any given page. Employing $classes for conditional styling One of the most useful dynamic styling tools is $classes. This variable is intended specifically as an aid to dynamic CSS styling. It allows for the easy creation of CSS selectors that are responsive to either the layout of the page or to the status of the person viewing the page. This technique is typically used to control the styling where there may be one, two, or three columns displayed, or to trigger display for authenticated users. Prior to Drupal 6, $layout was used to detect the page layout. With Drupal 6 we got instead, $body_classes. Now, in Drupal 7, it's $classes. While each was intended to serve a similar purpose, do not try to implement the previous incarnations with Drupal 7, as they are no longer supported! By default $classes is included with the body tag in the system's html.tpl.php file; this means it is available to all themes without the necessity of any additional steps on your part. With the variable in place, the class associated with the body tag will change automatically in response to the conditions on the page at that time. All you need to do to take advantage of this and create the CSS selectors that you wish to see applied in the various situations. The following chart shows the dynamic classes available to you by default in Drupal 7: If you are not certain what this looks like and how it can be used, simply view the homepage of your site with the Bartik theme active. Use the view source option in your browser to then examine the body tag of the page. You will see something like this: <body class="html front not-logged-in one-sidebar sidebar-first page-node">. The class definition you see there is the result of $classes. By way of comparison, log in to your site and repeat this test. The body class will now look something like this: <body class="html front logged-in one-sidebar sidebar-first page-node">. In this example, we see that the class has changed to reflect that the user viewing the page is now logged in. Additional statements may appear, depending on the status of the person viewing the page and the additional modules installed. While the system implements this technique in relation to the body tag, its usage is not limited to just that scenario; you can use $classes with any template and in a variety of situations. If you'd like to see a variation of this technique in action (without having to create it from scratch), take a look at the Bartik theme. Open the node.tpl.php file and you can see the $classes variable added to the div at the top of the page; this allows this template to also employ the conditional classes tool. Note that the placement of $classes is not critical; it does not have to be at the top of the file. You can call this at any point where it is needed. You could, for example, add it to a specific ordered list by printing out $classes in conjunction with the li tag, like this: <li class="<?php print $classes; ?>"> $classes is, in short, a tremendously useful aid to creating dynamic theming. It becomes even more attractive if you master adding your own variables to the function, as discussed in the next section. Adding new variables to $classes To make things even more interesting (and useful), you can add new variables to $classes through use of the variable process functions. This is implemented in similar fashion to other preprocess function. Let's look at an example, in this case, taken from Drupal.org. The purpose here is to add a striping class keyed to the zebra variable and to make it available through $classes. To set this up, follow these steps: Access your theme's template.php file. If you don't have one, create it. Add the following to the file: <?php function mythemename_preprocess_node(&$vars) { // Add a striping class. $vars['classes_array'][] = 'node-' . $vars['zebra']; } ?> Save the file. The variable will now be available in any template in which you implement $classes. Creating dynamic selectors for nodes Another handy resource you can tap into for CSS styling purposes is Drupal's node ID system. By default, Drupal generates a unique ID for each node of the website. Node IDs are assigned at the time of node creation and remain stable for the life of the node. You can use the unique node identifier as a means of activating a unique selector. To make use of this resource, simply create a selector as follows: #node-[nid] { } For example, assume you wish to add a border to the node with the ID of 2. Simply create a new selector in your theme's stylesheet, as shown: #node-2 { border: 1px solid #336600 } As a result, the node with the ID of 2 will now be displayed with a 1-pixel wide solid border. The styling will only affect that specific node. Creating browser-specific stylesheets A common solution for managing some of the difficulties attendant to achieving true cross-browser compatibility is to offer stylesheets that target specific browsers. Internet Explorer tends to be the biggest culprit in this area, with IE6 being particularly cringe-worthy. Ironically, Internet Explorer also provides us with one of the best tools for addressing this issue. Internet Explorer implements a proprietary technology known as Conditional Comments. It is possible to easily add conditional stylesheets to your Drupal system through the use of this technology, but it requires the addition of a contributed module to your system, called Conditional Stylesheets. While it is possible to set up conditional stylesheets without the use of the module, it is more work, requiring you to add multiple lines of code to your template.php. With the module installed, you just add the stylesheet declarations to your .info file and then, using a simple syntax, set the conditions for their use. Note also that the Conditional Stylesheets module is in the queue for inclusion in Drupal 8, so it is certainly worth looking at now. To learn more, visit the project site at http://drupal.org/project/conditional_styles. If, in contrast, you would like to do things manually by creating a preprocess function to add the stylesheet and target it by browser key, please see http://drupal.org/node/744328. Summary This article covers the basics needed to make your Drupal theme responsive to the contents and the users. By applying the techniques discussed in this article, you can control the theming of pages based on content, state of the pages, or the users viewing them. Taking the principles one step further, you can also make the theming of elements within a page conditional. The ability to control the templates used and the styling of the page and its elements is what we call dynamic theming. Further resources on this subject: Drupal 7: Customizing an Existing Theme [Article] Drupal 7 Themes: Dynamic Theming [Article] 25 Useful Extensions for Drupal 7 Themers [Article] Drupal and Ubercart 2.x: Install a Ready-made Drupal Theme [Article] Building an Admin Interface in Drupal 7 Module Development [Article] Content in Drupal: Frequently Asked Questions (FAQ) [Article] Drupal Web Services: Twitter and Drupal [Article]
Read more
  • 0
  • 0
  • 2003

article-image-drupal-7-themes-dynamic-theming
Packt
05 Jul 2011
11 min read
Save for later

Drupal 7 Themes: Dynamic Theming

Packt
05 Jul 2011
11 min read
  Drupal 7 Themes Create new themes for your Drupal 7 site with a clean layout and powerful CSS styling Designating a separate Admin theme Let's start with one of the simplest techniques, that is, designating a separate theme for the use of your admin interface. The Drupal 7 system comes bundled with the Seven theme, which is purpose-built for use by the administration interface. Seven is assigned as your site's admin theme by default. You can, however, change to any theme you desire. Changing the admin theme is done directly from within the admin system's Theme Manager. To change the admin theme, follow these steps: Log in and access your site's admin system. Select the Appearance option from the Management menu. After the Theme Manager loads in your browser, scroll down to the bottom of the page. You can see at the bottom of that page a combo box labeled Administration theme, as shown in the following screenshot. Select the theme you desire from the combo box. Click Save configuration, and your selected theme should appear immediately. The Administration theme combo box will display all the enabled themes on your site. If you don't see what you want listed in the combo box, scroll back up, and make sure you have enabled the theme you desire. If the theme you desire is not listed in the Theme Manager, you will need to install it first! Additionally note the option listed below the Administration theme combo box: Use the administration theme when editing or creating content. Though this option is enabled by default, you may want to de-select this option. If you de-select the option, the system will use the frontend theme for content creation and editing. In some cases, this is more desirable as it allows you to see the page in context, instead of inside the admin theme. It provides, in other words, a more realistic view of the final content item. Using multiple page templates Apart from basic blog sites, most websites today employ different page layouts for different purposes. In some cases this is as simple as one layout for the home page and another for the internal pages. Other sites take this much further and deliver different layouts based on content, function, level of user access, or other criteria. There are various ways you can meet this need with Drupal. Some of the approaches are quite simple and can be executed directly from the administration interface; others require you to work with the files that make up your Drupal theme. Creative use of configuration and block assignments can address some needs. Most people, however, will need to investigate using multiple templates to achieve the variety they desire. The bad news is that there is no admin system shortcut for controlling multiple templates in Drupal—you must manually create the various templates and customize them to suit your needs. The good news is that creating and implementing additional templates is not terribly difficult and is it possible to attain a high degree of granularity with the techniques described next. Indeed should you be so inclined, you could literally define a distinct template for each individual page of your site! While there are many good reasons for running multiple page templates, you should not create additional templates solely for the purpose of disabling regions to hide blocks. While the approach will work, it will result in a performance hit for the site, as the system will still produce the blocks, only to then wind up not displaying them for the pages. The better practice is to control your block visibility through the Blocks Manager. Drupal employs an order of precedence, implemented using a naming convention. You can unlock the granularity of the system through proper application of the naming convention. It is possible, for example, to associate templates with every element on the path, or with specific users, or with a particular functionality or node type—all through the simple process of creating a copy of the existing template and then naming it appropriately. In Drupal terms, this is called creating template suggestions. When the system detects multiple templates, it prefers the specific to the general. If the system fails to find multiple templates, it will apply the relevant default template from the Drupal core. The fundamental methodology of the system is to use the most specific template file it finds and ignore other, more general templates. This basic principle, combined with proper naming of the templates, gives you control over the template that will be applied in various situations. The default suggestions provided by the Drupal system should be sufficient for the vast majority of theme developers. However, if you find that you need additional suggestions beyond those provided by the system, it is possible to extend your site and add new suggestions. See http://drupal.org/node/190815 for an example of this advanced Drupal theming technique. Let's take a series of four examples to show how this system feature can be employed to provide solutions to common problems: Use a unique template for your site's home page Use a different template for a group of pages Assign a specific template to a specific page Designate a specific template for a specific user Creating a unique home page template Let's assume that you wish to set up a unique look and feel for the home page of a site. The ability to employ different appearance for the home page and the interior pages is one of the most common requests web developers hear. There are several techniques you can employ to achieve the result; which is right for you depends on the extent and nature of the variation required, and to a lesser extent, upon the flexibility of the theme you presently employ. For many people a combination of the techniques will be used. Another factor to consider is the abilities of the people who will be managing and maintaining the site. There is often a conflict between what is easiest for the developers and what will be easiest for the site administrators. You need to keep this in mind and strive to create manageable structures. It is, for example, much easier for a client to manage a site that populates the home page dynamically, then to have to create content in multiple places and remember to assign things in the proper fashion. In this regard, using dedicated templates for the home page is generally preferable. One option to address this issue is the creative use of configuration and assignment. You can achieve a degree of variety within a theme—without creating dedicated templates—by controlling the visibility and positioning of the blocks on the home page. Another option you may want to consider is using a contributed module to assist with this task. The Panels and Views modules in particular are quite useful for assembling complex home page layouts. See Useful Extensions for Themers for more information on these extensions. If configuration and assignment alone do not give you enough flexibility, you will want to consider using a dedicated template that is purpose-built for your home page content. To create a dedicated template for your home page, follow these steps: Access the Drupal installation on your server. Copy your theme's existing page.tpl.php file (if your theme does not have a page.tpl.php file, then copy the default page.tpl.php file from the folder /modules/system). Paste it back in the same directory as the original file and rename it page--front.tpl.php. Make any changes you desire to the new page--front.tpl.php. Save the file. Clear the Drupal theme cache. That's it—it's really that easy. The system will now automatically display your new template file for the site's home page, and use the default page.tpl.php for the rest of the site. Note that page--front.tpl.php will be applied to whatever page you specify as the site's front page using the site configuration settings. To override the default home page setting visit the Site Information page from the Configuration Manager. To change the default home page, enter the path of the page you desire to use as the home page into the field labeled Default home page. Next, let's use the same technique to associate a template with a group of pages. The file naming syntax has changed slightly in Drupal 7. In the past, multiple words contained in a file name were consistently separated with a single hyphen. In Drupal 7, a single hyphen is only used for compound words; a double hyphen is used for targeting a template. For example, page--front.tpl.php uses the double hyphen as it indicates that we are targeting the page template when displayed for the front page. In contrast, maintenance-page.tpl.php shows the single hyphen syntax, as it is a compound name. Remember, suggestions only work when placed in the same directory as the base template. In other words, to get page--front.tpl.php to work, you must place it in the same directory as page.tpl.php. Using a different template for a group of pages You can provide a template to be used by any distinct group of pages. The approach is the same as we saw in the previous section, but the name for the template file derives from the path for the pages in the group. For example, to theme the pages that relate to users, you would create the template page--user.tpl.php. A note on templates and URLs Drupal bases the template order of precedence on the default path generated by the system. If the site is using a module like Pathauto, that alters the path that appears to site visitors, remember that your templates will still be displayed based on the original paths. The exception here being page--front.tpl.php, which will be applied to whatever page you specify as the site's front page using the site's Configuration Manager. The following table presents a list of suggestions you can employ to theme various pages associated with the default page groupings in the Drupal system: The steps involved in creating a template-specific theme to a group of pages is the same as that used for the creation of a dedicated home page template: Access the Drupal installation on your server. Copy your theme's existing page.tpl.php file (if your theme does not have a page.tpl.php file, then copy the default page.tpl.php file from the folder /modules/system). Paste it back in the same directory as the original file and rename it as shown in the table above, for example page--user.tpl.php. Make any changes you desire to the new template. Save the file. Clear the Drupal theme cache. Note that the names given in the table above will set the template for all the pages within the group. If you need a more granular solution—that is, to create a template for a sub-group or an individual page within the group, see the discussion in the following sections. Assigning a specific template to a specific page Taking this to its extreme, you can associate a specific template with a specific page. By way of example, assume we wish to provide a unique template for a specific content item. Let's assume the page you wish to style is located at http://www.demosite.com/node/2. The path of the page gives you the key to the naming of the template you need to style it. In this case, you would create a copy of the page.tpl.php file and rename it to page--node--2.tpl.php. Using template suggestion wildcards One of the most interesting changes in Drupal 7 is the introduction of template suggestion wildcards. In the past, you would have to specify the integer value for individual nodes, for example, page--user--1.tpl.php. If you wished to also style the pages for the entire group of users, you had the choice of either creating page--user.tpl.php, that affects all user pages, including the login forms, or you would be forced to create individual templates to cover each of the individual users. With Drupal 7 we can now simply use a wildcard in place of the integer values, for example, page--user--%.tpl.php. The new template page--user--%.tpl.php will now affect all the individual user pages without affecting the login pages. Designating a specific template for a specific user Assume that you want to add a personalized theme for the user with the ID of 1 (the first user in your Drupal system, and for many sites, the ID used by the super user). To do this, copy the existing page.tpl.php file, rename it to reflect its association with the specific user, and make any changes to the new file. To associate the new template file with the user, name the file: page—-user--1.tpl. Now, when the user with ID=1 logs into the site, they will be presented with this template. Only user 1 will see this template and only when he or she is logged in and visiting the user page.
Read more
  • 0
  • 0
  • 2110

article-image-wordpress-3-security-risks-and-threats
Packt
04 Jul 2011
11 min read
Save for later

WordPress 3 Security: Risks and Threats

Packt
04 Jul 2011
11 min read
  WordPress 3 Ultimate Security Protect your WordPress site and its network         Read more about this book       (For more resources on WordPress, see here.) You may think that most of this is irrelevant to WordPress security. Sadly, you'd be wrong. Your site is only as safe as the weakest link: of the devices that assist in administering it or its server; of your physical security; or of your computing and online discipline. To sharpen the point with a simple example, whether you have an Automattic-managed wordpress.com blog or unmanaged dedicated site hosting, if a hacker grabs a password on your local PC, then all bets are off. If a hacker can borrow your phone, then all bets are off. If a hacker can coerce you to a malicious site, then all bets are off. And so on. Let's get one thing clear. There is no such thing as total security and anyone who says any different is selling something. Then again, what we can achieve, given ongoing attention, is to boost our understanding, to lock our locations, to harden our devices, to consolidate our networks, to screen our sites and, certainly not least of all, to discipline our computing practice. Even this carries no guarantee. Tell you what though, it's pretty darned tight. Let's jump in and, who knows, maybe even have a laugh here and there to keep us awake. Calculated risk So what is the risk? Here's one way to look at the problem: RISK = VULNERABILITY x THREAT A vulnerability is a weakness, a crack in your armour. That could be a dodgy wireless setup or a poorly coded plugin, a password-bearing sticky note, or an unencrypted e-mail. It could just be the tired security guy. It could be 1001 things, and then more besides. The bottom line vulnerability though, respectfully, is our ignorance. A threat, on the other hand, is an exploit, some means of hacking the flaw, in turn compromising an asset such as a PC, a router, a phone, your site. That's the sniffer tool that intercepts your wireless, the code that manipulates the plugin, a colleague that reads the sticky, whoever reads your mail, or the social engineer who tiptoes around security. The risk is the likelihood of getting hacked. If you update the flawed plugin, for instance, then the threat is redundant, reducing the risk. Some risk remains because, when a further vulnerability is found there will be someone, somewhere, who will tailor an exploit to threaten it. This ongoing struggle to minimize risk is the cat and mouse that is security. To minimize risk, we defend vulnerabilities against threats. You may be wondering, why bother calculating risk? After all, any vulnerability requires attention. You'd not be wrong but, such is the myriad complexity of securing multiple assets, any of which can add risk to our site, and given that budgets or our time are at issue, we need to prioritize. Risk factoring helps by initially flagging glaring concerns and, ideally assisted by a security policy, ensuring sensible ongoing maintenance. Securing a site isn't a one-time deal. Such is the threatscape, it's an ongoing discipline.   An overview of our risk Let's take a WordPress site, highlight potential vulnerabilities, and chew over the threats. WordPress is an interactive blogging application written in PHP and working in conjunction with a SQL database to store data and content. The size and complexity of this content manager is extended with third party code such as plugins and themes. The framework and WordPress sites are installed on a web server and that, the platform, and its file system are administered remotely. WordPress. Powering multi-millions of standalone sites plus another 20 million blogs at wordpress.com, Automattic's platform is an attack target coveted by hackers. According to wordpress.org 40% of self-hosted sites run the gauntlet with versions 2.3 to 2.9. Interactive. Just being online, let alone offering interaction, sites are targets. A website, after all, is effectively an open drawer in an otherwise lockable filing cabinet, the server. Now, we're inviting people server-side not just to read but to manipulate files and data. Application, size, and complexity. Not only do applications require security patching but, given the sheer size and complexity of WordPress, there are more holes to plug. Then again, being a mature beast, a non-custom, hardened WordPress site is in itself robust. PHP, third party code, plugins, and themes. Here's a whole new dynamic. The use of poorly written or badly maintained PHP and other code adds a slew of attack vectors. SQL database. Containing our most valuable assets, content and data, MySQL, and other database apps are directly available to users making them immediate targets for hackers. Data. User data from e-mails to banking information is craved by cybercriminals and its compromise, else that of our content, costs sites anything from reputation to a drop or ban in search results as well as carrying the remedial cost of time and money. Content and media. Content is regularly copied without permission. Likewise with media, which can also be linked to and displayed on other sites while you pay for its storage and bandwidth. Upload, FTP, and private areas provide further opportunities for mischief. Sites. Sites-plural adds risk because a compromise to one can be a compromise to all. Web server. Server technologies and wider networks may be hacked directly or via WordPress, jeopardizing sites and data, and being used as springboards for wider attacks. File system. Inadequately secured files provide a means of site and server penetration. Administered remotely. Casual or unsecured content, site, server, and network administration allows for multi-faceted attacks and, conversely, requires discipline, a secure local working environment, and impenetrable local-to-remote connectivity.   Meet the hackers This isn't some cunning ploy by yours-truly to see for how many readers I can attain visitor's rights, you understand. The fact is to catch a thief one has to think like one. Besides, not all hackers are such bad hats. Far from it. Overall there are three types-white hat, grey hat, and black hat-each with their sub-groups. White hat One important precedent sets white hats above and beyond other groups: permission. Also known as ethical hackers, these decent upstanding folks are motivated: To learn about security To test for vulnerabilities To find and monitor malicious activity To report issues To advise others To do nothing illegal To abide by a set of ethics to not harm anyone So when we're testing our security to the limit, that should include us. Keep that in mind. Black hat Out-and-out dodgy dealers. They have nefarious intent and are loosely sub-categorized: Botnets A botnet is a network of automated robots, or scripts, often involved in malicious activity such as spamming or data-mining. The network tends to be comprised of zombie machines, such as your server, which are called upon at will to cause general mayhem. Botnet operators, the actual black hats, have no interest in damaging most sites. Instead they want quiet control of the underlying server resources so their malbots can, by way of more examples, spread malware or Denial of Service (DoS) attacks, the latter using multiple zombies to shower queries to a server to saturate resources and drown out a site. Cybercriminals These are hackers and gangs whose activity ranges from writing and automating malware to data-mining, the extraction of sensitive information to extort or sell for profit. They tend not to make nice enemies, so I'll just add that they're awfully clever. Hacktivists Politically-minded and often inclined towards freedom of information, hacktivists may fit into one of the previous groups, but would argue that they have a justifiable cause. Scrapers While not technically hackers, scrapers steal content-often on an automated basis from site feeds-for the benefit of their generally charmless blog or blog farms. Script kiddies This broad group ranges anything from well-intentioned novices (white hat) to online graffiti artists who, when successfully evading community service, deface sites for kicks. Armed with tutorials galore and a share full of malicious warez, the hell-bent are a great threat because, seeking bragging rights, they spew as much damage as they possibly can. Spammers Again not technically hackers but this vast group leeches off blogs and mailing lists to promote their businesses which frequently seem to revolve around exotic pharmaceutical products. They may automate bomb marketing or embed hidden links but, however educational their comments may be, spammers are generally, but not always, just a nuisance and a benign threat. Misfits Not jargon this time, this miscellaneous group includes disgruntled employees, the generally unloved, and that guy over the road who never really liked you. Grey hat Grey hatters may have good intentions, but seem to have a knack for misplacing their moral compass, so there's a qualification for going into politics. One might argue, for that matter, that government intelligence departments provide a prime example. Hackers and crackers Strictly speaking, hackers are white hat folks who just like pulling things apart to see how they work. Most likely, as kids, they preferred Meccano to Lego. Crackers are black or grey hat. They probably borrowed someone else's Meccano, then built something explosive. Over the years, the lines between hacker and cracker have become blurred to the point that put-out hackers often classify themselves as ethical hackers. This author would argue the point but, largely in the spirit of living language, won't, instead referring to all those trying to break in, for good or bad, as hackers. Let your conscience guide you as to which is which instance and, failing that, find a good priest.   Physically hacked off So far, we have tentatively flagged the importance of a safe working environment and of a secure network from fingertips to page query. We'll begin to tuck in now, first looking at the physical risks to consider along our merry way. Risk falls into the broad categories of physical and technical, and this tome is mostly concerned with the latter. Then again, with physical weaknesses being so commonly exploited by hackers, often as an information-gathering preface to a technical attack, it would be lacking not to mention this security aspect and, moreover, not to sweet-talk the highly successful area of social engineering. Physical risk boils down to the loss or unauthorized use of (materials containing) data: Break-in or, more likely still, a cheeky walk-in Dumpster diving or collecting valuable information, literally from the trash Inside jobs because a disgruntled (ex-)employee can be a dangerous sort Lost property when you leave the laptop on the train Social engineering which is a topic we'll cover separately, so that's ominous Something just breaks ... such as the hard-drive Password-strewn sticky notes aside, here are some more specific red flags to consider when trying to curtail physical risk: Building security whether it's attended or not. By the way, who's got the keys? A cleaner, a doorman, the guy you sacked? Discarded media or paper clues that haven't been criss-cross shredded. Your rubbish is your competitor's profit. Logged on PCs left unlocked, unsecured, and unattended or with hard drives unencrypted and lacking strong admin and user passwords for the BIOS and OS. Media, devices, PCs and their internal/external hardware. Everything should be pocketed or locked away, perhaps in a safe. No Ethernet jack point protection and no idea about the accessibility of the cable beyond the building. No power-surge protection could be a false economy too. This list is not exhaustive. For mid-sized to larger enterprises, it barely scratches the surface and you, at least, do need to employ physical security consultants to advise on anything from office location to layout as well as to train staff to create a security culture. Otherwise, if you work in a team, at least, you need a policy detailing each and every one of these elements, whether they impact your work directly or indirectly. You may consider designating and sub-designating who is responsible for what and policing, for example, kit that leaves the office. Don't forget cell and smart phones and even diaries.  
Read more
  • 0
  • 0
  • 2614
Visually different images

article-image-wordpress-3-security-overall-risk-site-and-server
Packt
04 Jul 2011
7 min read
Save for later

WordPress 3 Security: Overall Risk to Site and Server

Packt
04 Jul 2011
7 min read
  WordPress 3 Ultimate Security Protect your WordPress site and its network         Read more about this book       (For more resources on WordPress, see here.) How proactive we can be depends on our hosting plan. Then again, harping back to my point about security’s best friend—awareness—even Automattic bloggers could do with a heads-up. Just as site and server security each rely on the other, this section mixes the two to outline the big picture of woe and general despair. The overall concern isn’t hard to grasp. The server, like any computer, is a filing cabinet. It has many drawers—or ports—that each contain the files upon which a service (or daemon) depends. Fortunately, most drawers can be sealed, welded shut, but are they? Then again, some administrative drawers, for instance containing control panels, must be accessible to us, only to us, using a super-secure key and with the service files themselves providing no frailty to assist forcing an entry. Others, generally in our case the web files drawer, cannot even be locked because, of course, were it so then no one could access our sites. To compound the concern, there’s a risk that someone rummaging about in one drawer can internally access the others and, from there, any networked cabinets. Let's break down our site and server vulnerabilities, vying them against some common attack scenarios which, it should be noted, merely tip the iceberg of malicious possibility. Just keep smiling.   Physical server vulnerabilities Just how secure is the filing cabinet? We’ve covered physical security and expanded on the black art of social engineering. Clearly, we have to trust our web hosts to maintain the data center and to screen their personnel and contractors. Off-server backup is vital.   Open ports with vulnerable services We manage ports, and hence differing types of network traffic, primarily with a firewall. That allows or denies data packets depending on the port to which they navigate. FTP packets, for example, navigate to the server’s port 21. The web service queues up for 80. Secure web traffic—https rather than http—heads for 443. And so on. Regardless of whether or not, say, an FTP server is installed, if 21 is closed then traffic is denied. So here’s the problem. Say you allow an FTP service with a known weakness. Along comes a hacker, exploits the deficiency and gains a foothold into the machine, via its port. Similarly, every service listening on every port is a potential shoo-in for a hacker. Attacking services with a (Distributed) Denial of Service attack Many in the blogging community will be aware of the Digg of death, a nice problem to have where a post’s popularity, duly Digged, leads to a sudden rush of traffic that, if the web host doesn’t intervene and suspend the site, can overwhelm server resources and even crash the box. What’s happened here is an unintentional denial of service, this time via the web service on port 80. As with most attacks, DoS attacks come in many forms but the malicious purpose, often concentrated at big sites or networks and sometimes to gain a commercial or political advantage, is generally to flood services and, ultimately, to disable HTTP. As we introduced earlier, the distributed variety are most powerful, synchronizing the combined processing power of a zombie network, or botnet, against the target.   Access and authentication issues In most cases, we simply deny access by disabling the service and closing its port. Many of us, after all, only ever need web and administration ports. Only? Blimey! Server ports, such as for direct server access or using a more user-friendly middleman such as cPanel, could be used to gain unwanted entry if the corresponding service can be exploited or if a hacker can glean your credentials. Have some typical scenarios. Buffer overflow attacks This highly prevalent kind of memory attack is assisted by poorly written software and utilizes a scrap of code that’s often introduced through a web form field or via a port-listening service, such as that dodgy FTP daemon mentioned previously. Take a simplistic example. You’ve got a slug of RAM in the box and, on submitting data to a form, that queues up in a memory space, a buffer, where it awaits processing. Now, imagine someone submits malicious code that's longer, containing more bits, than the programmer allowed for. Again, the data queues in its buffer but, being too long, it overflows, overwriting the form’s expected command and having itself executed instead. So what about the worry of swiped access credentials? Again, possibilities abound. Intercepting data with man-in-the-middle attacks The MITM is where someone sits between your keystrokes and the server, scouring the data. That could be, for example, a rootkit, a data logger, a network, or a wireless sniffer. If your data transits unencrypted, in plain text, as is the case with FTP or HTTP and commonly with e-mail, then everything is exposed. That includes login credentials. Cracking authentication with password attacks Brute force attacks, on the other hand, run through alphanumeric and special character combinations against a login function, such as for a control panel or the Dashboard, until the password is cracked. They’re helped immensely when the username is known, so there’s a hint not to use that regular old WordPress chestnut, admin. Brute forcing can be time-consuming, but can also be coordinated between multiple zombies, warp-speeding the process with the combined processing power. Dictionary attacks, meanwhile, throw A-Z word lists against the password and hybrid attacks morph brute force and dictionary techniques to crack naïve keys such as pa55worD. The many dangers of cross-site scripting (XSS) XSS crosses bad code—adds it—with an unsecured site. Site users become a secondary target here because when they visit a hacked page, and their browser properly downloads everything as it resolves, they retrieve the bad code to become infected locally. An in-vogue example is the iframe injection which adds a link that leads to, say, a malicious download on another server. When a visitor duly views the page, downloading it locally, malware and all, the attacker has control over that user’s PC. Lovely. There's more. Oh so much more. Books more in fact. There's too much to mention here, but another classic tactic is to use XSS for cookie stealing. ... All that’s involved here is a code injection to some poor page that reports to a log file on the hacker’s server. Page visitors have their cookies chalked up to the log and have their session hijacked, together with their session privileges. If the user’s logged into webmail, so can the hacker. If it’s online banking, goodbye to your funds. If the user’s a logged-in WordPress administrator, you get the picture. Assorted threats with cross-site request forgery (CSRF) This is not the same as XSS, but there are similarities, the main one being that, again, a blameless if poorly built site is crossed with malicious code to cause an effect. A user logs into your site and, in the regular way, is granted a session cookie. The user surfs some pages, one of them having been decorated with some imaginative code from an attacker which the user’s browser correctly downloads. Because that script said to do something to your site and because the unfortunate user hadn’t logged out of your site, relinquishing the cookie, the action is authorized by the user’s browser. What may happen to your site, for example, depends on the user’s privileges so could vary from a password change or data theft to a nice new theme effect called digital soup.  
Read more
  • 0
  • 0
  • 1142

article-image-gnu-octave-data-analysis-examples
Packt
28 Jun 2011
7 min read
Save for later

GNU Octave: data analysis examples

Packt
28 Jun 2011
7 min read
Loading data files When performing a statistical analysis of a particular problem, you often have some data stored in a file. You can save your variables (or the entire workspace) using different file formats and then load them back in again. Octave can, of course, also load data from files generated by other programs. There are certain restrictions when you do this which we will discuss here. In the following matter, we will only consider ASCII files, that is, readable text files. When you load data from an ASCII file using the load command, the data is treated as a two-dimensional array. We can then think of the data as a matrix where lines represent the matrix rows and columns the matrix columns. For this matrix to be well defined, the data must be organized such that all the rows have the same number of columns (and therefore the columns the same number of rows). For example, the content of a file called series.dat can be: Next we to load this into Octave's workspace: octave:1> load -ascii series.dat; whereby the data is stored in the variable named series. In fact, Octave is capable of loading the data even if you do not specify the ASCII format. The number of rows and columns are then: octave:2> size(series) ans = 4 3 I prefer the file extension .dat, but again this is optional and can be anything you wish, say .txt, .ascii, .data, or nothing at all. In the data files you can have: Octave comments Data blocks separated by blank lines (or equivalent empty rows) Tabs or single and multi-space for number separation Thus, the following data file will successfully load into Octave: # First block 1 232 334 2 245 334 3 456 342 4 555 321 # Second block 1 231 334 2 244 334 3 450 341 4 557 327 The resulting variable is a matrix with 8 rows and 3 columns. If you know the number of blocks or the block sizes, you can then separate the blocked-data. Now, the following data stored in the file bad.dat will not load into Octave's workspace: 1 232.1 334 2 245.2 3 456.23 4 555.6 because line 1 has three columns whereas lines 2-4 have two columns. If you try to load this file, Octave will complain: octave:3> load -ascii bad.dat error: load: bad.dat: inconsisitent number of columns near line 2 error:load: unable to extract matrix size from file 'bad.dat' Simple descriptive statistics Consider an Octave function mcintgr and its vectorized version mcintgrv. This function can evaluate the integral for a mathematical function f in some interval [a; b] where the function is positive. The Octave function is based on the Monte Carlo method and the return value, that is, the integral, is therefore a stochastic variable. When we calculate a given integral, we should as a minimum present the result as a mean or another appropriate measure of a central value together with an associated statistical uncertainty. This is true for any other stochastic variable, whether it is the height of the pupils in class, length of a plant's leaves, and so on. In this section, we will use Octave for the most simple statistical description of stochastic variables. Histogram and moments Let us calculate the integral given in Equation (5.9) one thousand times using the vectorized version of the Monte Carlo integrator: octave:4> for i=1:1000 > s(i) = mcintgrv("sin", 0, pi, 1000); > endfor The array s now contains a sequence of numbers which we know are approximately 2. Before we make any quantitative statistical description, it is always a good idea to first plot a histogram of the data as this gives an approximation to the true underlying probability distribution of the variable s. The easiest way to do this is by using Octave's hist function which can be called using: octave:5> hist(s, 30, 1) The first argument, s, to hist is the stochastic variable, the second is the number of bins that s should be grouped into (here we have used 30), and the third argument gives the sum of the heights of the histogram (here we set it to 1). The histogram is shown in the figure below. If hist is called via the command hist(s), s is grouped into ten bins and the sum of the heights of the histogram is equal to sum(s). From the figure, we see that mcintgrv produces a sequence of random numbers that appear to be normal (or Gaussian) distributed with a mean of 2. This is what we expected. It then makes good sense to describe the variable via the sample mean defined as: where N is the number of samples (here 1000) and si the i'th data point, as well as the sample variance given by: The variance is a measure of the distribution width and therefore an estimate of the statistical uncertainty of the mean value. Sometimes, one uses the standard deviation instead of the variance. The standard deviation is simply the square root of the variance To calculate the sample mean, sample variance, and the standard deviation in Octave, you use: octave:6> mean(s) ans = 1.9999 octave:7> var(s) ans = 0.002028 octave:8> std(s) ans = 0.044976 In the statistical description of the data, we can also include the skewness which measures the symmetry of the underlying distribution around the mean. If it is positive, it is an indication that the distribution has a long tail stretching towards positive values with respect to the mean. If it is negative, it has a long negative tail. The skewness is often defined as: We can calculate this in Octave via: octave:9> skewness(s) ans = -0.15495 This result is a bit surprising because we would assume from the histogram that the data set represents numbers picked from a normal distribution which is symmetric around the mean and therefore has zero skewness. It illustrates an important point—be careful to use the skewness as a direct measure of the distributions symmetry—you need a very large data set to get a good estimate. You can also calculate the kurtosis which measures the flatness of the sample distribution compared to a normal distribution. Negative kurtosis indicates a relative flatter distribution around the mean and a positive kurtosis that the sample distribution has a sharp peak around the mean. The kurtosis is defined by the following: It can be calculated by the kurtosis function. octave:10> kurtosis(s) ans = -0.02310 The kurtosis has the same problem as the skewness—you need a very large sample size to obtain a good estimate. Sample moments As you may know, the sample mean, variance, skewness, and kurtosis are examples of sample moments. The mean is related to the first moment, the variance the second moment, and so forth. Now, the moments are not uniquely defined. One can, for example, define the k'th absolute sample moment pka and k'th central sample moment pkc as: Notice that the first absolute moment is simply the sample mean, but the first central sample moment is zero. In Octave, you can easily retrieve the sample moments using the moment function, for example, to calculate the second central sample moment you use: octave:11> moment(s, 2, 'c') ans = 0.002022 Here the first input argument is the sample data, the second defines the order of the moment, and the third argument specifies whether we want the central moment 'c' or absolute moment 'a' which is the default. Compare the output with the output from Command 7—why is it not the same?
Read more
  • 0
  • 0
  • 8890

article-image-html5-audio-and-video-elements
Packt
28 Jun 2011
9 min read
Save for later

HTML5: Audio and Video Elements

Packt
28 Jun 2011
9 min read
Understanding audio and video file formats There are plenty of different audio and video file formats. These files may include not just video but also audio and metadata—all in one file. These file types include: .avi – A blast from the past, the Audio Video Interleave file format was invented by Microsoft. Does not support most modern audio and video codecs in use today. .flv – Flash video. This used to be the only video file format Flash fully supported. Now it also includes support for .mp4. .mp4 or .mpv – MPEG4 is based on Apple's QuickTime player and requires that software for playback. How it works... Each of the previously mentioned video file formats require a browser plugin or some sort of standalone software for playback. Next, we'll look at new open-source audio and video file formats that don't require plugins or special software and the browsers that support them. H.264 has become of the most commonly used high definition video formats. Used on Blu-ray Discs as well as many Internet video streaming sites including Flash, iTunes Music Store, Silverlight, Vimeo, YouTube, cable television broadcasts, and real-time videoconferencing. In addition, there is a patent on H.264 is therefore, by definition, not open source. Browsers that support H.264 video file format include: Google has now partially rejected the H.264 format and is leaning more toward its support of the new WebM video file format instead. Ogg might be a funny sounding name, but its potential is very serious, I assure you. Ogg is really two things: Ogg Theora, which is a video file format; and Ogg Vorbis, which is an audio file format. Theora is really much more of a video file compression format than it is a playback file format, though it can be used that way also. It has no patents and is therefore considered open source. Fun fact: According to Wikipedia, "Theora is named after Theora Jones, Edison Carter's controller on the Max Headroom television program." Browsers that support the Ogg video file format include: WebM is the newest entrant in the online video file format race. This open source audio/video file format development is sponsored by Google. A WebM file contains both an Ogg Vorbis audio stream as well as a VP8 video stream. It is fairly well supported by media players including Miro, Moovidia, VLC, Winamp, and more, including preliminary support by YouTube. The makers of Flash say it will support WebM in the future, as will Internet Explorer 9. Browsers that currently support WebM include: There's more... So far this may seem like a laundry list of audio and video file formats with spotty browser support at best. If you're starting to feel that way, you'd be right. The truth is no one audio or video file format has emerged as the one true format to rule them all. Instead, we developers will often have to serve up the new audio and video files in multiple formats while letting the browser decide whichever one it's most comfortable and able to play. That's a drag for now but here's hoping in the future we settle on fewer formats with more consistent results. Audio file formats There are a number of audio file formats as well. Let's take a look at those. AAC – Advanced Audio Coding files are better known as AACs. This audio file format was created by design to sound better than MP3s using the same bitrate. Apple uses this audio file format for its iTunes Music Store. Since the AAC audio file format supports DRM, Apple offers files in both protected and unprotected formats. There is an AAC patent, so by definition we can't exactly call this audio file format open source. All Apple hardware products, including their mobile iPhone and iPad devices as well as Flash, support the AAC audio file format. Browsers that support AAC include: MP3 – MPEG-1 Audio Layer 3 files are better known as MP3s. Unless you've been hiding under a rock, you know MP3s are the most ubiquitous audio file format in use today. Capable of playing two channels of sound, these files can be encoded using a variety of bitrates up to 320. Generally, the higher the bitrate, the better the audio file sounds. That also means larger file sizes and therefore slower downloads. There is an MP3 patent, so by definition we can't exactly call this audio file format open source either. Browsers that support MP3 include: Ogg – We previously discussed the Ogg Theora video file format. Now, let's take a look at the Ogg Vorbis audio format. As mentioned before, there is no patent on Ogg files and are therefore considered open source. Another fun fact: According to Wikipedia, "Vorbis is named after a Discworld character, Exquisitor Vorbis in Small Gods by Terry Pratchett." File format agnosticism We've spent a lot of time examining these various video and audio file formats. Each has its own plusses and minuses and are supported (or not) by various browsers. Some work better than others, some sound and look better than others. But here's the good news: The new HTML5 <video> and <audio> elements themselves are file-format agnostic! Those new elements don't care what kind of video or audio file you're referencing. Instead, they serve up whatever you specify and let each browser do whatever it's most comfortable doing. Can we stop the madness one day? The bottom line is that until one new HTML5 audio and one new HTML5 video file format emerges as the clear choice for all browsers and devices, audio and video files are going to have to be encoded more than once for playback. Creating accessible audio and video In this section we will pay attention to those people who rely on assistive technologies. How to do it... First, we'll start with Kroc Camen's "Video for Everybody" code chunk and examine how to make it accessibility friendly to ultimately look like this: <div id="videowrapper"> <video controls height="360" width="640"> <source src="__VIDEO__.MP4" type="video/mp4" /> <source src="__VIDEO__.OGV" type="video/ogg" /> <object width="640" height="360" type="application/ x-shockwave-flash" data="__FLASH__.SWF"> <param name="movie" value="__FLASH__.SWF" /> <param name="flashvars" value="controlbar=over&amp; image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" /> <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__" title="No video playback capabilities, please download the video below" /> </object> <track kind="captions" src="videocaptions.srt" srclang="en" /> <p>Final fallback content</p> </video> <div id="captions"></div> <p><strong>Download Video:</strong> Closed Format: <a href="__VIDEO__.MP4">"MP4"</a> Open Format: <a href="__VIDEO__.OGV">"Ogg"</a> </p> </div> How it works... The first thing you'll notice is we've wrapped the new HTML5 video element in a wrapper div. While this is not strictly necessary semantically, it will give a nice "hook" to tie our CSS into. <div id="videowrapper"> Much of the next chunk should be recognizable from the previous section. Nothing has changed here: <video controls height="360" width="640"> <source src="__VIDEO__.MP4" type="video/mp4" /> <source src="__VIDEO__.OGV" type="video/ogg" /> <object width="640" height="360" type="application/ x-shockwave-flash" data="__FLASH__.SWF"> <param name="movie" value="__FLASH__.SWF" /> <param name="flashvars" value="controlbar=over&amp; image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" /> <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__" title="No video playback capabilities, please download the video below" /> </object> So far, we're still using the approach of serving the new HTML5 video element to those browsers capable of handling it and using Flash as our first fallback option. But what happens next if Flash isn't an option gets interesting: <track kind="captions" src="videocaptions.srt" srclang="en" /> What the heck is that, you might be wondering. "The track element allows authors to specify explicit external timed text tracks for media elements. It does not represent anything on its own." - W3C HTML5 specification Here's our chance to use another new part of the HTML5 spec: the new <track> element. Now, we can reference the type of external file specified in the kind="captions". As you can guess, kind="captions" is for a caption file, whereas kind="descriptions" is for an audio description. Of course the src calls the specific file and srclang sets the source language for the new HTML5 track element. In this case, en represents English. Unfortunately, no browsers currently support the new track element. Lastly, we allow one last bit of fallback content in case the user can't use the new HTML5 video element or Flash when we give them something purely text based. <p>Final fallback content</p> Now, even if the user can't see an image, they'll at least have some descriptive content served to them. Next, we'll create a container div to house our text-based captions. So no browser currently supports closed captioning for the new HTML5 audio or video element, we'll have to leave room to include our own: <div id="captions"></div> Lastly, we'll include Kroc's text prompts to download the HTML5 video in closed or open file formats: <p><strong>Download Video:</strong> Closed Format: <a href="__VIDEO__.MP4">"MP4"</a> Open Format: <a href="__VIDEO__.OGV">"Ogg"</a> </p>
Read more
  • 0
  • 0
  • 1494
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $15.99/month. Cancel anytime
article-image-interacting-gnu-octave-operators
Packt
20 Jun 2011
6 min read
Save for later

Interacting with GNU Octave: Operators

Packt
20 Jun 2011
6 min read
GNU Octave Beginner's Guide Become a proficient Octave user by learning this high-level scientific numerical tool from the ground up The reader will benefit from the previous article on GNU Octave Variables. Basic arithmetic Octave offers easy ways to perform different arithmetic operations. This ranges from simple addition and multiplication to very complicated linear algebra. In this section, we will go through the most basic arithmetic operations, such as addition, subtraction, multiplication, and left and right division. In general, we should think of these operations in the framework of linear algebra and not in terms of arithmetic of simple scalars. Addition and subtraction We begin with addition. Time for action – doing addition and subtraction operations I have lost track of the variables! Let us start afresh and clear all variables first: octave:66> clear (Check with whos to see if we cleared everything). Now, we define four variables in a single command line(!) octave:67> a = 2; b=[1 2 3]; c=[1; 2; 3]; A=[1 2 3; 4 5 6]; Note that there is an important difference between the variables b and c; namely, b is a row vector, whereas c is a column vector. Let us jump into it and try to add the different variables. This is done using the + character: octave:68>a+a ans = 4 octave:69>a+b ans = 3 4 5 octave:70>b+b ans = 2 4 6 octave:71>b+c error: operator +: nonconformant arguments (op1 is 1x3, op2 is 3x1) It is often convenient to enter multiple commands on the same line. Try to test the difference in separating the commands with commas and semicolons. What just happened? The output from Command 68 should be clear; we add the scalar a with itself. In Command 69, we see that the + operator simply adds the scalar a to each element in the b row vector. This is named element-wise addition. It also works if we add a scalar to a matrix or a higher dimensional array. Now, if + is applied between two vectors, it will add the elements together element-wise if and only if the two vectors have the same size, that is, they have same number of rows or columns. This is also what we would expect from basic linear algebra. From Command 70 and 71, we see that b+b is valid, but b+c is not, because b is a row vector and c is a column vector—they do not have the same size. In the last case, Octave produces an error message stating the problem. This would also be a problem if we tried to add, say b with A: octave:72>b+A error: operator +: nonconformant arguments (op1 is 1x3, op2 is 2x3) From the above examples, we see that adding a scalar to a vector or a matrix is a special case. It is allowed even though the dimensions do not match! When adding and subtracting vectors and matrices, the sizes must be the same. Not surprisingly, subtraction is done using the - operator. The same rules apply here, for example: octave:73> b-b ans = 0 0 0 is fine, but: octave:74> b-c error: operator -: nonconformant arguments (op1 is 1x3, op2 is 2x3) produces an error. Matrix multiplication The * operator is used for matrix multiplication. Recall from linear algebra that we cannot multiply any two matrices. Furthermore, matrix multiplication is not commutative. For example, consider the two matrices: The matrix product AB is defined, but BA is not. If A is size n x k and B has size k x m, the matrix product AB will be a matrix with size n x m. From this, we know that the number of columns of the "left" matrix must match the number of rows of the "right" matrix. We may think of this as (n x k)(k x m) = n x m. In the example above, the matrix product AB therefore results in a 2 x 3 matrix: Time for action – doing multiplication operations Let us try to perform some of the same operations for multiplication as we did for addition: octave:75> a*a ans = 4 octave:76> a*b ans = 2 4 6 octave:77> b*b error: operator *: nonconformant arguments (op1 is 1x3, op2 is 1x3) octave:78> b*c ans = 14 What just happened? From Command 75, we see that * multiplies two scalar variables just like standard multiplication. In agreement with linear algebra, we can also multiply a scalar by each element in a vector as shown by the output from Command 76. Command 77 produces an error—recall that b is a row vector which Octave also interprets as a 1 x 3 matrix, so we try to perform the matrix multiplication (1 x 3)(1 x 3), which is not valid. In Command 78, on the other hand, we have (1 x 3)(3 x 1) since c is a column vector yielding a matrix with size 1 x 1, that is, a scalar. This is, of course, just the dot product between b and c. Let us try an additional example and perform the matrix multiplication between A and B discussed above. First, we need to instantiate the two matrices, and then we multiply them: octave:79> A=[1 2; 3 4]; B=[1 2 3; 4 5 6]; octave:80> A*B ans = 9 12 15 19 26 33 octave:81> B*A error: operator *: nonconformant arguments (op1 is 2x3, op2 is 2x2) Seems like Octave knows linear algebra! Element-by-element, power, and transpose operations If the sizes of two arrays are the same, Octave provides a convenient way to multiply the elements element-wise. For example, for B: octave:82> B.*B ans = 1 4 9 16 25 36 Notice that the period (full stop) character precedes the multiplication operator. The period character can also be used in connection with other operators. For example: octave:83> B.+B ans = 2 4 6 8 10 12 which is the same as the command B+B. If we wish to raise each element in B to the power 2.1, we use the element-wise power operator.ˆ: octave:84> B.^2.1 ans = 1.0000 4.2871 10.0451 18.3792 29.3655 43.0643 You can perform element-wise power operation on two matrices as well (if they are of the same size, of course): octave:85> B.^B ans = 1 4 27 256 3125 46656 If the power is a real number, you can use ˆ instead of .ˆ; that is, instead of Command 84 above, you can use: octave:84>Bˆ2.1 Transposing a vector or matrix is done via the 'operator. To transpose B, we simply type: octave:86> B' ans = 1 4 2 5 3 6 Strictly, the ' operator is a complex conjugate transpose operator. We can see this in the following examples: octave:87> B = [1 2; 3 4] + I.*eye(2) B = 1 + 1i 2 + 0i 3 + 0i 4 + 1i octave:88> B' ans = 1 - 1i 3 - 0i 2 - 0i 4 - 1i Note that in Command 87, we have used the .* operator to multiply the imaginary unit with all the elements in the diagonal matrix produced by eye(2). Finally, note that the command transpose(B)or the operator .' will transpose the matrix, but not complex conjugate the elements.
Read more
  • 0
  • 0
  • 8422

article-image-interacting-gnu-octave-variables
Packt
17 Jun 2011
8 min read
Save for later

Interacting with GNU Octave: Variables

Packt
17 Jun 2011
8 min read
GNU Octave Beginner's Guide Become a proficient Octave user by learning this high-level scientific numerical tool from the ground up          In the following, we shall see how to instantiate simple variables. By simple variables, we mean scalars, vectors, and matrices. First, a scalar variable with name a is assigned the value 1 by the command: octave:1> a=1 a = 1 That is, you write the variable name, in this case a, and then you assign a value to the variable using the equal sign. Note that in Octave, variables are not instantiated with a type specifier as it is known from C and other lower-level languages. Octave interprets a number as a real number unless you explicitly tell it otherwise. In Octave, a real number is a double-precision, floating-point number,which means that the number is accurate within the first 15 digits. Single precision is accurate within the first 6 digits. You can display the value of a variable simply by typing the variable name: octave:2>a a = 1 Let us move on and instantiate an array of numbers: octave:3 > b = [1 2 3] b = 1 2 3 Octave interprets this as the row vector: rather than a simple one-dimensional array. The elements (or the entries) in a row vector can also be separated by commas, so the command above could have been: octave:3> b = [1, 2, 3] b = 1 2 3 To instantiate a column vector: you can use: octave:4 > c = [1;2;3] c = 1 2 3 Notice how each row is separated by a semicolon. We now move on and instantiate a matrix with two rows and three columns (a 2 x 3 matrix): using the following command: octave:5 > A = [1 2 3; 4 5 6] A = 1 2 3 4 5 6 Notice that I use uppercase letters for matrix variables and lowercase letters for scalars and vectors, but this is, of course, a matter of preference, and Octave has no guidelines in this respect. It is important to note, however, that in Octave there is a difference between upper and lowercase letters. If we had used a lowercase a in Command 5 above, Octave would have overwritten the already existing variable instantiated in Command 1. Whenever you assign a new value to an existing variable, the old value is no longer accessible, so be very careful whenever reassigning new values to variables. Variable names can be composed of characters, underscores, and numbers. A variable name cannot begin with a number. For example, a_1 is accepted as a valid variable name, but 1_a is not. In this article, we shall use the more general term array when referring to a vector or a matrix variable. Accessing and changing array elements To access the second element in the row vector b, we use parenthesis: octave:6 > b(2) ans = 2 That is, the array indices start from 1. This is an abbreviation for "answer" and is a variable in itself with a value, which is 2 in the above example. For the matrix variable A, we use, for example: octave:7> A(2,3) ans = 6 to access the element in the second row and the third column. You can access entire rows and columns by using a colon: octave:8> A(:,2) ans = 2 5 octave:9 > A(1,:) ans = 1 2 3 Now that we know how to access the elements in vectors and matrices, we can change the values of these elements as well. To try to set the element A(2,3)to -10.1: octave:10 > A(2,3) = -10.1 A = 1.0000 2.0000 3.0000 4.0000 5.0000 -10.1000 Since one of the elements in A is now a non-integer number, all elements are shown in floating point format. The number of displayed digits can change depending on the default value, but for Octave's interpreter there is no difference—it always uses double precision for all calculations unless you explicitly tell it not to. You can change the displayed format using format short or format long. The default is format short. It is also possible to change the values of all the elements in an entire row by using the colon operator. For example, to substitute the second row in the matrix A with the vector b (from Command 3 above), we use: octave:11 > A(2,:) = b A = 1 2 3 1 2 3 This substitution is valid because the vector b has the same number of elements as the rows in A. Let us try to mess things up on purpose and replace the second column in A with b: octave:12 > A(:,2) = b error: A(I,J,...) = X: dimension mismatch Here Octave prints an error message telling us that the dimensions do not match because we wanted to substitute three numbers into an array with just two elements. Furthermore, b is a row vector, and we cannot replace a column with a row. Always read the error messages that Octave prints out. Usually they are very helpful. There is an exception to the dimension mismatch shown above. You can always replace elements, entire rows, and columns with a scalar like this: octave:13> A(:,2) = 42 A = 1 42 3 1 42 3 More examples It is possible to delete elements, entire rows, and columns, extend existing arrays, and much more. Time for action – manipulating arrays To delete the second column in A, we use: octave:14> A(:,2) = [] A = 1 3 1 3 We can extend an existing array, for example: octave:15 > b = [b 4 5] b = 1 2 3 4 5 Finally, try the following commands: octave:16> d = [2 4 6 8 10 12 14 16 18 20] d = 2 4 6 8 10 12 14 16 18 20 octave:17> d(1:2:9) ans = 2 6 10 14 18 octave:18> d(3:3:12) = -1 d = 2 4 -1 8 10 -1 14 16 -1 20 0 -1 What just happened? In Command 14, Octave interprets [] as an empty column vector and column 2 in A is then deleted in the command. Instead of deleting a column, we could have deleted a row, for example as an empty column vector and column 2 in A is then deleted in the command. octave:14> A(2,:)=[] On the right-hand side of the equal sign in Command 15, we have constructed a new vector given by [b 4 5], that is, if we write out b, we get [1 2 3 4 5] since b=[1 2 3]. Because of the equal sign, we assign the variable b to this vector and delete the existing value of b. Of course, we cannot extend b using b=[b; 4; 5] since this attempts to augment a column vector onto a row vector. Octave first evaluates the right-hand side of the equal sign and then assigns that result to the variable on the left-hand side. The right-hand side is named an expression. In Command 16, we instantiated a row vector d, and in Command 17, we accessed the elements with indices 1,3,5,7, and 9, that is, every second element starting from 1. Command 18 could have made you a bit concerned! d is a row vector with 10 elements, but the command instructs Octave to enter the value -1 into elements 3, 6, 9 and 12, that is, into an element that does not exist. In such cases, Octave automatically extends the vector (or array in general) and sets the value of the added elements to zero unless you instruct it to set a specific value. In Command 18, we only instructed Octave to set element 12 to -1, and the value of element 11 will therefore be given the default value 0 as seen from the output. In low-level programming languages, accessing non-existing or non-allocated array elements may result in a program crash the first time it is running2. This will be the best case scenario. In a worse scenario, the program will work for years, but then crash all of a sudden, which is rather unfortunate if it controls a nuclear power plant or a space shuttle. As you can see, Octave is designed to work in a vectorized manner. It is therefore often referred to as a vectorized programming language. Complex variables Octave also supports calculations with complex numbers. As you may recall, a complex number can be written as z = a + bi, where a is the real part, b is the imaginary part, and i is the imaginary unit defined from i2 = –49491. To instantiate a complex variable, say z = 1 + 2i, you can type: octave:19> z = 1 + 2I z = 1 + 2i When Octave starts, the variables i, j, I, and J are all imaginary units, so you can use either one of them. I prefer using I for the imaginary unit, since i and j are often used as indices and J is not usually used to symbolize i. To retrieve the real and imaginary parts of a complex number, you use: octave:20> real(z) ans = 1 octave:21>imag(z) ans = 2 You can also instantiate complex vectors and matrices, for example: octave:22> Z = [1 -2.3I; 4I 5+6.7I] Z = 1.0000 + 0.0000i 0.0000 - 2.3000i 0.0000 + 4.0000i 5.0000 + 6.7000i Be careful! If an array element has non-zero real and imaginary parts, do not leave any blanks (space characters) between the two parts. For example, had we used Z=[1 -2.3I; 4I 5 + 6.7I] in Command 22, the last element would be interpreted as two separate elements (5 and 6.7i). This would lead to dimension mismatch. The elements in complex arrays can be accessed in the same way as we have done for arrays composed of real numbers. You can use real(Z) and imag(Z) to print the real and imaginary parts of the complex array Z. (Try it out!)
Read more
  • 0
  • 0
  • 2757

article-image-overview-joomla-virtuemart
Packt
15 Jun 2011
12 min read
Save for later

An overview of Joomla! and VirtueMart

Packt
15 Jun 2011
12 min read
Navigating through the Joomla! and VirtueMart directories You should have a Joomla! and VirtueMart e-commerce site installed somewhere. If not, you should now install one first before reading on. From this point onward, we will assume that you can access a Joomla! VirtueMart site and can freely browse its content, either on your local computer using the file manager of your operating system or in a web server somewhere using an FTP client program. To work on the exercises, you should also be able to edit each of the files. OK. Let's start our study by navigating through the Joomla! directories. If you look at the root of your Joomla! site, you will be amazed how large the Joomla! project is. There are totally close to 5,000 files under some 350 directories! It would be difficult to find your way through this vast structure of files if there are no hints at all. Fortunately, Joomla! has a very good directory structure and will be easy to follow once you know its basic organization. Knowing your way through this vast structure is very important when embarking on any VirtueMart customization project of considerable size. The good news is that usually we only need to know a very small fraction of those 350 directories and 5,000 files. In the Joomla! root, the most important directories we need to know are the administrator, components, modules, and plugins directories (This does not mean that the other directories are not important. We highlight these few directories just because they are the directories we will reference from time-to-time) You will probably recognize that the last three of these shortlisted directories correspond to the three major extension types of Joomla! So within these directories, we will expect to see a series of subdirectories, each of which corresponds to an extension installed in the Joomla! framework. This is exactly the case, except for the plugins where the directories are arranged in terms of their type instead of their source. Let's take a closer look at one of the most important components that comes with Joomla!. Navigate to the components directory and open the subdirectory com_content. The com_content component is the one that manages articles we created in Joomla!. You have probably been using a lot of this component. Within this directory, you will find a number of files and a few subdirectories. We notice there is a file named controller.php and two subdirectories named models and views. We will have more to say on these in a moment. Let's move back to the root directory and take a look at the last important directory mentioned above. This administrator directory mimics the root directory in many respects. We see that most of the subdirectories we found in the root have a corresponding subdirectory within the administrator directory. For example, we find subdirectories named components and modules within the administrator as well. As we know, there are two main sections of a Joomla! website, also known as the frontend and the backend. The root directory and administrator directory are respectively the location where the frontend and backend files are located. While this dividing line is not rigid, we can use this as a guide when we want to locate a frontend or backend file. Since both the root and the administrator directories contain a subdirectory called components, to avoid ambiguity, we will refer to them as the root components and administrator components directory, respectively. Now, let's work our way a little bit down the directory tree to see how VirtueMart fits into this framework. Within the root components directory, you will see a subdirectory called com_virtuemart. Yes, this is the location where you can find all the files used by VirtueMart for the frontend. Under the com_virtuemart directory, among some other files and subdirectories, you will notice a themes subdirectory. You will find each of the VirtueMart themes you have installed there. The themes directory is the major work area. From now on, we will refer to the com_virtuemart directory under the root components directory as the root VirtueMart directory or the frontend VirtueMart directory. Within the administrator components directory, there is also a subdirectory called com_virtuemart where the backend VirtueMart files are located. Under this main directory, there are four subdirectories named as classes, html, languages, and sql. Obviously, these directories will contain, respectively, the class files, HTML files, language files, and SQL (also known as database) files. Actually, the classes and html directories have a deeper meaning than their names suggest, as we shall see in a moment. Structure of the Joomla! URL path Before leaving our high-level exploration of the Joomla! tree structure, let's digress a little bit to study how a Joomla! URL is built up. While the Joomla! directory structure is so complicated, the URL used to access the site is much simpler. Most of the time, the URL just starts with index.php?. (If you have a Search Engine Friendly or SEF system enabled, you should turn it off during the development and testing of your customization, or at least turn it off mentally while we are talking about the URL. You can turn off SEF in the Joomla! Configuration page.) For example, if we want to access the VirtueMart (frontend) home page, we can use the following URL: http://your_joomla_live_site/index.php?option=com_virtuemart Similarly, the URL http://your_joomla_live_site/administrator/index.php?option=com_virtuemart will bring up the VirtueMart backend control panel, if you're already logged in. All other Joomla! URL, in fact, work in the same way, although many times you see some additional parameters as well. (Don't forget to replace your_joomla_live_site in the above URL with your domain name and the Joomla! root directory, in case the site is not installed in the root.) Actually, the index.php script is the main entry into your Joomla! site. All major requests to the frontend start from here (major requests only since there are some other entry points as well, but they don't bother us at this point). Similarly, all major requests to the backend start from the file administrator/index.php. Restricting the entry point to the site makes it very easy to control authorized and unauthorized accesses. For example, if we want to put the site offline, we can simply change a configuration in Joomla! and all components will be offline as well. We don't need to change each page or even each component one-by-one. Understanding the structure of the Joomla! URL is pretty useful during the development and debugging process. Sometimes we may need to work on a partly live site in which the Joomla! site is already working, but the VirtueMart shop is still under construction. In such cases, it is common to unpublish the menu items for the shop so that the shop is still hidden from the public. The fact that the menu item is hidden actually means the shop is less accessible but not inaccessible. If we want to test the VirtueMart shop, we can still type the URL on the browser by ourselves. Using the URL http://your_joomla_live_site/index.php?option=com_virtuemart we can bring up the VirtueMart home page. We will learn some more tricks in testing individual shop pages along the way of our study of VirtueMart themes and templates. One simple application of what we learnt about the URL can be used when customizing Joomla!. When working with VirtueMart projects, we will need to go to the VirtueMart backend from time-to-time to modify the VirtueMart settings. As we all know, after logging in, what we have on the browser window is the control panel page. We will need to point to the components/virtuemart menu before we can open the VirtueMart backend home. This is not a complicated task, but will be very tedious if repeated every time we log back into the site. Can we make Joomla! smarter, to open the VirtueMart home by default when we log on? Yes, we can. The trick actually relates to what we talked about so far. If you want to customize Joomla! to open the VirtueMart backend by default, you can stay with me for the following warm-up exercise. I understand some of you may not want to change the default login page. Exercise 1.1: Making the Joomla! backend default to VirtueMart Open your favorite text editor. Navigate to the Joomla! site root. Open the file administrator/includes/helper.php. At around line 44 (the actual line may vary from version-to-version), change the code $option = 'com_cpanel'; to $option = 'com_virtuemart'; Save the file. Open your browser and log in to your Joomla! site. Alas, you should see the VirtueMart control panel instead of the Joomla! control panel. This simple exercise demonstrated that sometimes a useful change does not need complex coding. What we need is a little knowledge of how things work. I bet you probably understand what we have done above without explanation. After login, Joomla! will automatically go to the default component, hardcoded in the file helper.php. For standard Joomla!, this will be the com_cpanel component. In Exercise 1.1, we have changed this default backend component from com_cpanel to com_virtuemart. Instead of VirtueMart, we can certainly change the default to other components such as community builder or MOSET. Joomla! 1.5 presentation framework Since VirtueMart is a Joomla! component, it cannot exist outside Joomla!. So before diving into the detail of the VirtueMart engine, it pays to take a brief look at how Joomla! actually works. While an understanding of the presentation framework of Joomla! and VirtueMart may be useful for themes and templates development, it is not essential for the actual customization design. Joomla! emerged from version 1.0 and later developed into 1.5. In this upgrade, Joomla! has been basically rewritten from the ground up. A presentation structure called Model-View-Controller or MVC has been adopted in Joomla! 1.5. While a detailed explanation of the MVC structure is out of the scope, a basic understanding of its working will help us understand why and how VirtueMart 1.1 behaves in the way it is right now. Joomla! is a web application. Each page of Joomla! is in fact a text file consisting of HTML code. Depending on the detail parameters of a web request, Joomla! will generate a dynamic HTML page by combining data stored in the database and site configuration data stored in various PHP files. In the early history of dynamic web pages, program code were written in a way that HTML tags are mixed with presentation logic in one place. The spaghetti code, as it is sometimes called, makes maintenance and extension of the coding very difficult. As the basic structure of a dynamic web page is better understood, more and more new coding patterns emerge to make the life of a web developer easier. The MVC presentation framework is one of those patterns that have been proposed to build computer applications. This framework has gradually become the standard pattern for building web applications and has been adopted by many open source web projects. Models In the MVC presentation framework , the job of building a web page is divided into three main tiers. The backend tier is the data that is stored in the database (strictly speaking, there is no prescribed data storage format though a database is a natural way to manage the data). We need to grab data needed to build the web page. This tier of the job is done by the Model, which describes how data is stored and how data can be retrieved from the data server. Views The frontend tier determines what and how data is presented on the browser. This is the job of the View. For a given dataset from a Model, there can be many different ways to present the data. Let's say, we have a set of statistical data, for example. We can present this data as a bar graph or a pie chart. Each of these presentations is called a View of the same Model. Controllers Now statistical data is just a set of numbers. How can we convert them into a bar graph or a pie chart? That is exactly how the Controller comes into place. A Controller is a routine specifying how to convert the Model into various Views. One major advantage of this separation of data (Model) and presentation (View) makes changes to the application much easier. We can change the presentation independent of the underlying data and vice versa. So, in the Joomla! 1.5 world, we will have a set of Models which interface with the database, a set of Views to tell the browser how to present the data, and a set of Controllers that control how to convert the Model into the View. According to the best practice, all Joomla! 1.5 components should follow this same structure. Thus, each Joomla! 1.5 component should have two subdirectories called models and views. Also, the root directory will contain a controller.php which extends the Joomla! controller's capability. This structure is revealed as we look at the contents of a Joomla! component which we had done previously. However, because of historical reasons and others, not all components follow this best practice. VirtueMart is one of those exceptions.
Read more
  • 0
  • 0
  • 1735

article-image-wordpress-3-security-apache-modules
Packt
10 Jun 2011
6 min read
Save for later

WordPress 3 Security: Apache Modules

Packt
10 Jun 2011
6 min read
  WordPress 3 Ultimate Security Protect your WordPress site and its network         Read more about this book       (For more resources on WordPress, see here.) IP deny with mod_access Apache offers a sure-fire way to lock down admin, care of the mod_access module. Similar to cPanel's IP Deny Manager, the greater flexibility of hand-coding empowers us to allow or deny all but specified IP addresses, domains, hosts, and networks. For now, we'll prevent access to the wp-admin directory pages for all IPs except yours. Open an htaccess file in your wp-admin directory via your control panel or the terminal: nano /path/to/WP-root/wp-admin/.htaccess Add these lines, swapping the IP for yours: order deny,allowdeny from allallow from 123.45.67.890 Need access from more IPs? Just add more alongside the first one, single space separated. But. If your IP address is dynamic, which very often it is, you may find this method a little too effective. If you do become locked out, cruise server-side to switch the IP. What is my IP? That old chestnut: whatismyip – http://whatismyip.com IP spoofing A chestnut gone bad, denying alone won't protect against man-in-the-middle attacks, so if you got this farthinking that you could have avoided all the SSL stuff after all, no, you were right to do that. No safeguard is a silver bullet. Deny syntax sure helps though, if you're not on the move.   Password protect directories Password protection is a way to give access to a directory and its sub-tree to a selected few people and may be used, typically: To house private files to which you need access from anywhere By developers fine-tuning a new blog theme For a client zone on a commercial site As an extra layer of protection to, say, wp-login or phpMyAdmin The procedure is to choose a directory, granting access to specified users. These privileged directory users are separate from, and should not be confused with, your server or WordPress users, the control being governed by Apache rather than by Linux or your WordPress database. That's a good thing, adding an independent tier of protection. cPanel's Password Protect Directories There are various ways to secure a directory, so let's start off with the regular control panel option, which in cPanel, is called Password Protect Directories: Browse to the target directory in File Manager, right-clicking and choosing Password Protect (or click through the panel icon if you like). Select the checkbox and give the directory a name to appear on the authentication screen. Save and you are redirected to a confirmation page. Click back to the previous page and add a username and password to access the folder. Save the newly authorized user. Now you can surf to that folder or some file within, are asked for credentials, and can log in. So what did we really just do there? Clicked on some shiny icons, added some details, and cPanel interacted a bit over far too many pages. Let's get geeky, it's worth it.   Authentication with mod_auth When we protect a folder, cPanel uses Apache's mod_auth module to amend or create two hidden files, htaccess and passwd. htaccess lives in the folder to protect and passwd lives safely above the web root in the hush-hush htpasswd directory. Using an example file, we can compare our control panel actions with those using the terminal, interacting directly with mod_auth. Cue screenshots, using cPanel we did this: And mod_auth creates the ruleset in the htaccess file, which we equally could just type: AuthType BasicAuthName "Protect me pretty please"AuthUserFile "/home/USERNAME/.htpasswds/public_html/protectme/passwd"Require valid-user Then we did this: And mod_auth yawns a bit while it adds credentials to a password file: johndoe:L9c7m/hO16slA (John's password is encrypted, server-side, but he logs in using the plaintext hackth!s.) Now then. Two points. First, with the syntax learnt or duplicated, it's quicker to bin the middleman and just use the shell. More importantly, by directly chatting up Apache, we have a better array of security tools. To clarify, let's take this a step at a time. The htaccess file Before we look at the mod_auth syntax that goes in htaccess files, a quick aside ... A quick shout out to htaccess, bless We've met the hidden htaccess file already. It's essentially a convenient and versatile web configuration file that can be added to multiple directories. The directives these files contain can equally be placed in other types of files such as those for our virtual hosts (which is tidier, all those directives from htaccess files being in one place). Uniquely, however, rules added in htaccess can be parsed immediately, or in other words, without the need to restart Apache. Feel the power! One other thing about htaccess: you don't need root access to add or edit these files. Listen up, shared hosting people, this is very convenient because you don't have root access (to hack into your co-sharers directories!) to those configuration files, but you do have access to your own jailed (or chroot-ed) web files. And because htaccess files live with your files, you can tweak them at will. Now back to using htaccess to store that mod_auth syntax ... In this case, for any directory you want to protect, just add or append an htaccess file with your tailored mod_auth directives. Here's a closer look at the mod_auth syntax, beginning with its type: AuthType Basic Pretty basic then and more on that later. For when we navigate to the login page we want some kind of instructional message: AuthName "Protect me pretty please" Now the link to the directory's corresponding password file: AuthUserFile "/home/USERNAME/.htpasswds/public_html/DIRECTORY-TOPROTECT/passwd" And we'll specify to give access only to users recorded in the password file: Require valid-user So far so good. Carry on. The passwd file Often referred to as the htpasswd file, here's the syntax it houses: johndoe:L9c7m/hO16slA johndoe is the authorized, or required user. L9c7m/hO16slA is the encrypted form of hackth!s , his password. We use a handy tool, also called htpasswd, to encrypt that. Add as many usernames and passwords as you like to this file, each on a new line. The file itself can live and be called whatever you like as long as the AuthUserFile directive corresponds. One thing though: the file should be located above your web root.  
Read more
  • 0
  • 0
  • 1487
article-image-how-build-rss-reader-windows-phone-7
Packt
09 Jun 2011
10 min read
Save for later

How to Build a RSS Reader for Windows Phone 7

Packt
09 Jun 2011
10 min read
  Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7 Create enterprise-ready websites and applications that access Microsoft SharePoint on Windows Phone 7         Read more about this book       (For more resources on Microsoft Sharepoint, see here.) Security in SharePoint 2010 We begin this article with a discussion on security for a very simple reason: security in SharePoint is tricky. In addition to that one very simple reason, authenticating users against SharePoint from within a Windows Phone 7 client application is even trickier. In this article, the example RSS reader that we develop will only use anonymous access to the RSS feeds in SharePoint. Setting up anonymous access is very simple and we'll walk through the steps here. When writing this article, I came across a lot of errors on my testing server, but not my development server. After a couple of days of unsuccessful web searches and reinstalling different components, I discovered the root of my problem was due to the fact that the SharePoint 2010 Prerequisites install a non-final version of ADO. NET Data Services 1.5. Make sure the final version is installed from Microsoft. More information is available at the following URL: http://blogs.msdn.com/b/astoriateam/archive/2010/01/27/data-services-update-for-net-3-5-sp1-available-for-download.aspx There are two places where we need to make changes to our SharePoint site to enable anonymous access: Central Administration Site Permissions Central Administration Classic mode authentication is more or less just classic Windows authentication using NTLM or Kerberos. Although Internet Explorer Mobile in Windows Phone 7 can do the NTLM authentication, as we've been doing up to now to view SharePoint sites in the browser, the version of Silverlight that is included in Windows Phone 7 cannot currently use this authentication mechanism. Carry out the following steps to configure Central Administration for anonymous access: From the Start menu, select All Programs. Find the folder named Microsoft SharePoint 2010 Products in the list of programs and click on it. Click on SharePoint 2010 Central Administration. You need to select the Yes option on the User Account Control dialog that may appear. At this point, the home page for SharePoint 2010 Central Administration should appear as displayed in the following screenshot: (Move the mouse over the image to enlarge.) Next, click on Manage web applications. The page that appears lists out all of the web applications in the SharePoint site. There should be two items listed here, but it is possible there are more. Select the main website by clicking on its name. This main website is usually titled SharePoint – 80. Once selected, the ribbon bar across the top should light up, as all the icons become active. Carry out the following steps to enable anonymous access: Click on the Authentication Providers icon. In the Authentication Providers dialog that appears, select the Default link. The Edit Authentication dialog box will appear. In the third section, down under a heading of Anonymous Access there is a check box listed as Enable anonymous access. Check that box. Scroll all the way to the bottom of the dialog box and select the Save button. SharePoint 2010 will process the request. Then, return to the Authentication Providers dialog box and close it. There is one more section that may need tweaking and if this is a production environment, it should be considered. That section is Anonymous Policy. Click on the icon for it in the ribbon and a dialog box will appear. From here, we can customize the anonymous policy for the site. None – No policy basically leaves the door open for read and write access from anonymous users. This is a good policy to use when anyone who can access the site should also be able to modify the content of the site. This is a good policy for Wiki's. Deny Write – Has no write access allows the anonymous users to read the site, but they cannot write, update, or delete content. This is a good policy to use for sites that we want to specify particular authenticated accounts write access, but allow everyone the ability to read the content. Some Wiki's use this policy and a lot of blogs use this policy. Deny All – Has no access selecting this removes all permissions to the anonymous user. Secure content should always use this policy. Site Permissions Once we have updated the web application to allow anonymous access, we have to give anonymous users access to the site collection. To do this, we close Central Administration and open our SharePoint site. Once on the site, select Site Permissions from the Site Actions menu. This will open the Permissions home page. In the ribbon at the top, there is an icon named Anonymous Access. Click on that button and the Anonymous Access dialog will appear, as shown in the following screenshot: This dialog has three radio buttons to fine tune the access that anonymous users have. The key point to remember here is that although we are really opening up the site for everyone to see, we can break the inherit permissions model on a child page at any time if we need to remove anonymous access. Now that we have opened up our SharePoint site to anonymous users, we can begin to write applications for Windows Phone 7. In a production environment, we may not have the privilege of opening a SharePoint site this wide, but remember that we are only doing it for demonstration purposes here. We have to walk before we can run. Now, let's get started on the RSS reader.   Using WebClient to get data from the web As was stated in the introduction to this article, we are going to build a really simple RSS reader for Windows Phone 7. We are going to keep everything really simple. What that means is that we are going to focus on the pieces of code that actually do something. This is what we are going to do: Create our base project Add a text block to display the WebClient results Create a WebClient Use the WebClient to request the contents of our SharePoint home page Display the raw HTML that is returned in the text block on the page First, a quick word about WebClient. WebClient isn't the most robust method of making requests over a network, but it's really simple and works for simple cases, such as the one we are working with. Creating the base project We can start by creating our base project. This RSS reader will use the Visual Studio Silverlight for Windows Phone Windows Phone Application template. Carry out the following steps to start the project: Open Visual Studio 2010. Select File from the main menu and then select New Project…. In the New Project dialog box that appears, select Silverlight for Windows Phone. Then select Windows Phone Application from the list of templates for Windows Phone. Give the project a name, for example SimpleRSSReader. Give the Solution a name, for example Chapter06. Change the Location as desired and click on the OK button. At this point, Visual Studio will go off and create the solution and project. When it has finished, MainPage.xaml will appear on the screen in split screen mode, as shown in the following screenshot: Displaying WebClient results by adding a text block The first thing we are going to do here is add a text block to the content panel. Add the following code to the Grid that has a name of ContentPanel. <TextBlock x_Name="webClientResults" /> This creates a text block named webClientResults and puts it in ContentPanel. We could spruce this up a bit by providing a font size, or padding, but we are going to keep this really simple and only show the code needed to get things done. Save the progress. Creating a WebClient Open up the code behind by either clicking on it in the top tab bar, double-clicking the file name in Solution Explorer, or press F7 while in the XAML code. In the code behind, create a private member variable, outside the constructor, named client of type WebClient and a private member variable, also outside the constructor, named siteUrl of type string. The siteUrl should have a value that is the URL to your SharePoint home page. private WebClient client = new WebClient();private string siteUrl = "http://ssps2010/"; These are the variables that we'll be using in just a minute. The first is the WebClient that makes the requests on the network. The second is the Url for our SharePoint home page. This is the address that the WebClient will use to request a web page. Requesting the contents of our SharePoint home page Now that we have a WebClient, let us do something with it. Add the following code to the Main Page constructor: client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);client.DownloadStringAsync(new Uri(siteUrl)); The first line adds a new event handler to the DownloadStringCompleted event. This event handler is called client_DownloadStringCompleted and we will write it shortly. The second line is what starts an asynchronous request to our SharePoint home page to get the HTML content. Displaying the raw HTML that is returned Until now, we've created a place in the content panel to display our results. We've created a couple of variables. We've added a new event handler for when the WebClient finishes and we've made the web request for our SharePoint home page. Next, we are going to receive the result from the WebClient. Earlier, when we added a new event handler to the WebClient, we told WebClient that when it finishes downloading the string, it should call our method named client_DownloadStringCompleted. The following is the code for that method: void client_DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e) { if(e.Error == null) { webClientResults.Text = e.Result; }} First, we check to see if there is an error. To make this as simple as possible, we are not handling the situation where there is an error. We only care if there are no errors. Always check that errors are null. If there is an exception in the WebClient request, the DownloadStringCompletedEventArgs Error property will contain an object of type Exception. These exceptions can range from network connections being down, which is common for cell phones, to invalid URLs. We then take the result of the web request and put it in the text block we created earlier. Save the progress and press F5 to see the application run on the Windows Phone 7 Emulator. In the preceding screenshot, ApplicationTitle and PageTitle have also been updated. Both of these text blocks are found in the XAML in TitlePanel. We have successfully used WebClient to read data from the web and display it on the screen. It is still in a raw format though, and it isn't much of an RSS reader, especially since this page isn't even RSS. We will get there, but first let's find some RSS in SharePoint.  
Read more
  • 0
  • 0
  • 1160

article-image-cocoa-and-objective-c-handling-events
Packt
09 Jun 2011
8 min read
Save for later

Cocoa and Objective-C: Handling events

Packt
09 Jun 2011
8 min read
Some recipes in this article require Mac OS X Snow Leopard 10.6. The Trackpad preferences allow you to easily adjust many gestures that will used in the following recipes. To make sure that your trackpad is recognizing gestures, make sure that you have set the correct preferences to enable gesture support under the Trackpad System Preference. Interpreting the pinch gesture The pinch gesture is a gesture normally used for the zooming of a view or for changing the font size of text. In this recipe, we will create a custom view that handles the pinch gesture to resize a custom view. Getting ready In Xcode, create a new Cocoa Application and name it Pinch. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builders Inspector's palette, select the Identity tab and set the Class popup to MyView. Choose Save from the File menu to save the changes that you have made. In Xcode, Add the following code in the drawRect: method of the MyView class implementation: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; Next, we need to add the code to handle the pinch gesture. Add the following method to the MyView class implementation: - (void)magnifyWithEvent:(NSEvent *)event { NSSize size = [self frame].size; size.height = size.height * ([event magnification] + 1.0); size.width = size.width * ([event magnification] + 1.0); [self setFrameSize:size]; } Choose Build and Run from Xcode's toolbar to run the application. How it works... In our drawRect: method, we use Cocoa to draw a simple rounded rectangle with a three point wide gray stroke. Next, we implement the magnifyWithEvent: method. Because NSView inherits from NSResponder, we can override the magnifyWithEvent: method from the NSResponder class. When the user starts a pinch gesture, and the magnifyWithEvent: method is called, the NSEvent passed to us in the magnifyWithEvent: method which contains a magnification factor we can use to determine how much to scale our view. First, we get the current size of our view. We add one to the magnification factor and multiply by the frame's width and height to scale the view. Finally, we set the frame's new size. There's more... You will notice when running the sample code that our view resizes with the lower-left corner of our custom view remaining in a constant position. In order to make our view zoom in and out from the center, change the magnifyWithEvent: method's code to the following: NSSize size = [self frame].size; NSSize originalSize = size; size.height = size.height * ([event magnification] + 1.0); size.width = size.width * ([event magnification] + 1.0); [self setFrameSize:size]; CGFloat deltaX = (originalSize.width - size.width) / 2; CGFloat deltaY = (originalSize.height - size.height) / 2; NSPoint origin = self.frame.origin; origin.x = origin.x + deltaX; origin.y = origin.y + deltaY; [self setFrameOrigin:origin]; Basically, what we have done is moved our custom view's origin by the difference between the original size and the new size. Interpreting the swipe gesture The swipe gesture is detected when three or more fingers move across the trackpad. This gesture is often used to page through a series of images. In this recipe, we will create a custom view that interprets the swipe gesture in four different directions and displays the direction of the swipe in our custom view: Getting ready In Xcode, create a new Cocoa Application and name it Swipe. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builders Inspector's palette, select the Identity tab and set the Class popup to MyView. Choose Save from the File menu to save the changes that you have made. In Xcode, open the MyView.h file and add the direction variable to the class interface: NSString *direction; Open the MyView.m file and add the following code in the drawRect: method of the MyView class implementation: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; if (direction == nil) { direction = @""; } NSAttributedString *string = [[[NSAttributedString alloc] initWithString:direction] autorelease]; NSPoint point = NSMakePoint(([self bounds].size.width / 2) - ([string size].width / 2), ([self bounds].size.height / 2) - ([string size].height / 2)); [string drawAtPoint:point]; Add the following code to handle the swipe gesture: - (void)swipeWithEvent:(NSEvent *)event { if ([event deltaX] > 0) { direction = @"Left"; } else if ([event deltaX] < 0) { direction = @"Right"; } else if ([event deltaY] > 0) { direction = @"Up"; } else if ([event deltaY] < 0){ direction = @"Down"; } [self setNeedsDisplay:YES]; } In Xcode, choose Build and Run from the toolbar to run the application. How it works... As we did in the other recipes in this article, we draw a simple rounded rectangle in the drawRect: method of the view. However, we will also be drawing a string denoting the direction of the swipe in the middle of our view. In order to handle the swipe gesture, we override the swipeWithEvent: method from the NSResponder class which NSView inherits. By inspecting the values of deltaX and deltaY of the NSEvent passed into the swipeWithEvent: method, we can determine the direction of the swipe. We set the direction string with the direction of the swipe so we can draw it in the drawRect: method. Finally, we call setNeedsDisplay:YES to force our view to redraw itself. There's more... You might have noticed that we do not need to override the acceptsFirstResponder: method in our view in order to handle the gesture events. When the mouse is located within our view, we automatically receive the gesture events. All we need to do is implement the methods for the gestures we are interested in. Interpreting the rotate gesture The rotate gesture can be used in any number of ways in a custom view. From rotating the view itself or simulating a rotating dial in a custom control. This recipe will show you how to implement the rotate gesture to rotate a custom view. Using your thumb and index finger, you will be able to rotate the custom view around its center: Getting ready In Xcode, create a new Cocoa Application and name it Rotate. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m. Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builders Inspector's palette, select the Identity tab and set the Class popup to MyView. Choose Save from the File menu to save the changes that you have made. In Xcode, add the following code in the drawRect: method of the MyView class implementation: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; Next we need to add the code to handle the rotate gesture. Add the following method to the MyView class implementation: - (void)rotateWithEvent:(NSEvent *)event { CGFloat currentRotation = [self frameCenterRotation]; [self setFrameCenterRotation:(currentRotation + [event rotation])]; } Choose Build and Run from Xcode's toolbar to test the application. How it works... As we did in the previous recipe, we will create a simple rounded rectangle with a three-point stroke to represent our custom view. Our custom view overrides the rotateWithEvent: method from NSResponder to handle the rotation gesture. The rotation property of the NSEvent passed to us in the rotateWithEvent: contains the change in rotation from the last time the rotateWithEvent: method was called. We simply add this value to our view's frameCenterRotation value to get the new rotation. There's more... The value returned from NSEvent's rotation will be negative when the rotation is clockwise and positive when the rotation is counter-clockwise.
Read more
  • 0
  • 0
  • 3316

article-image-25-useful-extensions-drupal-7-themers
Packt
07 Jun 2011
5 min read
Save for later

25 Useful Extensions for Drupal 7 Themers

Packt
07 Jun 2011
5 min read
Drupal 7 Themes Create new themes for your Drupal 7 site with a clean layout and powerful CSS styling Drupal modules There exist within the Drupal.org site a number of modules that are relevant to your work of theming a site. Some are straightforward tools that make your standard theming tasks easier, others are extensions to Drupal functionality that enable to you do new things, or to do things from the admin interface that normally would require working with the code. The list here is not meant to be comprehensive, but it does list all the key modules that are either presently available for Drupal 7 or at least in development. There are additional relevant modules that are not listed here, as at the time this was written, they showed no signs of providing a Drupal 7 version. Caution One thing to keep in mind here—some of these modules attempt to reduce complex tasks to simple GUI-based admin interfaces. While that is a wonderful and worthy effort, you should be conscious of the fact that sometimes tools of this nature can raise performance and security issues and due to their complexity, sometimes cause conflicts with other modules that also are designed to perform at least part of the functions being fulfilled by the more complex module. As with any new module, test it out locally first and make sure it not only does what you want, but also does not provide any unpleasant surprises. The modules covered in this article include: Administration Menu Chaos Tool Suit Colorbox Conditional Stylesheets Devel @font-your-face Frontpage HTML5 Tools .mobi loader Mobile Theme Nice Menus Noggin Organic Groups Panels Semantic Views Skinr Style Guide Sweaver Taxonomy Theme Theme Developer ThemeKey Views Webform Administration Menu The Administration Menu was a mainstay of many Drupal sites built during the lifespan of Drupal 6.x. With the arrival of Drupal 7, we thought it unlikely we would need the module, as the new toolbar functionality in the core accomplished a lot of the same thing. In the course of writing this, however, we installed Administration Menu and were pleasantly surprised to find that not only can you run the old-style Administration Menu, but they have also now included the option to run a Toolbar-style Administration Menu, as shown in the following screenshot: The Administration Menu Toolbar offers all the options of the default Toolbar plus the added advantage of exposing all the menu options without having to navigate through sub-menus on the overlay. Additionally, you have fast access to clearing the caching, running cron, and disabling the Devel module (assuming you have it installed). A great little tweak to the new Drupal 7 administration interface. View the project at: http://drupal.org/project/admin_menu. Chaos Tool Suite This module provides a collection of APIs and tools to assist developers. Though the module is required by both the Views and Panels modules, discussed elsewhere in this article, it provides other features that also make it attractive. Among the tools to help themers are the Form Wizard, which simplifies the creation of complex forms, and the Dependent widget that allows you to set conditional field visibility on forms. The suite also includes CSS Tools to help cache and sanitize your CSS. Learn more at http://drupal.org/project/ctools. Colorbox The Colorbox module for Drupal provides a jQuery-based lightbox plugin. It integrates the third-party plugin of the same name (http://colorpowered.com/colorbox/). The module allows you to easily create lightboxes for images, forms, and content. The module supports the most commonly requested features, including slideshows, captions, and the preloading of images. Colorbox comes with a selection of styles or you can create your own with CSS. To run this module, you must first download and install the Colorbox plugin from the aforementioned URL. Visit the Colorbox Drupal module project page at: http://drupal.org/project/colorbox. Conditional Stylesheets The module allows themers to easily address cross-browser compatibility issues with Internet Explorer. With this module installed, you can add stylesheets targeting the browser via the theme's .info file, rather than having to modify the template.php file. The module relies on the conditional comments syntax originated by Microsoft. To learn more, visit the project site at http://drupal.org/project/conditional_styles. Devel The Devel module is a suite of tools that are useful to both module and theme developers. The module provides a suite of useful tools and utilities. Among the options it provides: Auto-generate content, menus, taxonomies, and users Print summaries of DB queries Print arrays Log performance Summaries of node access The module is also a prerequisite to the Theme Developer module, discussed later in this article. Learn more: http://drupal.org/project/devel. @font-your-face @font-your-face provides an admin interface for browsing and applying web fonts to your Drupal themes. The module employs the CSS @font-face syntax and draws upon a variety of online font resources, including Google Fonts, Typekit. com, KERNEST, and others. The system automatically loads fonts from the selected sources and you can apply them to the styles you designate—without having to manually edit the stylesheets. It's easy-to-use and has the potential to change the way you select and use fonts on your websites. @font-your-face requires the Views module to function. Learn more at the project site: http://drupal.org/project/fontyourface. Frontpage This module serves a very specific purpose—it allows you to designate, from the admin interface, different front pages for anonymous and authenticated users. Though you can accomplish the same thing through use of $classes and a bit of work, the module makes it possible for anyone to set this up without having to resort to coding. Visit the project site at http://drupal.org/project/frontpage.
Read more
  • 0
  • 0
  • 2851
article-image-customizing-sharepoint-communities-windows-phone-7
Packt
03 Jun 2011
9 min read
Save for later

Customizing SharePoint Communities for Windows Phone 7

Packt
03 Jun 2011
9 min read
  Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7 Create enterprise-ready websites and applications that access Microsoft SharePoint on Windows Phone 7         Read more about this book       (For more resources on Microsoft Sharepoint, see here.) Let's get started with the discussion of SharePoint communities by taking a look at blogs.   Blogs At this point in the 21st century, everyone is familiar with what a blog is. In SharePoint, a blog is a site that is characterized by entries of content being listed from newest at the top of the page to oldest at the bottom. Content is determined by the author and can contain metadata such as the author, date, and keywords or tags to designate the categories in which the content belongs. Creating a blog site in SharePoint A blog site can either be the root site or a site contained within another site. This is consistent with all site types in SharePoint. The reason this is pointed out though, is that when creating a new SharePoint engagement, it is important to truly think of the overall goal of the website as a whole. If the website will essentially be a blog with other content thrown in from time to time, then it makes sense for the root site to be of the type blog. Otherwise, it makes sense to make the root site something else like the team site or a blank site and then add a blog site within that root site. This is important to think about because to add a blog to an existing site is fairly straightforward. Simply, carry out the following steps: From the root site, click on the Site Actions menu. On the Site Actions menu, select the New Site option. From the Installed Items list, select Blog. Give the new blog site a Title and a URL name. Finally, click on the Create button. At this point, SharePoint will create a new blog site. The new blog will contain some seed data to get the blog going. There are three categories named appropriately: Category 1 Category 2 Category 3 The new blog site will also have a location for archives containing the one entry that was seeded in the site titled Welcome to your Blog! This can all be seen in the following screenshot: Customizing a SharePoint blog site Although this blog site is ready to go right now, we will probably want to customize it for our usage scenario. There are several places to customize it, which are as follows: About this blog Categories Blog Tools Links About this blog When new readers reach a blog they look for information about the blog so they can get a high level overview of what to expect from the content of the site. This is usually found in the "about this blog" section of the site. In the SharePoint blog site, the About this blog section is a Wiki Web Part found in the right column. Although we will learn more about Wikis in the next section, for now just know that this web part allows us a what-you-see-is-what-you-get (WYSIWYG) editing surface to enter any content we want. To get into this editing mode, carry out the following steps: From the Site Actions menu, select Edit Page. When the page changes to edit mode, click on the text inside the About this blog section. At this point, the ribbon at the top will have the following four main sections: Editing Tools: This has the basic text editing tools that are familiar to anyone who has used Word. Table Tools: The about section is actually a table with two rows and one column. The top cell has the image, and the bottom has the text. The Table Tools section of the ribbon allows us to manage this table. Page Tools: These are the basic tools that are global to the page and not specific to this section. Web Part Tools:This part of the ribbon contains tools that allow us to minimize, restore, or delete the web part. It also allows us to edit the Web Part Properties. These properties include the title, as well as other appearance features such as height and width. It also includes layout information and some advanced features. Categories The next section to customize on this blog site is the list of categories. When creating a blog entry, we can categorize the contents with a tag. The default categories for a new blog are as follows: Category 1 Category 2 Category 3 The following steps show how to customize these categories: Click on the title Categories in the left column. This will open the list page for the categories. The categories list will display the three default categories. For each category, click on the Edit icon, as shown in the following screenshot: (Move the mouse over the image to enlarge.) Change the Title to something that makes sense for the blog which we are creating. Click on the Save button. Repeat these steps for all three of the default categories. To add more categories, click on the Add new item link below the list of categories. To delete a category, carry out the following steps: Move the pointer over the title of the category. This will trigger an arrow to appear to the right of the title next to the edit icon. Click on this down arrow. In the context menu that appears, select the Delete Item option. A confirmation message will appear asking if we are sure we want to send it to the recycle bin. Click on OK and the category will be deleted. Blog Tools Now that we have a blog, how do we manage the content? This is where the Blog Tools section comes into use. There are 4 links to help us manage the blog, which are as follows: Create a post Manage posts Manage comments Launch blog program to post Create a post Clicking on the Create a post link will open a modal dialog with a form to fill out to create a new blog entry. The fields include the following: Title: This is a plain text field used for the title of the entry. Body: This is a rich text field that utilizes the edit ribbon. Category: Here we can select the categories that the entry is a part of. Published: Here we can set a date for our entry to be published. Publishing an entry in the future is helpful when we have information that isn't supposed to be public knowledge until a specifi c time and date, or when information needs to be published at a specifi c time and date. The preceding fields are shown in the following screenshot: Manage posts Blog entries, like most things in SharePoint, are items in a list. Clicking on the Manage posts link will display all the blog entries. From this list, we can perform many management functions such as the following: Manage approval status Edit entries View entries Manage permissions Delete entries Manage comments All of the comments are managed in a separate list from the blog entries. Clicking on the Manage comments link will display all of the comments for all of the blog entries in this site. From here we can view, edit, or delete the comments, as well as manage permissions. Managing permissions on comments and posts is a lot like managing permissions elsewhere in SharePoint. By default, the list items inherit the parent permissions, but occasionally we will want to have specific permissions for special cases. We could have a blog entry that we only want a small group of people to see, or maybe we want to save a comment, so that only we can see it. The manage permissions section is how we can deal with these cases. More information on managing permissions can be found in the online help or on TechNet at the following URL: http://technet.microsoft.com/en-us/library/cc721640.aspx Launch blog program to post Although creating a blog entry in the web browser works well, sometimes we may want to use a more powerful tool to create entries. The Launch blog program to post link will open Microsoft Word 2007, or a newer version, to edit a new blog entry. Configuring Windows Live Writer There is a link in Blog Tools to launch Microsoft Word 2007 or newer, to create a new blog entry. Although Word does a pretty good job of creating new blog entries, there is a free tool from Microsoft, named Windows Live Writer (http://explore.live.com/windows-live-writer) which is true genius when it comes to editing blog entries. Using this tool can make most, if not all, blog posting tasks much easier within SharePoint. Configuring Windows Live Writer for a SharePoint is simple: When setting up Windows Live Writer, select SharePoint from the What blog service do you use? Click on Next and enter the URL of the SharePoint blog. Click on Next and provide the SharePoint authentication information. That's all there is to it. The Windows Live Writer interface also displays a preview of what the blog entry will look like in the site by clicking on the Preview tab at the bottom, as shown in the following screenshot: Links Finally, the links section allows us to add hyperlinks to the page for easy access to anything. The default entry is to a photo library named Photos. Adding a new link is as simple as the following steps: Click on the Add new link hyperlink. Enter the URL for the link. Optionally, enter a description that will be used in place of the raw URL for display. Optionally, add any notes. Notes show up when viewing the full list of links. The full list of links can be viewed by clicking on the title Links from the home page. Click on Save, as shown in the following screenshot:  
Read more
  • 0
  • 0
  • 1073

article-image-html5-generic-containers
Packt
01 Jun 2011
15 min read
Save for later

HTML5: Generic Containers

Packt
01 Jun 2011
15 min read
  HTML5 Multimedia Development Cookbook Recipes for practical, real-world HTML5 multimedia driven development.         Read more about this book       (For more resources on Multimedia development, see here.) Introduction "On the web, a man should not be judged by the color of his skin but by the content of his content." - Internet meme To be correct according to the specification semantically, we need to know what the content is so we can wrap it with the most appropriate new element tag. While this may mean we developers have to think differently, a new challenge is exactly why we're here. In this article we'll look at some examples of how to do just that using several of HTML5's new elements. "In case of conflict, consider users over authors over implementers over specifiers over theoretical purity." - Priority of Constituencies Throughout this article, we'll show you how to use the new <article> element to mark up both blog posts and comments, add a meaningful publication date to an <article>, use the new <mark> element to highlight text, and how to note visual elements using the new <figure> element. We'll then turn our attention to some new methods of styling text with font replacement techniques, as well as adding drop shadows and gradients to our text.   Structuring a blog article "The <article> element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content." - WHATWG's HTML5 Draft Standard - http://whatwg.org/html5 Getting ready Blog entries are perfect candidates for the new <article> element, which is designed for syndicated content. For this recipe, let's start by identifying the major elements of a blog <article>: There's usually a headline in the form of a heading tag, the blog entry itself consisting of several paragraphs and perhaps one or more images, and some information that usually includes the author's name and other related metadata. Notice this is all self-contained related content. How to do it... We're going to continue using the new HTML5 <header> and <footer> elements. The headline, entry and meta-information should be wrapped in their own unique tags, like <h2>, multiple <p>s and the new &ltfooter>. Let's start with a foundation and add our new <article> element twice: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Blog Title</title> <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script>[endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body><article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer></article><article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer></article></body></html> Put your code on a diet? Ready for a shocker? Want to have your mind blown? The <html> and <head> and <body> tags (as well as their closing tags) are now optional in the HTML5 specification. Sure, you could leave them in there, and your pages will validate just fine, but why should we? If remove them from the previous code, we are left with the spartan: <!DOCTYPE html><meta charset="UTF-8"><title>Blog Title</title><!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script>[endif]--><meta name="viewport" content="width=device-width, initial-scale=1.0"><article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer></article><article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer></article> Don't believe me? Run that code through the World Wide Web Consortium's validator at: http://validator.w3.org, and you'll see it displays correctly in the browser. Well, not so fast buster. The problem is that removing those elements breaks our code for screen readers. Uh oh. Strike one. Also, removing the <body> tag breaks our new HTML5-enabling JavaScript for Internet Explorer. Strike two. And guess what? You can see it coming, can't you? Yes, removing the <html> tag removes the language of the page. There it is: Strike three. So let's add those elements back in, shall we? <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Blog Title</title> <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script>[endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article> <article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article></body></html> There, that's better. How it works... Remember, the new <article> element is a collection of related information intended for syndication via RSS or another means. There's more... Richer, more meaningful semantics is perhaps the most significant goal for HTML5. It's better for machines, better for authors, and most importantly, better for our audiences. Validation as an aid, not a crutch As we saw previously, removing the &lthtml> and <head> and <body> tags render a still valid page. So that begs the question of how valid validators are. Unlike the XML world, HTML5 can use incorrect syntax and still render just fine. The author makes every effort to validate his code whenever possible. It's not necessary to be slavish to the validator, but it's always a good quality control check. And the closer you get to valid code, the better chance browsers will display your work in as consistent a manner as possible. Eric Meyer's funny The author loves how CSS guru Eric Meyer thinks about validators: Where to find validators You can make good use of code validators at: http://validator.nu http://validator.w3.org   Highlighting text using the mark element "The &ltmark> element represents a run of text in one document marked or highlighted for reference purposes, due to its relevance in another context. When used in a quotation or other block of text referred to from the prose, it indicates a highlight that was not originally present but which has been added to bring the reader's attention to a part of the text that might not have been considered important by the original author when the block was originally written, but which is now under previously unexpected scrutiny. When used in the main prose of a document, it indicates a part of the document that has been highlighted due to its likely relevance to the user's current activity." - WHATWG's HTML5 Draft Standard - http://whatwg.org/html5 Getting ready When viewing search results, you'll often find the term for which you searched highlighted. Instead of relying on a semantically meaningless tag, we can now use the more meaningful <mark> element. How to do it... In this recipe, you'll see HTML5doctor.com has an excellent example of how to use the new <mark> element to highlight a search results term. This gives a useful semantic hook not only for styling but also for the machine tracking the results. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script>[endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <h1>716,000,000 search results for the query "<mark>HTML 5</mark>"</h1> <section id="search-results"> <article> <h2><a href="http://en.wikipedia.org/wiki/HTML_5"> <mark>HTML 5</mark> - Wikipedia, the free encyclopedia</a></h2> <p><mark>HTML 5</mark> is the next major revision of <mark>HTML</mark> ("hypertext markup language"), the core markup language of the World Wide Web. The WHATWG started work on the ... <a href="http://en.wikipedia.org/wiki/HTML_5"> Read more</a></p> </article> <article> <h2><a href="http://dev.w3.org/html5/spec/Overview.html"> <mark>HTML 5</mark></a></h2> <p>A vocabulary and associated APIs for <mark>HTML</mark> and XHTML. Editor's Draft 16 August 2009. Latest Published Version: http://w3.org/TR/<mark>html5</mark>/; Latest Editor's ... <a href="http://dev.w3.org/html5/spec/Overview.html"> Read more</a></p> </article> </section></body></html> Adding a simple style declaration like: <style type="text/css"> mark {background-color: yellow; font-weight: bold;}</style> in the <head> section helps us render this highlighted text: How it works... The new <mark> element simply highlights a word or phrase to draw the reader's attention. To do this, simply specify the <mark> to be bold or italicized or highlighted in some way in your corresponding Cascading Style Sheet. There's more... Sure, you could mark up and style a search-results page to use the <b> or <i> or even <span> tags to indicate for which term the search took place, but each of those tags only affects the presentation layer. They lack meaning. The new &ltmark> element can accomplish the same visual effect, while also adding that extra meaning to your markup. In fact, the new &ltmark> element is full of win. <Mark> long and prosper Another great use of the new <mark> element is highlighting a date in a calendar picker, as we often see on any date-based reservation system website like Priceline.com. Priceline.com highlights the current date by default when booking your itinerary. Instead of using a semantically meaningless tag to achieve this, the new <mark> element could be a perfect candidate to use. Waiting for browsers The new <mark> element isn't fully supported by any web browser at the time of this writing. Though the extra semantic meaning may not be apparent to machine readers, we can still use the new <mark> element as a stylistic "hook" until the day its meaning is fully supported by a variety of browsers. Is "future proof" a word? Remember that HTML5's new elements attempt to add extra meaning to our markup. The goal is never to take away meaning or break pages. With this in mind, it becomes much more palatable to layer on new elements like the <mark> element that's not fully implemented by browsers yet. Even if its meaning is not fully understood by machines yet, it certainly does not hurt to add it and make our pages as "future proof" as we possibly can. See also In 2001, Carrie Bickner prepared the "New York Public Library Online Style Guide" (http://legacy.www.nypl.org/styleguide) for branches of the NYPL to use when updating their websites. In this seminal publication, Bickner made the case for web standards by separating content (markup) from presentation (Cascading Style Sheets) from behavior (JavaScript). The publication was extremely forward-thinking for the time and was in use for many years.   Using the time element "The &lttime> element represents either a time on a 24-hour clock, or a precise date in the proleptic Gregorian calendar, optionally with a time and a time-zone offset." - WHATWG's HTML5 Draft Standard - http://whatwg.org/html5 Getting ready The new <time> element is a powerful way to display time or a specific date. How to do it... In this recipe we'll display dates and times that will be readable for both humans and machines. Let's look at four examples. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <!--[if lt IE 9]><script src=http://html5shiv.googlecode.com/svn/trunk/html5.js> </script>[endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <article> <header> <h2>Headline</h2> <time datetime="2010-11-29">November 29, 2010</time> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article> <article> <header> <h2>Headline</h2> <time datetime="2010-11-29">Nov. 29</time> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article> <article> <header> <h2>Headline</h2> <time datetime="2010-11-29">the date this was written</time> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article> <article> <header> <h2>Headline</h2> <time datetime="2010-11-29T11:34">the date and time this was written</time> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article></body></html> How it works... We can use the new <time> element to indicate specific dates, times, or both. There's more... The new &lttime> element specifies an exact moment in time—not a time period. Odd rules One interesting aspect of the new <time> element is that you can't use a date before the Christian Era. You also can't use a date like "November 2010." Whatever date we specify must be a positive, specific date—not a relative one. The HTML5 Working Group continues to address this seemingly arbitrary restriction. <time>'s Time will come Browsers display the new <time> element but don't do anything special with it—yet. Always remember SEO Time. Why are we so obsessed with it? One very valid reason to focus on time and dates on the web is Search Engine Optimization. SEO, once seen as some sort of mysterious voodoo only black hatted wizards understood, is now everyone's responsibility online. You spend time creating good code and expect a writer to create content worth reading. Now go one step further and ensure that your intended audience can actually find the content you have taken the time to create. And the new <time> element is just one of the ways search engines draw attention to the most recent content. See also The new HTML5 <time> element is a possible addition to the Microformats movement. Microformats promise to add additional semantic meaning to our markup. Though not officially a standard, Microformats are slowly gaining acceptance in the web development community. Learn more at Microformats.org.  
Read more
  • 0
  • 0
  • 2964