Monday, July 22, 2013

Facebook Canvas Tutorial

Creating your App

Start by visiting the App Dashboard. If you haven't created an application before you will be prompted to register. Note that you have to verify your Facebook account to create apps on Facebook.

Configuring your App

Apps on Facebook are loaded into the Canvas section of the Canvas Page. The Canvas is quite literally a blank canvas within Facebook on which to run your app. You populate the Canvas by providing a Canvas URL that contains the HTML, JavaScript and CSS that make up your app. When a person using your app requests the Canvas Page, we load the Canvas URL within an iframe on that page. This results in your app being displayed within the standard Facebook chrome.
For example, suppose that you have a web app available at //www.example.com/canvas. This is your Canvas URL. When you set up your app on Facebook, you must specify a Canvas Page name that is appended to //apps.facebook.com/. You can specify this by entering a unique name in the App Namespace field through the App Dashboard. In this example, we'll useyour_app as the Canvas Page name. When someone using your app navigates to //apps.facebook.com/your_app, they'll see the contents of www.example.com/canvas loaded inside of Facebook.com.
Note that www.example.com/canvas cannot forward to another URL via HTTP redirect responses, for example response code 301, but has to return the response directly.
Once you've created a Facebook app, go to the App on Facebook section and specify a Canvas and Secure Canvas URL:
 Because your app is loaded in the context of Facebook, you must be aware of certain size constraints when designing your user interface. You can manage settings for the size of your iframe in the Dev App on Facebook settings.

Canvas width

You can set your Canvas Width to Fixed (760px), the default setting, which makes your app have a fixed width of 760 pixels. You can also set your width to Fluid, which means that we set the iframe width to 100%. Your content will then be left-aligned and resize to fill the page as the user changes the width of their browser.

Canvas height

You can set the Canvas height to Fluid, the default setting, in which case the iframe height is set to 100% which means that it grows the fill the page and shows scroll-bars if your content exceeds the height of the page.
You can also set the height to Settable, in which case the height of the Canvas defaults to 800 pixels. You can change the height of the iframe by calling the FB.Canvas.setSize() method to fit your content. You can also call FB.Canvas.setAutoGrow() to enable Auto-grow functionality where you poll for the height of your content and grow the height of the parent iframe to match accordingly. Note these methods only work with Canvas height set to Settable.

Configuring for App Center

Once you have configured your app for Canvas, the next step is to configure the App Center settings. App Center is the central location for people to discover and try out new apps and a primary source of installs. Configuring these settings will allow you to customize your App Detail page to display your app description, icons, screenshots and other relevant promotional materials in the Facebook App Center. For more information on this step, see the App Center docs.

Authorization

In order to create a personalized user experience, Facebook sends your app information about the user. This information is passed to your Canvas URL using HTTP POST within a single signed_request parameter which contains a base64url encoded JSON object.
When someone first accesses your app, the signed_request parameter contains a limited amount of user data:
NameDescription
userA JSON array containing the locale string, country string and the age object (containing the min and max numbers of the age range) for the current person using the app.
algorithmA JSON string containing the mechanism used to sign the request.
issued_atA JSON number containing the Unix timestamp when the request was signed.
In order for you to gain access to all the information available to your app by default (like Facebook ID), people must authorize your app. We recommend that you use the Login Dialog for apps on Facebook.com. You invoke this dialog by redirecting the browser to the following URL (replacing the YOUR_APP_ID and YOUR_CANVAS_PAGE with the correct values found in the App Dashboard):
https://www.facebook.com/dialog/oauth?
client_id=YOUR_APP_ID&redirect_uri=YOUR_CANVAS_PAGE
 
Because of the way iframes are currently loaded for apps on Facebook.com, it's important that you navigate the top window of the browser to the Login dialog. Many apps do this by sending a script fragment to the browser setting the top.location.hrefproperty to the dialog URL. Please see the PHP example at the end of this section for an example.
By default, people using your app are asked to authorize the app to access their public profile. If your app needs more than this information to work correctly, you must request specific permissions from people. This is accomplished by adding a scope parameter to the Login dialog request followed by comma separated list of the required permissions. The following example shows how to ask for access to someone's email address and News Feed:
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID &redirect_uri=YOUR_CANVAS_PAGE&scope=email,read_stream

