public function emailShortcodes($attrs)
 {
     $output = '';
     if ($attrs['source'] == 'receipt' || $attrs['source'] == 'fulfillment' || $attrs['source'] == 'status' || $attrs['source'] == 'followup') {
         $order = new Cart66Order($attrs['id']);
         $data = array('bill_first_name', 'bill_last_name', 'bill_address', 'bill_address2', 'bill_city', 'bill_state', 'bill_country', 'bill_zip', 'ship_first_name', 'ship_last_name', 'ship_address', 'ship_address2', 'ship_city', 'ship_state', 'ship_country', 'ship_zip', 'phone', 'email', 'coupon', 'discount_amount', 'trans_id', 'shipping', 'subtotal', 'tax', 'total', 'non_subscription_total', 'custom_field', 'ordered_on', 'status', 'ip', 'products', 'fulfillment_products', 'receipt', 'receipt_link', 'ouid', 'shipping_method', 'account_id', 'tracking_number', 'feature_level', 'subscription_plan_name', 'active_until', 'billing_interval', 'username');
         if (in_array($attrs['att'], $data)) {
             switch ($attrs['att']) {
                 case 'bill_first_name':
                     // Intentional falling through
                 // Intentional falling through
                 case 'bill_last_name':
                 case 'ship_first_name':
                 case 'ship_last_name':
                     $output = ucfirst(strtolower($order->{$attrs}['att']));
                     break;
                 case 'bill_address':
                     if ($order->bill_address2 != '') {
                         $output = $order->{$attrs}['att'] . '<br />' . $order->bill_address2;
                     } else {
                         $output = $order->{$attrs}['att'];
                     }
                     break;
                 case 'ship_address':
                     if ($order->ship_address2 != '') {
                         $output = $order->{$attrs}['att'] . '<br />' . $order->ship_address2;
                     } else {
                         $output = $order->{$attrs}['att'];
                     }
                     break;
                 case 'products':
                     $output = Cart66Common::getView('/pro/views/emails/email-products.php', array('order' => $order, 'type' => $attrs['type'], 'code' => 'products'));
                     break;
                 case 'fulfillment_products':
                     $output = Cart66Common::getView('/pro/views/emails/email-products.php', array('order' => $order, 'type' => $attrs['type'], 'code' => 'fulfillment_products', 'variable' => $attrs['variable']));
                     break;
                 case 'receipt':
                     $output = Cart66Common::getView('/pro/views/emails/email-receipt.php', array('order' => $order, 'type' => $attrs['type']));
                     break;
                 case 'phone':
                     $output = Cart66Common::formatPhone($order->{$attrs}['att']);
                     break;
                 case 'total':
                     $output = Cart66Common::currency($order->{$attrs}['att'], false);
                     break;
                 case 'tax':
                     $output = Cart66Common::currency($order->{$attrs}['att'], false);
                     break;
                 case 'receipt_link':
                     $receiptPage = get_page_by_path('store/receipt');
                     $link = get_permalink($receiptPage->ID);
                     if (strstr($link, "?")) {
                         $link .= '&ouid=';
                     } else {
                         $link .= '?ouid=';
                     }
                     $output = $link . $order->ouid;
                     break;
                 case 'feature_level':
                     // Intentionally falling through
                 // Intentionally falling through
                 case 'active_until':
                 case 'subscription_plan_name':
                 case 'active_until':
                 case 'active_until':
                 case 'billing_interval':
                     if ($order->account_id) {
                         $sub = new Cart66AccountSubscription($order->account_id);
                         $output = $sub->{$attrs}['att'];
                     } else {
                         $output = "None";
                     }
                     break;
                 case 'username':
                     if ($order->account_id) {
                         $sub = new Cart66AccountSubscription($order->account_id);
                         $account = new Cart66Account();
                         $account->load($sub->account_id);
                         //Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Loaded account: " . print_r($account, true) );
                         $output = $account->{$attrs}['att'];
                     } else {
                         $output = "None";
                     }
                     break;
                 default:
                     $output = $order->{$attrs}['att'];
             }
         } elseif (substr($attrs['att'], 0, 8) == 'tracking') {
             $output = Cart66AdvancedNotifications::updateTracking($order, $attrs);
         } elseif (substr($attrs['att'], 0, 5) == 'date:') {
             $output = Cart66AdvancedNotifications::updateDate($attrs);
         } elseif (substr($attrs['att'], 0, 12) == 'date_ordered') {
             $output = Cart66AdvancedNotifications::updateDateOrdered($order, $attrs);
         }
         $shipping_options = array('ship_first_name', 'ship_last_name', 'ship_address', 'ship_address2', 'ship_city', 'ship_state', 'ship_country', 'ship_zip');
         if (in_array($attrs['att'], $shipping_options) && $order->shipping_method == 'None') {
             $output = '';
         }
     } elseif ($attrs['source'] == 'reminder') {
         $sub = new Cart66AccountSubscription($attrs['id']);
         $account = new Cart66Account();
         $account->load($sub->account_id);
         $data = array('billing_first_name', 'billing_last_name', 'feature_level', 'subscription_plan_name', 'active_until', 'billing_interval', 'username', 'opt_out_link');
         if (in_array($attrs['att'], $data)) {
             switch ($attrs['att']) {
                 case 'billing_first_name':
                     // Intentional falling through
                 // Intentional falling through
                 case 'billing_last_name':
                     $output = ucfirst(strtolower($sub->{$attrs}['att']));
                     break;
                 case 'active_until':
                     $output = date(get_option('date_format'), strtotime($sub->{$attrs}['att']));
                     break;
                 case 'username':
                     $output = $account->{$attrs}['att'];
                     break;
                 case 'opt_out_link':
                     $output = Cart66ProCommon::generateUnsubscribeLink($account->id);
                     break;
                 default:
                     $output = $sub->{$attrs}['att'];
             }
         }
     }
     Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] output: {$output}");
     return $output;
 }
 public function generateEmailToken($accountId)
 {
     $account = new Cart66Account();
     $account->load($accountId);
     $token = md5($account->id . $account->email . $account->created_at . '*c66*(#)');
     return $token;
 }
 public static function accountsPage()
 {
     $data = array();
     if (CART66_PRO) {
         $data['plan'] = new Cart66AccountSubscription();
         $data['activeUntil'] = '';
         $account = new Cart66Account();
         if (isset($_REQUEST['cart66-action']) && $_REQUEST['cart66-action'] == 'delete_account') {
             // Look for delete request
             if (isset($_REQUEST['accountId']) && is_numeric($_REQUEST['accountId'])) {
                 $account = new Cart66Account($_REQUEST['accountId']);
                 $account->deleteMe();
                 $account->clear();
             }
         } elseif (isset($_REQUEST['accountId']) && is_numeric($_REQUEST['accountId'])) {
             if (isset($_REQUEST['opt_out'])) {
                 $account = new Cart66Account();
                 $account->load($_REQUEST['accountId']);
                 $data = array('opt_out' => $_REQUEST['opt_out']);
                 $account->setData($data);
                 $account->save();
                 $account->clear();
             }
             // Look in query string for account id
             $account = new Cart66Account();
             $account->load($_REQUEST['accountId']);
             $id = $account->getCurrentAccountSubscriptionId(true);
             $data['plan'] = new Cart66AccountSubscription($id);
             // Return even if plan is expired
             if (date('Y', strtotime($data['plan']->activeUntil)) <= 1970) {
                 $data['activeUntil'] = '';
             } else {
                 $data['activeUntil'] = date('m/d/Y', strtotime($data['plan']->activeUntil));
             }
         }
         if ($_SERVER['REQUEST_METHOD'] == 'POST' && Cart66Common::postVal('cart66-action') == 'save account') {
             $acctData = $_POST['account'];
             // Format or unset password
             if (empty($acctData['password'])) {
                 unset($acctData['password']);
             } else {
                 $acctData['password'] = md5($acctData['password']);
             }
             // Strip HTML tags on notes field
             $acctData['notes'] = strip_tags($acctData['notes'], '<a><strong><em>');
             $planData = $_POST['plan'];
             $planData['active_until'] = date('Y-m-d 00:00:00', strtotime($planData['active_until']));
             // Updating an existing account
             if ($acctData['id'] > 0) {
                 $account = new Cart66Account($acctData['id']);
                 $account->setData($acctData);
                 $account_errors = $account->validate();
                 $sub = new Cart66AccountSubscription($planData['id']);
                 if ($planData['product_id'] != 'spreedly_subscription') {
                     $sub->setData($planData);
                     $subscription_product = new Cart66Product($sub->product_id);
                     $sub->subscription_plan_name = $subscription_product->name;
                     $sub->feature_level = $subscription_product->feature_level;
                     $sub->subscriber_token = '';
                 } else {
                     unset($planData['product_id']);
                     $sub->setData($planData);
                 }
                 $subscription_errors = $sub->validate();
                 $errors = array_merge($account_errors, $subscription_errors);
                 if (count($errors) == 0) {
                     $account->save();
                     $sub->save();
                     $account->clear();
                     $sub->clear();
                 } else {
                     $data['errors'] = $errors;
                     $data['plan'] = $sub;
                     $data['activeUntil'] = date('m/d/Y', strtotime($sub->activeUntil));
                 }
             } else {
                 // Creating a new account
                 $account = new Cart66Account();
                 $account->setData($acctData);
                 $account_errors = $account->validate();
                 if (count($account_errors) == 0) {
                     $sub = new Cart66AccountSubscription();
                     $sub->setData($planData);
                     $subscription_errors = $sub->validate();
                     if (count($subscription_errors) == 0) {
                         $account->save();
                         $sub->billingFirstName = $account->firstName;
                         $sub->billingLastName = $account->lastName;
                         $sub->billingInterval = 'Manual';
                         $sub->account_id = $account->id;
                         $subscription_product = new Cart66Product($sub->product_id);
                         $sub->subscription_plan_name = $subscription_product->name;
                         $sub->feature_level = $subscription_product->feature_level;
                         $sub->save();
                         $account->clear();
                         $data['just_saved'] = true;
                     } else {
                         $data['errors'] = $subscription_errors;
                     }
                 } else {
                     $data['errors'] = $account_errors;
                 }
             }
         }
         $data['url'] = Cart66Common::replaceQueryString('page=cart66-accounts');
         $data['account'] = $account;
     }
     $view = Cart66Common::getView('admin/accounts.php', $data);
     echo $view;
 }
 public function saveMijirehOrder($order_number)
 {
     global $wpdb;
     // Make sure the order is not already in the database
     $orders_table = Cart66Common::getTableName('orders');
     $sql = "select id from {$orders_table} where trans_id = %s";
     $sql = $wpdb->prepare($sql, $order_number);
     $order_id = $wpdb->get_var($sql);
     if (!$order_id) {
         // Save the order
         $order = new Cart66Order();
         $cloud_order = $this->pullOrder($order_number);
         $order_data = $this->buildOrderDataArray($cloud_order);
         Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Order data: " . print_r($order_data, true));
         $order_data = Cart66Common::deNullArrayValues($order_data);
         $order_id = $order->rawSave($order_data);
         // Save the order items
         $order_items_table = Cart66Common::getTableName('order_items');
         foreach ($cloud_order['items'] as $key => $item) {
             $product = new Cart66Product();
             $product->loadByItemNumber($item['sku']);
             $data = array('order_id' => $order_id, 'product_id' => $product->id, 'product_price' => $item['price'], 'item_number' => $item['sku'], 'description' => $item['name'], 'quantity' => $item['quantity'], 'duid' => md5($order_id . $item['sku']));
             // Look for gravity forms data
             if (isset($cloud_order['meta_data'][$key]['gforms_' . $item['sku']])) {
                 $data['form_entry_ids'] = $cloud_order['meta_data'][$key]['gforms_' . $item['sku']];
             }
             $fIds = array();
             if (isset($data['form_entry_ids'])) {
                 $fIds = explode(',', $data['form_entry_ids']);
                 if (is_array($fIds) && count($fIds)) {
                     foreach ($fIds as $entryId) {
                         if (class_exists('RGFormsModel')) {
                             if ($lead = RGFormsModel::get_lead($entryId)) {
                                 $lead['status'] = 'active';
                                 RGFormsModel::update_lead($lead);
                             }
                         }
                     }
                 }
             }
             $data = Cart66Common::deNullArrayValues($data);
             Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Trying to save this order item:" . print_r($data, true));
             $wpdb->insert($order_items_table, $data);
             $order_item_id = $wpdb->insert_id;
             // Decrement inventory after sale
             if (Cart66Setting::getValue('track_inventory') == 1) {
                 $option_info = '';
                 if (isset($cloud_order['meta_data']['options_' . $item['sku']])) {
                     $option_info = $cloud_order['meta_data']['options_' . $item['sku']];
                 }
                 Cart66Product::decrementInventory($data['product_id'], $option_info, $data['quantity']);
             }
             // Look for membership product upgrades/extensions
             if (isset($cloud_order['meta_data']['account_id']) && is_numeric($cloud_order['meta_data']['account_id'])) {
                 $order->load($order_id);
                 $account_id = $cloud_order['meta_data']['account_id'];
                 if ($mp = $order->getMembershipProduct()) {
                     $account = new Cart66Account();
                     $account->load($account_id);
                     $account->attachMembershipProduct($mp, $account->firstName, $account->lastName);
                     $order->account_id = $account->id;
                     $order->save();
                 }
             }
         }
         //update the number of redemptions for the promotion code.
         if (Cart66Session::get('Cart66Promotion')) {
             Cart66Session::get('Cart66Promotion')->updateRedemptions();
         }
         // Send email receipts
         if (CART66_PRO && CART66_EMAILS && Cart66Setting::getValue('enable_advanced_notifications') == 1) {
             $notify = new Cart66AdvancedNotifications($order_id);
             $notify->sendAdvancedEmailReceipts();
         } elseif (CART66_EMAILS) {
             $notify = new Cart66Notifications($order_id);
             $notify->sendEmailReceipts();
         }
         //Cart66Common::sendEmailReceipts($order_id);
     }
     // Redirect to receipt page
     $this->goToReceipt($order_id);
 }
 public function getMembershipPrice()
 {
     // Return pricing (if applicable) for different membership levels
     // Otherwise, just return the default pricing (without options or fancy subscription stuff)
     $price = $this->price;
     if (Cart66Common::isLoggedIn()) {
         $levels = Cart66Common::trimmedExplode(',', $this->priceMembership);
         foreach ($levels as $level) {
             list($subscription, $p) = Cart66Common::trimmedExplode(':', $level);
             $membershipPriceList[$subscription] = $p;
         }
         $account = new Cart66Account();
         if ($account->load(Cart66Session::get('Cart66AccountId'))) {
             $userFeatureLevel = $account->getFeatureLevel();
             if ($account->isActive() && array_key_exists($userFeatureLevel, $membershipPriceList)) {
                 $price = $membershipPriceList[$userFeatureLevel];
             }
         }
     }
     return $price;
 }
 public function getDiscountAmount($cartObject = null, $taxed_products = false)
 {
     $p = new Cart66Product();
     //Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Running getDiscountAmount()");
     $discount = 0;
     if (!$cartObject) {
         $cartObject = Cart66Session::get('Cart66Cart');
     }
     // First, check to see if a membership group is excluded from using this coupon
     if ($this->membership_eligibility) {
         Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] This coupon requires a membership to use:" . $this->membership_eligibility);
         if (Cart66Common::isLoggedIn()) {
             if ($this->membership_eligibility == "guest") {
                 // The user is logged in as a non-guest and this is a guest-only coupon. Return 0.00
                 Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] The user is logged in as a non-guest and this is a guest-only coupon.");
                 return number_format($discount, 2, '.', '');
             }
             $account = new Cart66Account();
             if ($account->load(Cart66Session::get('Cart66AccountId'))) {
                 $userFeatureLevel = $account->getFeatureLevel();
                 $allowedLevels = Cart66Common::trimmedExplode(',', $this->membership_eligibility);
                 Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] The user is logged in as " . $userFeatureLevel);
                 if (!in_array($userFeatureLevel, $allowedLevels)) {
                     // The user is logged in, but cannot use this coupon. Return 0.00
                     Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] The user is logged in as " . $userFeatureLevel . " and is not eligible to use this coupon.");
                     return number_format($discount, 2, '.', '');
                 }
             }
         } else {
             // The user is not logged in...and this coupon requires a login to work, no discount
             if ($this->membership_eligibility && $this->membership_eligibility != "guest") {
                 Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] The user is not logged in, cant use this coupon as guest.");
                 return number_format($discount, 2, '.', '');
             }
         }
     }
     if ($this->apply_to == "products" && !empty($cartObject)) {
         // coupon applies to products
         $products = explode(',', $this->products);
         $cartItems = $cartObject->getItems();
         Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] The number of items in the cart: " . count($cartItems));
         $usedThisOrder = 0;
         if (empty($this->products)) {
             // all products
             // apply coupon to every item in the cart
             $counter = 0;
             foreach ($cartItems as $item) {
                 $p->load($item->getProductId());
                 if (!$taxed_products || $taxed_products && $p->taxable == 1) {
                     $basePrice = $item->getBaseProductPrice();
                     $stayPositivePrice = $this->stayPositive($basePrice, $this->getAmount($basePrice));
                     $quantity = $item->getQuantity();
                     for ($i = 1; $i <= $quantity; $i++) {
                         if (empty($this->max_uses_per_order)) {
                             $discount += $stayPositivePrice;
                             Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Max uses per order is empty. Discount: {$discount}");
                         } elseif ($counter < $this->max_uses_per_order) {
                             $discount += $stayPositivePrice;
                             Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Max uses per order is NOT empty. Discount: {$discount} :: Stay Positive: {$stayPositivePrice}");
                         }
                         $counter++;
                     }
                 }
             }
         } else {
             // coupon applies to specific products
             foreach ($cartItems as $item) {
                 $p->load($item->getProductId());
                 if (!$taxed_products || $taxed_products && $p->taxable == 1) {
                     if ($this->exclude_from_products == 0) {
                         if (in_array($item->getProductId(), $products)) {
                             // add up discount
                             $itemQuantity = $item->getQuantity();
                             if ($this->max_uses_per_order > 0) {
                                 $usesRemaining = $this->max_uses_per_order - $usedThisOrder;
                                 $allowedQuantity = $usesRemaining <= $itemQuantity ? $usesRemaining : $itemQuantity;
                             } else {
                                 $allowedQuantity = $itemQuantity;
                             }
                             $productDiscount = $this->getAmount($item->getBaseProductPrice());
                             $discount += $allowedQuantity * $this->stayPositive($item->getBaseProductPrice(), $productDiscount);
                         }
                     } elseif ($this->exclude_from_products == 1) {
                         if (!in_array($item->getProductId(), $products)) {
                             // add up discount
                             $itemQuantity = $item->getQuantity();
                             if ($this->max_uses_per_order > 0) {
                                 $usesRemaining = $this->max_uses_per_order - $usedThisOrder;
                                 $allowedQuantity = $usesRemaining <= $itemQuantity ? $usesRemaining : $itemQuantity;
                             } else {
                                 $allowedQuantity = $itemQuantity;
                             }
                             $productDiscount = $this->getAmount($item->getBaseProductPrice());
                             $discount += $allowedQuantity * $this->stayPositive($item->getBaseProductPrice(), $productDiscount);
                         }
                     }
                 }
             }
         }
     }
     if ($this->apply_to == "shipping") {
         $shipping = $cartObject->getShippingCost();
         $discount = $shipping - $this->getAmount($shipping) < 0 ? $shipping : $this->getAmount($shipping);
     }
     if ($this->apply_to == "total") {
         $shipping = $cartObject->getShippingCost();
         $products = $cartObject->getSubTotal();
         $discount = $this->getAmount($shipping + $products, $shipping + $products);
     }
     if ($this->apply_to == "subtotal") {
         // coupon applies to subtotal
         $products = explode(',', $this->products);
         $cartItems = $cartObject->getItems();
         if (empty($this->products)) {
             $products = $cartObject->getSubTotal($taxed_products);
             $discount = $this->getAmount($products, $products);
         } else {
             $itemSubtotal = 0;
             // coupon applies to specific products
             foreach ($cartItems as $item) {
                 $p->load($item->getProductId());
                 if (!$taxed_products || $taxed_products && $p->taxable == 1) {
                     if ($this->exclude_from_products == 0) {
                         if (in_array($item->getProductId(), $products)) {
                             // add up discount
                             $itemSubtotal += $item->getProductPrice() * $item->getQuantity();
                         }
                     } elseif ($this->exclude_from_products == 1) {
                         if (!in_array($item->getProductId(), $products)) {
                             // add up discount
                             $itemSubtotal += $item->getProductPrice() * $item->getQuantity();
                         }
                     }
                 }
             }
             Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] item subtotal: {$itemSubtotal}");
             $discount = $this->getAmount($itemSubtotal, $itemSubtotal);
             $discount = $this->stayPositive($itemSubtotal, $discount);
         }
     }
     // format
     $discount = number_format($discount, 2, '.', '');
     return $discount;
 }