Upload scorm packages in moodle course module using moodle rest api - moodle

I have already created a course using moodle RestAPI(function name : core_course_create_courses). then i want to upload a scorm package in moodle course module/activity.
i have write some code for that,this code will create a module in that course. i don't know how to upload scorm package in that course module.
here is my code
Add function core_course_create_modules in lib/db/services.php at line no : 327
'core_course_create_modules' => array(
'classname' => 'core_course_external',
'methodname' => 'create_modules',
'classpath' => 'course/externallib.php',
'description' => 'Creates modules in a course',
'type' => 'write',
'capabilities' => 'moodle/course:manageactivities',
)
Add 3 method in Courses/externallib.php file
2.1)create_modules_parameters
=> `public static function create_modules_parameters() {
$courseconfig = get_config('moodlecourse'); //needed for many default values
return new external_function_parameters(
array(
'courseid' => new external_value(PARAM_INT, 'ID of the course'),
'modules' => new external_multiple_structure(
new external_single_structure(
array(
'modulename' => new external_value(PARAM_TEXT, 'Name of the module'),
'section' => new external_value(PARAM_INT, 'Sectionnumber'),
'name' => new external_value(PARAM_TEXT, "Title of the module", VALUE_OPTIONAL),
'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
'description' => new external_value(PARAM_TEXT, 'the new module description', VALUE_OPTIONAL),
'descriptionformat' => new external_format_value(PARAM_INT, 'description', VALUE_DEFAULT),
'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_DEFAULT, $courseconfig->groupmode),
'groupmembersonly' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_DEFAULT, 0),
'groupingid' => new external_value(PARAM_INT, 'grouping id',VALUE_DEFAULT, 0)
)
)
)
)
);
}`
2.2) create_modules
`public static function create_modules($courseid, $modules) {
global $CFG, $DB;
require_once($CFG->dirroot . "/course/lib.php");
require_once($CFG->dirroot . "/course/modlib.php");
$moduleinfo = new stdClass();
$course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
// Clean the parameters.
$params = self::validate_parameters(self::create_modules_parameters(), array('courseid' => $courseid,'modules' => $modules));
$context = context_course::instance($course->id);
require_capability('moodle/course:manageactivities', $context);
foreach ($params['modules'] as $mod) {
$module = (object) $mod;
$moduleobject = $DB->get_record('modules', array('name'=>$module->modulename), '*', MUST_EXIST);
if(trim($module->modulename) == ''){
throw new invalid_parameter_exception('Invalid module name');
}
if (!course_allowed_module($course, $module->modulename)){
throw new invalid_parameter_exception('Module "'.$module->modulename.'" is disabled');
}
if(is_null($module->visible)){
$module->visible = 1;
}
if(is_null($module->description)){
$module->description = '';
}
if(!is_null($module->name) && trim($module->name) != ''){
$moduleinfo->name = $module->name;
}
$moduleinfo->modulename = $module->modulename;
$moduleinfo->visible = $module->visible;
$moduleinfo->course = $courseid;
$moduleinfo->section = $module->section;
$moduleinfo->introeditor = array('text' => $module->description, 'format' => $module->descriptionformat, 'itemid' => 0);
$moduleinfo->quizpassword = '';
$moduleinfo->groupmode = $module->groupmode;
$moduleinfo->groupmembersonly = $module->groupmembersonly;
$moduleinfo->groupingid = $module->groupingid;
$retVal = create_module($moduleinfo);
$result[] = array('id'=>$retVal->id);
}
return $result;
}`
2.3)create_modules_returns
`public static function create_modules_returns() {
return new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_INT, 'new module id')
)
)
);
}`
Parameters to call function
$module['courseid'] = 1; //course id
$module['modules'][] = array(
"section" => 2,//PARAM_INT, 'Sectionnumber'
"modulename" => "scorm",//PARAM_TEXT, 'Name of the module'
"name" => "Testing1",// OPTIONAL PARAM_TEXT, "Title of the module",
"visible" => 1,// OPTIONAL PARAM_INT, '1: available to student, 0:not available',
"description"=>"testing module using rest api", // OPTIONAL PARAM_TEXT, 'the new module description',
"descriptionformat"=>1,//PARAM_INT, 'description', VALUE_DEFAULT
//"groupmode" => "",//PARAM_INT, 'no group, separate, visible', VALUE_DEFAULT, $courseconfig->groupmode
//"groupmembersonly" => "",//PARAM_INT, '1: yes, 0: no', VALUE_DEFAULT, 0
//"groupingid" => "",//PARAM_INT, 'grouping id',VALUE_DEFAULT, 0
);
as per above code ,
its take name field as a scorm packages, in the admin side its display name as a scorm, when i was click on that its display errors:
screenshot for error
so, i don't know how to upload scorm package in course module using moodle Rest api, how can i do ?
Thank you.