A full list of permissions is available in our permissions reference. There is a strong inverse correlation between the number of permissions your app requests and the number of users that will allow those permissions. The greater the number of permissions you ask for, the lower the number of users that will grant them; so we recommend that you only request the permissions you absolutely need for your app.
If people press click Don't Allow, your app is not authorized. The Login dialog redirects (via HTTP 302) to the URL you passed in the redirect_uri parameter with the following error information:
http://YOUR_CANVAS_PAGE?error_reason=user_denied&
error=access_denied&error_description=The+user+denied+your+request
If people click Allow, your app is authorized. The Login dialog redirects (via HTTP 302) to the URL you passed in the redirect_uriparameter. After the app has been authorized, the signed_request parameter will contain the following information on subsequent requests:
NameDescription
userA JSON array containing the locale string, country string and the age object (containing the min and maxnumbers of the age range).
algorithmA JSON string containing the mechanism used to sign the request.
issued_atA JSON number containing the Unix timestamp when the request was signed.
user_idA JSON string containing the person's Facebook user identifier (UID).
oauth_tokenA JSON string that you can pass to the Graph API.
expiresA JSON number containing the Unix timestamp when the oauth_token expires.
The following PHP example demonstrates how to access the signed_request parameter and prompt the user to authorize your app:
     $app_id = "YOUR_APP_ID";

     $canvas_page = "YOUR_CANVAS_PAGE_URL";

     $auth_url = "//www.facebook.com/dialog/oauth?client_id=" 
            . $app_id . "&redirect_uri=" . urlencode($canvas_page);

     $signed_request = $_REQUEST["signed_request"];

     list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

     $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);

     if (empty($data["user_id"])) {
            echo("<script> top.location.href='" . $auth_url . "'</script>");
     } else {
            echo ("Welcome User: " . $data["user_id"]);
     } 
You can learn more about the signed_request parameter including how to validate the signature in our Signed Request Referenceguide. Several of our SDKs, such as the JavaScript SDK and the PHP SDK make authentication and authorization straightforward.
Once someone has authorized your application, you can start using the Graph API to access that person's profile information as well as friend data.

Social channels

Facebook provides a number of different ways for people to share with their friends from your app. We call these social channels. Your app can publish directly to a person's News Feed, send Requests to their friends and leverage our automatic channels.

Feed

The News Feed is shown immediately to people when they go to Facebook, making it core to the Facebook experience. Your app can post to the News Feed, that is, share something with other people, by using the Feed dialog. The following example shows how to display this dialog within your Canvas Page:
$app_id = "YOUR_APP_ID";

         $canvas_page = "YOUR_CANVAS_PAGE_URL";

         $message = "Apps on Facebook.com are cool!";

         $feed_url = "//www.facebook.com/dialog/feed?app_id=" 
                . $app_id . "&redirect_uri=" . urlencode($canvas_page)
                . "&message=" . $message;

         if (empty($_REQUEST["post_id"])) {
            echo("<script> top.location.href='" . $feed_url . "'</script>");
         } else {
            echo ("Feed Post Id: " . $_REQUEST["post_id"]);
         }
 

Requests

Requests are a great way to enable people to invite their friends to your app or to take specific action like accept a gift or help complete a task. Your app can send requests by using the Request dialog. The following example shows how to display this dialog within your Canvas Page:
$app_id = "YOUR_APP_ID";

         $canvas_page = "YOUR_CANVAS_PAGE_URL";

         $message = "Would you like to join me in this great app?";

         $requests_url = "//www.facebook.com/dialog/apprequests?app_id=" 
                . $app_id . "&redirect_uri=" . urlencode($canvas_page)
                . "&message=" . $message;

         if (empty($_REQUEST["request_ids"])) {
            echo("<script> top.location.href='" . $requests_url . "'</script>");
         } else {
            echo "Request Ids: ";
            print_r($_REQUEST["request_ids"]);
         }
 
