Merge remote-tracking branch 'upstream/4.4' into 4.4-4.5-2014-09-29-13-10-47
[civicrm-core.git] / CRM / Core / CommunityMessages.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Manage the download, validation, and rendering of community messages
30 */
31 class CRM_Core_CommunityMessages {
32
33 const DEFAULT_MESSAGES_URL = 'https://alert.civicrm.org/alert?prot=1&ver={ver}&uf={uf}&sid={sid}&lang={lang}&co={co}';
34 const DEFAULT_PERMISSION = 'administer CiviCRM';
35
36 /**
37 * Default time to wait before retrying
38 */
39 const DEFAULT_RETRY = 7200; // 2 hours
40
41 /**
42 * @var CRM_Utils_HttpClient
43 */
44 protected $client;
45
46 /**
47 * @var CRM_Utils_Cache_Interface
48 */
49 protected $cache;
50
51 /**
52 * @var FALSE|string
53 */
54 protected $messagesUrl;
55
56 /**
57 * Create default instance
58 *
59 * @return CRM_Core_CommunityMessages
60 */
61 public static function create() {
62 return new CRM_Core_CommunityMessages(
63 new CRM_Utils_Cache_SqlGroup(array(
64 'group' => 'community-messages',
65 'prefetch' => FALSE,
66 )),
67 CRM_Utils_HttpClient::singleton()
68 );
69 }
70
71 /**
72 * @param CRM_Utils_Cache_Interface $cache
73 * @param CRM_Utils_HttpClient $client
74 * @param null $messagesUrl
75 */
76 public function __construct($cache, $client, $messagesUrl = NULL) {
77 $this->cache = $cache;
78 $this->client = $client;
79 if ($messagesUrl === NULL) {
80 $this->messagesUrl = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'communityMessagesUrl', NULL, '*default*');
81 }
82 else {
83 $this->messagesUrl = $messagesUrl;
84 }
85 if ($this->messagesUrl === '*default*') {
86 $this->messagesUrl = self::DEFAULT_MESSAGES_URL;
87 }
88 }
89
90 /**
91 * Get the messages document (either from the cache or by downloading)
92 *
93 * @return NULL|array
94 */
95 public function getDocument() {
96 $isChanged = FALSE;
97 $document = $this->cache->get('communityMessages');
98
99 if (empty($document) || !is_array($document)) {
100 $document = array(
101 'messages' => array(),
102 'expires' => 0, // ASAP
103 'ttl' => self::DEFAULT_RETRY,
104 'retry' => self::DEFAULT_RETRY,
105 );
106 $isChanged = TRUE;
107 }
108
109 if ($document['expires'] <= CRM_Utils_Time::getTimeRaw()) {
110 $newDocument = $this->fetchDocument();
111 if ($newDocument && $this->validateDocument($newDocument)) {
112 $document = $newDocument;
113 $document['expires'] = CRM_Utils_Time::getTimeRaw() + $document['ttl'];
114 }
115 else {
116 // keep the old messages for now, try again later
117 $document['expires'] = CRM_Utils_Time::getTimeRaw() + $document['retry'];
118 }
119 $isChanged = TRUE;
120 }
121
122 if ($isChanged) {
123 $this->cache->set('communityMessages', $document);
124 }
125
126 return $document;
127 }
128
129 /**
130 * Download document from URL and parse as JSON
131 *
132 * @return NULL|array parsed JSON
133 */
134 public function fetchDocument() {
135 list($status, $json) = $this->client->get($this->getRenderedUrl());
136 if ($status != CRM_Utils_HttpClient::STATUS_OK || empty($json)) {
137 return NULL;
138 }
139 $doc = json_decode($json, TRUE);
140 if (empty($doc) || json_last_error() != JSON_ERROR_NONE) {
141 return NULL;
142 }
143 return $doc;
144 }
145
146 /**
147 * Get the final, usable URL string (after interpolating any variables)
148 *
149 * @return FALSE|string
150 */
151 public function getRenderedUrl() {
152 return CRM_Utils_System::evalUrl($this->messagesUrl);
153 }
154
155 /**
156 * @return bool
157 */
158 public function isEnabled() {
159 return $this->messagesUrl !== FALSE && $this->messagesUrl !== 'FALSE';
160 }
161
162 /**
163 * Pick a message to display
164 *
165 * @return NULL|array
166 */
167 public function pick() {
168 $document = $this->getDocument();
169 $messages = array();
170 foreach ($document['messages'] as $message) {
171 if (!isset($message['perms'])) {
172 $message['perms'] = array(self::DEFAULT_PERMISSION);
173 }
174 if (!CRM_Core_Permission::checkAnyPerm($message['perms'])) {
175 continue;
176 }
177
178 if (isset($message['components'])) {
179 $enabled = array_keys(CRM_Core_Component::getEnabledComponents());
180 if (count(array_intersect($enabled, $message['components'])) == 0) {
181 continue;
182 }
183 }
184
185 $messages[] = $message;
186 }
187 if (empty($messages)) {
188 return NULL;
189 }
190
191 $idx = rand(0, count($messages) - 1);
192 return $messages[$idx];
193 }
194
195 /**
196 * @param string $markup
197 * @return string
198 */
199 public static function evalMarkup($markup) {
200 $config = CRM_Core_Config::singleton();
201 $vals = array(
202 'resourceUrl' => rtrim($config->resourceBase, '/'),
203 'ver' => CRM_Utils_System::version(),
204 'uf' => $config->userFramework,
205 'php' => phpversion(),
206 'sid' => md5('sid_' . (defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : '') . '_' . $config->userFrameworkBaseURL),
207 'baseUrl' => $config->userFrameworkBaseURL,
208 'lang' => $config->lcMessages,
209 'co' => $config->defaultContactCountry,
210 );
211 $vars = array();
212 foreach ($vals as $k => $v) {
213 $vars['%%' . $k . '%%'] = $v;
214 $vars['{{' . $k . '}}'] = urlencode($v);
215 }
216 return strtr($markup, $vars);
217 }
218
219 /**
220 * Ensure that a document is well-formed
221 *
222 * @param array $document
223 * @return bool
224 */
225 public function validateDocument($document) {
226 if (!isset($document['ttl']) || !is_integer($document['ttl'])) {
227 return FALSE;
228 }
229 if (!isset($document['retry']) || !is_integer($document['retry'])) {
230 return FALSE;
231 }
232 if (!isset($document['messages']) || !is_array($document['messages'])) {
233 return FALSE;
234 }
235 foreach ($document['messages'] as $message) {
236 // TODO validate $message['markup']
237 }
238
239 return TRUE;
240 }
241
242 }