Fail if we've already placed self.max_count orders today.
973412
def validate(self,
                 asset,
                 amount,
                 portfolio,
                 algo_datetime,
                 algo_current_data):
        
        algo_date = algo_datetime.date()

        # Reset order count if it's a new day.
        if self.current_date and self.current_date != algo_date:
            self.orders_placed = 0
        self.current_date = algo_date

        if self.orders_placed >= self.max_count:
            self.handle_violation(asset, amount, algo_datetime)
        self.orders_placed += 1
824701
def done(item, done_type=None, max_tries=None, ttl=None):
    ''''''
    if done_type is None or done_type == _c.FSQ_SUCCESS:
        return success(item)
    return fail(item, fail_type=done_type, max_tries=max_tries, ttl=ttl)
43757
def cancel_order(self, order_id, _async=False):
        
        params = {}
        path = f'/v1/order/orders/{order_id}/submitcancel'
        return api_key_post(params, path, _async=_async)
409373
def check_triggers(self, price, dt):
        
        stop_reached, limit_reached, sl_stop_reached = \
            self.check_order_triggers(price)
        if (stop_reached, limit_reached) \
                != (self.stop_reached, self.limit_reached):
            self.dt = dt
        self.stop_reached = stop_reached
        self.limit_reached = limit_reached
        if sl_stop_reached:
            # Change the STOP LIMIT order into a LIMIT order
            self.stop = None
1165037
def make_order(self, crypto, fiat, amount, price, type="limit"):
        
        raise NotImplementedError(
            self.name + " does not support making orders. "
            "Or rather it has no defined 'make_order' method."
        )
306115
def is_new_preorder( self, preorder_hash, lastblock=None ):
        
        if lastblock is None:
            lastblock = self.lastblock 

        preorder = namedb_get_name_preorder( self.db, preorder_hash, lastblock )
        if preorder is not None:
            return False
        else:
            return True
1041443
def _update_new_ordered_reqs_count(self):
        
        last_num_ordered = self._last_performance_check_data.get('num_ordered')
        num_ordered = sum(num for num, _ in self.monitor.numOrderedRequests.values())
        if num_ordered != last_num_ordered:
            self._last_performance_check_data['num_ordered'] = num_ordered
            return True
        else:
            return False
310753
function() {
      var iter;
      var ruleOfDay;
      var next;
      var compare;

      var maxTries = 500;
      var currentTry = 0;

      while (true) {
        if (currentTry++ > maxTries) {
          throw new Error(
            'max tries have occured, rule may be impossible to forfill.'
          );
        }

        next = this.ruleDate;
        iter = this._nextRecurrenceIter(this.last);

        // no more matches
        // because we increment the rule day or rule
        // _after_ we choose a value this should be
        // the only spot where we need to worry about the
        // end of events.
        if (!next && !iter) {
          // there are no more iterators or rdates
          this.complete = true;
          break;
        }

        // no next rule day or recurrence rule is first.
        if (!next || (iter && next.compare(iter.last) > 0)) {
          // must be cloned, recur will reuse the time element.
          next = iter.last.clone();
          // move to next so we can continue
          iter.next();
        }

        // if the ruleDate is still next increment it.
        if (this.ruleDate === next) {
          this._nextRuleDay();
        }

        this.last = next;

        // check the negative rules
        if (this.exDate) {
          compare = this.exDate.compare(this.last);

          if (compare < 0) {
            this._nextExDay();
          }

          // if the current rule is excluded skip it.
          if (compare === 0) {
            this._nextExDay();
            continue;
          }
        }

        //XXX: The spec states that after we resolve the final
        //     list of dates we execute exdate this seems somewhat counter
        //     intuitive to what I have seen most servers do so for now
        //     I exclude based on the original date not the one that may
        //     have been modified by the exception.
        return this.last;
      }
    }
1146366
protected function checkMinMaxAmount()
    {
        // Check if total order amount is in the module's limits
        $order_total = $this->getCurrentOrderTotalAmount();
        
        $min_amount = Atos::getConfigValue('atos_minimum_amount', 0);
        $max_amount = Atos::getConfigValue('atos_maximum_amount', 0);
        
        return
            $order_total > 0
            &&
            ($min_amount <= 0 || $order_total >= $min_amount) && ($max_amount <= 0 || $order_total <= $max_amount);
    }
