source: branches/version-2_12-dev/data/class/api/SC_Api_Operation.php @ 21713

Revision 21713, 16.8 KB checked in by AMUAMU, 12 years ago (diff)

#1604 (外部連携用APIの実装) 基本機構実装、Amazon API相当の機能の実装(商品一覧系)

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