If you prefer to have your app send requests directly to people 
(that is, to make an app-generated request), you post a request to 
the apprequest connection of the User Graph object:
 $app_id = YOUR_APP_ID;
  $app_secret = YOUR_APP_SECRET;

  $token_url = "//graph.facebook.com/oauth/access_token?" .
    "client_id=" . $app_id .
    "&client_secret=" . $app_secret .
    "&grant_type=client_credentials";

  $app_access_token = file_get_contents($token_url);

  $user_id = THE_CURRENT_USER_ID;

  $apprequest_url ="//graph.facebook.com/" .
    $user_id .
    "/apprequests?message='INSERT_UT8_STRING_MSG'" . 
    "&data='INSERT_STRING_DATA'&"  .   
    $app_access_token . "&method=post";

  $result = file_get_contents($apprequest_url);
  echo("App Request sent?", $result);
The message parameter is a UTF-8 string that describes the request. The data parameter is a string that the app can use to store any relevant data in order to process the request.
Once a new request is sent to someone, they see it as a counter on the app bookmark, and it also increments the counter next to the appropriate Dashboard.
If you would like to send an app-generated request to more than one person, you can use the ids parameter (see Selection in the Graph API) and enter a comma delimited string of people's IDs:
POST https://graph.facebook.com/apprequests?ids=user_id1,user_id2<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&message=Hello&access_token=APP ACCESS TOKEN
For more details about our channels, see the Social Channels core concept document.

Samples and next steps

If you're interested in building Facebook games, see our Games Tutorial, which walks you through implementing authorization, invites, feed stories, scores and achievements. It's a great place to get started.
This was a quick survey of the major integration points available to Facebook apps. Beyond these features, you can leverage all the different pieces of Facebook Platform including social plugins and the Graph API within your app. See Overview of the Facebook Platform for a complete summary of Facebook developer tools.
Please see our Integrating with Canvas for additional advanced best practices when integrating with Canvas.

Sunday, July 21, 2013

Sending E-mails in php using yahoo smtp

<?php 
require 'Mail/class.phpmailer.php';

$mail = new PHPMailer; 
$mail->IsSMTP(); // Set mailer to use SMTP  
$mail->Host 'plus.smtp.mail.yahoo.com'// Specify main and backup server 
$mail->SMTPAuth   true// Enable SMTP authentication  
$mail->Username   'yourname@yahoo.com'// SMTP username  
$mail->Password   'xxxxxxxxxxxxxxxxxxxxx'// SMTP password  
$mail->SMTPSecure 'ssl'// Enable encryption, 'ssl', 'tls' etc...  
$mail->Port       465// or 587 
$mail->Timeout    60// Message sent timeout  
$mail->From       'yourname@yahoo.com'; 
$mail->FromName   'Pritom Kumar Mondal'; 
// Add a recipient 
$mail->AddAddress('yourname@gmail.com''Pritom GMAIL'); 
$mail->AddAddress('yourname@yahoo.com''Pritom YAHOO'); 
$mail->AddReplyTo('yourname@gmail.com''Reply To');

$mail->AddCC('yourname@gmail.com');
$mail->AddBCC('yourname@gmail.com'); 
$mail->WordWrap 50// Set word wrap to 50 characters

// Add attachments 
 

$mail->AddAttachment('C:\\Contact List.csv''pritom.csv'); // Optional name 
$mail->IsHTML(true); // Set email format to HTML  
$mail->Subject 'E-mail sent using yahoo smtp'; 

$mail->Body    'This is the HTML message body <b>in bold!</b>, sent using yahoo smtp';

$mail->AltBody 'This is the body in plain text for non-HTML mail clients';

if (!
$mail->Send()) {
    echo 
'Message could not be sent.';
    echo 
'Mailer Error: ' $mail->ErrorInfo;
    exit;
}
echo 
'Message has been sent';?>

Best way to load (with variables) multiple php files content into a string

index.php
<?php
$fileName 
'output_file.php'; 

$content  '';
for (
$i 0$i 10$i++) {
    
$var1 "variable: 1 value is: " $i;
    
$var2 "variable: 2 value is: " $i 10;

    /* OR write: extract($vars); if you have additional parameters. */
    
ob_start();
    include 
$fileName;
    
$content .= ob_get_contents();
    
ob_end_clean();
}
echo 
$content;?>


output_file.php
<div>
    <div>var1 == <?php echo $var1; ?></div>
    <div>var2 == <?php echo $var2; ?></div>
</div>
<br/><br/>


And finally the output is:
<div>
    <div>var1 == variable: 1 value is: 0</div>
    <div>var2 == variable: 2 value is: 0</div>
</div>
<br/><br/>

<div>
    <div>var1 == variable: 1 value is: 1</div>
    <div>var2 == variable: 2 value is: 10</div>
</div>
<br/><br/>

<div>
    <div>var1 == variable: 1 value is: 2</div>
    <div>var2 == variable: 2 value is: 20</div>
</div>
<br/><br/>

<div>
    <div>var1 == variable: 1 value is: 3</div>
    <div>var2 == variable: 2 value is: 30</div>
</div>
<br/><br/>

<div>
    <div>var1 == variable: 1 value is: 4</div>
    <div>var2 == variable: 2 value is: 40</div>
</div>
<br/><br/>

<div>
    <div>var1 == variable: 1 value is: 5</div>
    <div>var2 == variable: 2 value is: 50</div>
</div>
<br/>

<br/>
<div>
    <div>var1 == variable: 1 value is: 6</div>
    <div>var2 == variable: 2 value is: 60</div>
</div>
<br/><br/>

<div>
    <div>var1 == variable: 1 value is: 7</div>
    <div>var2 == variable: 2 value is: 70</div>
</div>
<br/><br/>

<div>
    <div>var1 == variable: 1 value is: 8</div>
    <div>var2 == variable: 2 value is: 80</div>
</div>
<br/><br/>

<div>
    <div>var1 == variable: 1 value is: 9</div>
    <div>var2 == variable: 2 value is: 90</div>
</div>
<br/><br/>

Saturday, July 20, 2013

Send HTML and TEXT emails with PHP, PHPMailer, Attachments

If you are developing applications using PHP and you need to send email you can use the PHPMailer() class in PHP. Using a publicly available SMTP server to send the email is much easier than trying to setup your own email server. The following code snippet shows the various settings for the mailer. The code assumes that you have PHP 5.x version and you have class.phpmailer.php file in the include directory. Google uses ssl for the smtp connection. In order for this example to work with google smtp server, you need to enable ssl in your php.ini file by adding a line that says extension=php_openssl.dll

If you are not sure of the exact location of the php.ini file and you are using xampp, you can find the location of the php.ini file by navigating to http://localhost/xampp/phpinfo.php on your browser and look for the text "Loaded Configuration File". Once you find the file, edit it and look for the text "extension=php_openssl.dll". If the text is not found in your file, add a new line at the end of the file with the above text.
 
<?php
require 'Mail/class.phpmailer.php'; 
$mail = new PHPMailer; 
$mail->IsSMTP(); // Set mailer to use SMTP 
$mail->Host       'smtp.gmail.com'// Specify main and backup server 
$mail->SMTPAuth   true// Enable SMTP authentication 
$mail->Username   'username@gmail.com'// SMTP username 
$mail->Password   'XXXXXX'// SMTP password 
$mail->SMTPSecure 'ssl'// Enable encryption, 'ssl', 'tls' etc...
$mail->Port       465// or 587 
$mail->Timeout    60// Message sent timeout 
$mail->From       'username@gmail.com'; 
$mail->FromName   'Pritom K Mondal';

// Add a recipient
$mail->AddAddress('username@gmail.com''Pritom GMAIL'); 
$mail->AddAddress('username@yahoo.com''Pritom YAHOO');
$mail->AddAddress("username@domain.com""Pritom Domain"); 

$mail->AddReplyTo('username@gmail.com''Reply To');
$mail->AddCC('username@gmail.com'); 
$mail->AddBCC('username@gmail.com'); 
$mail->WordWrap 50// Set word wrap to 50 characters 

// Add attachments
$mail->AddAttachment('C:\\pritom.zip'); 
$mail->AddAttachment('C:\\Contact List.csv''pritom.csv'); // Optional name 

$mail->IsHTML(true); // Set email format to HTML 
$mail->Subject 'Here is the subject'; 
$mail->Body    'This is the HTML message body <b>in bold!</b>';
$mail->AltBody 'This is the body in plain text for non-HTML mail clients';