289521
def failed_login_limit_reached(self):
        
        login_limit = 10
        if self.failed_logins and self.failed_logins >= login_limit:
            return True
        else:
            return False
1044996
def _check_limit(self):
        """"""

        # First compress
        self._compress()

        # Then check the max size
        if len(self._store) >= self._max_size:
            self._store.popitem(last=False)
895026
public void onFailureNoWait() {
        Logger.d(TAG, "onFailureNoWait");
        int val = currentFailureCount.incrementAndGet();
        if (val > 50) {
            currentFailureCount.compareAndSet(val, MAX_FAILURE_COUNT);
            val = MAX_FAILURE_COUNT;
        }
    }
1286223
public Retryer<R> stopAfterAttempt(final int maxAttemptNumber) {
        checkArgument(maxAttemptNumber >= 1, "maxAttemptNumber must be >= 1 but is %d", maxAttemptNumber);
        return withStopStrategy(new StopStrategy() {
            
            @Override public boolean shouldStop(int previousAttemptNumber, long delaySinceFirstAttemptInMillis) {
                return previousAttemptNumber >= maxAttemptNumber;
            }
        });
    }
167340
def _check_items_limit(self):
        
        if self.items_limit and self.items_limit == self.get_metadata('items_count'):
            raise ItemsLimitReached('Finishing job after items_limit reached:'
                                    ' {} items written.'.format(self.get_metadata('items_count')))
1121725
def orderExecuted(self, orderId):
        '''  '''
        if orderId == self.__stopOrderId:
            LOG.debug("smaStrategy stop order canceled %s" % orderId)
            # stop order executed
            self.__clearStopOrder()
391479
def reject(self):
        """"""
        self.stochastic.revert()

        # Increment rejected count
        self.rejected[self.current_kernel] += 1

        if self.verbose > 1:
            print_(
                self._id,
                "rejected, reverting to value =",
                self.stochastic.value)
