/**
  * @covers Pql::CreateValue
  */
 public function testCreateValue()
 {
     $this->assertEquals('hello', Pql::CreateValue(new TextValue('hello'))->value);
     $this->assertEquals('value1', Pql::CreateValue('value1')->value);
     $this->assertEquals(false, Pql::CreateValue(false)->value);
     $this->assertEquals('1', Pql::CreateValue(1)->value);
     $this->assertEquals('1.02', Pql::CreateValue(1.02)->value);
     $this->assertEquals('2012-12-02T12:45:00+08:00', DateTimeUtils::ToStringWithTimeZone(Pql::CreateValue($this->dateTime1)->value));
     $this->assertEquals('2012-12-02', DateTimeUtils::ToString(Pql::CreateValue($this->dateTime1->date)->value));
 }
 /**
  *
  */
 public function testCreateTraining()
 {
     $factory = new MarketplaceFactory();
     $training = $factory->buildTraining();
     $training->setName('test training');
     $training->setDescription('test training description');
     $training->activate();
     $service = new TrainingServiceManager($repository = new SapphireTrainingServiceRepository());
     $repository->add($training);
     $courses = $service->getCoursesByDate($training->getIdentifier(), DateTimeUtils::getCurrentDate());
 }
 /**
  * @see sfValidatorBase
  */
 protected function doClean($value)
 {
     $clean = (string) $value;
     if (!DateTimeUtils::validTimeString($value)) {
         throw new sfValidatorError($this, 'invalid');
     }
     $clean = DateTimeUtils::formatTime(DateTimeUtils::parseTime($value));
     $cleanedSeconds = DateTimeUtils::getTimeSeconds($value);
     if ($cleanedSeconds < DateTimeUtils::getTimeSeconds($this->getOption('startTime'))) {
         throw new sfValidatorError($this, 'start_time', array('value' => $clean, 'start_time' => $this->getOption('start_time')));
     }
     if ($cleanedSeconds > DateTimeUtils::getTimeSeconds($this->getOption('endTime'))) {
         throw new sfValidatorError($this, 'end_time', array('value' => $clean, 'end_time' => $this->getOption('end_time')));
     }
     return $clean;
 }
 /**
  * @covers Pql::CreateValue
  */
 public function testCreateValue()
 {
     $this->assertEquals('hello', Pql::CreateValue(new TextValue('hello'))->value);
     $this->assertEquals('value1', Pql::CreateValue('value1')->value);
     $this->assertEquals(false, Pql::CreateValue(false)->value);
     $this->assertEquals('1', Pql::CreateValue(1)->value);
     $this->assertEquals('1.02', Pql::CreateValue(1.02)->value);
     $this->assertEquals('2012-12-02T12:45:00+08:00', DateTimeUtils::ToStringWithTimeZone(Pql::CreateValue($this->dateTime1)->value));
     $this->assertEquals('2012-12-02', DateTimeUtils::ToString(Pql::CreateValue($this->dateTime1->date)->value));
     $values = Pql::CreateValue([23, 42, 5, 10, 1])->values;
     $this->assertEquals(5, count($values));
     $this->assertEquals(23, $values[0]->value);
     $this->assertEquals(42, $values[1]->value);
     $this->assertEquals(5, $values[2]->value);
     $this->assertEquals(10, $values[3]->value);
     $this->assertEquals(1, $values[4]->value);
 }
