テストデータを使って、予測の正確さを計測する

コールバック関数に、予測の正誤判定ロジックを
クロージャで指定する

@param  array    $test_data    [description]
@param  callable $acc_callback [description]

@return string
192967
protected function check_accuracy($test_data, callable $acc_callback = null): string
    {
        if ($acc_callback === null) {
            return '';
        }

        $X = $test_data[0];
        $Y = $test_data[1];
        $sum = $acc = 0;
        foreach ($X as $key => $val) {
            $sum++;
            $res = $this->exec($val);
            if ($acc_callback($res, $Y[$key])) {
                $acc++;
            }
        }

        $ret = round($acc * 100 / $sum, 1);
        return "accuracy: $ret % ";
    }
330136
function get3DSecureLookupResponse($lookup_data_array) {
    // Set some defaults
    if (!isset($lookup_data_array['order_desc']) || $lookup_data_array['order_desc'] == '') $lookup_data_array['order_desc'] = 'Zen Cart(R) Transaction';
    if (!isset($lookup_data_array['order_number']) || $lookup_data_array['order_number'] == '') $lookup_data_array['order_number'] = zen_session_id();
    // format the card expiration
    $lookup_data_array['cc3d_exp_year'] = (strlen($lookup_data_array['cc3d_exp_year']) == 2 ? '20' : '') . $lookup_data_array['cc3d_exp_year'];
    // get the ISO 4217 currency
    $iso_currency = $this->getISOCurrency($lookup_data_array['currency']);
    // format the transaction amounts
    $raw_amount = $this->formatRawAmount($lookup_data_array['txn_amount'], $iso_currency);
    // determine the appropriate product code for submission
    $prodCode = FALSE;
    if (isset($_SESSION['cart'])) {
      if ($_SESSION['cart']->get_cart_type == 'virtual') {
        $prodCode = 'DIG';
      } else {
        $prodCode = 'PHY';
      }
    }

    // DEBUG ONLY: $this->zcLog(__FILE__ . '->' . __LINE__, 'session details: ' . print_r(array_merge($_POST, $_SESSION), true));

    // Build the XML cmpi_lookup message
    $data = '<CardinalMPI>';
    $data .= '<MsgType>cmpi_lookup</MsgType>';
    $data .= '<Version>1.7</Version>';
    $data .= '<ProcessorId>' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PROCESSOR) . '</ProcessorId>';
    $data .= '<MerchantId><![CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT) . ']]></MerchantId>';
    $data .= '<TransactionPwd><![CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD) . ']]></TransactionPwd>';
    $data .= '<TransactionType>CC</TransactionType>';
    $data .= '<TransactionMode>S</TransactionMode>';
    $data .= '<OrderNumber>' . $this->escapeXML($lookup_data_array['order_number']) . '</OrderNumber>';
    $data .= '<OrderDescription>' . $this->escapeXML($lookup_data_array['order_desc']) . '</OrderDescription>';
    $data .= '<Amount>' . $this->escapeXML($raw_amount) . '</Amount>';
    $data .= '<CurrencyCode>' . $this->escapeXML($iso_currency) . '</CurrencyCode>';
    $data .= '<CardNumber>' . $this->escapeXML($lookup_data_array['cc3d_card_number']) . '</CardNumber>';
    $data .= '<Cvv>' . $this->escapeXML($lookup_data_array['cc3d_checkcode']) . '</Cvv>';
    $data .= '<CardCode>' . $this->escapeXML($lookup_data_array['cc3d_checkcode']) . '</CardCode>';
    $data .= '<CardExpMonth>' . $this->escapeXML($lookup_data_array['cc3d_exp_month']) . '</CardExpMonth>';
    $data .= '<CardExpYear>' . $this->escapeXML($lookup_data_array['cc3d_exp_year']) . '</CardExpYear>';
    $data .= '<UserAgent>' . $this->escapeXML($_SERVER["HTTP_USER_AGENT"]) . '</UserAgent>';
    $ipAddress = current(explode(':', str_replace(',', ':', zen_get_ip_address())));
    $data .= '<IPAddress>' . $this->escapeXML($ipAddress) . '</IPAddress>';
    $data .= '<BrowserHeader>' . $this->escapeXML($_SERVER["HTTP_ACCEPT"]) . '</BrowserHeader>';
    $data .= '<OrderChannel>' . $this->escapeXML('MARK') . '</OrderChannel>';
    if (isset($lookup_data_array['merchantData'])) $data .= '<MerchantData>' . $this->escapeXML($lookup_data_array['merchantData']) . '</MerchantData>';
    if ($prodCode !== FALSE && $prodCode != '') $data .= '<ProductCode>' . $this->escapeXML($prodCode) . '</ProductCode>';
    $data .= '</CardinalMPI>';
    $debugData = str_replace(array('[CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_MERCHANT) . ']]', '[CDATA[' . $this->escapeXML(MODULE_PAYMENT_PAYPALDP_CARDINAL_PASSWORD) . ']]', $this->escapeXML($lookup_data_array['cc3d_card_number']), $this->escapeXML($lookup_data_array['cc3d_checkcode'])), '********', $data);

    if (MODULE_PAYMENT_CARDINAL_CENTINEL_DEBUGGING !== FALSE) {
      $this->zcLog('Cardinal Lookup 1', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup request (' . MODULE_PAYMENT_PAYPALDP_CARDINAL_TXN_URL . ') - ' . $debugData);
    }

    $responseString = $this->send3DSecureHttp(MODULE_PAYMENT_PAYPALDP_CARDINAL_TXN_URL, $data, $debugData);

    if (MODULE_PAYMENT_CARDINAL_CENTINEL_DEBUGGING !== FALSE) {
      $this->zcLog('Cardinal Lookup 2', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup response - ' . $responseString);
    }

    // parse the XML
    $parser = new CardinalXMLParser;
    $parser->deserializeXml($responseString);

    $errorNo = $parser->deserializedResponse['ErrorNo'];
    $errorDesc = $parser->deserializedResponse['ErrorDesc'];
    $enrolled = $parser->deserializedResponse['Enrolled'];

    if ($errorNo != 0) {
      $this->zcLog('Cardinal Lookup 3', '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup error - ' . $errorNo . ' - ' . $errorDesc);
      $errorText = 'Cardinal Lookup 3' . '[' . zen_session_id() . '] Cardinal Centinel - cmpi_lookup error - ' . $errorNo . ' - ' . $errorDesc;
      $errorText .= "\n\n" . 'There are 3 steps to configuring your Cardinal 3D-Secure service properly: ' . "\n1-Login to the Cardinal Merchant Admin URL supplied in your welcome package (NOT the test URL), and accept the license agreement.\n2-Set a transaction password.\n3-Copy your Cardinal Merchant ID and Cardinal Transaction Password into your ZC PayPal module.\n\nFor specific help, please contact implement@cardinalcommerce.com to sort out your account configuration issues.";
      $errorText .= "\n\nProblem observed while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication. THEIR PURCHASE WAS NOT SUCCESSFUL. Please resolve this matter to enable future checkouts.';
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, substr($errorDesc, 0, 75) . ' (' . $errorNo . ')', $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
    }

    // default the continue flag to 'N'
    $continue_flag = 'N';

    // determine whether the transaction should continue or fail based upon
    // the enrollment lookup results
    if (strcasecmp(MODULE_PAYMENT_PAYPALDP_CARDINAL_AUTHENTICATE_REQ, 'No') == 0) {
      $continue_flag = 'Y';
    } else if (strcmp($errorNo, '0') == 0) {
      if (strcasecmp($enrolled, 'Y') == 0) {
        $continue_flag = 'Y';
      } else if (strcasecmp($enrolled, 'N') == 0) {
        $cardType = $this->determineCardType($this->cc_card_number);
        if (strcasecmp($cardType, 'VISA') == 0 || strcasecmp($cardType, 'JCB') == 0) {
          $continue_flag = 'Y';
        }
      }
    } else if ($errorNo == 1001) { // merchant has an account configuration problem to fix
      $errorText = CENTINEL_ERROR_CODE_1001 . ' - ' . CENTINEL_ERROR_CODE_1001_DESC;
      $errorText .= "\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
      zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, CENTINEL_ERROR_CODE_1001_DESC . ' (' . CENTINEL_ERROR_CODE_1001 . ')', $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
      $continue_flag = 'Y';
    }

    if (strcasecmp('Y', $continue_flag) == 0) {
      // For validation/security purposes, mark the session that the lookup result was acceptable.
      $_SESSION['3Dsecure_enroll_lookup_attempted'] = 'Y';
    } else {
      // For validation/security purposes, mark the session that the lookup result was not acceptable.
      unset($_SESSION['3Dsecure_enroll_lookup_attempted']);
    }

    $result = array('continue_flag' => $continue_flag,
                    'enrolled' => $enrolled,
                    'transaction_id' => $parser->deserializedResponse['TransactionId'],
                    'error_no' => $errorNo,
                    'error_desc' => $errorDesc,
                    'acs_url' => $parser->deserializedResponse['ACSUrl'],
                    'spa_hidden_fields' => $parser->deserializedResponse['SPAHiddenFields'],
                    'payload' => $parser->deserializedResponse['Payload'],
                    'cc3d_card_number' => $parser->deserializedResponse['CardNumber'],
                    'cc3d_checkcode' => $parser->deserializedResponse['CardCode'],
                    'cc3d_exp_month' => $parser->deserializedResponse['CardExpMonth'],
                    'cc3d_exp_year' => $parser->deserializedResponse['CardExpYear'],
                    'EciFlag' => $parser->deserializedResponse['EciFlag'],
                    'cc3d_merchantdata' => $parser->deserializedResponse['MerchantData']);
    return $result;
  }
806909
public function getCallableData()
    {
        $result = parent::getCallableData();

        $data = $this->model->toArray();
        $data['class'] = $this->model->className();
        $result['object'] = $data;
        return $result;
    }
1110029
public static function authenticate($auth_data)
    {
        $password = $auth_data['password'];
        $login = $auth_data['login'];
        $user = self::getUser($login);
        if (! $user) {
            return false;
        }
        if (! $user->isActive()) {
            return false;
        }
        return User_Credential::checkCredential($login, $password) ? $user : false;
//         return ($user->checkPassword($password)) ? $user : false;
    }
1118078
private static function config($test = false)
    {
        $files = ['Config', 'Alias'];
        $folder = static::$root.'Config'.'/';

        self::call($files, $folder);
        //
        $files = ['ConfigException', 'DatabaseDriverNotFoundException', 'AliasedClassNotFoundException'];
        $folder = static::$root.'Config/Exceptions'.'/';

        self::call($files, $folder);
        //
        Config::load();
    }
521888
public function saveSuidTransaction ($save_function, $data, $suid_check = true, $args = []) {
		if (!static::SeesionOnSu()) {
			return null;
		}

		if ($suid_check === false && !static::EnableSuidSession()) {
			return null;
		}

		if (is_callable($data)) {
			$data = $data();
		}

		try {
			static::Begin();

			if (is_string($save_function) && strpos($save_function, '::') !== false) {
				//PHPネイティブでは指定できないが、'クラスパス::メソッド名'の指定に合わせるための処理
				$save_function = explode('::', $save_function, 2);
			} else if (is_callable($save_function)) {

			} else {
				//インスタンスメソッドを指定する場合
				$save_function = [$this, $save_function];
			}
			$ret = $save_function(...array_merge([$data], (array) $args));
		} catch (\Exception $e) {
			static::DeleteSuidSession();
			static::Rollback();
			throw $e;
		}

		static::DeleteSuidSession();
		static::Commit();

		return $ret;
	}
1289316
private function callFunction($callback, $data)
    {
        $exp = explode('@', $callback);

        if (method_exists($instance = new $exp[0](), $exp[1])) {
            return call_user_func_array([$instance, $exp[1]], [$data]);
        }
    }
874847
function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
  {
  global $php_errormsg;

    if (!function_exists('ads_connect')) return null;

    if (isset($php_errormsg)) $php_errormsg = '';
    $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
    if ($this->debug && $argDatabasename) {
            ADOConnection::outp("For PConnect(), $argDatabasename is not used. Place dsn in 1st parameter.");
    }
  //  print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush();
    if ($this->curmode === false) $this->_connectionID = ads_connect($argDSN,$argUsername,$argPassword);
    else $this->_connectionID = ads_pconnect($argDSN,$argUsername,$argPassword,$this->curmode);

    $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
    if ($this->_connectionID && $this->autoRollback) @ads_rollback($this->_connectionID);
    if (isset($this->connectStmt)) $this->Execute($this->connectStmt);

    return $this->_connectionID != false;
  }
1143572
public function consistentDataValdiateRule ($callback, $validate_rule = []) {
		return function () use ($callback, $validate_rule) {
			$consistent_validate_rule = [];

			foreach ($callback() as $id => $value) {
				$consistent_validate_rule[$id] = [
					'force_validate'	=> false,
					'force_value'		=> false,
					'value'	=> $value,
					['===', static::ReadSuidSession($id), 'raise_exception', 'message' => 'トランザクション中固定値がマッチしません。target:{:title} input:{:value}, session:{:operand:0}'],
				];
			}

			return $consistent_validate_rule + $validate_rule;
		};
	}
121204
public static function LasyClassVarConstAccessCallback ($name, $call_back) {
		if (!static::HasClassVar($name)) {
			static::$_ApplicationVariableTrait_Data[$name] = $call_back();
			static::$_ApplicationVariableTrait_ConstList[implode('=>', Arrays::AdjustArray($name))] = true;
		}
		return static::$_ApplicationVariableTrait_Data[$name];
	}
300528
public function getData()
    {
        if ($this->getTestMode()) {
            $this->validate('testKey');
        } else {
            $this->validate('signKey');
        }

        $result = [];
        $vars = array_merge($this->httpRequest->query->all(), $this->httpRequest->request->all());
        foreach ($vars as $key => $parameter) {
            if (strpos($key, 'ik_') === 0) {
                $result[$key] = $parameter;
            }
        }

        return $result;
    }
197487
public static Callbackip getcallbackip(String access_token){
		HttpUriRequest httpUriRequest = RequestBuilder.get()
				.setUri(BASE_URI + "/cgi-bin/getcallbackip")
				.addParameter(PARAM_ACCESS_TOKEN,API.accessToken(access_token))
				.build();
		return LocalHttpClient.executeJsonResult(httpUriRequest,Callbackip.class);
	}
196848
public function prepareNestedData($data, $lft = 0, $rgt = null, $root = 0)
    {
        $res = [];
        foreach ($data as $row) {
            $currentRoot = isset($row[$this->rootAttribute]) ? $row[$this->rootAttribute] : 0;
            if (is_null($rgt) || $row[$this->rightAttribute] < $rgt && $root == $currentRoot) {
                if ($lft + 1 == $row[$this->leftAttribute]) {
                    if ($row[$this->leftAttribute] + 1 !== $row[$this->rightAttribute]) {
                        $res[] = [
                            'id' => $row['id'],
                            'text' => $row[$this->modelLabelAttribute],
                            'a_attr' => [
                                'data-id' => $row['id'],
                            ],
                            'children' => self::prepareNestedData(
                                $data,
                                $row[$this->leftAttribute],
                                $row[$this->rightAttribute],
                                $currentRoot
                            ),
                            'state' => [
                                'selected' => in_array($row['id'], $this->selectedNodes),
                            ],
                        ];
                    } else {
                        $res[] = [
                            'id' => $row['id'],
                            'text' => $row[$this->modelLabelAttribute],
                            'a_attr' => [
                                'data-id' => $row['id'],
                            ],
                            'children' => [],
                            'state' => [
                                'selected' => in_array($row['id'], $this->selectedNodes),
                            ],
                        ];
                    }
                    $lft = $row[$this->rightAttribute];
                } else if ($row[$this->leftAttribute] == 1 && $root !== $currentRoot) {
                    $res[] = [
                        'id' => $row['id'],
                        'text' => $row[$this->modelLabelAttribute],
                        'a_attr' => [
                            'data-id' => $row['id'],
                        ],
                        'children' => self::prepareNestedData(
                            $data,
                            $row[$this->leftAttribute],
                            $row[$this->rightAttribute],
                            $currentRoot
                        ),
                        'state' => [
                            'selected' => in_array($row['id'], $this->selectedNodes),
                        ],
                    ];
                }
            }
        }
        return $res;
    }
109529
public static function Send($signal_type, \Peg\Lib\Signals\SignalData &$signal_data = null)
    {
        if(!isset(self::$listeners[$signal_type]))
            return;

        foreach(self::$listeners[$signal_type] as $callback_data)
        {
            $callback = $callback_data['callback'];

            if(is_object($signal_data))
                $callback($signal_data);
            else
                $callback();
        }
    }
515561
public function getAccessToken($query_data, $request_token) {

    $post = array(
      'client_id' => $this->getConfig('consumer_key'),
      'client_secret' => $this->getConfig('consumer_secret'),
      'redirect_uri' => $request_token['callback_uri'],
      'code' => $query_data['code'],
      'grant_type' => 'authorization_code',
    );
    //Get request token
    $response = $this->post($this->getConfig('access_token_path'), NULL, $post)->send();
    $access_token = array();
    parse_str($response->getBody(), $access_token);
    if (!isset($access_token['access_token'])) {
      // try to read json
      $access_token = $response->json();
    }
    $access_token['request_time'] = time();

    // Throw exception if there isn't a access token.
    if (!isset($access_token['access_token'])) {
      throw new \Exception('No access token found in response.');
    }

    if ($this->getConfig()->get('exchange_short_access_token')) {
      $access_token = $this->exchangeAccessToken($access_token);
    }

    // Return AccessToken
    return $this->normalizeAccessToken($access_token);
  }
905775
public function parse($_data)
    {
        $ctrlName = Config::getField('project', 'default_ctrl_name', 'main\\main');
        $methodName = Config::getField('project', 'default_method_name', 'main');
        $fd = Request::getFd();
        if (!empty($this->_buffer[$fd])) {
            $_data = $this->_buffer . $_data;
        }
        $packData = new MessagePacker($_data);
        $packLen = $packData->readInt();
        $dataLen = \strlen($_data);
        if ($packLen > $dataLen) {
            $this->_buffer[$fd] = $_data;
            return false;
        } elseif ($packLen < $dataLen) {
            $this->_buffer[$fd] = \substr($_data, $packLen, $dataLen - $packLen);
        } else {
            if (!empty($this->_buffer[$fd])) {
                unset($this->_buffer[$fd]);
            }
        }
        $packData->resetOffset();
        $params = $packData->readString();
        $data = \json_decode($params, true);
        $apn = Config::getField('project', 'ctrl_name', 'a');
        $mpn = Config::getField('project', 'method_name', 'm');
        if (isset($params[$apn])) {
            $ctrlName = \str_replace('/', '\\', $params[$apn]);
        }
        if (isset($params[$mpn])) {
            $methodName = $params[$mpn];
        }
        Request::init($ctrlName, $methodName, $data, Config::getField('project', 'view_mode', 'Zpack'));
        return true;
    }
1233907
public function request($callbackURL, $Amount, $Description, $Email = null, $Mobile = null, $additionalData = null)
    {
        $inputs = [
            'MerchantID'  => $this->merchantID,
            'CallbackURL' => $callbackURL,
            'Amount'      => $Amount,
            'Description' => $Description,
        ];
        if (!is_null($Email)) {
            $inputs['Email'] = $Email;
        }
        if (!is_null($Mobile)) {
            $inputs['Mobile'] = $Mobile;
        }
        if (!is_null($additionalData)) {
            $inputs['AdditionalData'] = $additionalData;
            $results = $this->driver->requestWithExtra($inputs);
        } else {
            $results = $this->driver->request($inputs);
        }

        if (empty($results['Authority'])) {
            $results['Authority'] = null;
        }
        $this->Authority = $results['Authority'];

        return $results;
    }