source: branches/version-2_13-dev/data/class/api/SC_Api_Operation.php @ 22856

Revision 22856, 17.0 KB checked in by Seasoft, 11 years ago (diff)

#2043 (typo修正・ソース整形・ソースコメントの改善 for 2.13.0)

  • 主に空白・空白行の調整。もう少し整えたいが、一旦現状コミット。
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
139        $access_key = $arrParam['AccessKeyId'];
140        $secret_key = SC_Api_Operation_Ex::getApiSecretKey($access_key);
141        if (SC_Utils_Ex::isBlank($secret_key)) {
142            return false;
143        }
144
145        // バイト順に並び替え
146        ksort($arrParam);
147
148        // 規定の文字列フォーマットを作成する
149        // Refer: https://images-na.ssl-images-amazon.com/images/G/09/associates/paapi/dg/index.html?Query_QueryAuth.html
150        $check_str = '';
151        foreach ($arrParam as $key => $val) {
152            switch ($key) {
153                case 'Signature':
154                    break;
155                default:
156                    $check_str .= '&' . SC_Utils_Ex::encodeRFC3986($key) . '=' . SC_Utils_Ex::encodeRFC3986($val);
157                    break;
158            }
159        }
160        $check_str = substr($check_str, 1);
161        $check_str = strtoupper($_SERVER['REQUEST_METHOD']) . "\n"
162                     . strtolower($_SERVER['SERVER_NAME']) . "\n"
163                     . $_SERVER['PHP_SELF'] . "\n"
164                     . $check_str;
165        $signature = base64_encode(hash_hmac('sha256', $check_str, $secret_key, true));
166        if ($signature === $arrParam['Signature']) {
167            return true;
168        }
169
170        return false;
171    }
172
173    /**
174     * IPチェックを実行する.
175     *
176     * @param  string 実行処理名
177     * @return boolean チェックに成功した場合 true; 失敗した場合 false
178     */
179    protected function checkIp($operation_name)
180    {
181        $ret = false;
182        $allow_hosts = SC_Api_Utils_Ex::getOperationSubConfig($operation_name, 'allow_hosts');
183        $arrAllowHost = explode("\n", $allow_hosts);
184        if (is_array($arrAllowHost) && count($arrAllowHost) > 0) {
185            if (array_search($_SERVER['REMOTE_ADDR'], $arrAllowHost) !== FALSE) {
186                $ret = true;
187            }
188        }
189
190        return $ret;
191    }
192
193    /**
194     * ApiAccessKeyに対応した秘密鍵を取得する。
195     *
196     * @param string $access_key
197     * @return string 秘密鍵文字列
198     */
199    protected function getApiSecretKey($access_key)
200    {
201        $objQuery =& SC_Query_Ex::getSingletonInstance();
202        $secret_key = $objQuery->get('api_secret_key', 'dtb_api_account', 'api_access_key = ? and enable = 1 and del_flg = 0', array($access_key));
203
204        return $secret_key;
205    }
206
207    /**
208     * オペレーションの実行権限をチェックする
209     *
210     * @param string オペレーション名
211     * @param array リクエストパラメータ
212     * @return boolean 権限がある場合 true; 無い場合 false
213     */
214    protected function checkOperationAuth($operation_name, &$arrParam, &$arrApiConfig)
215    {
216        if (SC_Utils_Ex::isBlank($operation_name)) {
217            return false;
218        }
219        $arrAuthTypes = explode('|', $arrApiConfig['auth_types']);
220        $result = false;
221        foreach ($arrAuthTypes as $auth_type) {
222            $ret = false;
223            switch ($auth_type) {
224                case self::API_AUTH_TYPE_REFERER:
225                    $ret = SC_Api_Operation_Ex::checkReferer();
226                    break;
227                case self::API_AUTH_TYPE_SESSION_TOKEN:
228                    $ret = SC_Helper_Session_Ex::isValidToken(false);
229                    break;
230                case self::API_AUTH_TYPE_API_SIGNATURE:
231                    $ret = SC_Api_Operation_Ex::checkApiSignature($operation_name, $arrParam, $arrApiConfig);
232                    break;
233                case self::API_AUTH_TYPE_CUSTOMER:
234                    $ret = SC_Api_Operation_Ex::checkCustomerAccount($arrParam['login_email'], $arrParam['login_password']);
235                    break;
236                case self::API_AUTH_TYPE_MEMBER:
237                    $ret = SC_Api_Operation_Ex::checkMemberAccount($arrParam['member_id'], $arrParam['member_password']);
238                    break;
239                case self::API_AUTH_TYPE_CUSTOMER_LOGIN_SESSION:
240                    $objCustomer = new SC_Customer_Ex();
241                    $ret = $objCustomer->isLoginSuccess();
242                    break;
243                case self::API_AUTH_TYPE_MEMBER_LOGIN_SESSION:
244                    $ret = SC_Utils_Ex::sfIsSuccess(new SC_Session_Ex(), false);
245                    break;
246                case self::API_AUTH_TYPE_IP:
247                    $ret = SC_Api_Operation_Ex::checkIp($operation_name);
248                    break;
249                case self::API_AUTH_TYPE_HOST:
250                    $ret = SC_Api_Operation_Ex::checkHost($operation_name);
251                    break;
252                case self::API_AUTH_TYPE_SSL:
253                    $ret = SC_Utils_Ex::sfIsHTTPS();
254                    break;
255                case self::API_AUTH_TYPE_OPEN:
256                    $result = true;
257                    break 2;    // foreachも抜ける
258                default:
259                    $ret = false;
260                    break;
261            }
262            if ($ret === true) {
263                $result = true;
264            } else {
265                $result = false;
266                break;  // 1つでもfalseがあれば,その時点で終了
267            }
268        }
269
270        return $result;
271    }
272
273    /**
274     * APIのリクエスト基本パラメーターの設定
275     *
276     * @param object SC_FormParam
277     * @return void
278     */
279    protected function setApiBaseParam(&$objFormParam)
280    {
281        $objFormParam->addParam('Operation', 'Operation', STEXT_LEN, 'an', array('EXIST_CHECK', 'GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
282        $objFormParam->addParam('Service', 'Service', STEXT_LEN, 'an', array('EXIST_CHECK', 'GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
283        $objFormParam->addParam('Style', 'Style', STEXT_LEN, 'an', array('GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
284        $objFormParam->addParam('Validate', 'Validate', STEXT_LEN, 'an', array('GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
285        $objFormParam->addParam('Version', 'Version', STEXT_LEN, 'an', array('GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
286    }
287
288    /**
289     * API実行
290     *
291     * @param array $arrPost リクエストパラメーター
292     * @return array(string レスポンス名, array レスポンス配列)
293     */
294    public function doApiAction($arrPost)
295    {
296        // 実行時間計測用
297        $start_time = microtime(true);
298
299        $objFormParam = new SC_FormParam_Ex();
300        SC_Api_Operation_Ex::setApiBaseParam($objFormParam);
301        $objFormParam->setParam($arrPost);
302        $objFormParam->convParam();
303
304        $arrErr = $objFormParam->checkError();
305        if (SC_Utils_Ex::isBlank($arrErr)) {
306            $arrParam = $objFormParam->getHashArray();
307            $operation_name = $arrParam['Operation'];
308            $service_name = $arrParam['Service'];
309            $style_name = $arrParam['Style'];
310            $validate_flag = $arrParam['Validate'];
311            $api_version = $arrParam['Version'];
312
313            SC_Api_Utils_Ex::printApiLog('access', $start_time, $operation_name);
314            // API設定のロード
315            $arrApiConfig = SC_Api_Utils_Ex::getApiConfig($operation_name);
316
317            if (SC_Api_Operation_Ex::checkOperationAuth($operation_name, $arrPost, $arrApiConfig)) {
318                SC_Api_Utils_Ex::printApiLog('Authority PASS', $start_time, $operation_name);
319
320                // オペレーション権限OK
321                // API オブジェクトをロード
322                $objApiOperation = SC_Api_Utils_Ex::loadApiOperation($operation_name, $arrParam);
323
324                if (is_object($objApiOperation) && method_exists($objApiOperation, 'doAction')) {
325                    // API オペレーション実行
326                    $operation_result = $objApiOperation->doAction($arrPost);
327
328                    // オペレーション結果処理
329                    if ($operation_result) {
330                        $arrOperationRequestValid = $objApiOperation->getRequestValidate();
331                        $arrResponseBody =  $objApiOperation->getResponseArray();
332                        $response_group_name = $objApiOperation->getResponseGroupName();
333                    } else {
334                        $arrErr = $objApiOperation->getErrorArray();
335                    }
336                } else {
337                    $arrErr['ECCUBE.Operation.NoLoad'] = 'オペレーションをロード出来ませんでした。';
338                }
339            } else {
340                $arrErr['ECCUBE.Authority.NoAuthority'] = 'オペレーションの実行権限がありません。';
341            }
342        }
343
344        if (count($arrErr) == 0) {
345            // 実行成功
346            $arrResponseValidSection = array('Request' => array(
347                                                            'IsValid' => 'True',
348                                                            $operation_name . 'Request' => $arrOperationRequestValid
349                                                            )
350                                            );
351            $response_outer = $operation_name . 'Response';
352            SC_Api_Utils_Ex::printApiLog('Operation SUCCESS', $start_time, $response_outer);
353        } else {
354            // 実行失敗
355            $arrResponseErrorSection = array();
356            foreach ($arrErr as $error_code => $error_msg) {
357                $arrResponseErrorSection[] = array('Code' => $error_code, 'Message' => $error_msg);
358            }
359            $arrResponseValidSection = array('Request' => array(
360                                                            'IsValid' => 'False',
361                                                            'Errors' => array('Error' => $arrResponseErrorSection)
362                                                            )
363                                            );
364            if (is_object($objApiOperation)) {
365                $response_outer = $operation_name . 'Response';
366            } else {
367                $response_outer = 'ECCUBEApiCommonResponse';
368            }
369            SC_Api_Utils_Ex::printApiLog('Operation FAILED', $start_time, $response_outer);
370        }
371
372        $arrResponse = array();
373        $arrResponse['OperationRequest'] = SC_Api_Operation_Ex::getOperationRequestEcho($arrPost, $start_time);
374        $arrResponse[$response_group_name] = array(); // Items
375        $arrResponse[$response_group_name] = $arrResponseValidSection;
376        if (is_array($arrResponseBody)) {
377            $arrResponse[$response_group_name] = array_merge((array)$arrResponse[$response_group_name], (array)$arrResponseBody);
378        }
379
380        return array($response_outer, $arrResponse);
381    }
382
383    /**
384     * APIのリクエストのエコー情報の作成
385     *
386     * @param array $arrParam リクエストパラメーター
387     * @param float $start_time 実行時間計測用開始時間
388     * @return array エコー情報配列 (XML用の _attributes 指定入り)
389     */
390    protected function getOperationRequestEcho($arrParam, $start_time)
391    {
392        $arrRet = array(
393                'HTTPHeaders' => array('Header' => array('_attributes' => array('Name' => 'UserAgent',
394                                                                                'Value' => htmlspecialchars($_SERVER['HTTP_USER_AGENT'])))),
395                'RequestId' => $start_time,
396                'Arguments' => array(),
397                );
398        foreach ($arrParam as $key => $val) {
399            $arrRet['Arguments'][] = array('_attributes' => array('Name' => htmlentities($key, ENT_NOQUOTES, 'UTF-8'), 'Value' => htmlentities($val, ENT_NOQUOTES, 'UTF-8')));
400        }
401        $arrRet['RequestProcessingTime'] = microtime(true) - $start_time;
402
403        return $arrRet;
404    }
405
406    // TODO: ここらへんは SC_Displayに持って行きたい所だが・・
407    public function sendApiResponse($type, $response_outer_name, &$arrResponse)
408    {
409        switch ($type) {
410            case 'xml':
411                SC_Api_Utils_Ex::sendResponseXml($response_outer_name, $arrResponse);
412                break;
413            case 'php':
414                SC_Api_Utils_Ex::sendResponsePhp($response_outer_name, $arrResponse);
415                break;
416            case 'json':
417            default:
418                SC_Api_Utils_Ex::sendResponseJson($response_outer_name, $arrResponse);
419                break;
420        }
421    }
422
423}
Note: See TracBrowser for help on using the repository browser.