Beispiel #5
0
 function testDay_yyyy_mm_dd()
 {
     $date = "2011-10-16";
     $day = DateTimeUtils::day_yyyy_mm_dd($date);
     $this->assertEqual(16, $day, "Il giorno non corrisponde!!");
     /*
     try
     {
         DateTimeUtils::day_yyyy_mm_dd("10-07-2012");
         $this->fail("Viene accettata una data in un formato non corretto!");
     }
     catch(InvalidParameterException $ex)
     {
         //ok
     }
     */
 }
 /**
  * Creates a String from the Value.
  *
  * @param Value $value the value to convert
  * @return string the string representation of the value
  * @throws InvalidArgumentException if value cannot be converted
  */
 public static function ToString(Value $value)
 {
     if ($value instanceof BooleanValue) {
         return $value->value ? 'true' : 'false';
     } else {
         if ($value instanceof NumberValue || $value instanceof TextValue) {
             return strval($value->value);
         } else {
             if ($value instanceof DateTimeValue) {
                 return isset($value->value) ? DateTimeUtils::ToStringWithTimeZone($value->value) : '';
             } else {
                 if ($value instanceof DateValue) {
                     return DateTimeUtils::ToString($value->value);
                 } else {
                     throw new InvalidArgumentException(sprintf("Unsupported Value type [%s]", get_class($value)));
                 }
             }
         }
     }
 }
    $lineItemService = $user->GetService('LineItemService', 'v201311');
    // Set the ID of the order to get line items from.
    $orderId = 'INSERT_ORDER_ID_HERE';
    // Calculate time from three days ago.
    $threeDaysAgo = date(DateTimeUtils::$DFP_DATE_TIME_STRING_FORMAT, strtotime('-3 day'));
    // Create bind variables.
    $vars = MapUtils::GetMapEntries(array('orderId' => new NumberValue($orderId), 'threeDaysAgo' => new TextValue($threeDaysAgo)));
    // Create statement object to only select line items belonging to the order
    // and have been modified in the last 3 days.
    $filterStatement = new Statement("WHERE orderId = :orderId " . "AND lastModifiedDateTime >= :threeDaysAgo " . "LIMIT 500", $vars);
    // Get line items by statement.
    $page = $lineItemService->getLineItemsByStatement($filterStatement);
    // Display results.
    if (isset($page->results)) {
        $i = $page->startIndex;
        foreach ($page->results as $lineItem) {
            // Format lastModifiedDateTime for printing.
            $lastModifiedDateTime = DateTimeUtils::GetDateTime($lineItem->lastModifiedDateTime);
            $lastModifiedDateTimeText = $lastModifiedDateTime->format(DateTimeUtils::$DFP_DATE_TIME_STRING_FORMAT);
            print $i . ') Line item with ID "' . $lineItem->id . '", belonging to order ID "' . $lineItem->orderId . '", with name "' . $lineItem->name . '", and last modified ' . $lastModifiedDateTimeText . " was found.\n";
            $i++;
        }
    }
    print 'Number of results found: ' . $page->totalResultSetSize . "\n";
} catch (OAuth2Exception $e) {
    ExampleUtils::CheckForOAuth2Errors($e);
} catch (ValidationException $e) {
    ExampleUtils::CheckForOAuth2Errors($e);
} catch (Exception $e) {
    print $e->getMessage() . "\n";
}
// DfpUser.php directly via require_once.
// $path = '/path/to/dfp_api_php_lib/src';
$path = dirname(__FILE__) . '/lib';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php';
require_once 'Google/Api/Ads/Dfp/Util/v201508/StatementBuilder.php';
require_once 'Google/Api/Ads/Dfp/Util/v201508/DateTimeUtils.php';
require_once dirname(__FILE__) . '/examples/Common/ExampleUtils.php';
try {
    // Get DfpUser from credentials in "../auth.ini"
    // relative to the DfpUser.php file's directory.
    $user = new DfpUser();
    // Log SOAP XML request and response.
    $user->LogDefaults();
    // Get DateUtils
    $dateTimeUtils = new DateTimeUtils();
    // Get the LineItemService.
    $lineItemService = $user->GetService('LineItemService', 'v201508');
    // Create a statement to select all line items.
    $statementBuilder = new StatementBuilder();
    $statementBuilder->OrderBy('id DESC')->Limit(StatementBuilder::SUGGESTED_PAGE_LIMIT);
    $statementBuilder->Where("EndDateTime >= '" . date('Y-m-d', time() - 86400 * 7) . "'");
    //$statementBuilder->Limit("100");
    // Default for total result set size.
    $totalResultSetSize = 0;
    printf("Downloading and saving results to file\n");
    $fn = "./line-items.csv";
    $fp = fopen($fn, "a");
    fwrite($fp, implode(',', array('orderId', 'orderName', 'lineItemId', 'lineItemName', 'externalId', 'creationDateTime', 'startDateTime', 'endDateTime', 'priority', 'costType', 'lineItemType', 'impressionsDelivered', 'clicksDelivered', 'expectedDeliveryPercentage', 'actualDeliveryPercentage', 'status', 'notes', 'isMissingCreatives', 'primaryGoalType', 'primaryGoalUnitType', 'primaryGoalUnits', 'targetingGeo', 'targetingExcludedAdunits', 'targetingBrowser', 'targetingCategory', 'targetingDevice', 'targetingOs', 'targetingOsVersion', 'targetingCustom', 'frequencyCaps', 'targetingPlatform')) . "\n");
    do {
        // Get line items by statement.
 // Get the ReportService.
 $reportService = $user->GetService('ReportService', 'v201605');
 // Create report query.
 $reportQuery = new ReportQuery();
 $reportQuery->dimensions = array('ORDER_ID', 'ORDER_NAME');
 $reportQuery->dimensionAttributes = array('ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME', 'ORDER_END_DATE_TIME');
 $reportQuery->columns = array('AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM');
 // Create statement to filter for an order.
 $statementBuilder = new StatementBuilder();
 $statementBuilder->Where('order_id = :orderId')->WithBindVariableValue('orderId', $orderId);
 // Set the filter statement.
 $reportQuery->statement = $statementBuilder->ToStatement();
 // Set the start and end dates or choose a dynamic date range type.
 $reportQuery->dateRangeType = 'CUSTOM_DATE';
 $reportQuery->startDate = DateTimeUtils::ToDfpDateTime(new DateTime('-10 days', new DateTimeZone('America/New_York')))->date;
 $reportQuery->endDate = DateTimeUtils::ToDfpDateTime(new DateTime('now', new DateTimeZone('America/New_York')))->date;
 // Create report job.
 $reportJob = new ReportJob();
 $reportJob->reportQuery = $reportQuery;
 // Run report job.
 $reportJob = $reportService->runReportJob($reportJob);
 // Create report downloader.
 $reportDownloader = new ReportDownloader($reportService, $reportJob->id);
 // Wait for the report to be ready.
 $reportDownloader->waitForReportReady();
 // Change to your file location.
 $filePath = sprintf('%s.csv.gz', tempnam(sys_get_temp_dir(), 'delivery-report-'));
 printf("Downloading report to %s ...\n", $filePath);
 // Download the report.
 $reportDownloader->downloadReport('CSV_DUMP', $filePath);
 printf("done.\n");
 $lineItem->lineItemType = 'SPONSORSHIP';
 // Create inventory targeting.
 $inventoryTargeting = new InventoryTargeting();
 $inventoryTargeting->targetedPlacementIds = array($targetPlacementId);
 // Set targeting for line item.
 $targeting = new Targeting();
 $targeting->inventoryTargeting = $inventoryTargeting;
 $lineItem->targeting = $targeting;
 // Create the creative placeholder.
 $creativePlaceholder = new CreativePlaceholder();
 $creativePlaceholder->size = new Size(300, 250, FALSE);
 // Set the size of creatives that can be associated with this line item.
 $lineItem->creativePlaceholders = array($creativePlaceholder);
 // Set the line item's time to be now until the projected end date time.
 $lineItem->startDateTimeType = 'IMMEDIATELY';
 $lineItem->endDateTime = DateTimeUtils::GetDfpDateTime(new DateTime('+1 week'));
 // Set the line item to use 50% of the impressions.
 $lineItem->unitType = 'IMPRESSIONS';
 $lineItem->unitsBought = 50;
 // Set the cost type to match the unit type.
 $lineItem->costType = 'CPM';
 // Get forecast for line item.
 $forecast = $forecastService->getForecast($lineItem);
 // Display results.
 $matchedUnits = $forecast->matchedUnits;
 $percentAvailableUnits = $forecast->availableUnits / $matchedUnits * 100;
 $unitType = strtolower($forecast->unitType);
 printf("%d %s matched.\n", $matchedUnits, $unitType);
 printf("%d%% %s available.\n", $percentAvailableUnits, $unitType);
 if (isset($forecast->possibleUnits)) {
     $percentPossibleUnits = $forecast->possibleUnits / $matchedUnits * 100;
 /**
  * @return string
  */
 public function getDays()
 {
     return DateTimeUtils::getDayDiff($this->dto->getStartDate(), $this->dto->getEndDate());
 }
 public static function updateResultFilters($peer)
 {
     $all_fields = $peer->__getAllFields();
     foreach (Params::keys() as $key) {
         if (self::isFilter($key, Params::get($key))) {
             $value = Params::get($key);
             $filter_call = self::getFilterCall($key);
             if (self::isDateReversingEnabled()) {
                 if ($all_fields[self::getFilterField($key)]["type"] == "date") {
                     $value = DateTimeUtils::reverse_date_dd_mm_yyyy(Params::get($key));
                 }
             }
             $peer->{$filter_call}($value);
         }
     }
 }
 /**
  * @param int $training_id
  * @param string $company_url_segment
  * @return array
  * @throws Exception
  */
 public function getCompanyTraining($training_id, $company_url_segment)
 {
     if (empty($company_url_segment)) {
         throw new Exception("Invalid Company");
     }
     //@todo: remove dataobjects dependencies
     $company = Company::get()->filter('URLSegment', $company_url_segment)->first();
     $training = empty($training_id) ? null : TrainingService::get()->byID($training_id);
     if (!$company) {
         throw new Exception("Invalid Company");
     }
     if (!$training) {
         //get default program
         $training = $company->getDefaultTraining();
     }
     //check if program belongs to selected company
     $training_company = $training->Company();
     if ($training_company->getIdentifier() != $company->getIdentifier()) {
         //if not , get default program
         $training = $company->getDefaultTraining();
     }
     if (!$this->training_manager->isActive($training->getIdentifier())) {
         return Security::permissionFailure($this->controller, "non active training!.");
     }
     $courses = $this->training_manager->getCoursesByDate($training->getIdentifier(), DateTimeUtils::getCurrentDate());
     $courses_vm = new ArrayList();
     foreach ($courses as $course) {
         $course_dto = new CourseDTO($course->getIdentifier(), $course->getName(), $course->getDescription(), $course->getTraining()->getIdentifier(), null, null, null, $course->level()->Level, $course->isOnline(), null, null, null, null, null, $course->getOnlineLink());
         $locations_dto = $this->course_repository->getLocationsByDate($course->getIdentifier(), DateTimeUtils::getCurrentDate());
         $locations_vm = new ArrayList();
         foreach ($locations_dto as $location_dto) {
             $locations_vm->push(new CourseLocationViewModel($location_dto));
         }
         $courses_vm->push(new CourseViewModel($course_dto, $locations_vm, $course->projects()));
     }
     $res = array('Company' => $company, 'Training' => $training, 'Courses' => $courses_vm, 'Slug' => $training->getSlug());
     return $res;
 }
Beispiel #14
0
    <?php 
DateTimeUtils::addDate('2012-12-01', 1, 'y');
DateTimeUtils::getWeekDay('2012/10/01', '/');
DateTimeUtils::isLeapYear('2012');
DateTimeUtils::timeFromNow(strtotime("2012-10-26 14:15:13"));
class DateTimeUtils
{
    /**
     * Checks for leap year, returns true if it is. No 2-digit year check. Also
     * handles julian calendar correctly.
     * @param integer $year year to check
     * @return boolean true if is leap year
     */
    public static function isLeapYear($year)
    {
        $year = self::digitCheck($year);
        if ($year % 4 != 0) {
            return false;
        }
        if ($year % 400 == 0) {
            return true;
        } else {
            if ($year > 1582 && $year % 100 == 0) {
                return false;
            }
        }
        return true;
    }
    /**
     * Fix 2-digit years. Works for any century.
     * Assumes that if 2-digit is more than 30 years in future, then previous century.
Beispiel #15
0
 public function setupWithMap($do, $params)
 {
     $all_fields = $this->__getAllFields();
     foreach ($params as $key => $value) {
         $saved = false;
         if ($all_fields[$key]["type"] == "date") {
             $do->{$key} = DateTimeUtils::reverse_date_dd_mm_yyyy($value);
             $saved = true;
         }
         if (!$saved) {
             $do->{$key} = $value;
         }
     }
     return $do;
 }
Beispiel #16
0
 public function __construct()
 {
     $this->constructTime = (new \DateTime())->getTimestamp();
     $this->type = DateTimeUtils::getType();
     $this->timestamp = DateTimeUtils::getTimestamp();
 }
 /**
  * Since this method doesn't support by google, they suggest this step :
  *  1) Get the line item using LineItemService.getLineItemsByStatement method
  *	2) Remove the id field from the LineItem object
  *	3) Use the LineItemService.createLineItems method with that new object
  *	4) Capture the new line item in the response
  *	5) Get all line item creative associations for the old line item using LineItemCreativeAssociationService
  *	6) For each LineItemCreativeAssociation object, replace the old line item ID with the new one
  *	7) Pass each LineItemCreativeAssociation object into the LineItemCreativeAssociationService.createLineItemCreativeAssociations method
  */
 public function copyLineItems($dtToCopy)
 {
     // Get the LineItemService.
     $lineItemService = $this->dfp_user->GetService('LineItemService', 'v201508');
     $statementBuilder = new StatementBuilder();
     $statementBuilder->Where('id = :id')->Limit(1)->WithBindVariableValue('id', $dtToCopy['lineItemId']);
     // Get the line item.
     $page = $lineItemService->getLineItemsByStatement($statementBuilder->ToStatement());
     if (isset($page->results)) {
         //echo "<br/>BEFORE<br/>";
         //echopre($page->results);
         //$newLineItem = $lineItemService->createLineItems($page->results);
         //echopre($newLineItem);
         /* Adjust name, startDateTime and endDateTime to keep the lineitem unique */
         $randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 5);
         $page->results[0]->name = $page->results[0]->name . "(copy-{$randomString})";
         $page->results[0]->startDateTime = DateTimeUtils::ToDfpDateTime(new DateTime('+1 day', new DateTimeZone('Asia/Jakarta')));
         $page->results[0]->endDateTime = DateTimeUtils::ToDfpDateTime(new DateTime('+2 day', new DateTimeZone('Asia/Jakarta')));
         $page->results[0]->allowOverbook = true;
         $newLineItem = $lineItemService->createLineItems($page->results);
         #echo "<br/>New Lineitems<br/>";
         #echopre($newLineItem);
         /*if line item copied with all creative below it*/
         if ($dtToCopy['withCreative'] > 0) {
             $licaService = $this->dfp_user->GetService('LineItemCreativeAssociationService', 'v201508');
             $statementBuilderLicas = new StatementBuilder();
             $statementBuilderLicas->Where('lineItemId = :lineItemId')->Limit(StatementBuilder::SUGGESTED_PAGE_LIMIT)->WithBindVariableValue('lineItemId', $dtToCopy['lineItemId']);
             // Get LICAs by statement.
             $pageLicas = $licaService->getLineItemCreativeAssociationsByStatement($statementBuilderLicas->ToStatement());
             if (isset($pageLicas->results)) {
                 #echo "<br/>data licas<br/>";
                 #echopre($pageLicas);
                 foreach ($pageLicas->results as $key => $val) {
                     $val->lineItemId = $newLineItem[0]->id;
                     // Create the LICAs on the server.
                     $licas = $licaService->createLineItemCreativeAssociations($val);
                     #echo $key  . "<br/>";
                     #echopre($licas);
                 }
             }
         }
     }
 }
    // relative to the DfpUser.php file's directory.
    $user = new DfpUser();
    // Log SOAP XML request and response.
    $user->LogDefaults();
    $proposalService = $user->GetService('ProposalService', 'v201608');
    // Create a statement to select Marketplace comments.
    $statementBuilder = new StatementBuilder();
    $statementBuilder->Where('proposalId = :proposalId')->WithBindVariableValue('proposalId', $proposalId);
    // Retrieve a small amount of Marketplace comments at a time, paging through
    // until all comments have been retrieved.
    $totalResultSetSize = 0;
    do {
        $page = $proposalService->getMarketplaceCommentsByStatement($statementBuilder->ToStatement());
        if ($page->results !== null) {
            // Print out some information for each Marketplace comment.
            $totalResultSetSize = $page->totalResultSetSize;
            $i = $page->startIndex;
            foreach ($page->results as $marketplaceComment) {
                printf("%d) Marketplace comment with creation time '%s' and comment '%s' " . "was found.\n", $i++, DateTimeUtils::ToStringWithTimeZone($marketplaceComment->creationTime), $marketplaceComment->comment);
            }
        }
        $statementBuilder->IncreaseOffsetBy(StatementBuilder::SUGGESTED_PAGE_LIMIT);
    } while ($statementBuilder->GetOffset() < $totalResultSetSize);
    printf("Number of results found: %d\n", $totalResultSetSize);
} catch (OAuth2Exception $e) {
    ExampleUtils::CheckForOAuth2Errors($e);
} catch (ValidationException $e) {
    ExampleUtils::CheckForOAuth2Errors($e);
} catch (Exception $e) {
    printf("%s\n", $e->getMessage());
}
 /**
  * @return bool|string
  */
 public function getEndDateDay()
 {
     return !is_null($this->getEndDate()) ? DateTimeUtils::getDay($this->getEndDate()) : '';
 }
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php';
require_once 'Google/Api/Ads/Dfp/Util/v201605/DateTimeUtils.php';
require_once 'Google/Api/Ads/Dfp/Util/v201605/StatementBuilder.php';
require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php';
try {
    // Get DfpUser from credentials in "../auth.ini"
    // relative to the DfpUser.php file's directory.
    $user = new DfpUser();
    // Log SOAP XML request and response.
    $user->LogDefaults();
    // Get the LineItemService.
    $lineItemService = $user->GetService('LineItemService', 'v201605');
    // Create a statement to select only recently updated line items.
    $statementBuilder = new StatementBuilder();
    $statementBuilder->Where('lastModifiedDateTime >= :lastModifiedDateTime')->OrderBy('id ASC')->Limit(StatementBuilder::SUGGESTED_PAGE_LIMIT)->WithBindVariableValue('lastModifiedDateTime', DateTimeUtils::ToDfpDateTime(new DateTime('-1 day', new DateTimeZone('America/New_York'))));
    // Default for total result set size.
    $totalResultSetSize = 0;
    do {
        // Get line items by statement.
        $page = $lineItemService->getLineItemsByStatement($statementBuilder->ToStatement());
        // Display results.
        if (isset($page->results)) {
            $totalResultSetSize = $page->totalResultSetSize;
            $i = $page->startIndex;
            foreach ($page->results as $lineItem) {
                printf("%d) Line item with ID %d, belonging to order %d, and name '%s' " . "was found.\n", $i++, $lineItem->id, $lineItem->orderId, $lineItem->name);
            }
        }
        $statementBuilder->IncreaseOffsetBy(StatementBuilder::SUGGESTED_PAGE_LIMIT);
    } while ($statementBuilder->GetOffset() < $totalResultSetSize);
require_once 'Google/Api/Ads/Dfp/Util/v201511/StatementBuilder.php';
require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php';
try {
    // Get DfpUser from credentials in "../auth.ini"
    // relative to the DfpUser.php file's directory.
    $user = new DfpUser();
    // Log SOAP XML request and response.
    $user->LogDefaults();
    // Get the ReconciliationReportService.
    $reconciliationReportService = $user->GetService('ReconciliationReportService', 'v201511');
    // Get the NetworkService.
    $networkService = $user->GetService('NetworkService', 'v201511');
    $network = $networkService->getCurrentNetwork();
    // Create a statement to select the last month's reconciliation report.
    $statementBuilder = new StatementBuilder();
    $statementBuilder->Where('startDate = :startDate')->OrderBy('id ASC')->Limit(1)->WithBindVariableValue('startDate', DateTimeUtils::ToString(DateTimeUtils::ToDfpDateTime(new DateTime('first day of last month', new DateTimeZone($network->timeZone)))->date));
    // Default for total result set size.
    $totalResultSetSize = 0;
    do {
        // Get reconciliation reports by statement.
        $page = $reconciliationReportService->getReconciliationReportsByStatement($statementBuilder->ToStatement());
        // Display results.
        if (isset($page->results)) {
            $totalResultSetSize = $page->totalResultSetSize;
            $i = $page->startIndex;
            foreach ($page->results as $reconciliationReport) {
                printf("%d) Reconciliation report with ID %d for month %s/%s was found.\n", $i++, $reconciliationReport->id, $reconciliationReport->startDate->month, $reconciliationReport->startDate->year);
            }
        }
        $statementBuilder->IncreaseOffsetBy(StatementBuilder::SUGGESTED_PAGE_LIMIT);
    } while ($statementBuilder->GetOffset() < $totalResultSetSize);
Beispiel #22
0
 /**
  * Creates a String from the Value.
  *
  * @param Value $value the value to convert
  * @return string the string representation of the value
  * @throws InvalidArgumentException if value cannot be converted
  */
 public static function ToString(Value $value)
 {
     if ($value instanceof BooleanValue) {
         return $value->value ? 'true' : 'false';
     } else {
         if ($value instanceof NumberValue || $value instanceof TextValue) {
             return strval($value->value);
         } else {
             if ($value instanceof DateTimeValue) {
                 return isset($value->value) ? DateTimeUtils::ToStringWithTimeZone($value->value) : '';
             } else {
                 if ($value instanceof DateValue) {
                     return DateTimeUtils::ToString($value->value);
                 } else {
                     if ($value instanceof SetValue) {
                         $pqlValues = $value->values;
                         if (!isset($pqlValues)) {
                             return '';
                         } else {
                             $valuesAsStrings = array();
                             foreach ($pqlValues as $pqlValue) {
                                 $valuesAsStrings[] = self::ToString($pqlValue);
                             }
                             return implode(',', $valuesAsStrings);
                         }
                     } else {
                         throw new InvalidArgumentException(sprintf("Unsupported Value type [%s]", get_class($value)));
                     }
                 }
             }
         }
     }
 }
     $lineItem = new LineItem();
     $lineItem->name = 'Line item #' . uniqid();
     $lineItem->orderId = $orderId;
     $lineItem->targeting = $targeting;
     $lineItem->lineItemType = 'STANDARD';
     $lineItem->allowOverbook = 'TRUE';
     // Create the creative placeholder.
     $creativePlaceholder = new CreativePlaceholder();
     $creativePlaceholder->size = new Size(300, 250, FALSE);
     // Set the size of creatives that can be associated with this line item.
     $lineItem->creativePlaceholders = array($creativePlaceholder);
     // Set the creative rotation type to even.
     $lineItem->creativeRotationType = 'EVEN';
     // Set the length of the line item to run.
     $lineItem->startDateTimeType = 'IMMEDIATELY';
     $lineItem->endDateTime = DateTimeUtils::GetDfpDateTime(new DateTime('+1 month'));
     // Set the cost per unit to $2.
     $lineItem->costType = 'CPM';
     $lineItem->costPerUnit = new Money('USD', 2000000);
     // Set the number of units bought to 500,000 so that the budget is
     // $1,000.
     $lineItem->unitsBought = 500000;
     $lineItem->unitType = 'IMPRESSIONS';
     $lineItems[] = $lineItem;
 }
 // Create the line items on the server.
 $lineItems = $lineItemService->createLineItems($lineItems);
 // Display results.
 if (isset($lineItems)) {
     foreach ($lineItems as $lineItem) {
         print 'A line item with with ID "' . $lineItem->id . '", belonging to order ID "' . $lineItem->orderId . '", and name "' . $lineItem->name . "\" was created.\n";
 public function getStartDay()
 {
     return DateTimeUtils::getDay($this->StartDate);
 }
 $adUnitTargeting->adUnitId = $rootAdUnitId;
 $adUnitTargeting->includeDescendants = true;
 $inventoryTargeting->targetedAdUnits = array($adUnitTargeting);
 // Create targeting.
 $targeting = new Targeting();
 $targeting->inventoryTargeting = $inventoryTargeting;
 // Create a proposal line item.
 $proposalLineItem = new ProposalLineItem();
 $proposalLineItem->name = sprintf('Proposal line item #%s', uniqid());
 $proposalLineItem->proposalId = $proposalId;
 $proposalLineItem->rateCardId = $rateCardId;
 $proposalLineItem->productId = $productId;
 $proposalLineItem->targeting = $targeting;
 // Set the length of the proposal line item to run.
 $proposalLineItem->startDateTime = DateTimeUtils::ToDfpDateTime(new DateTime('now', new DateTimeZone('America/New_York')));
 $proposalLineItem->endDateTime = DateTimeUtils::ToDfpDateTime(new DateTime('+1 month', new DateTimeZone('America/New_York')));
 // Set delivery specifications for the proposal line item.
 $proposalLineItem->deliveryRateType = 'EVENLY';
 $proposalLineItem->creativeRotationType = 'OPTIMIZED';
 // Set billing specifications for the proposal line item.
 $proposalLineItem->billingCap = 'CAPPED_CUMULATIVE';
 $proposalLineItem->billingSource = 'THIRD_PARTY_VOLUME';
 // Set pricing for the proposal line item for 1000 impressions at a CPM of $2
 // for a total value of $2.
 $goal = new Goal();
 $goal->units = 1000;
 $goal->unitType = 'IMPRESSIONS';
 $proposalLineItem->goal = $goal;
 $proposalLineItem->cost = new Money('USD', 2000000);
 $proposalLineItem->costPerUnit = new Money('USD', 2000000);
 $proposalLineItem->rateType = 'CPM';
 function logicToRaw($logic_value)
 {
     return DateTimeUtils::reverse_date_dd_mm_yyyy($logic_value);
 }
 /**
  * @covers DateTimeUtils::ToStringForTimeZone
  */
 public function testToStringForTimeZone()
 {
     $this->assertEquals($this->stringDateTime1, DateTimeUtils::ToStringForTimeZone($this->dfpDateTime1, self::TIME_ZONE_ID1));
     $this->assertEquals($this->stringDateTime2, DateTimeUtils::ToStringForTimeZone($this->dfpDateTime2, self::TIME_ZONE_ID2));
     $this->assertEquals($this->stringDateTime3, DateTimeUtils::ToStringForTimeZone($this->dfpDateTime3, self::TIME_ZONE_ID3));
     $this->assertEquals($this->stringDateTime1, DateTimeUtils::ToStringForTimeZone(DateTimeUtils::ToDfpDateTime($this->dateTime1->setTimeZone(new DateTimeZone(self::TIME_ZONE_ID2))), self::TIME_ZONE_ID1));
     $this->assertEquals($this->stringDateTime2, DateTimeUtils::ToStringForTimeZone(DateTimeUtils::ToDfpDateTime($this->dateTime2->setTimeZone(new DateTimeZone(self::TIME_ZONE_ID1))), self::TIME_ZONE_ID2));
     $this->assertEquals($this->stringDateTime3, DateTimeUtils::ToStringForTimeZone(DateTimeUtils::ToDfpDateTime($this->dateTime3->setTimeZone(new DateTimeZone(self::TIME_ZONE_ID1))), self::TIME_ZONE_ID3));
 }
 public function CompanyCombo()
 {
     $source = array();
     $result = $this->course_company_query->handle(new OpenStackImplementationNamesQuerySpecification(DateTimeUtils::getCurrentDate()));
     foreach ($result->getResult() as $dto) {
         $source[$dto->getValue()] = $dto->getValue();
     }
     $ddl = new DropdownField('company-term', $title = null, $source);
     $ddl->setEmptyString('-- Show All --');
     return $ddl;
 }
 $lineItem->roadblockingType = 'ONE_OR_MORE';
 // Set the creative rotation type.
 $lineItem->creativeRotationType = 'OPTIMIZED';
 // Create the creative placeholder size.
 $size = new Size();
 $size->width = 300;
 $size->height = 250;
 $size->isAspectRatio = false;
 // Create the creative placeholder.
 $creativePlaceholder = new CreativePlaceholder();
 $creativePlaceholder->size = $size;
 // Set the size of creatives that can be associated with this line item.
 $lineItem->creativePlaceholders = array($creativePlaceholder);
 // Set the length of the line item to run.
 $lineItem->startDateTimeType = 'IMMEDIATELY';
 $lineItem->endDateTime = DateTimeUtils::ToDfpDateTime(new DateTime('+30 days', new DateTimeZone('America/New_York')));
 // Set the cost type.
 $lineItem->costType = 'CPM';
 // Set the line item to use 50% of the impressions.
 $goal = new Goal();
 $goal->goalType = 'DAILY';
 $goal->unitType = 'IMPRESSIONS';
 $goal->units = 50;
 $lineItem->primaryGoal = $goal;
 // Get forecast for prospective line item.
 $prospectiveLineItem = new ProspectiveLineItem();
 $prospectiveLineItem->lineItem = $lineItem;
 $options = new AvailabilityForecastOptions();
 $options->includeContendingLineItems = true;
 $options->includeTargetingCriteriaBreakdown = true;
 $forecast = $forecastService->getAvailabilityForecast($prospectiveLineItem, $options);
$path = dirname(__FILE__) . '/../../../../lib';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php';
require_once 'Google/Api/Ads/Dfp/Util/v201508/StatementBuilder.php';
require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php';
try {
    // Get DfpUser from credentials in "../auth.ini"
    // relative to the DfpUser.php file's directory.
    $user = new DfpUser();
    // Log SOAP XML request and response.
    $user->LogAll();
    // Get the OrderService.
    $orderService = $user->GetService('OrderService', 'v201508');
    // Create a statement to select only orders that are starting soon.
    $statementBuilder = new StatementBuilder();
    $statementBuilder->Where('status = :status AND startDateTime >= :now AND startDateTime <= :soon')->OrderBy('id ASC')->Limit(StatementBuilder::SUGGESTED_PAGE_LIMIT)->WithBindVariableValue('status', 'APPROVED')->WithBindVariableValue('now', DateTimeUtils::ToDfpDateTime(new DateTime('now', new DateTimeZone('America/New_York'))))->WithBindVariableValue('soon', DateTimeUtils::ToDfpDateTime(new DateTime('5 day', new DateTimeZone('America/New_York'))));
    // Default for total result set size.
    $totalResultSetSize = 0;
    do {
        // Get orders by statement.
        $page = $orderService->getOrdersByStatement($statementBuilder->ToStatement());
        // Display results.
        if (isset($page->results)) {
            $totalResultSetSize = $page->totalResultSetSize;
            $i = $page->startIndex;
            foreach ($page->results as $order) {
                printf("%d) Order with ID %d, name '%s', and advertiser ID %d was " . "found.\n", $i++, $order->id, $order->name, $order->advertiserId);
            }
        }
        $statementBuilder->IncreaseOffsetBy(StatementBuilder::SUGGESTED_PAGE_LIMIT);
    } while ($statementBuilder->GetOffset() < $totalResultSetSize);