if (!
$mail->Send()) {
    echo 
'Message could not be sent.';
    echo 
'Mailer Error: ' $mail->ErrorInfo;
    exit;
}

echo 'Message has been sent'; 
?>

Download PHPMailer from here
https://github.com/Synchro/PHPMailer 

Thursday, July 18, 2013

Config default and customize Font in CKEDITOR

Selecting the default font name in drop-down.

config.font_defaultLabel = 'Arial';  /* Enter your favorite font name here */

And make your own css file and link it to creditor as following in config.js file:

config.contentsCss = 'css/mine.css';

The fonts in the font menu are configured using CKEDITOR.config.font_names:

config.font_names = CREDITOR.config.font_names + 
    'Arial/Arial, Helvetica, sans-serif;' +
    'Times New Roman/Times New Roman, Times, serif;' +
    'Verdana';
 
 

config.js

CKEDITOR.editorConfig = function( config )
{
    // Define changes to default configuration here. For example: 
    //config.language = 'fr'; 
    config.uiColor = '#FCFFEB'; 
    config.enterMode = CKEDITOR.ENTER_BR; 
    config.extraPlugins = "imageUploader,tableoperations";
    config.pasteFromWordRemoveFontStyles = false;
    config.disableNativeSpellChecker = false;
    config.font_defaultLabel = "Lucida Sans Unicode";
    config.contentsCss = BASE_URL + 'js/common/ckeditor/mine.css';
}; 

Wednesday, July 17, 2013

PHP: Recursively convert an object to an array

When pulling in array from outside data sources you often receive an array back. The problem is that sometimes even though you know you should have an array your application does not and therefore assigns it to the stdObject object, which of course is nothing. To make it usable you must convert it back into an array. With a simple object that may be as simple as a cast, but when you are working with large complex datasets that may be several layers deep you need to make sure you get at all of them. Enter beautiful recursion. After playing with PHPs array_walk_recursive() for a bit I hit on a custom recursive function that does exactly the job. Simply pass it your object and it will munch away at it trying to convert it into a PHP array. Take a gander at the code for this below.
<?php 
function object_to_array($obj)
{
    if (
is_object($obj)) {
        
$obj = (array) $obj;
    }
    if (
is_array($obj)) {
        
$new = array();
        foreach (
$obj as $key => $val) {
            
$new[$key] = object_to_array($val);
        }
    } else {
        
$new $obj;
    }
    return 
$new;
}
?>

http://ben.lobaugh.net/blog/567/php-recursively-convert-an-object-to-an-array

Tuesday, July 16, 2013

php preg_replace

Example # Using backreferences followed by numeric literals
<?php
$string 
'April 15, 2003';$pattern '/(\w+) (\d+), (\d+)/i';

$replacement '${1}1,$3';
echo 
preg_replace($pattern$replacement$string);?>
The above example will output:
April1,200

Example # Using indexed arrays with preg_replace()
<?php
$string 
'The quick brown fox jumped over the lazy dog.'; 

$patterns = array(); 
$patterns[0] = '/quick/';
$patterns[1] = '/brown/'; 
$patterns[2] = '/fox/'; 
$replacements = array();
$replacements[2] = 'bear'; 
$replacements[1] = 'black'; 
$replacements[0] = 'slow';
echo 
preg_replace($patterns$replacements$string);?>
The above example will output:
The bear black slow jumped over the lazy dog.

Example # Strip whitespace
This example strips excess whitespace from a string.
<?php
$str 
'foo   o';$str preg_replace('/\s\s+/'' '$str);// This will be 'foo o' nowecho $str;?>
Example # Using the count parameter
<?php
$count 
0;

echo 
preg_replace(array('/\d/''/\s/'), '*''xp 4 to', -$count);
echo 
$count//3?>
The above example will output:
xp***to
3

If you would like to remove a tag along with the text inside it then use the following code. 

<?php 
preg_replace
('/(<tag>.+?)+(<\/tag>)/i', '', $string); ?> 
example 
<?php $string='<span class="normalprice">55 PKR</span>'; ?> 
<?php 
$string 
= preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string); ?> 
This will results a null or empty string. 

<?php 
$string
='My String <span class="normalprice">55 PKR</span>'; 
$string = preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string); ?>