857697
function before_process() {
    global $order, $order_totals, $db, $messageStack, $lp_avs, $lp_trans_num;
    $myorder = array();

    // Calculate the next expected order id
    $last_order_id = $db->Execute("select * from " . TABLE_ORDERS . " order by orders_id desc limit 1");
    $new_order_id = $last_order_id->fields['orders_id'];
    $new_order_id = ($new_order_id + 1);
    // add randomized suffix to order id to produce uniqueness ... since it's unwise to submit the same order-number twice to the gateway
    $new_order_id = (string)$new_order_id . '-' . zen_create_random_value(6);

    // Build Info to send to Gateway
    $myorder["result"] = "LIVE";
    switch (MODULE_PAYMENT_LINKPOINT_API_TRANSACTION_MODE_RESPONSE) {
      case "TESTING: Successful": $myorder["result"] = "GOOD"; break;
      case "TESTING: Decline"   : $myorder["result"] = "DECLINE"; break;
      case "TESTING: Duplicate" : $myorder["result"] = "DUPLICATE"; break;
    }

    // "oid" - Order ID number must be unique. If not set, gateway will assign one.
    //$oid = zen_create_random_value(16, 'digits'); // Create a UID for the order
    $myorder["oid"] = $new_order_id; //"";    // time(); ????

    // prepare totals for submission
    $surcharges = 0;
    $creditsApplied = 0;
    global $order_totals;
    reset($order_totals);
    $myorder['subtotal'] = $myorder['tax'] = $myorder['shipping'] = $myorder['chargetotal'] = 0;
    for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
      if ($order_totals[$i]['code'] == '') continue;
      if (in_array($order_totals[$i]['code'], array('ot_total','ot_subtotal','ot_tax','ot_shipping'))) {
        if ($order_totals[$i]['code'] == 'ot_subtotal') $myorder["subtotal"]    = round($order_totals[$i]['value'],2);
        if ($order_totals[$i]['code'] == 'ot_tax')      $myorder["tax"]        += round($order_totals[$i]['value'],2);
        if ($order_totals[$i]['code'] == 'ot_shipping') $myorder["shipping"]    = round($order_totals[$i]['value'],2);
        if ($order_totals[$i]['code'] == 'ot_total')    $myorder["chargetotal"] = round($order_totals[$i]['value'],2);
      } else {
        global $$order_totals[$i]['code'];
        if (substr($order_totals[$i]['text'], 0, 1) == '-' || (isset($$order_totals[$i]['code']->credit_class) && $$order_totals[$i]['code']->credit_class == true)) {
          $creditsApplied += round($order_totals[$i]['value'],2);
        } else {
          $surcharges += round($order_totals[$i]['value'],2);
        }
      }
    }
    foreach(array('subtotal', 'tax', 'chargetotal', 'shipping') as $i) {
      if (isset($myorder[$i])) $myorder[$i] = number_format($myorder[$i], 2, '.', '');
    }

    if ($surcharges == 0 && $creditsApplied == 0 && $order->info['total'] >= $order->info['subtotal'] && sizeof($order->products) <= 20) {
    // itemized contents
      $num_line_items = 0;
      reset($order->products);
      for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
        $num_line_items++;
        $myorder["items"][$num_line_items]['id']          = $order->products[$i]['id'];

        $myorder["items"][$num_line_items]['description'] = substr(htmlentities($order->products[$i]['name'], ENT_QUOTES, 'UTF-8'), 0, 128);
        $myorder["items"][$num_line_items]['quantity']    = $order->products[$i]['qty'];
        $myorder["items"][$num_line_items]['price']       = number_format(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), 2, '.', '');
        // check and adjust for fractional quantities, which cannot be submitted as line-item details
        $q = $order->products[$i]['qty']; $q1 = strval($q); $q2 = (int)$q; $q3 = strval($q2);
        if ($q1 != $q3 || $myorder["items"][$num_line_items]['quantity'] * $myorder["items"][$num_line_items]['price'] != number_format($order->products[$i]['qty'] * $order->products[$i]['final_price'], 2, '.', '')) {
          $myorder["items"][$num_line_items]['quantity']    = 1;
          $myorder["items"][$num_line_items]['price']       = number_format(zen_round(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), $decimals) * $order->products[$i]['qty'], 2, '.', '');
          $myorder["items"][$num_line_items]['description'] = '(' . $order->products[$i]['qty'] . ' x )' . substr($myorder["items"][$num_line_items]['description'], 115);
        }

        if (isset($order->products[$i]['attributes'])) {
          $options_text_length = 0;
          for ($j=0, $m=sizeof($order->products[$i]['attributes']); $j<$m; $j++) {
            $options_text_length += strlen($order->products[$i]['attributes'][$j]['option'] . $order->products[$i]['attributes'][$j]['value']);
          }
          if ($options_text_length < 128) {
            for ($j=0, $m=sizeof($order->products[$i]['attributes']); $j<$m; $j++) {
              $myorder["items"][$num_line_items]['options' . $j]['name'] = substr(htmlentities($order->products[$i]['attributes'][$j]['option'], ENT_QUOTES, 'UTF-8'), 0, 128);
              $myorder["items"][$num_line_items]['options' . $j]['value'] = substr(htmlentities($order->products[$i]['attributes'][$j]['value'], ENT_QUOTES, 'UTF-8'), 0, 128);
            }
          }
        }
        // track one-time charges
        if ($order->products[$i]['onetime_charges'] != 0 ) {
          $num_line_items++;
          $myorder["items"][$num_line_items]['id']          = 'OTC';
          $myorder["items"][$num_line_items]['description'] = 'One Time Charges';
          $myorder["items"][$num_line_items]['quantity']    = 1;
          $myorder["items"][$num_line_items]['price']       = number_format(zen_add_tax($order->products[$i]['onetime_charges'], $order->products[$i]['tax']), 2, '.', '');
        }
      }
/*
        // deal with surcharges/fees
        $num_line_items++;
        $myorder["items"][$num_line_items]['id']          = 'Surcharge';
        $myorder["items"][$num_line_items]['description'] = $order_totals[$i]['title'];
        $myorder["items"][$num_line_items]['quantity']    = 1;
        $myorder["items"][$num_line_items]['price']       = number_format($order_totals[$i]['value'], 2, '.', '');
        $myorder["subtotal"] += $surcharges;
*/

     // FirstData can't accept more than 20 line-item submissions per transaction
      if ($num_line_items > 20) {
        unset($myorder["items"]);
        $num_line_items = 0;
      }
      // Verify that the line-item math works
      for ($i=1, $n=$num_line_items; $i <= $n; $i++) {
        $sum2 += ($myorder["items"][$i]['quantity'] * $myorder["items"][$i]['price']);
      }
      if (strval($sum2) != strval($myorder['subtotal'])) {
        unset($myorder['items']);
        $num_line_items = 0;
      }
    }

    // Subtotal Sanity Check in case there are addon modules affecting calculations
    $sum1 = strval($myorder['subtotal'] + $myorder['shipping'] + $myorder['tax']);
    if ($sum1 > $myorder['chargetotal']) {
      foreach(array('subtotal', 'tax', 'shipping', 'items') as $i) {
        if (isset($myorder[$i])) unset($myorder[$i]);
      }
    } elseif ($sum1 < $myorder['chargetotal']) {
      if ($num_line_items > 0 && $num_line_items < 20 && isset($myorder['items'])) {
        $num_line_items++;
        $myorder["items"][$num_line_items]['id']          = 'Adj';
        $myorder["items"][$num_line_items]['description'] = 'Rounding Adjustment';
        $myorder["items"][$num_line_items]['quantity']    = 1;
        $myorder["items"][$num_line_items]['price']       = number_format($myorder['chargetotal'] - $sum1, 2, '.', '');
        $myorder['subtotal'] += round($myorder['chargetotal'] - $sum1, 2);
        $myorder['subtotal'] = number_format($myorder['subtotal'], 2, '.', '');
      } else {
        foreach(array('subtotal', 'tax', 'shipping', 'items') as $i) {
          if (isset($myorder[$i])) unset($myorder[$i]);
        }
      }
    }
    // clean up zeros
    foreach(array('subtotal', 'tax', 'shipping') as $i) {
      if (isset($myorder[$i]) && $myorder[$i] == 0) unset($myorder[$i]);
    }

    $myorder["ip"]  = current(explode(':', str_replace(',', ':', zen_get_ip_address())));
    $myorder["ponumber"]    = "";

    // CARD INFO
    $myorder["cardnumber"]   = $_POST['cc_number'];
    $myorder["cardexpmonth"] = $_POST['cc_expires_month'];
    $myorder["cardexpyear"]  = $_POST['cc_expires_year'];
    $myorder["cvmindicator"] = "provided";
    $myorder["cvmvalue"]     = $_POST['cc_cvv'];

    // BILLING INFO
    $myorder["userid"]   = $_SESSION['customer_id'];
    $myorder["customerid"] = $_SESSION['customer_id'];
    $myorder["name"]     = htmlentities($_POST['cc_owner'], ENT_QUOTES, 'UTF-8'); //$order->billing['firstname'] . ' ' . $order->billing['lastname']);
    $myorder["company"]  = htmlentities($order->billing['company'], ENT_QUOTES, 'UTF-8');
    $myorder["address1"] = htmlentities($order->billing['street_address'], ENT_QUOTES, 'UTF-8');
    $myorder["address2"] = htmlentities($order->billing['suburb'], ENT_QUOTES, 'UTF-8');
    $myorder["city"]     = $order->billing['city'];
    $myorder["state"]    = $order->billing['state'];
    $myorder["country"]  = $order->billing['country']['iso_code_2'];
    $myorder["phone"]    = $order->customer['telephone'];
    //$myorder["fax"]      = $order->customer['fax'];
    $myorder["email"]    = $order->customer['email_address'];
    $myorder["addrnum"]  = $order->billing['street_address'];   // Required for AVS. If not provided, transactions will downgrade.
    $myorder["zip"]      = $order->billing['postcode']; // Required for AVS. If not provided, transactions will downgrade.

    // SHIPPING INFO
    $myorder["sname"]     = htmlentities($order->delivery['firstname'] . ' ' . $order->delivery['lastname'], ENT_QUOTES, 'UTF-8');
    $myorder["saddress1"] = htmlentities($order->delivery['street_address'], ENT_QUOTES, 'UTF-8');
    $myorder["saddress2"] = htmlentities($order->delivery['suburb'], ENT_QUOTES, 'UTF-8');
    $myorder["scity"]     = $order->delivery['city'];
    $myorder["sstate"]    = $order->delivery['state'];
    $myorder["szip"]      = $order->delivery['postcode'];
    $myorder["scountry"]  = $order->delivery['country']['iso_code_2'];

    // MISC
    $myorder["comments"] = "Website Order";
    // $myorder["referred"] = "";
    $myorder["ordertype"]  = (MODULE_PAYMENT_LINKPOINT_API_AUTHORIZATION_MODE == 'Authorize Only' ? 'PREAUTH': 'SALE');
    $this->payment_status = $myorder["ordertype"];

    // send request to gateway
    $result = $this->_sendRequest($myorder);

    // alert to customer if communication failure
    if (!is_array($result)) {
      $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_FAILURE_MESSAGE, 'error');
      zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
    }

    // resubmit without subtotals if subtotal error occurs
    if ($result["r_approved"] != "APPROVED" && !($result["r_approved"] == "SUBMITTED" && $result["r_message"] == 'APPROVED')) {
      if (in_array(substr($result['r_error'],0,10), array('SGS-002301', 'SGS-010503', 'SGS-005003'))) {
        foreach(array('items', 'subtotal', 'tax', 'shipping') as $i) {
          if (isset($myorder[$i])) unset($myorder[$i]);
        }
        $myorder["oid"] .= '-b';
        $myorder["chargetotal"] = ($myorder["chargetotal"] - 0.01);
        $result = $this->_sendRequest($myorder);
        if (!is_array($result)) {
          $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_FAILURE_MESSAGE, 'error');
          zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
        }
      }
    }

// PARSE Results
    $all_response_info = '';
    foreach($result as $key=>$value) {
      $all_response_info .= ' ' .$key . '='.$value;
    }
    if ($this->code_debug) $messageStack->add_session('header', $all_response_info, 'caution');

    $chargetotal = $myorder["chargetotal"];

// prepare transaction logging info
    $cust_info = '';
    $cc_number = substr($myorder["cardnumber"], 0, 4) . str_repeat('X', abs(strlen($myorder["cardnumber"]) - 8)) . substr($myorder["cardnumber"], -4);
    foreach($myorder as $key=>$value) {
      if ($key != 'cardnumber') {
        if ($key == 'cvmvalue') {
          $value = '****';
        }
        if ($key == 'cardexpmonth') {
          $cc_month = $value;
        }
        if ($key == 'cardexpyear') {
          $cc_year = $value;
        }
        if (is_array($value)) $value = print_r($value, true);
        if (!in_array($key, array('keyfile', 'configfile', 'transactionorigin', 'terminaltype', 'host', 'port'))) $cust_info .= ' ' .$key . '=' . $value . ';';
      } else {
        $cust_info .= ' ' .$key . '=' . $cc_number . ';';
      }
    }
    // store last 4 digits of CC number
//    $order->info['cc_number'] = str_repeat('X', (strlen($myorder["cardnumber"]) - 4)) . substr($myorder["cardnumber"], -4);
    // store first and last 4 digits of CC number ... which is the Visa-standards-compliant approach, same as observed by Linkpoint's services
    $order->info['cc_number'] = $cc_number;

    $order->info['cc_type'] = $_POST['cc_type'];
    $order->info['cc_owner'] = $_POST['cc_owner'];
    $order->info['cc_cvv'] = '***';
    $order->info['cc_expires'] = '';// $_POST['cc_expires'];


    $lp_trans_num = $result['r_ordernum'];
    $transaction_tax = $result['r_tax']; // The calculated tax for the order, when the ordertype is calctax.
    $transaction_shipping = $result['r_shipping']; // The calculated shipping charges for the order, when the ordertype is calcshipping.
    $this->response_codes = $result['r_avs']; // AVS Response for transaction

    // these are used to update the order-status-history upon order completion
    $this->transaction_id = $result['r_tdate'] . ' Order Number/Code: ' . $result['r_ordernum'];
    $this->auth_code = $result['r_code']; // The approval code for this transaction.

