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