commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-old / civicrm / vendor / civicrm / civicrm-cxn-rpc / src / Message / StdMessage.php
1 <?php
2
3 /*
4 * This file is part of the civicrm-cxn-rpc package.
5 *
6 * Copyright (c) CiviCRM LLC <info@civicrm.org>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this package.
10 */
11
12 namespace Civi\Cxn\Rpc\Message;
13
14 use Civi\Cxn\Rpc\AesHelper;
15 use Civi\Cxn\Rpc\Exception\InvalidMessageException;
16 use Civi\Cxn\Rpc\Message;
17 use Civi\Cxn\Rpc\CxnStore\CxnStoreInterface;
18 use Civi\Cxn\Rpc\Constants;
19
20 class StdMessage extends Message {
21 const NAME = 'CXN-0.2-AES-CBC-HMAC';
22
23 protected $cxnId;
24 protected $secret;
25
26 /**
27 * @param string $cxnId
28 * @param string $secret
29 * Base64-encoded secret.
30 * @param mixed $data
31 * Serializable data.
32 */
33 public function __construct($cxnId, $secret, $data) {
34 parent::__construct($data);
35 $this->cxnId = $cxnId;
36 $this->secret = $secret;
37 }
38
39 /**
40 * @return string
41 * @throws InvalidMessageException
42 */
43 public function encode() {
44 list($body, $signature) = AesHelper::encryptThenSign($this->secret, json_encode($this->data));
45 return self::NAME // unsignable; determines decoder
46 . Constants::PROTOCOL_DELIM . $this->cxnId // unsignable; determines key
47 . Constants::PROTOCOL_DELIM . $signature
48 . Constants::PROTOCOL_DELIM . $body;
49 }
50
51 /**
52 * @param CxnStoreInterface $cxnStore
53 * A repository that contains shared secrets.
54 * @param string $message
55 * Ciphertext.
56 * @return static
57 * @throws InvalidMessageException
58 */
59 public static function decode($cxnStore, $message) {
60 list ($parsedProt, $parsedCxnId, $parsedHmac, $parsedBody) = explode(Constants::PROTOCOL_DELIM, $message, 4);
61 if ($parsedProt != self::NAME) {
62 throw new InvalidMessageException('Incorrect coding. Expected: ' . self::NAME);
63 }
64 $cxn = $cxnStore->getByCxnId($parsedCxnId);
65 if (empty($cxn)) {
66 throw new InvalidMessageException('Unknown connection ID');
67 }
68
69 $jsonPlaintext = AesHelper::authenticateThenDecrypt($cxn['secret'], $parsedBody, $parsedHmac);
70
71 return new StdMessage($parsedCxnId, $cxn['secret'], json_decode($jsonPlaintext, TRUE));
72 }
73
74 /**
75 * @return string
76 */
77 public function getCxnId() {
78 return $this->cxnId;
79 }
80
81 /**
82 * @param string $cxnId
83 */
84 public function setCxnId($cxnId) {
85 $this->cxnId = $cxnId;
86 }
87
88 /**
89 * @return string
90 */
91 public function getSecret() {
92 return $this->secret;
93 }
94
95 /**
96 * @param string $secret
97 */
98 public function setSecret($secret) {
99 $this->secret = $secret;
100 }
101
102
103 }