//  Store Transaction history in Database
    $sql_data_array= array(array('fieldName'=>'lp_trans_num', 'value' => $result['r_ordernum'], 'type'=>'string'), // The order number associated with this transaction.
                           array('fieldName'=>'order_id', 'value' => $result['r_ordernum'], 'type'=>'integer'),
                           array('fieldName'=>'approval_code', 'value' => $result['r_code'], 'type'=>'string'), // The approval code for this transaction.
                           array('fieldName'=>'transaction_response_time', 'value' => $result['r_time'], 'type'=>'string'), // The time+date of the transaction server response.
                           array('fieldName'=>'r_error', 'value' => $result['r_error'], 'type'=>'string'),
                           array('fieldName'=>'customer_id', 'value' => $_SESSION['customer_id'] , 'type'=>'integer'),
                           array('fieldName'=>'avs_response', 'value' => $result['r_avs'], 'type'=>'string'), // AVS Response for transaction
                           array('fieldName'=>'transaction_result', 'value' => $result['r_approved'], 'type'=>'string'), // Transaction result: APPROVED, DECLINED, or FRAUD.
                           array('fieldName'=>'message', 'value' => $result['r_message'] . "\n" . $all_response_info, 'type'=>'string'), // Any message returned by the processor; e.g., CALL VOICE CENTER.
                           array('fieldName'=>'transaction_time', 'value' => $result['r_tdate'], 'type'=>'string'), // A server time-date stamp for this transaction.
                           array('fieldName'=>'transaction_reference_number', 'value' => $result['r_ref'], 'type'=>'string'), // Reference number returned by the CC processor.
                           array('fieldName'=>'fraud_score', 'value' => $result['r_score'], 'type'=>'integer'), // LinkShield fraud risk score.
                           array('fieldName'=>'cc_number', 'value' => $cc_number, 'type'=>'string'),
                           array('fieldName'=>'cust_info', 'value' => $cust_info, 'type'=>'string'),
                           array('fieldName'=>'chargetotal', 'value' => $chargetotal, 'type'=>'string'),
                           array('fieldName'=>'cc_expire', 'value' => $cc_month . '/' . $cc_year, 'type'=>'string'),
                           array('fieldName'=>'ordertype', 'value' => $myorder['ordertype'], 'type'=>'string'), // transaction type: PREAUTH or SALE
                           array('fieldName'=>'date_added', 'value' => 'now()', 'type'=>'noquotestring'));
    if (MODULE_PAYMENT_LINKPOINT_API_STORE_DATA == 'True') {
      $db->perform(TABLE_LINKPOINT_API, $sql_data_array);
    }

  //  Begin check of specific error conditions
    if ($result["r_approved"] != "APPROVED" && !($result["r_approved"] == "SUBMITTED" && $result["r_message"] == 'APPROVED')) {
      if (substr($result['r_error'],0,10) == 'SGS-020005') $messageStack->add_session('checkout_payment', $result['r_error'], 'error');  // Error (Merchant config file is missing, empty or cannot be read)
      if (substr($result['r_error'],0,10) == 'SGS-005000') $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_GENERAL_ERROR . '<br />' . $result['r_error'], 'error'); // The server encountered a database error
      if (substr($result['r_error'],0,10) == 'SGS-000001' || strstr($result['r_error'], 'D:Declined') || strstr($result['r_error'], 'R:Referral')) $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_DECLINED_MESSAGE . '<br />' . $result['r_error'], 'error');
      if (substr($result['r_error'],0,10) == 'SGS-005005' || strstr($result['r_error'], 'Duplicate transaction')) $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_DUPLICATE_MESSAGE . '<br />' . $result['r_error'], 'error');
      if (substr($result['r_error'],0,10) == 'SGS-002301') $messageStack->add_session('checkout_payment', 'Subtotal miscalculation. Please notify the storeowner.' . '<br />' . $result['r_error'], 'error');
    }
  //  End specific error conditions

  //  Begin Transaction Status does not equal APPROVED
    if ($result["r_approved"] != "APPROVED") {
      // alert to customer:
      $messageStack->add_session('checkout_payment', MODULE_PAYMENT_LINKPOINT_API_TEXT_DECLINED_MESSAGE, 'caution');
      zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
    }
  //  End Transaction Status does not equal APPROVED

    $avs_meanings = array();
    $avs_meanings['YY'] = ' - Street Address and Zip Code match.';
    $avs_meanings['YN'] = ' - Street Address matches but Zip Code does NOT match.';
    $avs_meanings['YX'] = ' - Street Address matches, but Zip Code comparison unavailable.';
    $avs_meanings['NY'] = ' - Street Address DOES NOT match, but Zip Code matches.';
    $avs_meanings['XY'] = ' - Street Address check not available, but Zip Code matches.';
    $avs_meanings['NN'] = ' - Street Address DOES NOT MATCH and Zip Code DOES NOT MATCH.';
    $avs_meanings['NX'] = ' - Street Address DOES NOT MATCH and Zip Code comparison unavailable.';
    $avs_meanings['XN'] = ' - Street Address check not available. Zip Code DOES NOT MATCH.';
    $avs_meanings['XX'] = ' - No validation for address or zip code could be performed (not available from issuing bank).';

    // Possible Fraud order. Allow transaction to process, but notify shop for owner to take appropriate action on order
    if (($result["r_approved"] == "APPROVED") && (substr($result['r_code'], 17, 2) != "YY")  && MODULE_PAYMENT_LINKPOINT_API_FRAUD_ALERT == 'Yes') {
      //DEBUG: $messageStack->add_session('header', 'possible fraud situation--> ' . $result['r_code'], 'caution');
      $message = 'Potential Fraudulent Order - Bad Address - Action Required' . "\n" .
                 'This alert occurs because the "Approval Code" below does not contain the expected YY response.' . "\n" .
                 'Thus, you might want to verify the address with the customer prior to shipping, or be sure to use Registered Mail with Signature Required in case they file a chargeback.' . "\n\n" .
                 'Customer Name: ' . $order->customer['firstname'] . ' ' . $order->customer['lastname'] . "\n\n" .
                 'AVS Result: ' . $result['r_avs'] . $avs_meanings[substr($result['r_avs'],0,2)] . "\n\n" .
                 'Order Number: ' . $lp_trans_num . "\n" .
                 'Transaction Date and Time: ' . $result['r_time'] . "\n" .
                 'Approval Code: ' . $result['r_code'] . "\n" .
                 'Reference Number: ' . $result['r_ref'] . "\n\n" .
                 'Error Message: ' . $result['r_error'] . "\n\n" .
                 'Transaction Result: ' . $result['r_approved'] . "\n\n" .
                 'Message: ' . $result['r_message'] . "\n\n" .
                 'Fraud Score: ' . ($result['r_score'] == '' ? 'Not Enabled' : $result['r_score']) . "\n\n" .
                 'AVS CODE MEANINGS: ' . "\n" .
                 'YY** = Street Address and Zip Code match.' . "\n" .
                 'YN** = Street Address matches but Zip Code does NOT match.' . "\n" .
                 'YX** = Street Address matches, but Zip Code comparison unavailable.' . "\n" .
                 'NY** = Street Address DOES NOT match, but Zip Code matches.' . "\n" .
                 'XY** = Street Address check not available, but Zip Code matches.' . "\n" .
                 'NN** = Street Address DOES NOT MATCH and Zip Code DOES NOT MATCH.' . "\n" .
                 'NX** = Street Address DOES NOT MATCH and Zip Code comparison unavailable.' . "\n" .
                 'XN** = Street Address check not available. Zip Code DOES NOT MATCH.' . "\n" .
                 'XX** = Neither validation is available.' . "\n";
      $html_msg['EMAIL_MESSAGE_HTML'] = nl2br($result['r_message']);
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, 'Potential Fraudulent Order - Bad Address - Action Required - ' . $lp_trans_num, $message, STORE_NAME, EMAIL_FROM, $html_msg, 'fraudalert');
    }
  // end fraud alert
  }