Related

Unable to get getConfigurationAndPricing in PromoStandard

I am trying to getting Product getConfigurationAndPricing using Promostandard Soap API but for some reason I am unable to get those information. Here is my code snapit
$productId = 'TM17907'
$client = new \SoapClient("https://pspriceconfig100.pcna.online/psPriceConfig.svc?singleWsdl", array('trace' => 1));
$options = array(
'wsVersion' => '1.0.0',
'id' => $apiUsername,
'password' => $apiPassword,
'productId' => $productId,
'currency' => 'USD',
'fobId' => '1',
'priceType' => 'List',
'localizationCountry'=>'US',
'localizationLanguage' => 'en',
'configurationType' => 'Decorated',
'cache_wsdl' => WSDL_CACHE_MEMORY
);
try{
$result = $client->__soapCall('getConfigurationAndPricing',[$options]);
} catch (\Exception $e){
$output->writeln("<error>HTTP issue generate in product ID : ".$productId.", Row No.".$currentRow."</error>");
continue;
}
I am using to get PCNA products.

Fedex SOAP Request Failing

I am looking for the reason why the below request is failing to retrieve information. This is copied from the Fedex developer website and it doesn't work. When my program hits the GetRates line it throws a could not connect to host exception. I tried adding the connection_timeout and setting the default_timeout in php and neither appear to work. I contacted the Fedex dev team and they are receiving my post successfully I am just not able to get any response besides the fault. Has anyone had experience with Fedex or know what might cause this to be failing?
I am posting my current code below. I am using PHP7 on an AS400 machine using Zendserver.
<?php
// Copyright 2009, FedEx Corporation. All rights reserved.
// Version 12.0.0
require_once('../library/fedex-common.php5');
$newline = "<br />";
//The WSDL is not included with the sample code.
//Please include and reference in $path_to_wsdl variable.
$path_to_wsdl = "../wsdl/RateService_v24.wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
ini_set('soap.wsdl_cache_ttl',0);
$client = new SoapClient($path_to_wsdl, array('trace' => 1, 'connection_timeout' => 30)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array(
'ParentCredential' => array(
'Key' => getProperty('parentkey'),
'Password' => getProperty('parentpassword')
),
'UserCredential' => array(
'Key' => getProperty('key'),
'Password' => getProperty('password')
)
);
$request['ClientDetail'] = array(
'AccountNumber' => getProperty('shipaccount'),
'MeterNumber' => getProperty('meter')
);
$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '24',
'Intermediate' => '0',
'Minor' => '0'
);
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
$request['RequestedShipment']['ServiceType'] = 'INTERNATIONAL_PRIORITY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
$request['RequestedShipment']['TotalInsuredValue']=array(
'Ammount'=>100,
'Currency'=>'USD'
);
$request['RequestedShipment']['Shipper'] = addShipper();
$request['RequestedShipment']['Recipient'] = addRecipient();
$request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment();
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = addPackageLineItem1();
try {
if(setEndpoint('changeEndpoint')){
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}
$response = $client -> getRates($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR'){
$rateReply = $response -> RateReplyDetails;
echo '<table border="1">';
echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td></tr><tr>';
$serviceType = '<td>'.$rateReply -> ServiceType . '</td>';
if($rateReply->RatedShipmentDetails && is_array($rateReply->RatedShipmentDetails)){
$amount = '<td>$' . number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",") . '</td>';
}elseif($rateReply->RatedShipmentDetails && ! is_array($rateReply->RatedShipmentDetails)){
$amount = '<td>$' . number_format($rateReply->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",") . '</td>';
}
if(array_key_exists('DeliveryTimestamp',$rateReply)){
$deliveryDate= '<td>' . $rateReply->DeliveryTimestamp . '</td>';
}else if(array_key_exists('TransitTime',$rateReply)){
$deliveryDate= '<td>' . $rateReply->TransitTime . '</td>';
}else {
$deliveryDate='<td> </td>';
}
echo $serviceType . $amount. $deliveryDate;
echo '</tr>';
echo '</table>';
printSuccess($client, $response);
}else{
printError($client, $response);
}
writeToLog($client); // Write to log file
} catch (SoapFault $exception) {
printFault($exception, $client);
}
function addShipper(){
$shipper = array(
'Contact' => array(
'PersonName' => 'Sender Name',
'CompanyName' => 'Sender Company Name',
'PhoneNumber' => '9012638716'
),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'Collierville',
'StateOrProvinceCode' => 'TN',
'PostalCode' => '38017',
'CountryCode' => 'US'
)
);
return $shipper;
}
function addRecipient(){
$recipient = array(
'Contact' => array(
'PersonName' => 'Recipient Name',
'CompanyName' => 'Company Name',
'PhoneNumber' => '9012637906'
),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'Richmond',
'StateOrProvinceCode' => 'BC',
'PostalCode' => 'V7C4V4',
'CountryCode' => 'CA',
'Residential' => false
)
);
return $recipient;
}
function addShippingChargesPayment(){
$shippingChargesPayment = array(
'PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => getProperty('billaccount'),
'CountryCode' => 'US'
)
)
);
return $shippingChargesPayment;
}
function addLabelSpecification(){
$labelSpecification = array(
'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
'ImageType' => 'PDF', // valid values DPL, EPL2, PDF, ZPLII and PNG
'LabelStockType' => 'PAPER_7X4.75'
);
return $labelSpecification;
}
function addSpecialServices(){
$specialServices = array(
'SpecialServiceTypes' => array('COD'),
'CodDetail' => array(
'CodCollectionAmount' => array(
'Currency' => 'USD',
'Amount' => 150
),
'CollectionType' => 'ANY' // ANY, GUARANTEED_FUNDS
)
);
return $specialServices;
}
function addPackageLineItem1(){
$packageLineItem = array(
'SequenceNumber'=>1,
'GroupPackageCount'=>1,
'Weight' => array(
'Value' => 50.0,
'Units' => 'LB'
),
'Dimensions' => array(
'Length' => 108,
'Width' => 5,
'Height' => 5,
'Units' => 'IN'
)
);
return $packageLineItem;
}
?>

