0

my scypt php connects to facebbok to extract data, indeed, each time this file is executed, it asks me for an authentication page via login and password, but I need to put this file on the OVH servers in order to automate it according to crons.

How to make this file do authentication without login request and password so that the server automatically execute it?

Thank you in advance

<?php

session_start();
require_once __DIR__ . '/src/Facebook/autoload.php'; // download official fb sdk for php @ https://github.com/facebook/php-graph-sdk

$fb = new Facebook\Facebook([
  'app_id' => 'xxxxxxxxxxxxxxx',
  'app_secret' => 'xxxxxxxxxxxxxx',
  'default_graph_version' => 'v3.2',
  ]);

$helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];

$permissions = array('email','read_insights');

try {
    if (isset($_SESSION['facebook_access_token'])) 
      {
        $accessToken = $_SESSION['facebook_access_token'];
      } 
    else 
      {
          $accessToken = $helper->getAccessToken();
      }
  } 
catch(Facebook\Exceptions\FacebookResponseException $e) 
  {
      // When Graph returns an error
      echo 'Graph returned an error: ' . $e->getMessage();
      exit;
  } 
catch(Facebook\Exceptions\FacebookSDKException $e) 
  {
      // When validation fails or other local issues
      echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
  }

if (isset($accessToken)) {
  if (isset($_SESSION['facebook_access_token']))
    {
      $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    } 
  else 
    {
        // getting short-lived access token
        $_SESSION['facebook_access_token'] = (string) $accessToken;
          // OAuth 2.0 client handler
        $oAuth2Client = $fb->getOAuth2Client();
        // Exchanges a short-lived access token for a long-lived one
        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);

        $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;

        // setting default access token to be used in script
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }

  // redirect the user back to the same page if it has "code" GET variable
  if (isset($_GET['code'])){
        header('Location: ./');}


  // getting basic info about user
  try {
    // GET LIST OF TOKEN PAGES
     // $token = array("EAASb1xN23i4BALzzOUYKWdNAhZAJtubpfiWESFXh1zZBZAGuMEHG49OLZA0QDFBrYsMx3FtRomWeSWrfDnbXsIXhrizpmYCfWHcBqqCrHV5t4NfJXkaPPMR0WpVIJJKLJpN7dZB2CRhCTZC3aQUtAq5UqzxV6VVL6sGXbknTWvhgZDZD");

     $token = array("xxxxxxxx","xxxxxxxxx","xxxxxxxxx" ); 

        // GET LISTS OG PAGE IN MY ACCOUNTS
        $profile_request = $fb->get('/me/accounts?fields=id&limit=50'); 
    $profile = $profile_request->getGraphList();
    // print_r('<br>'.$profile); 
        print_r('<br>');
        // create new array of id to eliminate id unwanted
       $colors = array("yyyy","yyyy","yyyy");

    // get  all id 
      $data3 = array();
      foreach ($profile as $row3) {$data3[]=$row3['id']; }
    // differences id wanted
    $result= array_diff($data3,$colors);




$tabjfh[][] = array();
$longeurMinus= count($result) ;
$longeurToken= count($token);
// print_r('tableau des id :'.$longeurMinus ."<br>");
// print_r('tableau des token:'.$longeurToken."<br>////////////////// <br>");


$i=0 ;
foreach ($result as $row4)
{ 
$tabjfh[$i][0]=$row4 ;
// print_r(" id[".$i."] :".$row4."<br/>");
$i=$i+1   ;
} 

// remplissage  de token
for ($i=0; $i < $longeurToken; $i++) 
{ 
$tabjfh[$i][1]=$token[$i] ;
// print_r("Token : [".$i."] : ".$tabjfh[$i][1]."<br/>");
}


$tabclik=  array();
$tablik=  array();
$tabpositive=  array();
$tabinteraction=  array();
$tabengagement=  array();

// print_r(" <br/> liste token id <br/> ");
// print_r(" <br/>  longueur : ".$longeurMinus) ;
// print_r("<br/>") ; 

for ($i=0; $i <$longeurMinus ; $i++) 
{ 
     $aujourdui= date('Y-m-d');


    // echo "fffffffffffffffff" .$aujourdui;
        // print_r(" <br/>****    token :".$tabjfh[$i][1]." id  ".$tabjfh[$i][0]."<br/>");

      // *************************** Les statistiques disponibles table facebook ****************************



// multiples values : page-id/insights/?metric=page_fan_adds_unique,page_fan_adds
// 150425421686227/insights/?fields=period=day,values&metric=page_fan_adds_unique,page_fan_adds
//EXEMPLE: Le nombre de fans sur toutes les pages
// $response = $fb->get("/".$tabjfh[$i][0]."/insights/page_fans/day?since=".$aujourdui."&until=".$aujourdui,$tabjfh[$i][1]);


// nombre de fans
$like = $fb->get("/".$tabjfh[$i][0]."/insights/page_fans/day?since=".$aujourdui."&until=".$aujourdui,$tabjfh[$i][1]); 

        $likerep = $like->getGraphList();
        $likerep =json_decode($likerep);
        $tablik[]= $likerep ;



//Le nombre de clics sur les coordonnées de votre Page et le bouton call-to-action.
$clik = $fb->get("/".$tabjfh[$i][0]."/insights/page_total_actions/day?since=".$aujourdui."&until=".$aujourdui,$tabjfh[$i][1]);

        $clikrep = $clik->getGraphList();
        $clikrep =json_decode($clikrep);
        $tabclik[]= $clikrep ; 




// Nombre de fois où les personnes ont réagi de manière positive, en fonction du type d’action: other, like... il faut faire la somme avent de reuperer la valeur
$positive = $fb->get("/".$tabjfh[$i][0]."/insights/page_positive_feedback_by_type/day?since=".$aujourdui."&until=".$aujourdui,$tabjfh[$i][1]);  

        $posrep = $positive->getGraphList();
        $posrep =json_decode($posrep);
        $tabpositive[]= $posrep ;

// Le nombre de fois où des personnes ont cliqué sur un de vos contenus:interaction sur la page
$interaction = $fb->get("/".$tabjfh[$i][0]."/insights/page_consumptions/day?since=".$aujourdui."&until=".$aujourdui,$tabjfh[$i][1]);  

        $posint = $interaction->getGraphList();
        $posint =json_decode($posint);
        $tabinteraction[]= $posint ;


// Nombre de fois où les personnes ont interagi avec vos publications à travers des mentions J’aime, des commentaires, des partages et autres:engagement
$engagement = $fb->get("/".$tabjfh[$i][0]."/insights/page_post_engagements/day?since=".$aujourdui."&until=".$aujourdui,$tabjfh[$i][1]); 


        $poseng = $engagement->getGraphList();
        $poseng =json_decode($poseng);
        $tabengagement[]= $poseng ;

        // $connect=mysql_connect('localhost','root','')or die(mysql_erreur());
        //   mysql_select_db('stat2018',$connect)or die(mysql_erreur());
        //   $req2="INSERT INTO `sessions`(`id`, `date`, `session`, `id_client`) values  ('','$a','$b','".$VIEW_ID."')";
        //   mysql_query($req2);


}

       // $tabe =$tabclik[0]->values ;
       // print_r( "ffffffffffffffffff".$tabe[0]->end_time->date);



  } 
  catch(Facebook\Exceptions\FacebookResponseException $e)
   {
          // When Graph returns an error
          echo 'Graph returned an error: ' . $e->getMessage();
          session_destroy();
          // redirecting user back to app login page
          header("Location: ./");
          exit;
   } 
  catch(Facebook\Exceptions\FacebookSDKException $e)
    {
        // When validation fails or other local issues
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit; 
    }

 echo('<br> <pre>')  ;

