queryWithOrderBy() public static method

public static queryWithOrderBy ( $object, $queryData, $orderByField, $ascending = true, $limit = 1000, $page, $returnFields = false, Infusionsoft_App $app = null )
$app Infusionsoft_App
 public static function queryWithOrderBy($object, $queryData, $orderByField = null, $ascending = true, $limit = 1000, $page = 0, $returnFields = false, Infusionsoft_App $app = null)
 {
     if (PHP_INT_SIZE < 8) {
         throw new Exception("This version oh php is not 64 bit it is " . PHP_INT_SIZE * 8 . ' bit.  ContactGroupAssign cannot be synced unless running on a 64bit version of php.');
     }
     Infusionsoft_ContactGroupAssign::removeField('Id');
     if (is_array($returnFields) && in_array('Id', $returnFields)) {
         unset($returnFields[array_search('Id', $returnFields)]);
         $returnFields[] = 'ContactId';
         $returnFields[] = 'GroupId';
         $returnFields = array_values($returnFields);
     }
     $results = Infusionsoft_DataService::queryWithOrderBy($object, $queryData, $orderByField, $ascending, $limit, $page, $returnFields, $app);
     Infusionsoft_ContactGroupAssign::addCustomField('Id');
     self::addCompoundKeyToResults($results);
     if ($orderByField == 'ContactId' && $ascending && count($results) > 0) {
         if ($page > 0) {
             self::removeRecordsForContactsAlreadyProcessed(self::$lastProcessedContactId, $results);
         }
         $lastRecordOfResultSet = end($results);
         $lastContactId = $lastRecordOfResultSet->ContactId;
         self::$lastProcessedContactId = $lastContactId;
         $foundLastRecordForLastContact = false;
         $extraPages = 1;
         while (!$foundLastRecordForLastContact && count($results) > 0) {
             Infusionsoft_ContactGroupAssign::removeField('Id');
             $extraResults = Infusionsoft_DataService::queryWithOrderBy($object, $queryData, $orderByField, $ascending, $limit, $page + $extraPages, $returnFields, $app);
             Infusionsoft_ContactGroupAssign::addCustomField('Id');
             self::addCompoundKeyToResults($extraResults);
             foreach ($extraResults as $extraResult) {
                 //If somehow, between calls, a lot of tags are applied, and our "last" contact gets pushed down to the second page, we need to not break because of new contacts higher up on the page.
                 if ($extraResult->ContactId <= $lastContactId) {
                     $results[] = $extraResult;
                 } else {
                     $foundLastRecordForLastContact = true;
                     break;
                 }
             }
             if (count($extraResults) == 0) {
                 $foundLastRecordForLastContact = true;
             }
             $extraPages++;
         }
         return $results;
     }
     /** @var Infusionsoft_ContactGroupAssign $result */
     return $results;
 }
 public static function getLastOrderId($recurringOrderId)
 {
     //find all Orders with a matching JobRecurringId and put them in this array, sorted by date.
     $matchingOrders = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_Job(), array('JobRecurringId' => $recurringOrderId), 'DateCreated', false);
     if (empty($matchingOrders)) {
         $subscription = new Infusionsoft_RecurringOrder($recurringOrderId);
         if ($subscription->OriginatingOrderId != null) {
             $matchingOrders[] = new Infusionsoft_Job($subscription->OriginatingOrderId);
         }
     }
     if (!empty($matchingOrders)) {
         $latestMatchingOrder = array_shift($matchingOrders);
         return $latestMatchingOrder->Id;
     } else {
         return false;
     }
 }
 public static function queryWithOrderBy($object, $queryData, $orderByField, $ascending = true, $limit = 1000, $month = 0, $returnFields = false, Infusionsoft_App $app = null)
 {
     //Set a hard date for earliest_month_to_query so that we don't get into infinite loops trying to find commissions in the 1700's (this happens when you sync an empty application)
     if ($month == 0) {
         $firstOrder = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_Job(), array('Id' => '%'), 'Id', true, 1);
         if (!empty($firstOrder)) {
             self::$earliest_month_to_query = $firstOrder[0]->DateCreated;
         }
     }
     if (empty(self::$earliest_month_to_query)) {
         self::$earliest_month_to_query = '2013-01-01';
     }
     //Calculate beginning of this month
     $startDate = date('Y-m-01 00:00:00', strtotime(" - {$month} months"));
     $startDate = date(Infusionsoft_Service::apiDateFormat, strtotime($startDate));
     $endDate = date('Y-m-t 23:59:59', strtotime($startDate));
     $endDate = date(Infusionsoft_Service::apiDateFormat, strtotime($endDate));
     //get an array of all affiliates
     $affiliates = self::$affiliates_cache;
     if (empty($affiliates)) {
         $page = 0;
         do {
             $affiliatesPage = Infusionsoft_DataService::query(new Infusionsoft_Affiliate(), array('Id' => '%'), 1000, $page, array('Id'), $app);
             $page += 1;
             $affiliates = array_merge($affiliates, $affiliatesPage);
         } while (sizeof($affiliatesPage) >= 1000);
     }
     //Now get all of the commissions from each one
     $objects = array();
     while (count($objects) < $limit && $startDate >= self::$earliest_month_to_query) {
         foreach ($affiliates as $affiliate) {
             if (get_class($object) == 'Infusionsoft_Commission') {
                 $objects = array_merge($objects, Infusionsoft_APIAffiliateService::affCommissions($affiliate->Id, $startDate, $endDate, $app));
             } elseif (get_class($object) == 'Infusionsoft_Clawback') {
                 $objects = array_merge($objects, Infusionsoft_APIAffiliateService::affClawbacks($affiliate->Id, $startDate, $endDate, $app));
             }
         }
         $startDate = date('Y-m-d', strtotime($startDate . '- 1 month'));
         $endDate = date('Y-m-t 23:59:59', strtotime($startDate));
         $startDate = date(Infusionsoft_Service::apiDateFormat, strtotime($startDate));
         $endDate = date(Infusionsoft_Service::apiDateFormat, strtotime($endDate));
     }
     self::$orderByField = $orderByField;
     usort($objects, array('Infusionsoft_AffiliateDataService', 'sortCommissions'));
     return $objects;
 }
 public function save($app = null)
 {
     if ($this->Id == '') {
         $invoices = Infusionsoft_DataService::query(new Infusionsoft_Invoice(), array('JobId' => $this->OrderId), 1000, 0, false, $app);
         if (count($invoices) == 0) {
             throw new Infusionsoft_Exception("Could not get invoice for order: " . $this->OrderId . " while creating adding an order item.");
         }
         /** @var Infusionsoft_Invoice $invoice */
         $invoice = array_shift($invoices);
         $result = Infusionsoft_InvoiceService::addOrderItem($invoice->Id, $this->ProductId, $this->ItemType, $this->PPU, $this->Qty, $this->ItemDescription, $this->Notes, $app);
         if (!$result) {
             throw new Infusionsoft_Exception("Couldn't save orderitem: " . json_encode($this->toArray()));
         }
         //Infusionsoft doesn't always use consecutive Ids, but it is very very very rare that the id won't be consecutive if a new record is inserted very quickly after the previous, so even though this isn't ideal, it's what we are doing.
         $newestOrderItems = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_OrderItem(), array('OrderId' => $this->OrderId), 'Id', false, 1);
         $newestOrderItem = array_shift($newestOrderItems);
         $this->Id = $newestOrderItem->Id;
     }
     $result = parent::save($app);
     return $result;
 }
    <input type="submit">
    <input type="hidden" name="go">