Facebook marketing ap: cant create Ad

I receive an erro of Invalid parameter but it doesnt tell me which invalid parameter is. The error is:
Fatal error: Uncaught exception
'FacebookAds\Http\Exception\AuthorizationException' with message
'Invalid parameter' in
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Exception\RequestException.php:140
Stack trace: #0
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Client.php(215):
FacebookAds\Http\Exception\RequestException::create(Object(FacebookAds\Http\Response))
1 C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Request.php(282):
FacebookAds\Http\Client->sendRequest(Object(FacebookAds\Http\Request))
2 C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Api.php(151):
FacebookAds\Http\Request->execute() #3
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Api.php(193):
FacebookAds\Api->executeRequest(Object(FacebookAds\Http\Request)) #4
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Object\AbstractCrudObject.php(208):
FacebookAds\Api->call('/act_XXXXXXXX...', 'POST', Array) #5 C:\A in
C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Exception\RequestException.php
on line 140
This is my code and it seems that the error is in the last object $ad = new Ad, everything is created fine until the Ad, it shows me this error.
<?php
//date_default_timezone_set('America/Lima');
//require_once('vendor/autoload.php');
//$campaign_id = '6053849657204';
// Configurations
$access_token = 'MYTOKEN';
$app_id = 'MYAPPID';
$app_secret = 'MYAPPSECRET';
$account_id = 'act_MYACCOUNT';
define('SDK_DIR', __DIR__ . ''); // Path to the SDK directory
$loader = include SDK_DIR.'/vendor/autoload.php';
date_default_timezone_set('America/Los_Angeles');
// Configurations - End
if(is_null($access_token) || is_null($app_id) || is_null($app_secret)) {
throw new \Exception(
'You must set your access token, app id and app secret before executing'
);
}
if (is_null($account_id)) {
throw new \Exception(
'You must set your account id before executing');
}
use FacebookAds\Api;
Api::init($app_id, $app_secret, $access_token);
/**
* Step 1 Read the AdAccount (optional)
*/
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
$account = (new AdAccount($account_id))->read(array(
AdAccountFields::ID,
AdAccountFields::NAME,
AdAccountFields::ACCOUNT_STATUS,
));
echo "\nUsing this account: ";
echo $account->id."\n";
// Check the account is active
if($account->{AdAccountFields::ACCOUNT_STATUS} !== 1) {
throw new \Exception(
'This account is not active');
}
/**
* Step 2 Create the Campaign
*/
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Values\AdObjectives;
$campaign = new Campaign(null, $account->id);
$campaign->setData(array(
CampaignFields::NAME => 'Noticia 1',
CampaignFields::OBJECTIVE => AdObjectives::LINK_CLICKS,
));
$campaign->validate()->create(array(
Campaign::STATUS_PARAM_NAME => Campaign::STATUS_PAUSED,
));
echo "Campaign ID:" . $campaign->id . "\n";
/**
* Step 3 Search Targeting
*/
use FacebookAds\Object\TargetingSearch;
use FacebookAds\Object\Search\TargetingSearchTypes;
use FacebookAds\Object\TargetingSpecs;
use FacebookAds\Object\Fields\TargetingSpecsFields;
$results = TargetingSearch::search(
$type = TargetingSearchTypes::INTEREST,
$class = null,
$query = 'facebook');
// we'll take the top result for now
$target = (count($results)) ? $results->current() : null;
echo "Using target: ".$target->name."\n";
$targeting = new TargetingSpecs();
$targeting->{TargetingSpecsFields::GEO_LOCATIONS}
= array('countries' => array('PE'));
/*$targeting->{TargetingSpecsFields::INTERESTS} = array(
array(
'id' => $target->id,
'name' => $target->name,
),
);*/
/**
* Step 4 Create the AdSet
*/
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\Values\OptimizationGoals;
use FacebookAds\Object\Values\BillingEvents;
$adset = new AdSet(null, $account->id);
$adset->setData(array(
AdSetFields::NAME => 'Latam 1',
AdSetFields::CAMPAIGN_ID => $campaign->id,
AdSetFields::DAILY_BUDGET => '150',
AdSetFields::TARGETING => $targeting,
AdSetFields::OPTIMIZATION_GOAL => OptimizationGoals::REACH,
AdSetFields::BILLING_EVENT => BillingEvents::IMPRESSIONS,
AdSetFields::BID_AMOUNT => '1',
AdSetFields::START_TIME =>
(new \DateTime("+1 week"))->format(\DateTime::ISO8601),
AdSetFields::END_TIME =>
(new \DateTime("+2 week"))->format(\DateTime::ISO8601),
));
$adset->validate()->create(array(
AdSet::STATUS_PARAM_NAME => AdSet::STATUS_ACTIVE,
));
echo 'AdSet ID: '. $adset->id . "\n";
/**
* Step 5 Create an AdImage
*/
use FacebookAds\Object\AdImage;
use FacebookAds\Object\Fields\AdImageFields;
$image = new AdImage(null, $account->id);
$image->{AdImageFields::FILENAME}
= dirname(__FILE__).'/image.jpg';
$image->create();
echo 'Image Hash: '.$image->hash . "\n";
/**
* Step 6 Create an AdCreative
*/
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\AdCreativeObjectStorySpec;
use FacebookAds\Object\Fields\AdCreativeObjectStorySpecFields;
use FacebookAds\Object\Fields\AdCreativeFields;
$link_data = new AdCreativeLinkData();
$link_data->setData(array(
AdCreativeLinkDataFields::MESSAGE => 'MY DESC',
AdCreativeLinkDataFields::LINK => 'MY WEB',
AdCreativeLinkDataFields::CAPTION => 'My caption',
AdCreativeLinkDataFields::IMAGE_HASH => $image->hash,
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => 'MY PAGE ID',
AdCreativeObjectStorySpecFields::LINK_DATA => $link_data,
));
$creative = new AdCreative(null, $account->id);
$creative->setData(array(
AdCreativeFields::NAME => 'Sample Creative',
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));
$creative->create();
echo 'Creative ID: '.$creative->id . "\n";
/**
* Step 7 Create an Ad
*/
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdFields;
$datax = array(
AdFields::NAME => 'My Ad',
AdFields::ADSET_ID => $adset->id,
AdFields::CREATIVE => array(
'creative_id' => $creative->id,
),
);
$ad = new Ad(null, $account->id);
$ad->setData($datax);
$ad->create(array(
Ad::STATUS_PARAM_NAME => Ad::STATUS_PAUSED,
));
echo 'Ad ID:' . $ad->id . "\n";
The issue was that you needed to specify a valid Link and Page ID. I figured that out by adding more logging in the code below by adding this piece of code,
use FacebookAds\Logger\CurlLogger;
Api::init($app_id, $app_secret, $access_token);
// Create the CurlLogger
$logger = new CurlLogger();
// To write to a file pass in a file handler
// $logger = new CurlLogger(fopen('test','w'));
// Attach the logger to the Api instance
Api::instance()->setLogger($logger);
Once you've added the above code to your php project, it will console output the curl version of the API calls being executed by the SDK. You can make the API call that was failing in a terminal using curl and get the specific error that the API throws for debugging. (Currently in the PHP SDK the exact error doesn't get propagated up in the exceptions.)
You can check out the complete working code snippet here,
<?php
$access_token = '<ACCESS_TOKEN>';
$app_id = <APP_ID>;
$app_secret = '<APP_SECRET>';
// should begin with "act_" (eg: $account_id = 'act_1234567890';)
$account_id = 'act_<ACCOUNT_ID>';
$page_id = 0; // REPLACE THIS WITH VALID PAGE ID.
// Configurations - End
if (is_null($access_token) || is_null($app_id) || is_null($app_secret)) {
throw new \Exception(
'You must set your access token, app id and app secret before executing'
);
}
if (is_null($account_id)) {
throw new \Exception(
'You must set your account id before executing');
}
define('SDK_DIR', __DIR__ . '/..'); // Path to the SDK directory
$loader = include SDK_DIR.'/vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
Api::init($app_id, $app_secret, $access_token);
// Create the CurlLogger
$logger = new CurlLogger();
// To write to a file pass in a file handler
// $logger = new CurlLogger(fopen('test','w'));
// Attach the logger to the Api instance
Api::instance()->setLogger($logger);
/**
* Step 1 Read the AdAccount (optional)
*/
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
$account = (new AdAccount($account_id))->read(array(
AdAccountFields::ID,
AdAccountFields::NAME,
AdAccountFields::ACCOUNT_STATUS,
));
echo "\nUsing this account: ";
echo $account->id."\n";
// Check the account is active
if($account->{AdAccountFields::ACCOUNT_STATUS} !== 1) {
throw new \Exception(
'This account is not active');
}
/**
* Step 2 Create the Campaign
*/
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Values\AdObjectives;
$campaign = new Campaign(null, $account->id);
$campaign->setData(array(
CampaignFields::NAME => 'Noticia 1',
CampaignFields::OBJECTIVE => AdObjectives::LINK_CLICKS,
));
$campaign->validate()->create(array(
Campaign::STATUS_PARAM_NAME => Campaign::STATUS_PAUSED,
));
echo "Campaign ID:" . $campaign->id . "\n";
/**
* Step 3 Search Targeting
*/
use FacebookAds\Object\TargetingSearch;
use FacebookAds\Object\Search\TargetingSearchTypes;
use FacebookAds\Object\TargetingSpecs;
use FacebookAds\Object\Fields\TargetingSpecsFields;
$results = TargetingSearch::search(
$type = TargetingSearchTypes::INTEREST,
$class = null,
$query = 'facebook');
// we'll take the top result for now
$target = (count($results)) ? $results->current() : null;
echo "Using target: ".$target->name."\n";
$targeting = new TargetingSpecs();
$targeting->{TargetingSpecsFields::GEO_LOCATIONS}
= array('countries' => array('PE'));
/*$targeting->{TargetingSpecsFields::INTERESTS} = array(
array(
'id' => $target->id,
'name' => $target->name,
),
);*/
/**
* Step 4 Create the AdSet
*/
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\Values\OptimizationGoals;
use FacebookAds\Object\Values\BillingEvents;
$adset = new AdSet(null, $account->id);
$adset->setData(array(
AdSetFields::NAME => 'Latam 1',
AdSetFields::CAMPAIGN_ID => $campaign->id,
AdSetFields::DAILY_BUDGET => '150',
AdSetFields::TARGETING => $targeting,
AdSetFields::OPTIMIZATION_GOAL => OptimizationGoals::REACH,
AdSetFields::BILLING_EVENT => BillingEvents::IMPRESSIONS,
AdSetFields::BID_AMOUNT => '1',
AdSetFields::START_TIME =>
(new \DateTime("+1 week"))->format(\DateTime::ISO8601),
AdSetFields::END_TIME =>
(new \DateTime("+2 week"))->format(\DateTime::ISO8601),
));
$adset->validate()->create(array(
AdSet::STATUS_PARAM_NAME => AdSet::STATUS_ACTIVE,
));
echo 'AdSet ID: '. $adset->id . "\n";
/**
* Step 5 Create an AdImage
*/
use FacebookAds\Object\AdImage;
use FacebookAds\Object\Fields\AdImageFields;
$image = new AdImage(null, $account->id);
$image->{AdImageFields::FILENAME}
= dirname(__FILE__).'/image.jpg';
$image->create();
echo 'Image Hash: '.$image->hash . "\n";
/**
* Step 6 Create an AdCreative
*/
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\AdCreativeObjectStorySpec;
use FacebookAds\Object\Fields\AdCreativeObjectStorySpecFields;
use FacebookAds\Object\Fields\AdCreativeFields;
$link_data = new AdCreativeLinkData();
$link_data->setData(array(
AdCreativeLinkDataFields::MESSAGE => 'MY DESC',
AdCreativeLinkDataFields::LINK => 'www.google.com',
AdCreativeLinkDataFields::CAPTION => 'My caption',
AdCreativeLinkDataFields::IMAGE_HASH => $image->hash,
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => $page_id,
AdCreativeObjectStorySpecFields::LINK_DATA => $link_data,
));
$creative = new AdCreative(null, $account->id);
$creative->setData(array(
AdCreativeFields::NAME => 'Sample Creative',
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));
$creative->create();
echo 'Creative ID: '.$creative->id . "\n";
/**
* Step 7 Create an Ad
*/
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdFields;
$datax = array(
AdFields::NAME => 'My Ad',
AdFields::ADSET_ID => $adset->id,
AdFields::CREATIVE => array(
'creative_id' => $creative->id,
),
);
$ad = new Ad(null, $account->id);
$ad->setData($datax);
$ad->create(array(
Ad::STATUS_PARAM_NAME => Ad::STATUS_PAUSED,
));
echo 'Ad ID:' . $ad->id . "\n";

