Participant import fix - broken uniqueName fields, mapping saving, event_id
[civicrm-core.git] / CRM / Extension / Browser.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * This class glues together the various parts of the extension
14 * system.
15 *
16 * @package CRM
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 */
19 class CRM_Extension_Browser {
20
21 /**
22 * An URL for public extensions repository.
23 *
24 * Note: This default is now handled through setting/*.php.
25 *
26 * @deprecated
27 */
28 const DEFAULT_EXTENSIONS_REPOSITORY = 'https://civicrm.org/extdir/ver={ver}|cms={uf}';
29
30 /**
31 * Relative path below remote repository URL for single extensions file.
32 */
33 const SINGLE_FILE_PATH = '/single';
34
35 /**
36 * The name of the single JSON extension cache file.
37 */
38 const CACHE_JSON_FILE = 'extensions.json';
39
40 // timeout for when the connection or the server is slow
41 const CHECK_TIMEOUT = 5;
42
43 /**
44 * @var GuzzleHttp\Client
45 */
46 protected $guzzleClient;
47
48 /**
49 * @return \GuzzleHttp\Client
50 */
51 public function getGuzzleClient(): \GuzzleHttp\Client {
52 return $this->guzzleClient ?? new \GuzzleHttp\Client();
53 }
54
55 /**
56 * @param \GuzzleHttp\Client $guzzleClient
57 */
58 public function setGuzzleClient(\GuzzleHttp\Client $guzzleClient) {
59 $this->guzzleClient = $guzzleClient;
60 }
61
62 /**
63 * @param string $repoUrl
64 * URL of the remote repository.
65 * @param string $indexPath
66 * Relative path of the 'index' file within the repository.
67 * @param string $cacheDir
68 * Local path in which to cache files.
69 */
70 public function __construct($repoUrl, $indexPath, $cacheDir) {
71 $this->repoUrl = $repoUrl;
72 $this->cacheDir = $cacheDir;
73 $this->indexPath = empty($indexPath) ? self::SINGLE_FILE_PATH : $indexPath;
74 if ($cacheDir && !file_exists($cacheDir) && is_dir(dirname($cacheDir)) && is_writable(dirname($cacheDir))) {
75 CRM_Utils_File::createDir($cacheDir, FALSE);
76 }
77 }
78
79 /**
80 * Determine whether the system policy allows downloading new extensions.
81 *
82 * This is reflection of *policy* and *intent*; it does not indicate whether
83 * the browser will actually *work*. For that, see checkRequirements().
84 *
85 * @return bool
86 */
87 public function isEnabled() {
88 return (FALSE !== $this->getRepositoryUrl());
89 }
90
91 /**
92 * @return string
93 */
94 public function getRepositoryUrl() {
95 return $this->repoUrl;
96 }
97
98 /**
99 * Refresh the cache of remotely-available extensions.
100 */
101 public function refresh() {
102 $file = $this->getTsPath();
103 if (file_exists($file)) {
104 unlink($file);
105 }
106 }
107
108 /**
109 * Determine whether downloading is supported.
110 *
111 * @return array
112 * List of error messages; empty if OK.
113 */
114 public function checkRequirements() {
115 if (!$this->isEnabled()) {
116 return [];
117 }
118
119 $errors = [];
120
121 if (!$this->cacheDir || !is_dir($this->cacheDir) || !is_writable($this->cacheDir)) {
122 $civicrmDestination = urlencode(CRM_Utils_System::url('civicrm/admin/extensions', 'reset=1'));
123 $url = CRM_Utils_System::url('civicrm/admin/setting/path', "reset=1&civicrmDestination=${civicrmDestination}");
124 $errors[] = array(
125 'title' => ts('Directory Unwritable'),
126 'message' => ts('Your extensions cache directory (%1) is not web server writable. Please go to the <a href="%2">path setting page</a> and correct it.<br/>',
127 array(
128 1 => $this->cacheDir,
129 2 => $url,
130 )
131 ),
132 );
133 }
134
135 return $errors;
136 }
137
138 /**
139 * Get a list of all available extensions.
140 *
141 * @return CRM_Extension_Info[]
142 * ($key => CRM_Extension_Info)
143 */
144 public function getExtensions() {
145 if (!$this->isEnabled() || count($this->checkRequirements())) {
146 return [];
147 }
148
149 $exts = [];
150
151 $remote = $this->_discoverRemote();
152 if (is_array($remote)) {
153 foreach ($remote as $dc => $e) {
154 $exts[$e->key] = $e;
155 }
156 }
157
158 return $exts;
159 }
160
161 /**
162 * Get a description of a particular extension.
163 *
164 * @param string $key
165 * Fully-qualified extension name.
166 *
167 * @return CRM_Extension_Info|NULL
168 */
169 public function getExtension($key) {
170 // TODO optimize performance -- we don't need to fetch/cache the entire repo
171 $exts = $this->getExtensions();
172 if (array_key_exists($key, $exts)) {
173 return $exts[$key];
174 }
175 else {
176 return NULL;
177 }
178 }
179
180 /**
181 * @return CRM_Extension_Info[]
182 * @throws CRM_Extension_Exception_ParseException
183 */
184 private function _discoverRemote() {
185 $tsPath = $this->getTsPath();
186 $timestamp = FALSE;
187
188 if (file_exists($tsPath)) {
189 $timestamp = file_get_contents($tsPath);
190 }
191
192 // 3 minutes ago for now
193 $outdated = (int) $timestamp < (time() - 180) ? TRUE : FALSE;
194
195 if (!$timestamp || $outdated) {
196 $remotes = json_decode($this->grabRemoteJson(), TRUE);
197 }
198 else {
199 $remotes = json_decode($this->grabCachedJson(), TRUE);
200 }
201
202 $this->_remotesDiscovered = [];
203 foreach ((array) $remotes as $id => $xml) {
204 $ext = CRM_Extension_Info::loadFromString($xml);
205 $this->_remotesDiscovered[] = $ext;
206 }
207
208 if (file_exists(dirname($tsPath))) {
209 file_put_contents($tsPath, (string) time());
210 }
211
212 return $this->_remotesDiscovered;
213 }
214
215 /**
216 * Loads the extensions data from the cache file. If it is empty
217 * or doesn't exist, try fetching from remote instead.
218 *
219 * @return string
220 */
221 private function grabCachedJson() {
222 $filename = $this->cacheDir . DIRECTORY_SEPARATOR . self::CACHE_JSON_FILE . '.' . md5($this->getRepositoryUrl());
223 $json = NULL;
224 if (file_exists($filename)) {
225 $json = file_get_contents($filename);
226 }
227 if (empty($json)) {
228 $json = $this->grabRemoteJson();
229 }
230 return $json;
231 }
232
233 /**
234 * Connects to public server and grabs the list of publicly available
235 * extensions.
236 *
237 * @return string
238 * @throws \CRM_Extension_Exception
239 */
240 private function grabRemoteJson() {
241 set_error_handler(array('CRM_Extension_Browser', 'downloadError'));
242
243 if (FALSE === $this->getRepositoryUrl()) {
244 // don't check if the user has configured civi not to check an external
245 // url for extensions. See CRM-10575.
246 return '';
247 }
248
249 $filename = $this->cacheDir . DIRECTORY_SEPARATOR . self::CACHE_JSON_FILE . '.' . md5($this->getRepositoryUrl());
250 $url = $this->getRepositoryUrl() . $this->indexPath;
251
252 $client = $this->getGuzzleClient();
253 $response = $client->request('GET', $url, ['sink' => $filename, 'timeout' => \Civi::settings()->get('http_timeout')]);
254 restore_error_handler();
255
256 if ($response->getStatusCode() !== 200) {
257 throw new CRM_Extension_Exception(ts('The CiviCRM public extensions directory at %1 could not be contacted - please check your webserver can make external HTTP requests', [1 => $this->getRepositoryUrl()]), 'connection_error');
258 }
259
260 // Don't call grabCachedJson here, that would risk infinite recursion
261 return file_get_contents($filename);
262 }
263
264 /**
265 * @return string
266 */
267 private function getTsPath() {
268 return $this->cacheDir . DIRECTORY_SEPARATOR . 'timestamp.txt';
269 }
270
271 /**
272 * A dummy function required for suppressing download errors.
273 *
274 * @param $errorNumber
275 * @param $errorString
276 */
277 public static function downloadError($errorNumber, $errorString) {
278 }
279
280 }