source: branches/version-2_13_0/data/class/api/SC_Api_Operation.php @ 23188

Revision 23188, 18.7 KB checked in by h_yoshimoto, 11 years ago (diff)

#2102 APIの有効/無効フラグを追加。デフォルトでOFFに。

Line 
1<?php
2/*
3 * This file is part of EC-CUBE
4 *
5 * Copyright(c) 2000-2013 LOCKON CO.,LTD. All Rights Reserved.
6 *
7 * http://www.lockon.co.jp/
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22 */
23
24/**
25 * APIの実行処理本体
26 * 権限チェックと設定チェックを行い、APIオペレーション本体を呼び出す。
27 * 結果データの生成
28 *
29 * @package Api
30 * @author LOCKON CO.,LTD.
31 * @version $Id$
32 */
33
34class SC_Api_Operation
35{
36    /** API_DEBUG_MODE */
37    const API_DEBUG_MODE = false;
38
39    /** 認証タイプ */
40    const API_AUTH_TYPE_REFERER = '1';          // リファラー
41    const API_AUTH_TYPE_SESSION_TOKEN = '2';    // CSRF TOKEN
42    const API_AUTH_TYPE_API_SIGNATURE = '3';    // API 署名認証 推奨
43    const API_AUTH_TYPE_CUSTOMER = '4';         // 会員認証
44    const API_AUTH_TYPE_MEMBER = '5';           // 管理者認証
45    const API_AUTH_TYPE_CUSTOMER_LOGIN_SESSION = '6';   // 顧客ログインセッションが有効
46    const API_AUTH_TYPE_MEMBER_LOGIN_SESSION = '7';     // 管理者ログインセッションが有効
47    const API_AUTH_TYPE_IP = '8';               // IP認証
48    const API_AUTH_TYPE_HOST = '9';             // ホスト認証
49    const API_AUTH_TYPE_SSL = '10';             // SSL強制
50    const API_AUTH_TYPE_OPEN = '99';            // 完全オープン
51
52    /**
53     * 有効な管理者ID/PASSかどうかチェックする
54     *
55     * @param  string  $member_id       ログインID文字列
56     * @param  string  $member_password ログインパスワード文字列
57     * @return boolean ログイン情報が有効な場合 true
58     */
59    protected function checkMemberAccount($member_id, $member_password)
60    {
61        $objQuery =& SC_Query_Ex::getSingletonInstance();
62        //パスワード、saltの取得
63        $cols = 'password, salt';
64        $table = 'dtb_member';
65        $where = 'login_id = ? AND del_flg <> 1 AND work = 1';
66        $arrData = $objQuery->getRow($cols, $table, $where, array($member_id));
67        if (SC_Utils_Ex::isBlank($arrData)) {
68            return false;
69        }
70        // ユーザー入力パスワードの判定
71        if (SC_Utils_Ex::sfIsMatchHashPassword($member_password, $arrData['password'], $arrData['salt'])) {
72            return true;
73        }
74
75        return false;
76    }
77
78    /**
79     * 会員ログインチェックを実行する.
80     *
81     * @param  string  $login_email ログインメールアドレス
82     * @param  string  $password    ログインパスワード
83     * @return boolean ログインに成功した場合 true; 失敗した場合 false
84     */
85    protected function checkCustomerAccount($login_email, $login_password)
86    {
87        $objCustomer = new SC_Customer_Ex();
88        if ($objCustomer->getCustomerDataFromEmailPass($login_password, $login_email)) {
89            return true;
90        } else {
91            return false;
92        }
93    }
94
95    /**
96     * リファラーチェックを実行する.
97     *
98     * @return boolean チェックに成功した場合 true; 失敗した場合 false
99     */
100    protected function checkReferer()
101    {
102        $ret = false;
103        if (!SC_Utils_Ex::isBlank($_SERVER['HTTP_REFERER'])) {
104            $domain  = SC_Utils_Ex::sfIsHTTPS() ? HTTPS_URL : HTTP_URL;
105            $pattern = sprintf('|^%s.*|', $domain);
106            $referer = $_SERVER['HTTP_REFERER'];
107            if (preg_match($pattern, $referer)) {
108               $ret = true;
109            }
110        }
111
112        return $ret;
113    }
114
115    /**
116     * HMAC-SHA 署名認証チェック
117     * Refer: http://www.soumu.go.jp/main_sosiki/joho_tsusin/top/ninshou-law/law-index.html
118     *
119     * @param  string 実行処理名
120     * @param array リクエストパラメータ
121     * @return boolean 署名認証に成功した場合 true; 失敗した場合 false
122     */
123    protected function checkApiSignature($operation_name, $arrParam, $arrApiConfig)
124    {
125        if (SC_Utils_Ex::isBlank($arrParam['Signature'])) {
126            return false;
127        }
128        if (SC_Utils_Ex::isBlank($arrParam['Timestamp'])) {
129            return false;
130        }
131/*
132        $allow_account_id = SC_Api_Operation_Ex::getOperationSubConfig($operation_name, 'allow_account_id', $arrApiConfig);
133        if (!SC_Utils_Ex::isBlank($allow_account_id) and) {
134            $arrAllowAccountIds = explode('|', $allow_account_id);
135        }
136*/
137
138        $access_key = $arrParam['AccessKeyId'];
139        $secret_key = SC_Api_Operation_Ex::getApiSecretKey($access_key);
140        if (SC_Utils_Ex::isBlank($secret_key)) {
141            return false;
142        }
143
144        // バイト順に並び替え
145        ksort($arrParam);
146
147        // 規定の文字列フォーマットを作成する
148        // Refer: https://images-na.ssl-images-amazon.com/images/G/09/associates/paapi/dg/index.html?Query_QueryAuth.html
149        $check_str = '';
150        foreach ($arrParam as $key => $val) {
151            switch ($key) {
152                case 'Signature':
153                    break;
154                default:
155                    $check_str .= '&' . SC_Utils_Ex::encodeRFC3986($key) . '=' . SC_Utils_Ex::encodeRFC3986($val);
156                    break;
157            }
158        }
159        $check_str = substr($check_str, 1);
160        $check_str = strtoupper($_SERVER['REQUEST_METHOD']) . "\n"
161                     . strtolower($_SERVER['SERVER_NAME']) . "\n"
162                     . $_SERVER['PHP_SELF'] . "\n"
163                     . $check_str;
164        $signature = base64_encode(hash_hmac('sha256', $check_str, $secret_key, true));
165        if ($signature === $arrParam['Signature']) {
166            return true;
167        }
168
169        return false;
170    }
171
172    /**
173     * IPチェックを実行する.
174     *
175     * @param  string 実行処理名
176     * @return boolean チェックに成功した場合 true; 失敗した場合 false
177     */
178    protected function checkIp($operation_name)
179    {
180        $ret = false;
181        $allow_hosts = SC_Api_Utils_Ex::getOperationSubConfig($operation_name, 'allow_hosts');
182        $arrAllowHost = explode("\n", $allow_hosts);
183        if (is_array($arrAllowHost) && count($arrAllowHost) > 0) {
184            if (array_search($_SERVER['REMOTE_ADDR'], $arrAllowHost) !== FALSE) {
185                $ret = true;
186            }
187        }
188
189        return $ret;
190    }
191
192    /**
193     * ApiAccessKeyに対応した秘密鍵を取得する。
194     *
195     * @param  string $access_key
196     * @return string 秘密鍵文字列
197     */
198    protected function getApiSecretKey($access_key)
199    {
200        $objQuery =& SC_Query_Ex::getSingletonInstance();
201        $secret_key = $objQuery->get('api_secret_key', 'dtb_api_account', 'api_access_key = ? and enable = 1 and del_flg = 0', array($access_key));
202
203        return $secret_key;
204    }
205
206    /**
207     * オペレーションの実行権限をチェックする
208     *
209     * @param string オペレーション名
210     * @param array リクエストパラメータ
211     * @return boolean 権限がある場合 true; 無い場合 false
212     */
213    protected function checkOperationAuth($operation_name, &$arrParam, &$arrApiConfig)
214    {
215        if (SC_Utils_Ex::isBlank($operation_name)) {
216            return false;
217        }
218        $arrAuthTypes = explode('|', $arrApiConfig['auth_types']);
219        $result = false;
220        foreach ($arrAuthTypes as $auth_type) {
221            $ret = false;
222            switch ($auth_type) {
223                case self::API_AUTH_TYPE_REFERER:
224                    $ret = SC_Api_Operation_Ex::checkReferer();
225                    break;
226                case self::API_AUTH_TYPE_SESSION_TOKEN:
227                    $ret = SC_Helper_Session_Ex::isValidToken(false);
228                    break;
229                case self::API_AUTH_TYPE_API_SIGNATURE:
230                    $ret = SC_Api_Operation_Ex::checkApiSignature($operation_name, $arrParam, $arrApiConfig);
231                    break;
232                case self::API_AUTH_TYPE_CUSTOMER:
233                    $ret = SC_Api_Operation_Ex::checkCustomerAccount($arrParam['login_email'], $arrParam['login_password']);
234                    break;
235                case self::API_AUTH_TYPE_MEMBER:
236                    $ret = SC_Api_Operation_Ex::checkMemberAccount($arrParam['member_id'], $arrParam['member_password']);
237                    break;
238                case self::API_AUTH_TYPE_CUSTOMER_LOGIN_SESSION:
239                    $objCustomer = new SC_Customer_Ex();
240                    $ret = $objCustomer->isLoginSuccess();
241                    break;
242                case self::API_AUTH_TYPE_MEMBER_LOGIN_SESSION:
243                    $ret = SC_Utils_Ex::sfIsSuccess(new SC_Session_Ex(), false);
244                    break;
245                case self::API_AUTH_TYPE_IP:
246                    $ret = SC_Api_Operation_Ex::checkIp($operation_name);
247                    break;
248                case self::API_AUTH_TYPE_HOST:
249                    $ret = SC_Api_Operation_Ex::checkHost($operation_name);
250                    break;
251                case self::API_AUTH_TYPE_SSL:
252                    $ret = SC_Utils_Ex::sfIsHTTPS();
253                    break;
254                case self::API_AUTH_TYPE_OPEN:
255                    $result = true;
256                    break 2;    // foreachも抜ける
257                default:
258                    $ret = false;
259                    break;
260            }
261            if ($ret === true) {
262                $result = true;
263            } else {
264                $result = false;
265                break;  // 1つでもfalseがあれば,その時点で終了
266            }
267        }
268
269        return $result;
270    }
271
272    /**
273     * APIのリクエスト基本パラメーターの設定
274     *
275     * @param object SC_FormParam
276     * @return void
277     */
278    protected function setApiBaseParam(&$objFormParam)
279    {
280        $objFormParam->addParam('Operation', 'Operation', STEXT_LEN, 'an', array('EXIST_CHECK', 'GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
281        $objFormParam->addParam('Service', 'Service', STEXT_LEN, 'an', array('EXIST_CHECK', 'GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
282        $objFormParam->addParam('Style', 'Style', STEXT_LEN, 'an', array('GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
283        $objFormParam->addParam('Validate', 'Validate', STEXT_LEN, 'an', array('GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
284        $objFormParam->addParam('Version', 'Version', STEXT_LEN, 'an', array('GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
285    }
286
287    /**
288     * API実行
289     *
290     * @param  array        $arrPost リクエストパラメーター
291     * @return array(string レスポンス名, array レスポンス配列)
292     */
293    public function doApiAction($arrPost)
294    {
295        // 実行時間計測用
296        $start_time = microtime(true);
297
298        $objFormParam = new SC_FormParam_Ex();
299        SC_Api_Operation_Ex::setApiBaseParam($objFormParam);
300        $objFormParam->setParam($arrPost);
301        $objFormParam->convParam();
302
303        $arrErr = SC_Api_Operation_Ex::checkParam($objFormParam);
304       
305        // API機能が有効であるかをチェック.
306        if (API_ENABLE_FLAG == false){
307            $arrErr['ECCUBE.Function.Disable'] = 'API機能が無効です。';
308        }
309        if (SC_Utils_Ex::isBlank($arrErr)) {
310            $arrParam = $objFormParam->getHashArray();
311            $operation_name = $arrParam['Operation'];
312            $service_name = $arrParam['Service'];
313            $style_name = $arrParam['Style'];
314            $validate_flag = $arrParam['Validate'];
315            $api_version = $arrParam['Version'];
316
317            SC_Api_Utils_Ex::printApiLog('access', $start_time, $operation_name);
318            // API設定のロード
319            $arrApiConfig = SC_Api_Utils_Ex::getApiConfig($operation_name);
320
321            if (SC_Api_Operation_Ex::checkOperationAuth($operation_name, $arrPost, $arrApiConfig)) {
322                SC_Api_Utils_Ex::printApiLog('Authority PASS', $start_time, $operation_name);
323
324                // オペレーション権限OK
325                // API オブジェクトをロード
326                $objApiOperation = SC_Api_Utils_Ex::loadApiOperation($operation_name, $arrParam);
327
328                if (is_object($objApiOperation) && method_exists($objApiOperation, 'doAction')) {
329                    // API オペレーション実行
330                    $operation_result = $objApiOperation->doAction($arrPost);
331
332                    // オペレーション結果処理
333                    if ($operation_result) {
334                        $arrOperationRequestValid = $objApiOperation->getRequestValidate();
335                        $arrResponseBody =  $objApiOperation->getResponseArray();
336                        $response_group_name = $objApiOperation->getResponseGroupName();
337                    } else {
338                        $arrErr = $objApiOperation->getErrorArray();
339                    }
340                } else {
341                    $arrErr['ECCUBE.Operation.NoLoad'] = 'オペレーションをロード出来ませんでした。';
342                }
343            } else {
344                $arrErr['ECCUBE.Authority.NoAuthority'] = 'オペレーションの実行権限がありません。';
345            }
346        }
347
348        if (count($arrErr) == 0) {
349            // 実行成功
350            $arrResponseValidSection = array('Request' => array(
351                                                            'IsValid' => 'True',
352                                                            $operation_name . 'Request' => $arrOperationRequestValid
353                                                            )
354                                            );
355            $response_outer = $operation_name . 'Response';
356            SC_Api_Utils_Ex::printApiLog('Operation SUCCESS', $start_time, $response_outer);
357        } else {
358            // 実行失敗
359            $arrResponseErrorSection = array();
360            foreach ($arrErr as $error_code => $error_msg) {
361                $arrResponseErrorSection[] = array('Code' => $error_code, 'Message' => $error_msg);
362            }
363            $arrResponseValidSection = array('Request' => array(
364                                                            'IsValid' => 'False',
365                                                            'Errors' => array('Error' => $arrResponseErrorSection)
366                                                            )
367                                            );
368            if (is_object($objApiOperation)) {
369                $response_outer = $operation_name . 'Response';
370            } else {
371                $response_outer = 'ECCUBEApiCommonResponse';
372            }
373            SC_Api_Utils_Ex::printApiLog('Operation FAILED', $start_time, $response_outer);
374        }
375
376        $arrResponse = array();
377        $arrResponse['OperationRequest'] = SC_Api_Operation_Ex::getOperationRequestEcho($arrPost, $start_time);
378        $arrResponse[$response_group_name] = array(); // Items
379        $arrResponse[$response_group_name] = $arrResponseValidSection;
380        if (is_array($arrResponseBody)) {
381            $arrResponse[$response_group_name] = array_merge((array) $arrResponse[$response_group_name], (array) $arrResponseBody);
382        }
383
384        return array($response_outer, $arrResponse);
385    }
386
387    /**
388     * APIのリクエストのエコー情報の作成
389     *
390     * @param  array $arrParam   リクエストパラメーター
391     * @param  float $start_time 実行時間計測用開始時間
392     * @return array エコー情報配列 (XML用の _attributes 指定入り)
393     */
394    protected function getOperationRequestEcho($arrParam, $start_time)
395    {
396        $arrRet = array(
397                'HTTPHeaders' => array('Header' => array('_attributes' => array('Name' => 'UserAgent',
398                                                                                'Value' => htmlspecialchars($_SERVER['HTTP_USER_AGENT'])))),
399                'RequestId' => $start_time,
400                'Arguments' => array(),
401                );
402        foreach ($arrParam as $key => $val) {
403            $arrRet['Arguments'][] = array('_attributes' => array('Name' => htmlentities($key, ENT_NOQUOTES, 'UTF-8'), 'Value' => htmlentities($val, ENT_NOQUOTES, 'UTF-8')));
404        }
405        $arrRet['RequestProcessingTime'] = microtime(true) - $start_time;
406
407        return $arrRet;
408    }
409
410    // TODO: ここらへんは SC_Displayに持って行きたい所だが・・
411    public function sendApiResponse($type, $response_outer_name, &$arrResponse)
412    {
413        switch ($type) {
414            case 'xml':
415                SC_Api_Utils_Ex::sendResponseXml($response_outer_name, $arrResponse);
416                break;
417            case 'php':
418                SC_Api_Utils_Ex::sendResponsePhp($response_outer_name, $arrResponse);
419                break;
420            case 'json':
421            default:
422                SC_Api_Utils_Ex::sendResponseJson($response_outer_name, $arrResponse);
423                break;
424        }
425    }
426   
427    /**
428     * APIのリクエスト基本パラメーターのチェック
429     *
430     * @param object $objFormParam
431     * @return array $arrErr
432     */
433    protected function checkParam($objFormParam)
434    {
435        $arrErr = $objFormParam->checkError();
436        if (!preg_match("/^[a-zA-Z0-9\-\_]+$/", $objFormParam->getValue('Operation')) && !SC_Utils::isBlank($objFormParam->getValue('Operation'))) {
437            $arrErr['ECCUBE.Operation.ParamError'] = 'Operationの値が不正です。';
438        }
439        if (!preg_match("/^[a-zA-Z0-9\-\_]+$/", $objFormParam->getValue('Service')) && !SC_Utils::isBlank($objFormParam->getValue('Service'))) {
440            $arrErr['ECCUBE.Service.ParamError'] = 'Serviceの値が不正です。';
441        }
442        if (!preg_match("/^[a-zA-Z0-9\-\_]+$/", $objFormParam->getValue('Style')) && !SC_Utils::isBlank($objFormParam->getValue('Style'))) {
443            $arrErr['ECCUBE.Style.ParamError'] = 'Styleの値が不正です。';
444        }
445        if (!preg_match("/^[a-zA-Z0-9\-\_]+$/", $objFormParam->getValue('Validate')) && !SC_Utils::isBlank($objFormParam->getValue('Validate'))) {
446            $arrErr['ECCUBE.Validate.ParamError'] = 'Validateの値が不正です。';
447        }
448        if (!preg_match("/^[a-zA-Z0-9\-\_\.]+$/", $objFormParam->getValue('Version')) && !SC_Utils::isBlank($objFormParam->getValue('Version'))) {
449            $arrErr['ECCUBE.Version.ParamError'] = 'Versionの値が不正です。';
450        }
451        return $arrErr;
452    }
453}
Note: See TracBrowser for help on using the repository browser.