</form>

<?php 
include '../infusionsoft.php';
include 'testUtils.php';
if (isset($_REQUEST['go'])) {
    $dayDelta = $_GET['dayDelta'];
    if ($dayDelta < 0) {
        $start = $dayDelta;
        $end = 0;
    } else {
        $start = 0;
        $end = $dayDelta;
    }
    $startDate = $_GET['startDate'];
    $dateField = $_GET['dateField'];
    $contacts = array();
    for ($i = $start; $i <= $end; $i++) {
        $date = date('Y-m-d', strtotime($startDate) + $i * 24 * 60 * 60);
        $newContacts = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_Contact(), array($dateField => $date . '%'), $dateField, false);
        echo 'Found ' . count($newContacts) . ' where ' . $dateField . ' is ' . $date . '<br/>';
        $contacts = array_merge($contacts, $newContacts);
    }
    var_dump($contacts);
}
?>
</body>
</html>
?>
<pre><?php 
didItWorkObject($out);
?>
</pre>

<h1>Testing Loading of an object by Id Using Query</h1><?php 
$out = Infusionsoft_DataService::query(new Infusionsoft_Contact(), array('Id' => $contact->Id));
?>
<pre><?php 
didItWorkNonEmptyArray($out);
?>
</pre>

<h1>Testing Loading of an object by Id Using Query With Order By</h1><?php 
$out = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_Contact(), array('Id' => $contact->Id), "FirstName", true);
?>
<pre><?php 
didItWorkNonEmptyArray($out);
?>
</pre>