// declaration d'un tableau pour faire le remplissage
// $tao =;




// **************** tableau de clik
foreach ($tabclik as $value) 
{    
         //  affichage de tt les valeur détaillées:
     print_r($value[0]);
    // nom de la stat
         print_r($value[0]->name."<br>");

         // peiode
         print_r($value[0]->period."<br>"); 
         $tabe =  $value[0]->values ;

         // valeur 
         print_r($tabe[0]->value."<br>"); 

         // date

         $date = $tabe[0]->end_time->date;
         $date = strstr($date, ' ', true);
         print_r($date."<br>"); 


     // affichage de id  
         $id=$value[0]->id;
         $id = strstr($id, '/', true);
          // 2eme methode: $id = explode("/", $id) ;
     print_r($id."<br>");

     // il faut terminer laccès à tt les varaibles    
         // convertion de type date puis extraction de de year/month/dy
     // $u=$tabe[0]->end_time->date;
     // $date= strstr($u, ' ', true);
     // $new_date = $u->format("Y-m-d "); 
     // print_r($date."<br>");

}  

echo('</pre>')  ; 


// ********************tableau de fans 

echo(' <br> <br> <br><pre>')  ;
foreach ($tablik as $v) 
{ 
    // nom de la stat
         print_r($v[0]->name."<br>");

         // peiode
         print_r($v[0]->period."<br>"); 


         // valeur 
          $tabe =  $v[0]->values ; 
         print_r($tabe[0]->value."<br>"); 

         // date

         $date = $tabe[0]->end_time->date;
         $date = strstr($date, ' ', true);
         print_r($date."<br>"); 


     // affichage de id  
         $id=$v[0]->id;
         $id = strstr($id, '/', true);
          // 2eme methode: $id = explode("/", $id) ;
     print_r($id."<br>");



} 
echo('</pre>')  ;

// ********************tableau de positive 


echo('<pre>')  ;
foreach ($tabpositive as $pos) 
{       
     // print_r($pos[0]);

    // nom de la stat
         print_r($pos[0]->name."<br>");

         // // peiode
         // print_r($pos[0]->period."<br>"); 
         // $tabe =  $pos[0]->values ; 

         // valeur 
        $answer=$tabe[0]->value->answer;
        $claim=$tabe[0]->value->claim;
        $comment=$tabe[0]->value->comment;

        $like=$tabe[0]->value->like;
        $link=$tabe[0]->value->link;
        $other=$tabe[0]->value->other;
        $rsvp=$tabe[0]->value->rsvp;

  if (empty($answer)) {
        $answer=0;
        }
  if (empty($claim)) {
        $claim=0;
        }
  if (empty($like)) {
        $like=0;
        }
  if (empty($like)) {
        $x=0;
        }
  if (empty($link)) {
        $link=0;
        }
  if (empty($other)) {
        $other=0;
        }


  if (empty($comment)) {
        $comment=0;
        }

if (empty($rsvp)) {
        $rsvp=0;
        }

$s= $rsvp + $other + $link + $like + $claim +$answer +$comment;
 print_r($s."<br>"); 

         // date

         // $date = $tabe[0]->end_time->date;
         // $date = strstr($date, ' ', true);
         // print_r($date."<br>"); 


     // affichage de id  
         $id=$pos[0]->id;
         $id = strstr($id, '/', true);
          // 2eme methode: $id = explode("/", $id) ;
     print_r($id."<br>");
         } 
echo('</pre>')  ;

// ********************tableau des interactions 
echo('<pre>')  ;
foreach ($tabinteraction as $valu) 
{ 

  // print_r($valu[0]);
  // nom de la stat
    print_r($valu[0]->name."<br>");
  // valeur 
   $tabe =  $valu[0]->values ; 
   print_r($tabe[0]->value."<br>"); 

  // affichage de id  
  $id=$valu[0]->id;
  $id = strstr($id, '/', true);
  print_r($id."<br>");

} 
echo('</pre>')  ;

// ********************tableau des engagements

echo('<pre>')  ;
foreach ($tabengagement as $vv) 
{ 
  // print_r($vv[0]);
    // nom de la stat
  print_r($vv[0]->name."<br>");
  // valeur 
    $tabe =  $vv[0]->values ; 
    print_r($tabe[0]->value."<br>"); 

  // affichage de id  
  $id=$vv[0]->id;
  $id = strstr($id, '/', true);
  print_r($id."<br>");

} 
echo('</pre>')  ;

$tabAll =  array();




