Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use Aura\Router\Exception;
- use Facebook;
- use FacebookAds\Api;
- use FacebookAds\Object;
- use Facebook\Exceptions;
- use Ip\Controller;
- use Ip\Pagination\Pagination;
- /*
- * @class AdvertisingController
- */
- class AdvertisingController
- {
- private $access_token = null;
- private $app_id = null;
- private $app_secret = null;
- static $fb_params;
- public $fb_instance;
- public $requests;
- private $my_facebook_id;
- public $current_facebook_ads_account = null;
- public $current_facebook_ads_campaign = null;
- public function __construct()
- {
- if (ipDb()->isMySQL()) {
- try {
- $result = ipDb()->fetchAll("SELECT * FROM ip_advertising_fb_admin_data");
- foreach (current($result) as $property_name => $property_value) {
- if (property_exists(get_class($this), $property_name)) {
- $this->$property_name = $property_value;
- } elseif ($property_name == 'used_account') {
- $this->current_facebook_ads_account = $property_value;
- } elseif ($property_name == 'app_user') {
- $this->my_facebook_id = $property_value;
- }
- }
- } catch (Exception $e) {
- print_r($e);
- }
- if (is_null($this->app_id) && is_null($this->app_secret)) {
- ipDb()->insert('advertising_fb_admin_data', array(
- 'app_id' => '1406995719530360',
- 'app_secret' => '046c382d24e764cca8a344a78fbc41ea'
- ));
- }
- }
- $this->setFacebookParams();
- $this->fb_instance = new Facebook\Facebook(static::$fb_params);
- }
- private function setFacebookParams()
- {
- static::$fb_params = [
- 'app_id' => $this->app_id,
- 'app_secret' => $this->app_secret,
- 'default_graph_version' => 'v2.7',
- ];
- }
- public function AdvertisingList()
- {
- ipResponse()->setTitle(__('Cars for Adverts list', 'Advertising', false));
- if (is_null($this->access_token)) {
- $this->redirectToAdvertisingLogin();
- } elseif (is_null($this->current_facebook_ads_account)) {
- $this->AdvertisingSelectAdAccount();
- }
- $query = $this->getQuery();
- $inventory = new Models\AdvertisingInventory();
- $listings = $inventory->getListings($query, 20);
- $totalPages = $inventory->getTotalPages(20);
- $pagination = new Pagination([
- 'totalPages' => $totalPages,
- 'currentPage' => $query['page'],
- 'pagerSize' => 20
- ]);
- return ipView('view/advertisingList.php', [
- 'listings' => $listings,
- 'searchOptions' => $query,
- 'pageSize' => 20,
- 'advertising_reset' => !is_null($this->current_facebook_ads_account) ? $this->AdvertisingAccountResetLink() : '',
- 'pagination' => $pagination->render(ipFile('Plugin/Advertising/view/pagination.php'))
- ])->render();
- }
- /***************************
- * Redirect methods block
- ***************************/
- private function header302()
- {
- header('HTTP/1.1 302 Found');
- }
- private function redirectToAdvertisingList()
- {
- $this->header302();
- header('Location: ' . ipRouteUrl('Advertising_list'));
- }
- private function redirectToAdvertisingLogin()
- {
- $this->header302();
- header('Location: ' . ipRouteUrl('Advertising_login'));
- }
- /*******************************
- * End of redirect methods block
- *******************************/
- /*****************************
- * Facebook Login Block
- *****************************/
- public function AdvertisingLogin()
- {
- $helper = $this->fb_instance->getRedirectLoginHelper();
- $permissions = ['ads_management', 'read_insights', 'ads_read', 'manage_pages']; // optional
- $reauthentication_url = $helper->getReAuthenticationUrl('http://portal.automote.local/AdvertisingLoginCallback', $permissions);
- $loginUrl = $helper->getLoginUrl('http://portal.automote.local/AdvertisingLoginCallback', $permissions);
- ipDb()->update('advertising_fb_admin_data', array(
- 'reauthentication_url' => $reauthentication_url,
- 'login_url' => $loginUrl
- ), array(
- 'app_id' => $this->app_id
- ));
- return ipView('view/advertisingFacebookLogin.php', [
- 'loginUrl' => $loginUrl
- ])->render();
- }
- public function AdvertisingAccountResetLink()
- {
- $resetUrl = ipRouteUrl('Advertising_unset_ad_account');;
- return <<<HTML
- <div class="panel-group" style="position: fixed; top: 50px; left: 0; z-index: 1050">
- <div class="panel panel-default">
- <div class="panel-body">Reset Account</div>
- </div>
- <div class="panel panel-default">
- <div class="panel-body">
- <a href='$resetUrl' class='btn btn-default'><span class='glyphicon glyphicon-refresh'></span> Reset account select!</a>
- <span>Current Account selected: $this->current_facebook_ads_account</span>
- </div>
- </div>
- </div>
- HTML;
- }
- public function AdvertisingLoginCallback()
- {
- $helper = $this->fb_instance->getRedirectLoginHelper();
- try {
- $accessToken = $helper->getAccessToken();
- } catch (Facebook\Exceptions\FacebookResponseException $e) {
- // When Graph returns an error
- if ($e->getMessage() == 'This authorization code has been used.') {
- $this->redirectToAdvertisingList();
- } else {
- 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)) {
- // Logged in!
- $LongLivedAccessToken = $this->AdvertisingExtendingFacebookToken($accessToken->__toString());
- $longLivedAccessTokenObject = new Facebook\Authentication\AccessToken($LongLivedAccessToken);
- $this->fb_instance->setDefaultAccessToken($longLivedAccessTokenObject);
- $request = $this->fb_instance->get('/me');
- $app_user = $request->getDecodedBody()['id'];
- $logout_url = $helper->getLogoutUrl($longLivedAccessTokenObject, ipRouteUrl('Advertising_list'));
- ipDb()->update('advertising_fb_admin_data', array(
- 'access_token' => $LongLivedAccessToken,
- 'app_user' => $app_user,
- 'logout_url' => $logout_url
- ), array(
- 'app_id' => $this->app_id
- ));
- $this->redirectToAdvertisingList();
- // Now you can redirect to another page and use the
- }
- }
- private function AdvertisingExtendingFacebookToken($token)
- {
- // OAuth 2.0 client handler
- $oAuth2Client = $this->fb_instance->getOAuth2Client();
- // Exchanges a short-lived access token for a long-lived one
- return $oAuth2Client->getLongLivedAccessToken($token)->__toString();
- }
- /*******************************
- * End of Facebook Login Block
- ******************************/
- /*****************************
- * Facebook Ads Authentication Block
- *****************************/
- public function AdvertisingSelectAdAccount()
- {
- Api::init($this->app_id, $this->app_secret, $this->access_token);
- // Add to header of your file
- if (is_null($this->current_facebook_ads_account)) {
- $common_facebook_ad_account_user = new Object\AdAccountUser($this->my_facebook_id);
- $account = new Object\AdAccount(); // Getting AdAccount instance
- $current_user_facebook_ad_accounts = $common_facebook_ad_account_user->getAdAccounts(/*$account::getFields()*/)->getArrayCopy();
- $head = "";
- $body = "";
- $i = 0;
- foreach ($current_user_facebook_ad_accounts as $data) {
- $data = $data->exportAllData();
- $data = array_filter($data, function ($value) {
- return $value !== '' && !is_array($value);
- });
- if ($i == 0) {
- $head = "<tr><th>" . join("</th><th>", array_keys($data)) . "</th><th>Select Account</th></tr>";
- }
- $select_ad_account_link = ipRouteUrl('Advertising_set_current_facebook_ads_account', array('account_id' => $data['id']));
- $body .= "<tr><td>" . join("</td><td>", $data) . "</td><td><a href='$select_ad_account_link'>Select</a></td></tr>";
- $i++;
- }
- $route = ipRouteUrl('Advertising_new_ad_account');
- echo <<<HTML
- <div class="container">
- <div class="well">
- <h3>List of available accounts</h3>
- <table class="table table-bordered">
- <thead>
- $head
- </thead>
- <tbody>
- $body
- </tbody>
- </table>
- <a href="$route" class="btn btn-lg btn-primary">Create new account</a>
- </div>
- </div>
- HTML;
- } else {
- $this->redirectToAdvertisingList();
- }
- }
- /*****************************
- * End Facebook Ads Authentication Block
- *****************************/
- /*****************************
- * Facebook Ads Controls Block
- *****************************/
- /**
- * @param string $current_facebook_ads_account
- */
- public function AdvertisingSetCurrentFacebookAdsAccount($account_id)
- {
- $this->current_facebook_ads_account = $account_id;
- ipDb()->update('advertising_fb_admin_data', array(
- 'used_account' => $account_id
- ), array(
- 'app_id' => $this->app_id
- ));
- $this->redirectToAdvertisingList();
- }
- /**
- * @param string $app_id
- */
- public function AdvertisingSetCurrentFacebookAdsCampaign($campaign_id)
- {
- $this->current_facebook_ads_campaign = $campaign_id;
- $_SESSION['current_facebook_ads_account'] = $campaign_id;
- $this->redirectToAdvertisingList();
- }
- /**
- * @return null
- */
- public function AdvertisingUnsetAdAccount()
- {
- unset($this->current_facebook_ads_account);
- unset($_SESSION['current_facebook_ads_account']);
- ipDb()->update('advertising_fb_admin_data', array(
- 'used_account' => null
- ), array(
- 'app_id' => $this->app_id
- ));
- $this->redirectToAdvertisingList();
- }
- /*
- * @public AdvertisingPublishItem
- * @use FacebookAds\Http\Exception\RequestException
- */
- public function AdvertisingPublishItem($id)
- {
- $inventory = new Models\AdvertisingInventory();
- $item = $inventory->getListing($id)->getAttributes();
- $item['properties'] = json_decode($item['properties'], true);
- /**
- * Step 1 Instantiate an API
- *
- * @link https://developers.facebook.com/docs/marketing-api/sdks#init-sdk
- */
- try {
- Api::init($this->app_id, $this->app_secret, $this->access_token);
- } catch (\Exception $e) {
- return $this->AdvertisingRenderErrorMessage($e);
- }
- /**
- * Step 2 Query to create campaign
- * @var $campaign
- * @link https://developers.facebook.com/docs/marketing-api/reference/ad-campaign-group
- *
- * TODO: Implement ad image widget sizing: https://www.facebook.com/business/help/103816146375741
- */
- try {
- $account = new Object\AdAccount($this->current_facebook_ads_account);
- $campaign = new Object\Campaign(null, $this->current_facebook_ads_account); // Getting AdAccount instance
- $ad_campaigns = $account->getCampaigns($campaign::getFields())->getArrayCopy(); // Checks of there are any campaigns already created
- $current_campaign = null;
- if (!empty($ad_campaigns)) {
- foreach ($ad_campaigns as $ad_campaign) { // loops through campaigns
- var_dump($ad_campaign); exit();
- $campaign_data = $ad_campaign->exportAllData();
- if ($campaign_data['name'] == 'Sell old inventory') { // If campaign name matches the name given to new campaign, created campaign is then used
- $current_campaign = $ad_campaign;
- }
- }
- }
- if (!is_null($current_campaign)) { // Checks if campaign is already assigned if yes, then its used.
- $campaign = $current_campaign;
- } else { // else new one is created
- $campaign->setData(array(
- Object\Fields\CampaignFields::NAME => 'Sell old inventory',
- Object\Fields\CampaignFields::OBJECTIVE => Object\Values\CampaignObjectiveValues::LINK_CLICKS,
- ));
- $campaign->validate()->create(array(
- Object\Campaign::STATUS_PARAM_NAME => Object\Campaign::STATUS_PAUSED
- ));
- }
- //$campaignData = $campaign->getData();
- echo 'Campaign ID: ' . $campaign->id . " <br>\n";
- } catch (\Exception $e) {
- return $this->AdvertisingRenderErrorMessage($e);
- }
- /**
- * Step 3 Search for targeting topic
- * @var $targeting
- * @link https://developers.facebook.com/docs/marketing-api/targeting-specs/v2.7
- */
- try {
- $results = Object\TargetingSearch::search(
- Object\Search\TargetingSearchTypes::INTEREST,
- null,
- 'Automobiles');
- $target = (count($results)) ? $results->current() : null;
- //if (!is_null($target)) {
- echo "Using target: " . $target->name . "<br/>";
- $targeting = new Object\Targeting();
- $targeting->{Object\Fields\TargetingFields::GEO_LOCATIONS} = array(
- 'countries' => array('NZ')
- );
- $targeting->{Object\Fields\TargetingFields::INTERESTS} = array(
- array(
- 'id' => $target->id,
- 'name' => $target->name,
- ),
- );
- //}
- } catch (\Exception $e) {
- return $this->AdvertisingRenderErrorMessage($e);
- }
- /**
- * Step 4 Create an AdSet
- * @var $adset
- * @link https://developers.facebook.com/docs/marketing-api/reference/ad-campaign
- */
- try {
- $adset = new Object\AdSet(null, $this->current_facebook_ads_account);
- //$fields = $adset::getFields();
- $available_adsets = $campaign->getAdSets(array(Object\Fields\AdSetFields::NAME,Object\Fields\AdSetFields::ID));
- $current_adset = null;
- if (!empty($available_adsets)) {
- foreach ($available_adsets as $ad_set) { // loops through adsets
- if ($adset->name == $item['title']) { // If adset name matches the name given to new campaign, created campaign is then used
- $current_adset = $ad_set;
- }
- }
- }
- if (!is_null($current_adset)) {
- $adset = $current_adset;
- /*$adset->read(array(
- Object\Fields\AdSetFields::PROMOTED_OBJECT,
- Object\Fields\AdSetFields::NAME
- ));
- echo $adset->name."<br>";
- echo $adset->promoted_object."<br>";*/
- } else {
- $start_time = (new \DateTime("+1 week"))->format(\DateTime::ISO8601);
- $end_time = (new \DateTime("+2 week"))->format(\DateTime::ISO8601);
- $adset->setData(array(
- Object\Fields\AdSetFields::NAME => $item['title'],
- Object\Fields\AdSetFields::OPTIMIZATION_GOAL => Object\Values\AdSetOptimizationGoalValues::LINK_CLICKS,
- Object\Fields\AdSetFields::BILLING_EVENT => Object\Values\AdSetBillingEventValues::LINK_CLICKS,
- Object\Fields\AdSetFields::BID_AMOUNT => 100,
- Object\Fields\AdSetFields::DAILY_BUDGET => 500,
- Object\Fields\AdSetFields::CAMPAIGN_ID => $campaign->id,
- Object\Fields\AdSetFields::TARGETING => $targeting,
- Object\Fields\AdSetFields::START_TIME => $start_time,
- Object\Fields\AdSetFields::END_TIME => $end_time,
- /*Object\Fields\AdSetFields::PROMOTED_OBJECT => (object) array(
- Object\Fields\AdPromotedObjectFields::PAGE_ID => '178698438995498',
- )*/
- ));
- $adset->create(array(
- Object\AdSet::STATUS_PARAM_NAME => Object\AdSet::STATUS_PAUSED,
- ));
- }
- echo 'Adset ID: ' . $adset->id . " <br>\n";
- } catch (\Exception $e) {
- return $this->AdvertisingRenderErrorMessage($e);
- }
- //New method
- /**
- * Step 5 Create an AdImage
- * @var $image
- * @link https://developers.facebook.com/docs/marketing-api/reference/ad-image
- */
- try {
- $image = new Object\AdImage(null, $this->current_facebook_ads_account); // Invokes images preparation for Facebook ad instance
- $target_path = __DIR__ . '/assets/temp/'; // path where images will be streamed to
- if (!file_exists($target_path)) {
- mkdir($target_path, 0755); // creating path if one doesn't exist
- }
- $files_in_dir = array_diff(scandir($target_path), array('..', '.')); // checking for existing files in target directory
- $size = getimagesize($item['properties']['images_large'][0]); // getting image details
- $extension = image_type_to_extension($size[2]); // getting image extension from type
- $target_file_name = preg_replace(['/\./', '/\\s/', '/\\t/'], "_", strtolower($item['title'])) . $extension; // creating proper file name
- $target_file = $target_path . $target_file_name; // setting full target directory
- if (array_search($target_file_name, $files_in_dir) === false) { // checking if target file already exists
- $image_file = file_get_contents($item['properties']['images_large'][0]);
- file_put_contents($target_file, $image_file);
- }
- $image->{Object\Fields\AdImageFields::FILENAME} = $target_file; // Using target file as ad image
- $image->create();
- echo 'Image Hash: ' . $image->hash . " <br>\n";
- } catch (\Exception $e) {
- return $this->AdvertisingRenderErrorMessage($e);
- }
- /**
- * Step 6 Create an AdCreative
- */
- try {
- $creative = new Object\AdCreative(null, $this->current_facebook_ads_account);
- $available_creatives = $adset->getAdCreatives($creative::getFields());
- $current_creative = null;
- if (!empty($available_creatives)) {
- foreach ($available_creatives as $creative) { // loops through adsets
- if ($creative->name == 'Creative of '.$item['title']) { // If adset name matches the name given to new campaign, created campaign is then used
- $current_creative = $creative;
- }
- }
- }
- if (!is_null($current_creative)) {
- $creative = $current_creative;
- } else {
- $creative = new Object\AdCreative(null, $this->current_facebook_ads_account);
- $creative->setData(array(
- Object\Fields\AdCreativeFields::NAME => 'Creative of '.$item['title'],
- Object\Fields\AdCreativeFields::TITLE => $item['title'],
- Object\Fields\AdCreativeFields::BODY => $item['properties']['description'],
- Object\Fields\AdCreativeFields::IMAGE_HASH => $image->hash,
- Object\Fields\AdCreativeFields::LINK_URL => ipConfig()->get('globalPortalUrl'),
- Object\Fields\AdCreativeFields::OBJECT_URL => ipConfig()->get('globalPortalUrl'),
- ));
- $creative->create();
- }
- echo 'Creative ID: ' . $creative->id . " <br>\n";
- } catch (\Exception $e) {
- return $this->AdvertisingRenderErrorMessage($e);
- }
- /**
- * Step 7 Create an Ad
- *
- * Then, use the image hash returned from above. Finally, create your ad along with ad creative.
- * Please note that the ad creative is not created independently, rather its data structure
- * is appended to the ad group
- *
- * @link https://developers.facebook.com/docs/marketing-api/reference/adgroup
- */
- try {
- $ad = new Object\Ad(null, $this->current_facebook_ads_account);
- $last_ad = $adset->getAds($ad::getFields())->end()->exportData();
- //var_dump($last_ad); exit();
- $ad->setData(array(
- Object\Fields\AdFields::NAME => $item['title'].' #1',
- Object\Fields\AdFields::ADSET_ID => $adset->id,
- Object\Fields\AdFields::CREATIVE => array('creative_id' => $creative->id),
- ));
- $ad->create(array(
- Object\Ad::STATUS_PARAM_NAME => Object\Ad::STATUS_PAUSED,
- ));
- echo 'Ad ID:' . $ad->id . " <br>\n";
- } catch (\Exception $e) {
- return $this->AdvertisingRenderErrorMessage($e);
- }
- _e('Ad was posted successfully', 'Advertising');
- return;
- }
- /**
- * @param null $current_facebook_ads_account
- */
- public function AdvertisingNewAdAccount()
- {
- }
- /*****************************
- * End of Facebook Ads Controls Block
- *****************************/
- public function AdvertisingRenderErrorMessage($response)
- {
- $class_name = get_class($response);
- if (strpos($class_name, 'FacebookAds\Http\Exception') !== false) {
- return ipView('view/advertisingErrorMessageFacebookException.php', [
- 'message' => $response->getMessage(),
- 'code' => $response->getCode(),
- 'trace' => $response->getTraceAsString(),
- 'subcode' => $response->getErrorSubcode(), // @link https://developers.facebook.com/docs/marketing-api/error-reference#errorcodes
- 'error_user_title' => $response->getErrorUserTitle(),
- 'error_user_msg' => $response->getErrorUserMessage(),
- 'blame_spec' => $response->getErrorBlameFieldSpecs() // @link https://developers.facebook.com/docs/marketing-api/error-reference#blame_field_specs
- ])->render();
- } else {
- return ipView('view/advertisingErrorMessageException.php', [
- 'message' => $response->getMessage(),
- 'code' => $response->getCode(),
- 'trace' => $response->getTraceAsString()
- ])->render();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment