/**
 * Insert InvoiceDBO into database
 *
 * @param InvoiceDBO &$dbo InvoiceDBO to add to database
 */
function add_InvoiceDBO(&$dbo)
{
    $DB = DBConnection::getDBConnection();
    // Build SQL
    $sql = $DB->build_insert_sql("invoice", array("accountid" => intval($dbo->getAccountID()), "date" => $dbo->getDate(), "periodbegin" => $dbo->getPeriodBegin(), "periodend" => $dbo->getPeriodEnd(), "note" => $dbo->getNote(), "terms" => intval($dbo->getTerms()), "outstanding" => $dbo->getOutstanding()));
    // Run query
    if (!mysql_query($sql, $DB->handle())) {
        throw new DBException(mysql_error($DB->handle()));
    }
    // Get auto-increment ID
    $id = mysql_insert_id($DB->handle());
    // Validate ID
    if ($id === false) {
        // DB error
        throw new DBException("Could not retrieve ID from previous INSERT!");
    }
    if ($id == 0) {
        // No ID?
        throw new DBException("Previous INSERT did not generate an ID");
    }
    // Add line-items to database as well
    if (($itemdbo_array = $dbo->getItems()) != null) {
        foreach ($itemdbo_array as $itemdbo) {
            $itemdbo->setInvoiceID($id);
            add_InvoiceItemDBO($itemdbo);
        }
    }
    // Update Purchase DBO's with a prev invoice id set to -1
    foreach ($dbo->getUpdatePurchases() as $purchaseDBO) {
        $purchaseDBO->setPrevInvoiceID($id);
        switch (get_class($purchaseDBO)) {
            case "DomainServicePurchaseDBO":
                update_DomainServicePurchaseDBO($purchaseDBO);
                break;
            case "HostingServicePurchaseDBO":
                update_HostingServicePurchaseDBO($purchaseDBO);
                break;
            case "ProductPurchaseDBO":
                update_ProductPurchaseDBO($purchaseDBO);
                break;
        }
    }
    // Store ID in DBO
    $dbo->setID($id);
}
 /**
  * Renew Domain
  *
  * Set the DomainServucePurchase date to the date provided in the form, then update
  * the DomainServicePurchaseDBO in the database
  */
 function renew_domain()
 {
     $registry = ModuleRegistry::getModuleRegistry();
     if (!($module = $registry->getModule($this->get['dpurchase']->getModuleName()))) {
         throw new SWException("Failed to load registrar module: " . $this->get['dpurchase']->getModuleName());
     }
     // Update DBO
     $this->get['dpurchase']->setDate(DBConnection::format_datetime($this->post['date']));
     $this->get['dpurchase']->setTerm($this->post['term'] ? $this->post['term']->getTermLength() : null);
     update_DomainServicePurchaseDBO($this->get['dpurchase']);
     // Update Registrar (but only if the "contact registrar" box was checked)
     if ($this->post['registrar']) {
         $module->renewDomain($this->get['dpurchase'], $this->get['dpurchase']->getTerm());
     }
     // Success!
     $this->setMessage(array("type" => "[DOMAIN_RENEWED]"));
     $this->goback();
 }