Merge pull request #3580 from monishdeb/CRM-14701
[civicrm-core.git] / CRM / Core / CommunityMessages.php
CommitLineData
ecbe1139
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
ecbe1139
TO
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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 */
31class CRM_Core_CommunityMessages {
32
20eff8a7 33 const DEFAULT_MESSAGES_URL = 'https://alert.civicrm.org/alert?prot=1&ver={ver}&uf={uf}&sid={sid}&lang={lang}&co={co}';
dc92f2f8 34 const DEFAULT_PERMISSION = 'administer CiviCRM';
e8977170 35
ecbe1139
TO
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
e8977170
TO
51 /**
52 * @var FALSE|string
53 */
54 protected $messagesUrl;
55
847c93ac
TO
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
ecbe1139
TO
71 /**
72 * @param CRM_Utils_Cache_Interface $cache
73 * @param CRM_Utils_HttpClient $client
74 */
e8977170 75 public function __construct($cache, $client, $messagesUrl = NULL) {
ecbe1139
TO
76 $this->cache = $cache;
77 $this->client = $client;
e8977170 78 if ($messagesUrl === NULL) {
847c93ac 79 $this->messagesUrl = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'communityMessagesUrl', NULL, '*default*');
e8977170
TO
80 }
81 else {
82 $this->messagesUrl = $messagesUrl;
83 }
847c93ac
TO
84 if ($this->messagesUrl === '*default*') {
85 $this->messagesUrl = self::DEFAULT_MESSAGES_URL;
86 }
ecbe1139
TO
87 }
88
89 /**
d1b65097 90 * Get the messages document (either from the cache or by downloading)
ecbe1139
TO
91 *
92 * @return NULL|array
93 */
94 public function getDocument() {
ecbe1139
TO
95 $isChanged = FALSE;
96 $document = $this->cache->get('communityMessages');
97
98 if (empty($document) || !is_array($document)) {
99 $document = array(
100 'messages' => array(),
101 'expires' => 0, // ASAP
102 'ttl' => self::DEFAULT_RETRY,
103 'retry' => self::DEFAULT_RETRY,
104 );
105 $isChanged = TRUE;
106 }
107
108 if ($document['expires'] <= CRM_Utils_Time::getTimeRaw()) {
847c93ac 109 $newDocument = $this->fetchDocument();
8bfc3cb1 110 if ($newDocument && $this->validateDocument($newDocument)) {
ecbe1139
TO
111 $document = $newDocument;
112 $document['expires'] = CRM_Utils_Time::getTimeRaw() + $document['ttl'];
e8977170
TO
113 }
114 else {
d1b65097 115 // keep the old messages for now, try again later
ecbe1139
TO
116 $document['expires'] = CRM_Utils_Time::getTimeRaw() + $document['retry'];
117 }
118 $isChanged = TRUE;
119 }
120
121 if ($isChanged) {
122 $this->cache->set('communityMessages', $document);
123 }
124
125 return $document;
126 }
127
128 /**
129 * Download document from URL and parse as JSON
130 *
ecbe1139
TO
131 * @return NULL|array parsed JSON
132 */
847c93ac
TO
133 public function fetchDocument() {
134 list($status, $json) = $this->client->get($this->getRenderedUrl());
ecbe1139
TO
135 if ($status != CRM_Utils_HttpClient::STATUS_OK || empty($json)) {
136 return NULL;
137 }
138 $doc = json_decode($json, TRUE);
139 if (empty($doc) || json_last_error() != JSON_ERROR_NONE) {
140 return NULL;
141 }
142 return $doc;
143 }
144
847c93ac
TO
145 /**
146 * Get the final, usable URL string (after interpolating any variables)
147 *
148 * @return FALSE|string
149 */
150 public function getRenderedUrl() {
151 return CRM_Utils_System::evalUrl($this->messagesUrl);
152 }
153
154 /**
155 * @return bool
156 */
157 public function isEnabled() {
158 return $this->messagesUrl !== FALSE && $this->messagesUrl !== 'FALSE';
159 }
160
ecbe1139 161 /**
d1b65097 162 * Pick a message to display
ecbe1139 163 *
ecbe1139
TO
164 * @return NULL|array
165 */
dc92f2f8
TO
166 public function pick() {
167 $document = $this->getDocument();
168 $messages = array();
169 foreach ($document['messages'] as $message) {
170 if (!isset($message['perms'])) {
171 $message['perms'] = array(self::DEFAULT_PERMISSION);
172 }
173 if (!CRM_Core_Permission::checkAnyPerm($message['perms'])) {
174 continue;
175 }
176
177 if (isset($message['components'])) {
178 $enabled = array_keys(CRM_Core_Component::getEnabledComponents());
179 if (count(array_intersect($enabled, $message['components'])) == 0) {
180 continue;
181 }
182 }
183
184 $messages[] = $message;
185 }
186 if (empty($messages)) {
187 return NULL;
188 }
189
190 $idx = rand(0, count($messages) - 1);
191 return $messages[$idx];
ecbe1139
TO
192 }
193
194 /**
195 * @param string $markup
196 * @return string
197 */
198 public static function evalMarkup($markup) {
d1b65097
TO
199 $config = CRM_Core_Config::singleton();
200 $vals = array(
201 'resourceUrl' => rtrim($config->resourceBase, '/'),
202 'ver' => CRM_Utils_System::version(),
203 'uf' => $config->userFramework,
204 'php' => phpversion(),
205 'sid' => md5('sid_' . (defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : '') . '_' . $config->userFrameworkBaseURL),
206 'baseUrl' => $config->userFrameworkBaseURL,
207 'lang' => $config->lcMessages,
208 'co' => $config->defaultContactCountry,
209 );
210 $vars = array();
211 foreach ($vals as $k => $v) {
847c93ac
TO
212 $vars['%%' . $k . '%%'] = $v;
213 $vars['{{' . $k . '}}'] = urlencode($v);
d1b65097
TO
214 }
215 return strtr($markup, $vars);
ecbe1139
TO
216 }
217
8bfc3cb1
TO
218 /**
219 * Ensure that a document is well-formed
220 *
221 * @param array $document
222 * @return bool
223 */
224 public function validateDocument($document) {
225 if (!isset($document['ttl']) || !is_integer($document['ttl'])) {
226 return FALSE;
227 }
228 if (!isset($document['retry']) || !is_integer($document['retry'])) {
229 return FALSE;
230 }
231 if (!isset($document['messages']) || !is_array($document['messages'])) {
232 return FALSE;
233 }
234 foreach ($document['messages'] as $message) {
235 // TODO validate $message['markup']
236 }
237
238 return TRUE;
239 }
240
ecbe1139 241}