/***************************************************************************************************************/
$i =  -1 ;
foreach ($tabclik as $value) 
{    
      $i++ ;  
         //  affichage de tt les valeur détaillées:
     // print_r($value[0]);
    // nom de la stat
         // print_r($value[0]->name."<br>");

         // peiode
         print_r($value[0]->period."<br>"); 
         $tabe =  $value[0]->values ;

         // valeur 
         // print_r($tabe[0]->value."<br>"); 

         // date

         $date = $tabe[0]->end_time->date;
         $date = strstr($date, ' ', true);
         // print_r($date."<br>"); 


     // affichage de id  
         $id=$value[0]->id;
         $id = strstr($id, '/', true);

     // print_r($id."<br>");



         // ***********tableau engagement
     $tab32 = $tabengagement[$i] ; 
     $tabe =  $tab32[0]->values  ;    
     // print_r($tabe[0]->value."okkkkkk  <br>");

     // *************tableau clik
    $tab29=$tabclik[$i];
    $tab =  $tab29[0]->values ;      

    // ************tableau like 
          $tab33 =  $tablik[$i]; 
        $t= $tab33[0]->values; 



    // **************tableau interaction
    $tab31=$tabinteraction[$i];
    $ta =  $tab31[0]->values  ;   


  // **************tableau comm  positive
        $tab30=$tabpositive[$i];
        $answer=$tab30[0]->value->answer;
        $claim=$tab30[0]->value->claim;
        $comment=$tab30[0]->value->comment;

        $like=$tab30[0]->value->like;
        $link=$tab30[0]->value->link;
        $other=$tab30[0]->value->other;
        $rsvp=$tab30[0]->value->rsvp;

  if (empty($answer)) {
        $answer=0;
        }
  if (empty($claim)) {
        $claim=0;
        }
  if (empty($like)) {
        $like=0;
        }
  if (empty($like)) {
        $x=0;
        }
  if (empty($link)) {
        $link=0;
        }
  if (empty($other)) {
        $other=0;
        }


  if (empty($comment)) {
        $comment=0;
        }

if (empty($rsvp)) {
        $rsvp=0;
        }

$s= $rsvp + $other + $link + $like + $claim +$answer +$comment;



     $tabAll[]=array($date,
             $id,
             $t[0]->value,
             $tab[0]->value,
             $s,
             $tabe[0]->value,
             $ta[0]->value
             );  


     // il faut terminer laccès à tt les varaibles    
         // convertion de type date puis extraction de de year/month/dy
     // $u=$tabe[0]->end_time->date;
     // $date= strstr($u, ' ', true);
     // $new_date = $u->format("Y-m-d "); 
     // print_r($date."<br>");

}


foreach ($tabAll as $valuooe) {
$connect= new mysqli('server', 'users', 'psw', 'bdd');

print_r(" date ".$valuooe[0]." <br> ID :  <br> ".$valuooe[1]." <br> like".$valuooe[2]."<br> clik".$valuooe[3]." <br> positive commentaires ".$valuooe[4]."<br> engagement ".$valuooe[5]."<br>  interaction".$valuooe[6]."<br/>");

$req2="INSERT INTO `facebook`(`id`, `date`, `id_client`,`jaime`, `clics`, `potsitiveact`, `engagement`, `interaction`)
VALUES ('','".$valuooe[0]."','$valuooe[1]',".$valuooe[2].",".$valuooe[3].",".$valuooe[4].",".$valuooe[5].",".$valuooe[6].")";
mysqli_query($connect,$req2);
mysql_close();

}

echo('</pre>');


/***************************************************************************************************************/

}

else {
  // replace your website URL same as added in the developers.facebook.com/apps e.g. if you used http instead of https and you used non-www version or www version of your website then you must add the same here
  $loginUrl = $helper->getLoginUrl('https://www.mondomain.com', $permissions);
    // echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';


header('Location: '.$loginUrl); 
    // echo '<a href="' . $helper->getLoginUrl() . '">Login</a>';

      }

try {
  // Returns a `FacebookFacebookResponse` object

} catch(FacebookExceptionsFacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
//  function get token automatic
 // function generate_token($args){
//     $r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
//     $longtoken=$r->access_token;
//     $r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/me?access_token={$longtoken}")); // get user id
//     $userid=$r->id;
//     $r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/{$userid}/accounts?access_token={$longtoken}")); // get permanent token
//     foreach($r->data as $d) 
//      if($d->id==$args['pageid']) 
//        return $d->access_token;
// }

``
  • You’re going to have to rewrite this, because in a cron environment you are not going to have a session. Store your access token somewhere where the script can read it from. (Even extended tokens expire after some time though, so you will need a way for the user to login and create a new one. No, there is no way to automate the process of getting a new user token.) – 04FS May 15 '19 at 13:59
  • Hello, thank you for your help, you do not have a tutorial yet. thank you in advance – Amira Ben Faiza May 16 '19 at 09:13

0 Answers0