Cant Create Facebook Ad via Ads API

I am trying to create a Facebook AD via their PHP SDK. The problem lies in the creation of the ad itself. If I comment out the last piece, its creates the adset. When I run this code, I get the error "a Parent ID is required"
try {
///////////////////////////// CREATE AD SET ////////////////////////////////////
$data = array(
AdSetFields::NAME => $adname,
AdSetFields::BID_TYPE => 'CPC',
AdSetFields::BID_INFO => array(
'CLICKS' => 6,
),
AdSetFields::CAMPAIGN_STATUS => AdSet::STATUS_PAUSED,
AdSetFields::DAILY_BUDGET => 500000,
AdSetFields::CAMPAIGN_GROUP_ID => $campaign_id,
AdSetFields::TARGETING => array(
'age_min' => 30,
'age_max' => 45,
'page_types' => array(
'desktopfeed',
),
'geo_locations' => array(
'countries' => array(
'US',
),
),
),
);
$adset = new AdSet(null, $account_id);
$adset->create($data);
$adset_id = $adset->id;
echo $adset_id.'-';
//////////////////////CREATE AD IMAGE ///////////////////////////////
$image = new AdImage(null, $account_id);
$image->{AdImageFields::FILENAME} = '../adimages/epsom.jpg';
$image->create();
$creative = new AdCreative(null, $account_id);
$creative->setData(array(
AdCreativeFields::TITLE => $adtitle,
AdCreativeFields::BODY => $addesc,
AdCreativeFields::OBJECT_URL => $tracking_promoted_url,
AdCreativeFields::IMAGE_HASH => $image->hash,
));
$creative->create();
echo $creative->id.'-';
/////////////////////////////// CREATE AD GROUP ////////////////////////////
$fields = array(array(
AdGroupFields::CREATIVE =>
array('creative_id' => $creative->id),
AdGroupFields::ADGROUP_STATUS => AdGroup::STATUS_PAUSED,
AdGroupFields::NAME => 'My First AdGroup',
AdGroupFields::CAMPAIGN_ID => $adset_id,
));
$ad = new AdGroup();
$ad->create($fields);
echo 'AdGroup ID:' . $adgroup->id . "-";
} catch (RequestException $e) {
echo 'Caught Exception: '.$e->getMessage().PHP_EOL
.'Code: '.$e->getCode().PHP_EOL
.'HTTP status Code: '.$e->getHttpStatusCode().PHP_EOL;
}
You're missing the parent ID parameter when you create the adgroup. The 2nd parameter should be the account ID you want to create this adgroup under:
$adgroup = new Adgroup(null, $accountId);
If you copied this from a doc, let me know and we can update.
You may reference to the latest doc: https://developers.facebook.com/docs/marketing-api/reference/ad-campaign
From there, you will need to specify the ad account id(AD_ACCOUNT_ID) and ad campaign id(CAMPAIGN_GROUP_ID)

