Wednesday, July 12, 2017

How to download excel file using phpExcel core and joomla

its easy way to download php with mysql data into custom excel file using phpExcel library.

Please check below code step by step :

download PHPExcel library



public function downloadPHPexcel()
{  

require_once (JPATH_SITE.'/phpexcel/Classes/PHPExcel.php');
require_once (JPATH_SITE.'/phpexcel/Classes/PHPExcel/IOFactory.php');
ini_set('memory_limit','2048M');      

$jinput = JFactory::getApplication()->input;
$buildername = $jinput->get('buildername', '', 'STRING');
$date1 = $jinput->get('date1', '', 'STRING');
$date2 = $jinput->get('date2', '', 'STRING');
$db = JFactory::getDbo();
$query  = $db->getQuery(true);      
$query ="SELECT *
FROM #__splms_videohit_track AS
courseTitle ASC";

$db->setQuery($query);
$isbtotalResult = $db->loadAssocList();
 
// Set title and meta data//
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("Creator")
            ->setLastModifiedBy("Modified")
            ->setTitle("Title")
            ->setSubject("Report")
            ->setDescription("ISB Report")
            ->setKeywords("report")
            ->setCategory("Report");
$rowNo = 1;      


$objPHPExcel->getActiveSheet()->setTitle(strtoupper($buildername.'_Members'));
// Set Header Column name//
$objPHPExcel->getDefaultStyle()->getFont()->setName('Calibiri')->setSize(11);
$objPHPExcel->getActiveSheet()->mergeCells('A1:F1');
$objPHPExcel->getActiveSheet()->getStyle('A1:F1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);      
$objPHPExcel->getActiveSheet()->getStyle('A1:F1')->getFont()->setBold(true);      
$objPHPExcel->getActiveSheet()->setCellValue('A'.$rowNo, 'Bk® Confidential');
$rowNo=3;      
$objPHPExcel->getActiveSheet()->getStyle('A3:F3')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->setCellValue('A'.$rowNo, 'Course Title');
$objPHPExcel->getActiveSheet()->setCellValue('B'.$rowNo, 'Registrant Name');
$objPHPExcel->getActiveSheet()->setCellValue('C'.$rowNo, 'Registrant Email');
$objPHPExcel->getActiveSheet()->setCellValue('D'.$rowNo, 'Register Date');

$objPHPExcel->getActiveSheet()->setAutoFilter('A3:D3');
//foreach loop for data get
$rowNo++;
foreach($isbtotalResult as $isbResultDetail){
     
   $objPHPExcel->getActiveSheet()->setCellValue('A'.$rowNo, $isbResultDetail['courseTitle']);
   $objPHPExcel->getActiveSheet()->setCellValue('B'.$rowNo, $isbResultDetail['name']);      
   $objPHPExcel->getActiveSheet()->setCellValue('C'.$rowNo, $isbResultDetail['email']);
   $objPHPExcel->getActiveSheet()->setCellValue('D'.$rowNo, $isbResultDetail['redate']);

   $rowNo++;
}
//for loop end      
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
for( $i='C'; $i<= 'D'; $i++ ){
   $objPHPExcel->getActiveSheet()->getColumnDimension($i)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->getStyle('A'.$colHeder)->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('B'.$colHeder)->getAlignment()->setWrapText(true);

$styleArray = array(
 'borders' => array(
     'allborders' => array(
 'style' => PHPExcel_Style_Border::BORDER_THIN
     )
 )
);
$rowNo = $objPHPExcel->getActiveSheet()->getHighestRow();
$objPHPExcel->getActiveSheet()->getStyle(
   'A1:' .
   $objPHPExcel->getActiveSheet()->getHighestColumn() .
   ($rowNo-1)
)->applyFromArray($styleArray);      


$reportFormat    = 'xlsx';
$year  = date('Y',strtotime($date1));
$Month = date('M',strtotime($date1));
$fileName         = 'My_Company_Engagement_Report_'.$Month.'_'.$year.'.'.$reportFormat;
$csvfileName = $fileName;
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->setPreCalculateFormulas(true);
$objWriter->setIncludeCharts(TRUE);
header("Content-Description: File Transfer");
header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=".$csvfileName);
header("Content-Transfer-Encoding: binary");
header("Expires: 0");
header("Cache-Control: must-revalidate");
header("Pragma: public");
$objWriter->save('php://output');
exit;
}

finally did then call the function : downloadPHPexcel();

Tuesday, July 11, 2017

How to configure PHP with Mongodb and sample

Hi All,

It`s simple as mysql db configuration , do not worry about it , please follow below step to run demo application using mango db.

Step ->download  For window enable the driver "extension=mongo.so" 

configure for Ubuntu 14.04, : run "sudo apt-get install php5-mongo "

Step 2 : Download the sample PHP with mongo crud application

Step 3 : Extract CRUD folder into you xampp directory or /var/www/html/

finally run your sample : http://localhost/php-mongodb-crud

hope it will help you :) Enjoy Guys


Some of the below mongodb commands

Please read commands from official mongodb site 

Saturday, January 21, 2017

How to silently or offline post content to users wall Twitter [Solved]

How to silently post share into  Twitter user wall following below  instruction. its difficult if you might be you are going wrong direction . do not worry for this please follow step by step.

Step1- Dowonload Twitter Auth here

Step2-> Create a project folder in xampp/htdoc/TwSilentPost

1. Then create config.php within project folder

<?php
#####################config.php#######################
define('CONSUMER_KEY', 'XXXXXX');
define('CONSUMER_SECRET', 'XXXXXXXXX');
define('OAUTH_CALLBACK', 'http://localhost/TwSilentPost/process.php');
?>

Step2-> Go to Twitter App login create app and input all required information against app

Callback URL :  http://localhost/TwSilentPost/process.php



Step3->create process.php and paste below code

<?php
#######################process.php###############################
session_start();
include_once("config.php");
include_once("inc/twitteroauth.php");
$hostName = 'http://'.$_SERVER['HTTP_HOST'];

if(isset($_REQUEST['oauth_token']) && $_SESSION['token']  !== $_REQUEST['oauth_token']) {

//If token is old, distroy session and redirect user to index.php
session_destroy();
header('Location: index.php');

}elseif(isset($_REQUEST['oauth_token']) && $_SESSION['token'] == $_REQUEST['oauth_token']) {

//Successful response returns oauth_token, oauth_token_secret, user_id, and screen_name
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['token'] , $_SESSION['token_secret']);
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);


if($connection->http_code == '200')
{

//Redirect user to twitter
$_SESSION['status'] = 'verified';
$_SESSION['request_vars'] = $access_token;


$oauth_token = $_SESSION['request_vars']['oauth_token'];
$oauth_token_secret = $_SESSION['request_vars']['oauth_token_secret'];
###############################store auth token and auth secret key in Database table######
##INSTER TABLE (userid,TwAtuhToken,TwAuthSecreet)values(123,$oauth_token,$oauth_token_secret);
##################################################################

header('Location: success_msg.php');
}else{
die("error, try again later!");
}

}else{

if(isset($_GET["denied"]))
{
header('Location: index.php');
die();
}

//Fresh authentication
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);

//Received token info from twitter
$_SESSION['token'] = $request_token['oauth_token'];
$_SESSION['token_secret'] = $request_token['oauth_token_secret'];

//Any value other than 200 is failure, so continue only if http code is 200
if($connection->http_code == '200')
{
//redirect user to twitter
$twitter_url = $connection->getAuthorizeURL($request_token['oauth_token']);
header('Location: ' . $twitter_url);
}else{
die("error connecting to twitter! try again later!");
}
}
?>

Step4->Create index.php

<?php
##################index.php########################
echo '<a href="process.php"><img src="images/sign-in-with-twitter.png" width="151" height="24" border="0" /></a>';
?>


Step5-> create postTw.php file for share content to user wall
<?php
##############################postTw.php########################
include_once("config.php");
include_once("inc/twitteroauth.php");

$statusText="hey, this is test.bikash";
$twitter_oauth_token = get access token from db
$twitter_oauth_token_secret           = get access secret key from db
if($twitter_oauth_token_secret!='' && $twitter_oauth_token!='')
{
             $connection = new TwitterOAuth(CONSUMER_KEY,                       CONSUMER_SECRET, $twitter_oauth_token, $twitter_oauth_token_secret);
            $my_update = $connection->post('statuses/update',               array('status' => $statusText));
}



?>
Out put in Twitter wall like, Hope it will help you, please comment if you have any question on this.




Tuesday, January 17, 2017

How to silently or offline post content to user wall Linkedin[Solved] ?

Hey Guys,

I had lot of research for silent post into LinkedIn user wall and company page , finally I have integrated as custome the solution and and get long live access token of user/page from Linked to share their user wall/page wall.

Below are the step to post LinkedIn

Step1 -> Login to LinkedIn developer account create app
Step 2 -> Download LinkedIn API 


#######################LinkedIn.OAuth2.class.php#################
<?php

require_once('OAuth2.class.php');

class LinkedInOAuth2 extends OAuth2 {

public function __construct($access_token=''){
$this->access_token_url = "https://www.linkedin.com/uas/oauth2/accessToken";
$this->authorize_url = "https://www.linkedin.com/uas/oauth2/authorization";
parent::__construct($access_token);
$this->access_token_name='oauth2_access_token';
}

public function getAuthorizeUrl($client_id,$redirect_url,$scope=''){
$additional_args = array();
if($scope!=''){
if(is_array($scope)){
$additional_args['scope']=implode(" ",$scope);
$additional_args['scope'] = $additional_args['scope'];
}else{
$additional_args['scope'] = $scope;
}
}
$additional_args['state'] = md5(time());
return parent::getAuthorizeUrl($client_id,$redirect_url,$additional_args);
}

public function getAccessToken($client_id="", $secret="", $redirect_url="", $code = ""){
$result = parent::getAccessToken($client_id, $secret, $redirect_url, $code);
$result = json_decode($result,true);
if(isset($result['error'])){
$this->error = $result['error'].' '.$result['error_description'];
return false;
}else{
$this->access_token = $result['access_token'];
return $result;
}
}

public function getProfile(){
$params=array();
$fields = array(
'current-status',
'id',
'picture-url',
'first-name',
'last-name',    
'public-profile-url',
'num-connections',
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/people/~:({$request})";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getUserProfile($user_id){
$params=array();
$fields = array(
'current-status',
'id',
'picture-url',
'first-name',
'last-name',    
'public-profile-url',
'num-connections',
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/people/".$user_id.":({$request})";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getConnections(){
$params=array();
$params['url'] = "https://api.linkedin.com/v1/people/~/connections";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getGroups(){
$fields = array(
'group:(id,name)',
'membership-state',
'show-group-logo-in-profile',
'allow-messages-from-members',
'email-digest-frequency',    
'email-announcements-from-managers',
'email-for-every-new-post'
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/people/~/group-memberships:({$request})";
$params['method']='get';
$params['args']['format']='json';
$params['args']['count']=200;
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getGroup($group_id=""){
if(!$group_id) return false;
$fields = array(
'id',
'small-logo-url',
'large-logo-url',
'name',
'short-description',
'description',
'site-group-url',
'num-members'
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/groups/".$group_id.":({$request})";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getCompanies(){
$fields = array(
'id',
'name'
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/people/~:(first-name,positions:(company:({$request})))";
$params['method']='get';
$params['args']['format']='json';
$params['args']['count']=100;
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getCompany($company_id=""){
if(!$company_id)return false;
$fields = array(
'id',
'name',
'website-url',
'square-logo-url',
'logo-url',
'blog-rss-url',
'description',
'num-followers'
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/companies/".$company_id.":({$request})";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getAdminCompanies(){
$fields = array(
'id',
            'name'
);
$request = join(',',$fields);

$params['url'] = "https://api.linkedin.com/v1/companies:({$request})";
$params['method']='get';
$params['args']['format']='json';
$params['args']['count']=100;
$params['args']['is-company-admin']='true';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getFollowedCompanies(){
$fields = array(
'id',
'name'
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/people/~/following/companies:({$request})";
$params['method']='get';
$params['args']['format']='json';
$params['args']['count']=200;
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getStatuses($self = false, $start=0,$count = 20){
$params['url'] = "https://api.linkedin.com/v1/people/~/network/updates";
$params['method']='get';
$params['args']['format']='json';
if($start != 0 )$params['args']['start']=$start;
if($count != 0 )$params['args']['count']=$count;
if($self){
$params['args']['scope']='self';
}
$params['args']['type']='SHAR';
$params['args']['order']='recency';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getUserStatuses($user_id, $self = true, $start=0,$count = 20){
$params['url'] = "https://api.linkedin.com/v1/people/id=".$user_id."/network/updates";
$params['method']='get';
$params['args']['format']='json';
if($start != 0 )$params['args']['start']=$start;
if($count != 0 )$params['args']['count']=$count;
if($self){
$params['args']['scope']='self';
}
$params['args']['type']='SHAR';
$params['args']['order']='recency';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getGroupPosts($group_id, $start=0,$count = 20, $order="", $category="",$role=""){
$fields = array(
'id',
'creator:(id,first-name,last-name,picture-url,headline)',
'title',
'summary',
'likes',
'comments',
'site-group-post-url',
'creation-timestamp',
'attachment:(image-url,content-domain,content-url,title,summary)',
'relation-to-viewer'
);
$request = join(',',$fields);
if($role !=""){
$params['url'] = "https://api.linkedin.com/v1/people/~/group-memberships/".$group_id."/posts:({$request})";
}else{
$params['url'] = "https://api.linkedin.com/v1/groups/".$group_id."/posts:({$request})";
}
$params['method']='get';
$params['args']['format']='json';
if($start != 0 )$params['args']['start']=$start;
if($count != 0 )$params['args']['count']=$count;
if($order != '' )$params['args']['order']=$order;
if($category != '' )$params['args']['category']=$category;
if($role != '' )$params['args']['role']=$role;
$params['args']['ts']=time();
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getCompanyUpdates($company_id, $start=0,$count = 20){
if(!$company_id)return false;
$params['url'] = "https://api.linkedin.com/v1/companies/".$company_id."/updates";
$params['method']='get';
$params['args']['format']='json';
if($start != 0 )$params['args']['start']=$start;
if($count != 0 )$params['args']['count']=$count;
$params['args']['order']='recency';
$params['args']['ts']=time();
$params['args']['event-type']='status-update';
$params['args']['twitter-post']='false';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}
//returns as ARRAY, if chaning to object change in getGroupPostResponses
protected function getPostMeta($post_id){
$fields = array(
'id',
'site-group-post-url',
'creation-timestamp'
);  
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/posts/".$post_id.":({$request})";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getGroupPostResponses($post_id, $start = 0){
$fields = array(
'id',
'text',
'creator:(id,first-name,last-name,picture-url)',
'creation-timestamp'
);
$post_info = $this->getPostMeta($post_id);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/posts/".$post_id."/comments:({$request})";
$params['method']='get';
$params['args']['format']='json';
$params['args']['count']=500;
if($start != 0 )$params['args']['start']=$start;
$params['args']['order']='recency';
$content_return =  $this->makeRequest($params);
$content_return = json_decode($content_return,true);
$content_return['siteGroupPostUrl'] = isset($post_info['siteGroupPostUrl']) ? $post_info['siteGroupPostUrl'] : '';
return $content_return;
}

public function getNetworkPostResponses($update_key){
$params['url'] = "https://api.linkedin.com/v1/people/~/network/updates/key=".$update_key."/update-comments";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getCompanyUpdateResponses($company_id,$update_id){
$params['url'] = "https://api.linkedin.com/v1/companies/".$company_id."/updates/key=".$update_id."/update-comments";
$params['method']='get';
$params['args']['format']='json';
$params['args']['event-type']='status-update';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function shareStatus($args=array()){
$params['url'] = 'https://api.linkedin.com/v1/people/~/shares';
$params['method']='post';
$params['headers']['Content-Type']='application/json';
$params['headers']['x-li-format']='json';
$json=array();
if(isset($args['comment']))
{
$json['comment'] = $args['comment'];
}
if(isset($args['title']) || isset($args['submitted-url']) || isset($args['submitted-image-url']) || isset($args['description']) ){
$json['content']=array();
if(isset($args['title'])){
$json['content']['title'] = $args['title'];
}
if(isset($args['submitted-url'])){
$json['content']['submitted-url'] = $args['submitted-url'];
}
if(isset($args['submitted-image-url'])){
$json['content']['submitted-image-url'] = $args['submitted-image-url'];
}
if(isset($args['description'])){
$json['content']['description'] = $args['description'];
}
}
$json['visibility']['code']='anyone';

$params['args']=json_encode($json);

$result =  $this->makeRequest($params);
return json_decode($result,true);
// return: array('updateKey'=>'...','updateUrl'=>'...')
}

public function postToGroup($group_id,$title,$message,$content=array()){
$params['url'] = 'https://api.linkedin.com/v1/groups/'.$group_id.'/posts';
$params['method']='post';
$params['headers']['Content-Type']='application/json';
$params['headers']['x-li-format']='json';
$json = array('title'=>$title,'summary'=>$message);

if(is_array($content) AND count($content)>0) {
// If the content of the post is specified (e.g., a link to a website), add it here
$json['content'] = array();
if(isset($content['title'])){
$json['content']['title'] = $content['title'];
}
if(isset($content['submitted-url'])){
$json['content']['submitted-url'] = $content['submitted-url'];
}
if(isset($content['submitted-image-url'])){
$json['content']['submitted-image-url'] = $content['submitted-image-url'];
}
if(isset($content['description'])){
$json['content']['description'] = $content['description'];
}
}
$params['args']=json_encode($json);
$result =  $this->makeRequest($params);
return json_decode($result,true);
}


public function postToCompany($company_id,$message,$content=array())
{
$params['url'] = 'https://api.linkedin.com/v1/companies/'.$company_id.'/shares';
$params['method']='post';
$params['headers']['Content-Type']='application/json';
$params['headers']['x-li-format']='json';
$json = array('comment'=>$message , 'visibility'=> array('code'=>'anyone'));

if(is_array($content) AND count($content)>0) {
// If the content of the post is specified (e.g., a link to a website), add it here
$json['content'] = array();
if(isset($content['title'])){
$json['content']['title'] = $content['title'];
}
if(isset($content['submitted-url'])){
$json['content']['submitted-url'] = $content['submitted-url'];
}
if(isset($content['submitted-image-url'])){
$json['content']['submitted-image-url'] = $content['submitted-image-url'];
}
if(isset($content['description'])){
$json['content']['description'] = $content['description'];
}
}
$params['args']=json_encode($json);
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function deleteFromGroup($post_id){
$params['url'] = 'https://api.linkedin.com/v1/posts/'.$post_id;
$params['method']='delete';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function commentToGroupPost($post_id,$response_text){
$params['url'] = 'https://api.linkedin.com/v1/posts/'.$post_id.'/comments';
$params['method']='post';
$params['headers']['Content-Type']='application/json';
$params['headers']['x-li-format']='json';
$json = array('text'=>$response_text);
$params['args']=json_encode($json);
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function commentToNetworkPost($post_id,$response_text){
$params['url'] = 'https://api.linkedin.com/v1/people/~/network/updates/key='.$post_id.'/update-comments';
$params['method']='post';
$params['headers']['Content-Type']='application/json';
$params['headers']['x-li-format']='json';
$json = array('comment'=>$response_text);
$params['args']=json_encode($json);
$result =  $this->makeRequest($params);
return json_decode($result,true);
}


/**
* Set the access token manually
*
* @param string $token
* @throws \InvalidArgumentException
* @return \LinkedIn\LinkedIn
*/
public function setAccessToken($token)
{
$token = trim($token);
if (empty($token)) {
throw new \InvalidArgumentException('Invalid access token');
}

$this->access_token = $token;

return $this;
}
}

?>



######################LinkedIn.OAuth2.class.php#################




#######################OAuth2.class.php#########################

<?php

class OAuth2{

    protected $access_token;
    protected $access_token_url;
    protected $authorize_url;
    protected $access_token_name;
    public $error;

    function __construct($access_token=''){
        $this->access_token = $access_token;
        $this->error = "";
        $this->access_token_name='access_token';
    }

    public function getAuthorizeUrl($client_id,$redirect_url, $additional_args=array() ){
        $auth_link = $this->authorize_url.
                    "?response_type=code".
                    "&client_id=".$client_id.
                    "&redirect_uri=".urlencode($redirect_url);
        foreach($additional_args as $k=>$v){
            $auth_link.='&'.$k.'='.urlencode($v);
        }
        return $auth_link;
    }


    public function getAccessToken($client_id="", $secret="", $redirect_url="", $code = ""){
        if($code==""){
            $code = isset($_REQUEST['code'])?$_REQUEST['code']:"";
        }
        $params=array();
        $params['url'] = $this->access_token_url;
        $params['method']='post';
        $params['args']=array(  'code'=>$code,
                                'client_id'=>$client_id,
                                'redirect_uri'=>$redirect_url,
                                'client_secret'=>$secret,
                                'grant_type'=>'authorization_code');
        $result = $this->makeRequest($params);
        return $result;
    }

    protected function makeRequest($params=array()){
        $this->error = '';
        $method=isset($params['method'])?$params['method']:'get';
        $headers = isset($params['headers'])?$params['headers']:array();
        $args = isset($params['args'])?$params['args']:'';
        $url = $params['url'];

        $url.='?';
        if($this->access_token){
            $url .= $this->access_token_name.'='.$this->access_token;
        }

        if($method=='get'){
            $url.='&'.$this->preparePostFields($args);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        if($method=='post'){
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->preparePostFields($args));
        }elseif($method=='delete'){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        }elseif($method=='put'){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        }
        if(is_array($headers) && !empty($headers)){
            $headers_arr=array();
            foreach($headers as $k=>$v){
                $headers_arr[]=$k.': '.$v;
            }
            curl_setopt($ch,CURLOPT_HTTPHEADER,$headers_arr);
        }
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    protected function preparePostFields($array) {
        if(is_array($array)){
            $params = array();
            foreach ($array as $key => $value) {
                $params[] = $key . '=' . urlencode($value);
            }
            return implode('&', $params);
        }else{
            return $array;
        }
    }

}

?>
######################OAuth2.class.php#########################

Step 3-> create a LinkedInconfig.php

#################Start Paste into config file############################
define("LINKEDIN_API_KEY", "XXXXXXX");
define("LINKEDIN_API_SECRETE_KEY", "XXXXXXXX");
define("LINKEDIN_CALLBACK_URL", "http://localhost/LinkedIn/test.php");
#################End Paste into config file###############################

Step 3-> create a file linkedin_app.php
##################Start####################################
<?php

require_once('config.php');
require_once('LinkedIn.OAuth2.class.php');

class LinkedIn
{
    /**
     * Function to get LinkedIn Authorize URL and access token
    */
    function fnLinkedInConnect()
    {
        # Object of class
        $ObjLinkedIn = new LinkedInOAuth2();
        $strApiKey = LINKEDIN_API_KEY;
        $strSecreteKey = LINKEDIN_API_SECRETE_KEY;

        //put here your redirect url
        $strRedirect_url = LINKEDIN_CALLBACK_URL;

        $strCode = isset($_REQUEST['code']) ? $_REQUEST['code'] : '';

        if ($strCode == "") {

            try {
                # Get LinkedIn Authorize URL
                #If the user authorizes your application they will be redirected to the redirect_uri that you specified in your request .
                $strGetAuthUrl = $ObjLinkedIn->getAuthorizeUrl($strApiKey, $strRedirect_url);
            } catch (Exception $e) {

            }
            header("Location: ".$strGetAuthUrl);
            exit;
        }

        # Get LinkedIn Access Token
        /**
         * Access token is unique to a user and an API Key. You need access tokens in order to make API calls to LinkedIn on behalf of the user who authorized your application.
         * The value of parameter expires_in is the number of seconds from now that this access_token will expire in (5184000 seconds is 60 days).
         * You should have a mechanism in your code to refresh the tokens before they expire in order to continue using the same access tokens.
         */
        $arrAccess_token = $ObjLinkedIn->getAccessToken($strApiKey, $strSecreteKey, $strRedirect_url, $strCode);
        $strAccess_token = $arrAccess_token["access_token"];
##########################store access token into database#############################
      ### insert into table (accessToken)value($strAccess_token);
    }
###################get company page############################

function fnGetLinkedCompanyPages()
    {
         #############get access token from db####################
$strAccess_token = 'set access token from db';


        # Object of class
        $ObjLinkedin = new LinkedInOAuth2($strAccess_token);

        # Get List of company pages
        try {
            $arrAdminCompany = $ObjLinkedin->getAdminCompanies();
        } catch (Exception $e) {

        }

        $arrAdminCompanyValue = $arrAdminCompany["values"];
        $intTotalCount = count($arrAdminCompany["_total"]);

        $arrLinkedInPages = array();
        $intCount = 0;
        if (is_array($arrAdminCompanyValue) && count($arrAdminCompanyValue) > 0) {
            foreach ($arrAdminCompanyValue as $arrAdminCompanyInfo) {
                $intFlag = 0;

                $arrLinkedInPages[$intCount]["id"] = (int) $arrAdminCompanyInfo["id"];
                $arrLinkedInPages[$intCount]["name"] = stripslashes($arrAdminCompanyInfo["name"]);
            }
        }

        return $arrLinkedInPages;
    }

#########################share to linkedIn company page##############################
function postToCompanyPage($company_id)
{


                  #############get access token from db####################
$strAccess_token = 'set access token from db';

$message="this for testing Api Integration";
$content =array(
            "title" =>'Sr Software Developer(php)',
            "description" => 'Urgent opeing in Java Developer having 5+year exp at Veebrij Software pvt ltd',
            "submitted-url" => 'http://www.test/orange-software-p-ltd-noida-urgently-looking-for-2--senior-back-end-developer-c-sql-net/811/jobview',
            "submitted-image-url" => 'http://www.test/com/uploads/profileimage/recruiter/company_1460711697.jpg',

"visibility" => array(
            "code" => "anyone"
)
        );
$ObjLinkedin = new LinkedInOAuth2($strAccess_token);


try {
         
            $arrResponse = $ObjLinkedin->postToCompany($company_id, $message,$content);
         

print_r($arrResponse);
exit;

            // not post given error
            if ($arrResponse['updateKey'] == "") {
                $strErrorMessage = "SET ERROR MESSAGE";
            }

        } catch (Exception $e) {

        }

}

#########################post to user wall################################

function fnPostMessage()
{
   
        $strStatusMessage = "Sr Software engineer(Java) test";
        $strAccess_token ='get access token from db';

        # Object of class
        $ObjLinkedin = new LinkedInOAuth2($strAccess_token);
$content =array(
            "title" =>'Sr Software engineer(Java) testvvs',
            "description" => 'Urgent opeing in Java Developer having 5+year exp at Veebrij Software pvt ltd',
            "submitted-url" => 'http://www.test.com/orange-software-p-ltd-noida-urgently-looking-for-2--senior-back-end-developer-c-sql-net/811/jobview',
            "submitted-image-url" => 'http://www.test.com/uploads/profileimage/recruiter/company_1460711697.jpg',

"visibility" => array(
            "code" => "anyone"
)
        );
 try {
            $strErrorMessage = '';
       
            $arrResponse = $ObjLinkedin->shareStatus($content);

            // not post given error
            if ($arrResponse['updateKey'] == "") {
                $strErrorMessage = "SET ERROR MESSAGE";
            }

        } catch (Exception $e) {

        }
        return $strErrorMessage;
   }


}

####################### create output file LinkedsharePost.php###################


<?php
create out put final linkedin share page like LinkedsharePost.php

#Include necessary class files
require_once('linkedin_app.php');

$li = new LinkedIn();
$li->fnLinkedInConnect();
$linkedinpages = $li->fnGetLinkedCompanyPages();
##get company id from array################
print_r($linkedinpages);

$updatePostPage=$li->postToCompanyPage(PASS COMPANYID);
print_r($linkedinpages);




Finally we have done all of the step, hope it will help you. please comment if anyone face any difficulty.


Friday, January 13, 2017

How to post silently or offline content post to user wall facebook[Solved] ?

Hi All,

I would like to share this post for help some one that looking for silently post their content to users wall . so it is very easy to integrate Facebook Graph Api using PHP API in  your website. I do not want to waste your time it small step which you need to follow bellow .


Step-1->  Download Facebook SDK from Facebook PHP SDK 
Step-2-> Create a your project folder paste the SDK into c:\xampp\fb\directory
Step-3-> Create a new file getAccessToken.php
Folder structure 
c:\xampp\fb\
c:\xampp\fb\src\Facebook

 1. autoload.php
##########START#####################################################
<?php
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
  throw new Exception('The Facebook SDK v4 requires PHP version 5.4 or higher.');
}

spl_autoload_register(function ($class)
{
  // project-specific namespace prefix
  $prefix = 'Facebook\\';

  // base directory for the namespace prefix
  $base_dir = defined('FACEBOOK_SDK_V4_SRC_DIR') ? FACEBOOK_SDK_V4_SRC_DIR : __DIR__ . '/src/Facebook/';

  // does the class use the namespace prefix?
  $len = strlen($prefix);
  if (strncmp($prefix, $class, $len) !== 0) {
    // no, move to the next registered autoloader
    return;
  }

  // get the relative class name
  $relative_class = substr($class, $len);

  // replace the namespace prefix with the base directory, replace namespace
  // separators with directory separators in the relative class name, append
  // with .php
  $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

  // if the file exists, require it
  if (file_exists($file)) {
    require $file;
  }
});
##########END###########################################################


2. getAccessToken.php
#########START##############getAccessToken.php################################
<?php
session_start();
// added in v4.0.0
require_once 'autoload.php';

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;

// start session

// inti app with app id and secret
FacebookSession::setDefaultApplication( 'APPid','SecretId' );

// login helper with redirect_uri

    $helper = new FacebookRedirectLoginHelper('http://127.0.1/fb/postwall.php' );

try {
  $session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
  // When Facebook returns an error
} catch( Exception $ex ) {
  // When validation fails or other local issues
}

// see if we have a session
if (isset($session))
{   
    $hostName    =        'http://'.$_SERVER['HTTP_HOST'];
    $getAccesstoken        =        $session->getToken();
}
 ###################INSERT TOKEN INTO DB###############################
 INSET INTO TABLE(USER_ID,FBACCESSTOKEN)VALUE('1001',$getAccesstoken);
###################INSERT TOKEN INTO DB################################
   

########################END################################### 


###########CREATE FILE#######silentPostWall.php###############################

<?php

    require_once('autoload.php');
    use Facebook\FacebookSession;  
    use Facebook\FacebookRequest;


#######SET CONFIGURATION FACEBOOK####################
                   FacebookSession::setDefaultApplication( 'AAPID','SCRETEKEY' ); 

###GET USER ACCESSTOKEN FROM DATABASE WHICH YOU STORED##########
                     $facebookAccesstokenFromdb    =    TABLE('td_usersAccessToken','1001');
                      

                        if(!empty($facebookAccesstokenCode) && $facebookAccesstokenCode!='NULL')
                        {
                            $pageSession = new FacebookSession($
facebookAccesstokenFromdb);
                            $request = (new FacebookRequest($pageSession, 'POST', '/me/feed', array(
                            'name' =>'Title',
                            'caption' => 'Title Caption',
                            'link' => 'URL',
                            'message' =>  'Des'
                            )))->execute();
                        }


###########END FILE#######silentPostWall.php###############################

 Finally you have done! 

Note : You need get permission approve "PUBLISH_ACTION" From Facebook to publish user wall.before you get approval you can post the content to developer user wall only.

Step1-> Create a screen cast video and give the instruction where your website user can enter their post  custom.



 Hope it will help you.. :)