Thursday, April 23

Drupal 7 Bootstrap Process ( drupal_bootstrap ) - Part 2


This is the second part of my Drupal 7 Line by Line series. In the first part I walked through Drupal 7 index.php. As you recall there are only four lines of code and two function calls that display all the pages on your Drupal 7 site.
In this post I'll start walking through one of those functions: drupal_bootstrap(). If you recall from Part 1 I said this function is starts up (bootstraps) all of Drupal's mechanisms required to handle a page request. This is only part of the story and only half the truth. A more accurate description would be that it loads up only as much of Drupal's functionality a php script needs so that the php script can uses that functionality to do something.
When drupal_bootstrap is called from index.php it is passed a single argument: BOOTSTRAP_FULL. In order for index.php (a php script) to display a web page (what the script does) it needs Drupal to bootstrap all of its mechanisms (i.e. a full bootstrap).
Lets see what the phpDoc comment and function signature for drupal_bootstrap() have to say:
<?php/**
* A string describing a phase of Drupal to load. Each phase adds to the
* previous one, so invoking a later phase automatically runs the earlier
* phases too. The most important usage is that if you want to access the
* Drupal database from a script without loading anything else, you can
* include bootstrap.inc, and call drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE).
*
* @param $phase
*   A constant. Allowed values are the DRUPAL_BOOTSTRAP_* constants.
* @param $new_phase
*   A boolean, set to FALSE if calling drupal_bootstrap from inside a
*   function called from drupal_bootstrap (recursion).
* @return
*   The most recently completed phase.
*
*/
function drupal_bootstrap($phase = NULL, $new_phase = TRUE) { ?>
This basically tells us that when we call this function we have to tell it which bootstrap phase to run by passing a value to the $phase variable. The function accepts a second argument $new_phase which by default is "TRUE".

Executing drupal_bootstrap(BOOTSTRAP_FULL)

So the first thing that the function does when its run is define a static variable called $phases. That variable is assigned an array that is populated with the constants that represent the 7 phases of the bootstrap process.

<?php
 
static $phases = array(
   
DRUPAL_BOOTSTRAP_CONFIGURATION,
   
DRUPAL_BOOTSTRAP_PAGE_CACHE,
   
DRUPAL_BOOTSTRAP_DATABASE,
   
DRUPAL_BOOTSTRAP_VARIABLES,
   
DRUPAL_BOOTSTRAP_SESSION,
   
DRUPAL_BOOTSTRAP_PAGE_HEADER,
   
DRUPAL_BOOTSTRAP_LANGUAGE,
   
DRUPAL_BOOTSTRAP_FULL,
  );
?>
The function then defines two more static variables $final_phase and $stored_phase (given an initial value of -1).

<?php
 
// When not recursing, store the phase name so it's not forgotten while
  // recursing.
 
if ($new_phase) {
   
$final_phase = $phase;
  }
?>
$new_phase is TRUE by default - therefore the $final_phase is assigned the value of $phase which in this case is BOOTSTAP_FULL which has an integer value of 7.

<?php
 
if (isset($phase)) {
   
// Call a phase if it has not been called before and is below the requested
    // phase.
   
while ($phases && $phase > $stored_phase && $final_phase > $stored_phase) {?>
If $phase has a value (it does) the function enters a while loop. The conditions of the while loop are:
if the $phases array has something in it (it currently does)
AND $phase (currently BOOTSTRAP_FULL or 7)
is greater than $stored_phase (currently -1)
AND $final_phase (also currently 7)
is greater than $stored_phase (currently -1)
do stuff.
In more general terms, the function is going to keep looping until each bootstrap phase is complete and it reaches the bootstrap phase that was first passed to the function.

<?php
      $current_phase
= array_shift($phases);       // This function is re-entrant. Only update the completed phase when the
      // current call actually resulted in a progress in the bootstrap process.
     
if ($current_phase > $stored_phase) {
       
$stored_phase = $current_phase;
      }
?>
Once inside the while loop the function 'shifts off' the first value of the $phases array and assigns the value to $current_phase.
If you look back, you'll see that the first element of the $phases array was DRUPAL_BOOTSTRAP_CONFIGURATION. Therefore $current_phase gets assigned that value once the array is shifted.
After that, the function then checks if $current_phase is greater than the $stored_phase and if so assigns the value of $current_phase to $stored_phase. This is all about keeping track of what the current bootstrap phase is and what the phase was. Remember, this function is going to be looping through all the phases. In each loop drupal_bootstrap could be called again recursively.

Meat and Potatoes

We arrive at the part that actually starts doing the bootstrapping (starting up) of the individual parts of Drupal.

<?phpswitch ($current_phase) {
        case
DRUPAL_BOOTSTRAP_CONFIGURATION:
         
_drupal_bootstrap_configuration();
          break;         case
DRUPAL_BOOTSTRAP_PAGE_CACHE:
         
_drupal_bootstrap_page_cache();
          break;         case
DRUPAL_BOOTSTRAP_DATABASE:
         
_drupal_bootstrap_database();
          break;         case
DRUPAL_BOOTSTRAP_VARIABLES:
         
_drupal_bootstrap_variables();
          break;         case
DRUPAL_BOOTSTRAP_SESSION:
          require_once
DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
         
drupal_session_initialize();
          break;         case
DRUPAL_BOOTSTRAP_PAGE_HEADER:
         
_drupal_bootstrap_page_header();
          break;         case
DRUPAL_BOOTSTRAP_LANGUAGE:
         
drupal_language_initialize();
          break;         case
DRUPAL_BOOTSTRAP_FULL:
          require_once
DRUPAL_ROOT . '/includes/common.inc';
         
_drupal_bootstrap_full();
          break;
      }
?>
There is a switch/case statement that checks what the $current_phase is and then executes the code in the appropriate case.
At this stage in this line by line journey the $current_phase is DRUPAL_BOOTSTRAP_CONFIGURATION so
_drupal_bootstrap_configuration() gets called.

What happens next

Good question, but the answer will have to wait. This is a good time to stop for now since each phase in the bootstrap process requires its own post. Next time we'll take a look at _drupal_bootstrap_configuration.
While you are waiting, and if you are at all curious about the origins of the bootstrap process, you can check out http://drupal.org/node/18213 where drupal_bootstrap was born.

Drupal 7 Bootstrap Process ( drupal_bootstrap ) - Part 1



This is the beginning of what I hope will be a series of posts that take you through a Drupal 7 page load line by line.

Here is the code I dove into: index.php - as it was in the days of Drupal 4.4:
<?php// $Id: index.php,v 1.76 2003/11/25 19:26:20 dries Exp $ include_once "includes/bootstrap.inc";drupal_page_header();
include_once
"includes/common.inc"; fix_gpc_magic(); menu_build("system"); if (menu_active_handler_exists()) {
 
menu_execute_active_handler();
}
else {
 
drupal_not_found();
}
drupal_page_footer(); ?>
And that's how I became a Drupal developer. I went down the rabbit hole. I began stepping through the code (without a deubugger!) trying to sort out what it was that Drupal was doing so that I could find what I needed to change to make my site look the way I wanted to. By the time I found my answer I had learned more about Drupal than I needed or wanted to know at the time. I was also hooked.
And the rest, as they say, was history.
With the release of Drupal 7 I thought I would repeat the exercise. This time however I will document the experience to share with you. We can learn something new together.

Here is index.php - as it is today:

<?php// $Id: index.php,v 1.99 2009/10/15 14:07:25 dries Exp $ /**
* @file
* The PHP page that serves all page requests on a Drupal installation.
*
* The routines here dispatch control to the appropriate handler, which then
* prints the appropriate page.
*
* All Drupal code is released under the GNU General Public License.
* See COPYRIGHT.txt and LICENSE.txt.
*/
/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd()); require_once DRUPAL_ROOT . '/includes/bootstrap.inc';drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);menu_execute_active_handler();?>
The first thing you'll notice is that Drupal has a lot more documentation inside the code than it did 6 versions ago. This will make stepping through and explaining the code line by line a little easier (since much of the work is already done). Its worth noting that the code comments are in phpDoc format and are used to generate the code documentation found at http://api.drupal.org/
As you can see in the code comments index.php serves (nearly1) all page requests on your website. In other words, index.php is where code execution begins whether you request http://example.com/home or http://example.com/news/january/headlines or http://example.com/admin/rule/the/world.
Yes. Four (4) lines of code return every single page on your Drupal site! That's pretty amazing. So what's going on here.
A call is made to getcwd() which returns the current working directory which gets assigned to the DRUPAL_ROOT constant.
Basically Drupal is telling itself which directory in the server's file system it is installed and assigning that information to a constant that will be used elsewhere in the code.
Using that constant Drupal then includes the file bootstrap.inc from the includes directory using require_once.
<?php// $Id: bootstrap.inc,v 1.459 2010/12/30 04:35:00 webchick Exp $
/**
* @file
* Functions that need to be loaded on every Drupal request.
*/
//3000 or so more lines of code
?>
Bootstrap.inc contains roughly 80 functions that "need to be loaded on every Drupal request". As soon as bootstrap.inc gets included 37 new constants get defined.
From those 80 or so functions and 37 or so new constants only the drupal_bootstrap function is called with the value of the DRUPAL_BOOTSTRAP_FULL constant as an argument.
The short version of what is happening in this one function call is Drupal is told to start up (bootstrap) all of its mechanisms required to handle the page request. It loads configuration information, page caching system(s), database(s), session handling, translation system, modules, and everything else you can imagine (and things you might not have imagined) that are required to handle a page request.
The long version of what happens in this one function call is what many follow up posts in this series will be about. You'll have to come back for those.
Finally, the last line in index.php calls the function menu_execute_active_handler(). The short version of what this function does is to act like a telephone operator and direct or route your call to the appropriate function that can answer you.
It takes a look at the path of the requested URL (i.e. the parts after the domain name e.g. news/headlines/december) and figure out which function is responsible for handling requests for that path. Once menu_execute_active_handler() finds the function to call, it calls it. What happens at the point depends entirely on which function was called, but in most cases an html page is sent to the browser.
Once again the long version of what happens is left for another time.

Summary

And there you have it: Four lines of code and only two function calls. All you need to get a page out of Drupal. Sounds easy.
Next time I'll start looking in depth at the bootstrap process in bootstrap.inc and the drupal_bootstrap() function.
If you have any questions, suggestions or corrections just leave a comment. I truly appreciate the feedback.

Friday, April 17

Caching Data in Drupal 7

A Beginner's Guide to Caching Data in Drupal 7

Building complicated, dynamic content in Drupal is easy, but it can come at a price. A lot of the stuff that makes a site engaging can spell 'performance nightmare' under heavy load, thrashing the database to perform complex queries and expensive calculations every time a user looks at a node or loads a particular page.
One solution is to turn on page caching on Drupal's performance options administration page. That speeds things up for anonymous users by caching the output of each page, greatly reducing the number of DB queries needed when they hit the site. That doesn't help with logged in users, however: because page level caching is an all-or-nothing affair, it only works for the standardized, always-the-same view that anonymous users see when they arrive.
Eventually there comes a time when you have to dig in to your code, identify the database access hot spots, and add caching yourself. Fortunately, Drupal's built-in caching APIs and some simple guidelines can make that task easy.

The basics

The first rule of optimization and caching is this: never do something time consuming twice if you can hold onto the results and re-use them. Let's look at a simple example of that principle in action:
<?phpfunction my_module_function() {
 
$my_data = &drupal_static(__FUNCTION__);
  if (!isset(
$my_data)) {
   
// Do your expensive calculations here, and populate $my_data
    // with the correct stuff..
 
}
  return
$my_data;
}
?>

The important part to look at in this function is the variable named $my_data; we're initializing it with an odd-looking call to drupal_static(). The drupal_static() function is new to Drupal 7, and provides functions with a temporary "storage bin" for data that should stick around even after they're done executing. drupal_static() will return an empty value the first time we call it, but any changes to the variable will be preserved when the function is called again. That means that our function can check if the variable is already populated, and return it immediately without doing any more work. This pattern appears all over the place in Drupal -- including important functions like node_load(). Calling node_load() for a particular node ID requires database hits the first time, but the resulting information is kept in a static variable for the duration of the page load. That way, displaying a node once in a list, a second time in a block, and a third time in a list of related links (for example) doesn't require three full trips to the database.
In Drupal 6, these static variables were created using the PHP 'static' keyword rather than the drupal_static() function. It was also common to provide a $reset parameter on each function that used this pattern, giving modules that needed the freshest information a way to bypass the caching code. While that approach still works in Drupal 7, drupal_static() allows the process to be centralized. When modules need absolutely fresh data, they can call drupal_static_reset() to clear out any temporarily cached information.

Making it stick: Drupal's cache functions

You might notice that the static variable technique only stores data for the duration of a single page load. For even better performance, it's often possible to cache data in a more permanent fashion...
<?phpfunction my_module_function() {
 
$my_data = &drupal_static(__FUNCTION__);
  if (!isset(
$my_data)) {
    if (
$cache = cache_get('my_module_data')) {
     
$my_data = $cache->data;
    }
    else {
     
// Do your expensive calculations here, and populate $my_data
      // with the correct stuff..
     
cache_set('my_module_data', $my_data, 'cache');
    }
  }
  return
$my_data;
}
?>
This version of the function still uses the static variable, but it adds another layer: database caching. Drupal's APIs provide three key functions you'll need to be familiar with: cache_get(), cache_set(), and cache_clear_all(). Let's look at how they're used.
After the initial check of the static variable, this function looks in Drupal's cache for data stored with a particular key. If it finds it, $my_data is set to $cache->data and we're done. Combined with the static variable, future calls during this page request won't even need to call cache_get()!
If no cached version is found, the function does the actual work of generating the data. Then it saves it TO the cache so future requests will find it. The key that you pass in as the first parameter can by anything you choose, though it's important to avoid colliding with any other modules' keys. Starting the key with the name of your module is always a good idea.
The end result? A slick little function that saves time whenever it can -- first checking for an in-memory copy of the data, then checking the cache, and finally calculating it from scratch if necessary. You'll see this pattern a lot if you dig into the guts of data-intensive Drupal modules.

Keeping up to date

What happens, though, if the data that you've cached becomes outdated and needs to be recalculated? By default, cached information stays around until some module explicitly calls the cache_clear_all() function, emptying out your record. If your data is updated sporadically, you might consider simply calling cache_clear_all('my_module_data', 'cache') each time you save the changes to it. If you're caching quite a few pieces of data (perhaps versions of a particular block for each role on the site), there's a third 'wildcard' parameter:
<?php
cache_clear_all
('my_module', 'cache', TRUE); ?>
This clears out all the cache values whose keys start with 'my_module'.
If you don't need your cached data to be perfectly up-to-the-second, but you want to keep it reasonably fresh, you can also pass in an expiration date to the cache_set() function. For example:
<?php
cache_set
('my_module_data', $my_data, 'cache', time() + 360); ?>
The final parameter is a unix timestamp value representing the 'expiration date' of the cache data. The easiest way to calculate it is to use the time() function, and add the data's desired lifetime in seconds. Expired entries will be automatically discarded as they pass that date.

Controlling where cached data is stored

You might have noticed that cache_set()'s third parameter is 'cache' -- the name of the table that stores the default cache data. If you're storing large amounts of data in the cache, you can set up your own dedicated cache table and pass its name into the function. That will help keep your cache lookups speedy no matter what other modules are sticking into their own tables. The Views module uses that technique to maintain full control over when its cache data is cleared.
The easiest place to set up a custom cache table is in your module's install file, in the hook_schema() function. It's where all of the custom tables used by your module are defined, and you can even make use of one of Drupal's internal helper functions to simplify the process.
<?phpfunction mymodule_schema() {
 
$schema['cache_mymodule'] = drupal_get_schema_unprocessed('system', 'cache');
  return
$schema;
}
?>
Using the drupal_get_schema_unprocessed() function, the code above retrieves the definition of the System module's standard Cache table, and creates a clone of it named 'cache_mymodule'. Prefixing the name of custom cache tables with the word 'cache' is common practice in Drupal, and helps keep the assorted cache tables organized.
If you're really hoping to squeeze the most out of your server, Drupal also supports the use of alternative caching systems. By changing a single line in your site's settings.php file, you can point it to different implementations of the standard cache_set(), cache_get(), and cache_clear_all() functions. The most popular integration is with the open source memcached project, but other approaches are possible (such as a file-based cache or against PHP's APC). As long as you've used the standard Drupal caching functions, your module's code won't have to be altered.

Advanced caching with renderable content

In Drupal 7, "renderable arrays" are used extensively when building the contents of each page for display. Modules can define page elements like blocks, tables, forms, and even nodes as structured arrays; when the time comes to render the page to HTML, Drupal automatically uses the drupal_render() function to process them, calling the theme layer and other helper functions automatically. Some complex page elements, though, can take quite a bit of time to render into HTML. By adding a special #cache property onto the renderable element, you can instruct the drupal_render() function to cache and reuse the rendered HTML each time the page element is built.
<?php
$content
['my_content'] = array(
 
'#cache' => array(
   
'cid' => 'my_module_data',
   
'bin' => 'cache',
   
'expire' => time() + 360,
  ),
 
// Other element properties go here...);?>
The #cache property contains a list of values that mirror the parameters you would pass to the cache_get() and cache_set() if you were calling them manually. For more information on how caching of renderable elements works, check out the detailed documentation for the drupal_render() function on api.drupal.org.

A few caveats

Like all good things, it's possible to overdo it with caching. Sometimes, it just doesn't make sense -- if you're looking up a single record from a table, saving the result to a database cache is silly. Using the Devel module is a good way to spot the functions where caching will pay off: it can log the queries that are used on your site and highlight the ones that are slow, or the ones that are repeated numerous times on each page.
Other times, the data you're using will just be a bad fit for the standard caching system. If you need to join cached data in SQL queries, for example, cache_set()'s practice of string data as a serialized string will be a problem. In those cases, you'll need to come up with a solution that's specific to your module. VotingAPI maintains one table full of individual votes and another table full of calculated results (averages, sums, etc.) for quick joining when sorting and filtering nodes.
Finally, it's important to remember that the cache is not long term storage! Since other modules can call cache_clear_all() and wipe it out, you should never put something into it if you can't recalculate it again using the original source data.

SOURCE: www.lullabot.com

Tuesday, April 14

Print table of given number.

//Program to print table of given number
    #include<stdio.h>
    #include<conio.h>
    int main()
    {
     int n,k=1,m;
     clrscr();
     printf("Enter the number\n");
     scanf("%d",&n);
     while(k<11)
     {
       m=n*k;
       printf("%d*%d=%d\n",n,k,m);
       k++;
     }
   
      getch();
      return 0;
    }


To Run this Program Copy it in text editor and save as .c
Then double click on it and then it will get opened in your compiler.
Click on run.

Print table of the numbers from 1 to 10

//Program to print table of the numbers from 1 to 10
    #include<stdio.h>
    #include<conio.h>
    int main()
    {
      int row, col;
      clrscr();
      printf("Table of 1 to 10 is as\n");
      for(row=1;row<=10;row++)
      {
        for(col=1;col<=10;col++)
        {
          printf("%4d",row*col);
        }
        printf("\n");
      }
      getch();
      return 0;
    }


To Run this Program Copy it in text editor and save as .c
Then double click on it and then it will get opened in your compiler.
Click on run.

Wednesday, April 8

Free space on your smartphone or tablet.



You're in the park with your family and one of the kids does something unbelievably cute. You quickly grab your smartphone to take a video and ... "Not enough room."

A full smartphone or tablet can't take pictures, download music, add new apps, or even install operating system updates that contain important security fixes. You need to free up some space fast, and I can tell you how without losing any important information.


Clear out apps

Apps can make your phone or tablet do some useful and amazing things. I have plenty of great apps from games and utilities to security and photo editors on my site, but they can fill up your available space before you realize it. You probably don't need every one of those latest-addicting-must-have game apps, or three to-do list apps.

In Apple, iOS 8, go to Settings >> General >> Usage>> Manage Storage. For iOS 7 and earlier, it's just Settings>>General>>Usage. Here you'll see a list of apps and how much space they use. This helps you make an informed decision about where to go fat-trimming. To delete an app you don't want, simply tap its name. Then tap the "Delete App" button on the next screen.

In Android, go to Settings >> Applications (Settings >> Application Manager on some gadgets). Swipe left until you end up on the "Downloaded" tab. Here you'll see a list of apps you've downloaded and how much space they use. To remove an app, just tap the name and then tap the "Uninstall" button. Start removing the apps you no longer use, then take a look at the largest apps that are left and think about how much you really need them.

With Android, you can also go to Settings >> Storage to get a detailed breakdown of how much space you have and what's using it, such as Apps, Pictures, Audio, Downloads, etc. Tapping a category will take you to the relevant area of Android. So, tapping on "Apps" will take you to the Application Management screen while tapping "Pictures" will take you to your photo gallery app.

In Windows Phone 8, go to the Start screen and swipe left to get the App list. Tap and hold an app and then tap "Uninstall." Tap "Yes," and the app will go away.


Organize your photos and videos


Smartphone cameras make it easy to snap dozens of pictures of that family outing, friendly get-together or just a funny random moment you see while out and about. Do that every couple of days for a year or two and it's no wonder your phone is full.

Take a look through your phone's camera app. Are there any accidental photos, such as photos of the floor, sky or doorway you can delete? Are most of your good photos already posted to social media?

To free up space, you can transfer and organize photos and videos on your home computer or online storage using programs like iPhoto, Dropbox or Picasa. With Android, you might also be able to plug your gadget into your computer and drag the files directly and then delete them from your gadget.

Your camera isn't just for photos; it can shoot video, too. A dozen one-minute videos you shot at birthday parties and other celebrations can take up gigabytes of space. You'll definitely want to move these over to a computer to free up space. You can also upload them to an online storage site like Dropbox or Google Drive, or put them on a video-sharing site like YouTube. If you don't want everyone seeing them, mark them as private so only people you choose can see them.


Stream music and movies

Your smartphone or tablet works great as a media player for music and videos, but those take up a lot of space. Instead of loading your entire media library on your gadget, consider using a cloud streaming service instead.

For iPhones and iPads, Apple's iTunes Match will hold your entire music library in the cloud and stream to you the songs you want. Sure it costs $25 a year, but that's much less than spending hundreds on a new gadget with more storage that will just fill up again.

Google Play Music is another solution. This service can hold your entire music library, including songs from iTunes, and stream your music to you whenever you want. The only space it takes up is for the Google Play Music app, not each individual song or album. There's also an option to get a subscription to add new music and movies, much like iTunes.

Of course that's not your only option for streaming music instead of storing it. Click here to explore more streaming music options that give you a nearly infinite music library.

When it comes to movies, just five feature-length HD movies will take up 15GB or more of space. That's all the space available on many gadgets and a large chunk of others.

If you purchased movies via iTunes, Amazon or Google Play, those are available in the cloud and you can stream them using each service's respective app. Don't forget you can also stream movies from Netflix, Hulu and other services using their apps.

Unless you're traveling and you won't have Wi-Fi access, you don't need to store movies on your gadget. If you are traveling, though, be sure to check out the VLC app (Android or iOS, Free) that can play any movie file. It cuts down on the headaches of making sure your movies are in the right format.

SOURCE: usatoday.com

Friday, April 3

SSL basic fundamentals.



Your PC contacts a Google server, which returns a certificate. Your computer uses that certificate to encrypt a data session. The server confirms that the key is good and establishes the secure session with your PC. When certificates are signed by third parties, it allows the false server to execute a classic man-in-the-middle attack.


In a man-in-the-middle attack, an intervening certificate authority can pretend to be the genuine issuing authority, particularly if the intermediate certificate company is given the full authority of an issuing CA, which is what happened here. That’s not supposed to happen, as Google points out — the original Certificate Authority, CNNIC (the Chinese Internet Network Information Center) should never have given such authority to MCS Holding in the first place.






SOURCE: extremetech.com