<?php
/**
 * core.framework
 *
 * @category   Core
 * @package    Core_Router
 * @subpackage Route
 * @copyright  Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license    proprietary
 */

/**
 * @category   Core
 * @package    Core_Router
 * @subpackage Route
 * @copyright  Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license    proprietary
 */
class Core_Router_Route_Plugin_Facebook extends Core_Router_Route_Plugin_Abstract
{
    /**
     * @var array
     */
    protected $_headersRequest = array(
        'getPost(signed_request)',
    );

    /**
     * @var string
     */
    protected $_secret;

    public function setSecret($secret)
    {
        $this->_secret = $secret;
        return $this;
    }

    public function getSecret()
    {
        return $this->_secret;
    }

    /**
     * @param array $values  Values to match against
     * @param array $request Request headers to inspect
     *
     * @return mixed
     */
    protected function _match(array $values, array $request = null)
    {
        $session = Core_Application::get('session');
        if (null !== ($request['getPost(signed_request)'])) {
            // we have a valid Facebook request
            $request = $this->_decodeSignedRequest($request['getPost(signed_request)']);

            if (null !== $request) {
                // store to session here
                $data = array('facebook' => $request);
                $session->set('facebook_signed_request', $data);
                return $data;
            }
        } else if (null !== ($data = $session->get('facebook_signed_request'))) {
            return $data;
        }
        return null;
    }

    protected function _decodeSignedRequest($signedRequest)
    {
        list($encodedSignature, $payload) = explode('.', $signedRequest, 2);

        // decode the data
        $signature = $this->_base64UrlDecode($encodedSignature);
        $data      = json_decode($this->_base64UrlDecode($payload), true);
        if (('HMAC-SHA256' !== strtoupper($data['algorithm']))
            || ($signature !== hash_hmac('sha256', $payload, $this->getSecret(), true))) {
            return null;
        }

        return $data;
    }

    protected function _base64UrlDecode($input)
    {
        return base64_decode(strtr($input, '-_', '+/'));
    }
}