Drupal 7 | Form managed file upload image preview

I'm can't get to work image preview on Drupal 7 Form managed file.
I have for code like this in template.php:
function testform($form, &$form_state) {
$form = array();
$form['con_image'] = array(
'#type' => 'managed_file',
'#title' => t('Image'),
'#required' => TRUE,
'#default_value' => variable_get('con_image', ''),
'#progress_indicator' => 'bar',
'#progress_message' => 'Uploading ...',
'#upload_location' => 'public://gallery/',
'#theme' => 'test',
'#upload_validators' => array(
'file_validate_is_image' => array(),
'file_validate_extensions' => array('jpg jpeg'),
'file_validate_image_resolution' => array('6000x4000','800x600'),
'file_validate_size' => array(6 * 1024 * 1024),
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Add to site'),
);
return $form;
}
I call testform after checking additional conditions (like userpoints) via code
$arr = drupal_get_form('testform');
print drupal_render($arr);
The form itself is working, I'm able to add image to node (programmatically) but cannot get the preview of image during upload process. I try to use #theme but it seems doesn't work at all.
My theme function looks like this:
function theme_test($variables) {
$element = $variables['element'];
$output = '';
$base = drupal_render_children($element); // renders element as usual
if($element['fid']['#value'] != 0) {
// if image is uploaded show its thumbnail to the output HTML
$output .= '<div class="multifield-thumbnail">';
$output .= theme('image_style', array('style_name' => 'thumbnail', 'path' => file_load($element['fid']['#value'])->uri, 'getsize' => FALSE));
$output .= '</div>';
}
Any ideas?
You need to declare your theme with a hook_theme in your module.
function yourmodule_theme() {
return array(
'test' => array(
'render element' => 'element',
)
);
}