<h1>Testing Delete</h1>
<?php 
$out = $contact->delete();
?>
<pre>
It Worked!
</pre>
 public static function chargeInvoiceArbitraryAmountUsingPayPlan($invoiceId, $cardId, $amount, $merchantAccountId, $paymentNotes = 'API Arbitrary Payment')
 {
     $result = false;
     //Get Invoice info so we can set the temporary PayPlan to match the amount we want to charge
     $invoice = new Infusionsoft_Invoice($invoiceId);
     if ($amount + $invoice->TotalPaid <= $invoice->InvoiceTotal) {
         $temporaryFirstPayment = $amount + $invoice->TotalPaid;
     } else {
         $temporaryFirstPayment = $invoice->InvoiceTotal - $invoice->TotalPaid;
     }
     //Get current PayPlan info so we can set it back after taking the payment
     $payPlan = Infusionsoft_DataService::query(new Infusionsoft_PayPlan(), array('InvoiceId' => $invoiceId));
     if (!empty($payPlan)) {
         $payPlan = reset($payPlan);
         /**
          * @var Infusionsoft_PayPlan $payPlan
          */
         $payPlanItems = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_PayPlanItem(), array('PayPlanId' => $payPlan->Id), 'DateDue', true);
         $payPlanStartDate = $payPlan->StartDate;
         $payPlanFirstPaymentAmount = $payPlan->FirstPayAmt;
         $numberOfPayments = count($payPlanItems) - 1;
         $payPlanItemDueDate1 = null;
         $daysBetweenPayments = 1;
         foreach ($payPlanItems as $index => $payPlanItem) {
             if ($index == 0) {
                 continue;
             }
             /**
              * @var Infusionsoft_PayPlanItem $payPlanItem
              */
             if ($payPlanItemDueDate1 == null) {
                 $payPlanItemDueDate1 = $payPlanItem->DateDue;
             } else {
                 $daysBetweenPayments = round((strtotime($payPlanItem->DateDue) - strtotime($payPlanItemDueDate1)) / 60 / 60 / 24);
                 break;
             }
         }
         if ($payPlanItemDueDate1 == null) {
             $payPlanItemDueDate1 = $payPlanStartDate;
         }
     } else {
         //If there is no PayPlan, then just set the order to the default of all due up front
         CakeLog::write('warning', 'PayPlan not found for InvoiceId: ' . $invoiceId . ' PayPlan will be set to the default');
         $payPlanFirstPaymentAmount = $invoice->InvoiceTotal;
         $payPlanStartDate = $invoice->DateCreated;
         $numberOfPayments = 0;
         $payPlanItemDueDate1 = $invoice->DateCreated;
         $daysBetweenPayments = 1;
     }
     try {
         Infusionsoft_InvoiceService::addPaymentPlan($invoiceId, 0, $cardId, $merchantAccountId, 1, 1, $temporaryFirstPayment, Infusionsoft_App::formatDate(date('Y-m-d')), Infusionsoft_App::formatDate(date('Y-m-d', strtotime(' + 1 day'))), 1, 1);
         $result = Infusionsoft_InvoiceService::chargeInvoice($invoiceId, $paymentNotes, $cardId, $merchantAccountId, false);
     } catch (Exception $e) {
         CakeLog::write('error', 'Failed to charge invoice arbitrary amount! InvoiceId: ' . $invoiceId . ' Infusionsoft error: ' . $e->getMessage());
     }
     try {
         Infusionsoft_InvoiceService::addPaymentPlan($invoiceId, 0, $cardId, $merchantAccountId, 1, 3, $payPlanFirstPaymentAmount, $payPlanStartDate, $payPlanItemDueDate1, $numberOfPayments, $daysBetweenPayments);
     } catch (Exception $e) {
         CakeLog::write('error', 'Failed to reset payment plan after chargeInvoiceArbitraryAmount! InvoiceId: ' . $invoiceId . ' PayPlan Details: ' . json_encode(compact('payPlanFirstPaymentAmount', 'payPlanStartDate', 'payPlanItemDueDate1', 'numberOfPayments', 'daysBetweenPayments')));
     }
     return $result;
 }
<?php

