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

Revision 22567, 17.0 KB checked in by shutta, 11 years ago (diff)

#2043 (typo修正・ソース整形・ソースコメントの改善 for 2.12.4)
Zend Framework PHP 標準コーディング規約のコーディングスタイルへ準拠。
classおよびfunctionの開始波括弧「{」のスタイルを修正。

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
34
35class SC_Api_Operation
36{
37
38    /** API_DEBUG_MODE */
39    const API_DEBUG_MODE = false;
40
41    /** 認証タイプ */
42    const API_AUTH_TYPE_REFERER = '1';          // リファラー
43    const API_AUTH_TYPE_SESSION_TOKEN = '2';    // CSRF TOKEN
44    const API_AUTH_TYPE_API_SIGNATURE = '3';    // API 署名認証 推奨
45    const API_AUTH_TYPE_CUSTOMER = '4';         // 会員認証
46    const API_AUTH_TYPE_MEMBER = '5';           // 管理者認証
47    const API_AUTH_TYPE_CUSTOMER_LOGIN_SESSION = '6';   // 顧客ログインセッションが有効
48    const API_AUTH_TYPE_MEMBER_LOGIN_SESSION = '7';     // 管理者ログインセッションが有効
49    const API_AUTH_TYPE_IP = '8';               // IP認証
50    const API_AUTH_TYPE_HOST = '9';             // ホスト認証
51    const API_AUTH_TYPE_SSL = '10';             // SSL強制
52    const API_AUTH_TYPE_OPEN = '99';            // 完全オープン
53
54    /**
55     * 有効な管理者ID/PASSかどうかチェックする
56     *
57     * @param string $member_id ログインID文字列
58     * @param string $member_password ログインパスワード文字列
59     * @return boolean ログイン情報が有効な場合 true
60     */
61    protected function checkMemberAccount($member_id, $member_password)
62    {
63        $objQuery =& SC_Query_Ex::getSingletonInstance();
64        //パスワード、saltの取得
65        $cols = 'password, salt';
66        $table = 'dtb_member';
67        $where = 'login_id = ? AND del_flg <> 1 AND work = 1';
68        $arrData = $objQuery->getRow($cols, $table, $where, array($member_id));
69        if (SC_Utils_Ex::isBlank($arrData)) {
70            return false;
71        }
72        // ユーザー入力パスワードの判定
73        if (SC_Utils_Ex::sfIsMatchHashPassword($member_password, $arrData['password'], $arrData['salt'])) {
74            return true;
75        }
76        return false;
77    }
78
79    /**
80     * 会員ログインチェックを実行する.
81     *
82     * @param string $login_email ログインメールアドレス
83     * @param string $password ログインパスワード
84     * @return boolean ログインに成功した場合 true; 失敗した場合 false
85     */
86    protected function checkCustomerAccount($login_email, $login_password)
87    {
88        $objCustomer = new SC_Customer_Ex();
89        if ($objCustomer->getCustomerDataFromEmailPass($login_password, $login_email)) {
90            return true;
91        } else {
92            return false;
93        }
94    }
95
96    /**
97     * リファラーチェックを実行する.
98     *
99     * @return boolean チェックに成功した場合 true; 失敗した場合 false
100     */
101    protected function checkReferer()
102    {
103        $ret = false;
104        if (!SC_Utils_Ex::isBlank($_SERVER['HTTP_REFERER'])) {
105            $domain  = SC_Utils_Ex::sfIsHTTPS() ? HTTPS_URL : HTTP_URL;
106            $pattern = sprintf('|^%s.*|', $domain);
107            $referer = $_SERVER['HTTP_REFERER'];
108            if (preg_match($pattern, $referer)) {
109               $ret = true;
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        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        return $ret;
189    }
190
191    /**
192     * ApiAccessKeyに対応した秘密鍵を取得する。
193     *
194     * @param string $access_key
195     * @return string 秘密鍵文字列
196     */
197    protected function getApiSecretKey($access_key)
198    {
199        $objQuery =& SC_Query_Ex::getSingletonInstance();
200        $secret_key = $objQuery->get('api_secret_key', 'dtb_api_account', 'api_access_key = ? and enable = 1 and del_flg = 0', array($access_key));
201        return $secret_key;
202    }
203
204    /**
205     * オペレーションの実行権限をチェックする
206     *
207     * @param string オペレーション名
208     * @param array リクエストパラメータ
209     * @return boolean 権限がある場合 true; 無い場合 false
210     */
211    protected function checkOperationAuth($operation_name, &$arrParam, &$arrApiConfig)
212    {
213        if (SC_Utils_Ex::isBlank($operation_name)) {
214            return false;
215        }
216        $arrAuthTypes = explode('|', $arrApiConfig['auth_types']);
217        $result = false;
218        foreach ($arrAuthTypes as $auth_type) {
219            $ret = false;
220            switch ($auth_type) {
221                case self::API_AUTH_TYPE_REFERER:
222                    $ret = SC_Api_Operation_Ex::checkReferer();
223                    break;
224                case self::API_AUTH_TYPE_SESSION_TOKEN:
225                    $ret = SC_Helper_Session_Ex::isValidToken(false);
226                    break;
227                case self::API_AUTH_TYPE_API_SIGNATURE:
228                    $ret = SC_Api_Operation_Ex::checkApiSignature($operation_name, $arrParam, $arrApiConfig);
229                    break;
230                case self::API_AUTH_TYPE_CUSTOMER:
231                    $ret = SC_Api_Operation_Ex::checkCustomerAccount($arrParam['login_email'], $arrParam['login_password']);
232                    break;
233                case self::API_AUTH_TYPE_MEMBER:
234                    $ret = SC_Api_Operation_Ex::checkMemberAccount($arrParam['member_id'], $arrParam['member_password']);
235                    break;
236                case self::API_AUTH_TYPE_CUSTOMER_LOGIN_SESSION:
237                    $objCustomer = new SC_Customer_Ex();
238                    $ret = $objCustomer->isLoginSuccess();
239                    break;
240                case self::API_AUTH_TYPE_MEMBER_LOGIN_SESSION:
241                    $ret = SC_Utils_Ex::sfIsSuccess(new SC_Session_Ex(), false);
242                    break;
243                case self::API_AUTH_TYPE_IP:
244                    $ret = SC_Api_Operation_Ex::checkIp($operation_name);
245                    break;
246                case self::API_AUTH_TYPE_HOST:
247                    $ret = SC_Api_Operation_Ex::checkHost($operation_name);
248                    break;
249                case self::API_AUTH_TYPE_SSL:
250                    $ret = SC_Utils_Ex::sfIsHTTPS();
251                    break;
252                case self::API_AUTH_TYPE_OPEN:
253                    $result = true;
254                    break 2;    // foreachも抜ける
255                default:
256                    $ret = false;
257                    break;
258            }
259            if ($ret === true) {
260                $result = true;
261            } else {
262                $result = false;
263                break;  // 1つでもfalseがあれば,その時点で終了
264            }
265        }
266        return $result;
267    }
268
269    /**
270     * APIのリクエスト基本パラメーターの設定
271     *
272     * @param object SC_FormParam
273     * @return void
274     */
275    protected function setApiBaseParam(&$objFormParam)
276    {
277        $objFormParam->addParam('Operation', 'Operation', STEXT_LEN, 'an', array('EXIST_CHECK', 'GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
278        $objFormParam->addParam('Service', 'Service', STEXT_LEN, 'an', array('EXIST_CHECK', 'GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
279        $objFormParam->addParam('Style', 'Style', STEXT_LEN, 'an', array('GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
280        $objFormParam->addParam('Validate', 'Validate', STEXT_LEN, 'an', array('GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
281        $objFormParam->addParam('Version', 'Version', STEXT_LEN, 'an', array('GRAPH_CHECK', 'MAX_LENGTH_CHECK'));
282    }
283
284    /**
285     * API実行
286     *
287     * @param array $arrPost リクエストパラメーター
288     * @return array(string レスポンス名, array レスポンス配列)
289     */
290    public function doApiAction($arrPost)
291    {
292        // 実行時間計測用
293        $start_time = microtime(true);
294
295        $objFormParam = new SC_FormParam_Ex();
296        SC_Api_Operation_Ex::setApiBaseParam($objFormParam);
297        $objFormParam->setParam($arrPost);
298        $objFormParam->convParam();
299
300        $arrErr = $objFormParam->checkError();
301        if (SC_Utils_Ex::isBlank($arrErr)) {
302            $arrParam = $objFormParam->getHashArray();
303            $operation_name = $arrParam['Operation'];
304            $service_name = $arrParam['Service'];
305            $style_name = $arrParam['Style'];
306            $validate_flag = $arrParam['Validate'];
307            $api_version = $arrParam['Version'];
308
309            SC_Api_Utils_Ex::printApiLog('access', $start_time, $operation_name);
310            // API設定のロード
311            $arrApiConfig = SC_Api_Utils_Ex::getApiConfig($operation_name);
312
313            if (SC_Api_Operation_Ex::checkOperationAuth($operation_name, $arrPost, $arrApiConfig)) {
314                SC_Api_Utils_Ex::printApiLog('Authority PASS', $start_time, $operation_name);
315
316                // オペレーション権限OK
317                // API オブジェクトをロード
318                $objApiOperation = SC_Api_Utils_Ex::loadApiOperation($operation_name, $arrParam);
319
320                if (is_object($objApiOperation) && method_exists($objApiOperation, 'doAction')) {
321                    // API オペレーション実行
322                    $operation_result = $objApiOperation->doAction($arrPost);
323
324                    // オペレーション結果処理
325                    if ($operation_result) {
326                        $arrOperationRequestValid = $objApiOperation->getRequestValidate();
327                        $arrResponseBody =  $objApiOperation->getResponseArray();
328                        $response_group_name = $objApiOperation->getResponseGroupName();
329                    } else {
330                        $arrErr = $objApiOperation->getErrorArray();
331                    }
332                } else {
333                    $arrErr['ECCUBE.Operation.NoLoad'] = 'オペレーションをロード出来ませんでした。';
334                }
335            } else {
336                $arrErr['ECCUBE.Authority.NoAuthority'] = 'オペレーションの実行権限がありません。';
337            }
338        }
339
340        if (count($arrErr) == 0) {
341            // 実行成功
342            $arrResponseValidSection = array('Request' => array(
343                                                            'IsValid' => 'True',
344                                                            $operation_name . 'Request' => $arrOperationRequestValid
345                                                            )
346                                            );
347            $response_outer = $operation_name . 'Response';
348            SC_Api_Utils_Ex::printApiLog('Operation SUCCESS', $start_time, $response_outer);
349        } else {
350            // 実行失敗
351            $arrResponseErrorSection = array();
352            foreach ($arrErr as $error_code => $error_msg) {
353                $arrResponseErrorSection[] = array('Code' => $error_code, 'Message' => $error_msg);
354            }
355            $arrResponseValidSection = array('Request' => array(
356                                                            'IsValid' => 'False',
357                                                            'Errors' => array('Error' => $arrResponseErrorSection)
358                                                            )
359                                            );
360            if (is_object($objApiOperation)) {
361                $response_outer = $operation_name . 'Response';
362            } else {
363                $response_outer = 'ECCUBEApiCommonResponse';
364            }
365            SC_Api_Utils_Ex::printApiLog('Operation FAILED', $start_time, $response_outer);
366        }
367
368        $arrResponse = array();
369        $arrResponse['OperationRequest'] = SC_Api_Operation_Ex::getOperationRequestEcho($arrPost, $start_time);
370        $arrResponse[$response_group_name] = array(); // Items
371        $arrResponse[$response_group_name] = $arrResponseValidSection;
372        if (is_array($arrResponseBody)) {
373            $arrResponse[$response_group_name] = array_merge((array)$arrResponse[$response_group_name], (array)$arrResponseBody);
374        }
375
376        return array($response_outer, $arrResponse);
377    }
378
379    /**
380     * APIのリクエストのエコー情報の作成
381     *
382     * @param array $arrParam リクエストパラメーター
383     * @param float $start_time 実行時間計測用開始時間
384     * @return array エコー情報配列 (XML用の _attributes 指定入り)
385     */
386    protected function getOperationRequestEcho($arrParam, $start_time)
387    {
388        $arrRet = array(
389                'HTTPHeaders' => array('Header' => array('_attributes' => array('Name' => 'UserAgent',
390                                                                                'Value' => htmlspecialchars($_SERVER['HTTP_USER_AGENT'])))),
391                'RequestId' => $start_time,
392                'Arguments' => array(),
393                );
394        foreach ($arrParam as $key => $val) {
395            $arrRet['Arguments'][] = array('_attributes' => array('Name' => htmlentities($key, ENT_NOQUOTES, 'UTF-8'), 'Value' => htmlentities($val, ENT_NOQUOTES, 'UTF-8')));
396        }
397        $arrRet['RequestProcessingTime'] = microtime(true) - $start_time;
398        return $arrRet;
399    }
400
401    // TODO: ここらへんは SC_Displayに持って行きたい所だが・・
402    public function sendApiResponse($type, $response_outer_name, &$arrResponse)
403    {
404        switch ($type) {
405            case 'xml':
406                SC_Api_Utils_Ex::sendResponseXml($response_outer_name, $arrResponse);
407                break;
408            case 'php':
409                SC_Api_Utils_Ex::sendResponsePhp($response_outer_name, $arrResponse);
410                break;
411            case 'json':
412            default:
413                SC_Api_Utils_Ex::sendResponseJson($response_outer_name, $arrResponse);
414                break;
415        }
416    }
417
418}
Note: See TracBrowser for help on using the repository browser.