include '../infusionsoft.php';
include 'object_editor_all_tables.php';
include '../tests/testUtils.php';
?>
<br/><?php 
renderLoadForm();
if (!empty($_GET['OrderItemId'])) {
    $order_item = new Infusionsoft_OrderItem($_GET['OrderItemId']);
    $order = new Infusionsoft_Job($order_item->OrderId);
    $subscription = new Infusionsoft_RecurringOrder($order->JobRecurringId);
    $orders = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_Job(), array('JobRecurringId' => $subscription->Id), 'StartDate');
    $order_items = array();
    $invoices = array();
    foreach ($orders as $order) {
        $order_items[$order->Id] = Infusionsoft_DataService::query(new Infusionsoft_OrderItem(), array('OrderId' => $order->Id));
        $invoices[$order->Id] = Infusionsoft_DataService::query(new Infusionsoft_Invoice(), array('JobId' => $order->Id));
        if (is_array($invoices[$order->Id]) && count($invoices[$order->Id]) > 0) {
            $invoice_items[$order->Id] = Infusionsoft_DataService::query(new Infusionsoft_InvoiceItem(), array('InvoiceId' => $invoices[$order->Id][0]->Id));
            $invoice_payments[$order->Id] = Infusionsoft_DataService::query(new Infusionsoft_InvoicePayment(), array('InvoiceId' => $invoices[$order->Id][0]->Id));
            if (count($invoice_payments[$order->Id] > 0)) {
                foreach ($invoice_payments[$order->Id] as $invoice_payment) {
                    $invoice_payment_payments[$invoice_payment->Id] = new Infusionsoft_Payment($invoice_payment->PaymentId);
                }
            }
        }
    }
    $contact = new Infusionsoft_Contact($order->ContactId);
    ?>
<h1>Contact</h1><?php 
<form>
    <input type="submit">
    <input type="hidden" name="go">
</form>
<?php 
include '../infusionsoft.php';
include 'testUtils.php';
if (isset($_REQUEST['go'])) {
    $out = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_PayPlanItem(), array('Id' => '%'), 'Id', false);
    var_dump($out);
}
    ?>
"><?php 
    echo $file_name;
    ?>
</a><br/><br/><?php 
    if ($_GET['object'] == 'Template') {
        echo 'Exporting email templates into files.' . "<br/>";
        $page = 0;
        do {
            echo 'Fetching page ' . $page . '<br/>';
            flush();
            $object_fields = $object->getFields();
            if (in_array('Id', $object_fields)) {
                $results = Infusionsoft_DataService::queryWithOrderBy(new $class_name(), array('Id' => '%'), 'Id', true, 100, $page);
            } else {
                $results = Infusionsoft_DataService::queryWithOrderBy(new $class_name(), array($object_fields[0] => '%'), $object_fields[0], true, 100, $page);
            }
            foreach ($results as $result) {
                if ($result->PieceType == 'Email' && substr($result->PieceTitle, 0, 14) != 'An email draft' && substr($result->PieceTitle, 0, 12) != 'API Template' && $result->Categories != 'Product Fulfillment') {
                    try {
                        $template = Infusionsoft_APIEmailService::getEmailTemplate($result->Id);
                        $file_name = "../exports/" . $_GET['object'] . '_' . $result->Id . '_' . date('Ymd-h.i.s') . '.txt';
                        echo 'Creating file: ' . $file_name . '<br/>';
                        $file = fopen($file_name, 'w');
                        fwrite($file, 'Title: ' . $template['pieceTitle'] . "\n");
                        fwrite($file, 'Categories: ' . $template['categories'] . "\n");
                        fwrite($file, 'From: ' . $template['fromAddress'] . "\n");
                        fwrite($file, 'To: ' . $template['toAddress'] . "\n");
                        fwrite($file, 'Cc: ' . $template['ccAddress'] . "\n");
                        fwrite($file, 'Bcc: ' . $template['bccAddress'] . "\n");
                        fwrite($file, 'Subject: ' . $template['subject'] . "\n\n");
<?php

include '../infusionsoft.php';
$contact = new Infusionsoft_Contact();
$customFields = Infusionsoft_CustomFieldService::getCustomFields(new Infusionsoft_Contact());
/** @var Infusionsoft_DataFormField $customField */
$customFieldsAsArray = array();
foreach ($customFields as $customField) {
    $customFieldsAsArray[] = '_' . $customField->Name;
}
$contact->addCustomFields($customFieldsAsArray);
$contacts = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_Contact(), array('Id' => '%'), 'LastUpdated', 1, 1, array('Id'));
var_dump($contacts);