Merge pull request #3350 from eileenmcnaughton/comments
[civicrm-core.git] / CRM / Extension / Browser.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 * This class glues together the various parts of the extension
30 * system.
31 *
32 * @package CRM
33 * @copyright CiviCRM LLC (c) 2004-2014
34 * $Id$
35 *
36 */
37 class CRM_Extension_Browser {
38
39 /**
40 * An URL for public extensions repository
41 */
42 const DEFAULT_EXTENSIONS_REPOSITORY = 'https://civicrm.org/extdir/ver={ver}|cms={uf}';
43
44 /**
45 * @param string $repoUrl URL of the remote repository
46 * @param string $indexPath relative path of the 'index' file within the repository
47 * @param string $cacheDir local path in which to cache files
48 */
49 public function __construct($repoUrl, $indexPath, $cacheDir) {
50 $this->repoUrl = $repoUrl;
51 $this->cacheDir = $cacheDir;
52 $this->indexPath = $indexPath;
53 if ($cacheDir && !file_exists($cacheDir) && is_dir(dirname($cacheDir)) && is_writeable(dirname($cacheDir))) {
54 CRM_Utils_File::createDir($cacheDir, FALSE);
55 }
56 }
57
58 /**
59 * Determine whether the system policy allows downloading new extensions.
60 *
61 * This is reflection of *policy* and *intent*; it does not indicate whether
62 * the browser will actually *work*. For that, see checkRequirements().
63 *
64 * @return bool
65 */
66 public function isEnabled() {
67 return (FALSE !== $this->getRepositoryUrl());
68 }
69
70 public function getRepositoryUrl() {
71 return $this->repoUrl;
72 }
73
74 public function refresh() {
75 $file = $this->getTsPath();
76 if (file_exists($file)) {
77 unlink($file);
78 }
79 }
80
81 /**
82 * Determine whether downloading is supported
83 *
84 * @return array list of error messages; empty if OK
85 */
86 public function checkRequirements() {
87 if (!$this->isEnabled()) {
88 return array();
89 }
90
91 $errors = array();
92
93 if (!$this->cacheDir || !is_dir($this->cacheDir) || !is_writeable($this->cacheDir)) {
94 $civicrmDestination = urlencode(CRM_Utils_System::url('civicrm/admin/extensions', 'reset=1'));
95 $url = CRM_Utils_System::url('civicrm/admin/setting/path', "reset=1&civicrmDestination=${civicrmDestination}");
96 $errors[] = array(
97 'title' => ts('Directory Unwritable'),
98 '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/>',
99 array(
100 1 => $this->cacheDir,
101 2 => $url,
102 )
103 )
104 );
105 }
106
107 return $errors;
108 }
109
110 /**
111 * Get a list of all available extensions
112 *
113 * @return array ($key => CRM_Extension_Info)
114 */
115 public function getExtensions() {
116 if (!$this->isEnabled() || count($this->checkRequirements())) {
117 return array();
118 }
119
120 $exts = array();
121
122 $remote = $this->_discoverRemote();
123 if (is_array($remote)) {
124 foreach ($remote as $dc => $e) {
125 $exts[$e->key] = $e;
126 }
127 }
128
129 return $exts;
130 }
131
132 /**
133 * Get a description of a particular extension
134 *
135 * @param $key
136 *
137 * @return CRM_Extension_Info|NULL
138 */
139 public function getExtension($key) {
140 // TODO optimize performance -- we don't need to fetch/cache the entire repo
141 $exts = $this->getExtensions();
142 if (array_key_exists($key, $exts)) {
143 return $exts[$key];
144 } else {
145 // throw new CRM_Extension_Exception("Unknown remote extension: $key");
146 return NULL;
147 }
148 }
149
150 private function _discoverRemote() {
151 $tsPath = $this->getTsPath();
152 $timestamp = FALSE;
153
154 if (file_exists($tsPath)) {
155 $timestamp = file_get_contents($tsPath);
156 }
157
158 // 3 minutes ago for now
159 $outdated = (int) $timestamp < (time() - 180) ? TRUE : FALSE;
160
161 if (!$timestamp || $outdated) {
162 $remotes = $this->grabRemoteKeyList();
163 $cached = FALSE;
164 }
165 else {
166 $remotes = $this->grabCachedKeyList();
167 $cached = TRUE;
168 }
169
170 $this->_remotesDiscovered = array();
171 foreach ($remotes as $id => $rext) {
172 $xml = $this->grabRemoteInfoFile($rext['key'], $cached);
173 if ($xml != FALSE) {
174 $ext = CRM_Extension_Info::loadFromString($xml);
175 $this->_remotesDiscovered[] = $ext;
176 }
177 }
178
179 if (file_exists(dirname($tsPath))) {
180 file_put_contents($tsPath, (string) time());
181 }
182
183 return $this->_remotesDiscovered;
184 }
185
186 private function grabCachedKeyList() {
187 $result = array();
188 $cachedPath = $this->cacheDir . DIRECTORY_SEPARATOR;
189 $files = scandir($cachedPath);
190 foreach ($files as $dc => $fname) {
191 if (substr($fname, -4) == '.xml') {
192 $result[] = array('key' => substr($fname, 0, -4));
193 }
194 }
195 return $result;
196 }
197
198 /**
199 * Connects to public server and grabs the list of publically available
200 * extensions.
201 *
202 * @access public
203 *
204 * @return Array list of extension names
205 */
206 private function grabRemoteKeyList() {
207
208 ini_set('default_socket_timeout', CRM_Utils_VersionCheck::CHECK_TIMEOUT);
209 set_error_handler(array('CRM_Extension_Browser', 'downloadError'));
210
211 if (!ini_get('allow_url_fopen')) {
212 ini_set('allow_url_fopen', 1);
213 }
214
215 if(FALSE === $this->getRepositoryUrl()) {
216 // don't check if the user has configured civi not to check an external
217 // url for extensions. See CRM-10575.
218 CRM_Core_Session::setStatus(ts('Not checking remote URL for extensions since ext_repo_url is set to false.'), ts('Check Settings'), 'alert');
219 return array();
220 }
221
222 $exts = array();
223 list ($status, $extdir) = CRM_Utils_HttpClient::singleton()->get($this->getRepositoryUrl() . $this->indexPath);
224 if ($extdir === FALSE || $status !== CRM_Utils_HttpClient::STATUS_OK) {
225 CRM_Core_Session::setStatus(ts('The CiviCRM public extensions directory at %1 could not be contacted - please check your webserver can make external HTTP requests or contact CiviCRM team on <a href="http://forum.civicrm.org/">CiviCRM forum</a>.<br />', array(1 => $this->getRepositoryUrl())), ts('Connection Error'), 'error');
226 } else {
227 $lines = explode("\n", $extdir);
228
229 foreach ($lines as $ln) {
230 if (preg_match("@\<li\>(.*)\</li\>@i", $ln, $out)) {
231 // success
232 $extsRaw[] = $out;
233 $key = strip_tags($out[1]);
234 if (substr($key, -4) == '.xml') {
235 $exts[] = array('key' => substr($key, 0, -4));
236 }
237 }
238 }
239 }
240
241 // CRM-13141 There may not be any compatible extensions available for the requested CiviCRM version + CMS. If so, $extdir is empty so just return a notification.
242 if (empty($exts)) {
243 $config = CRM_Core_Config::singleton();
244 CRM_Core_Session::setStatus(ts('There are currently no extensions on the CiviCRM public extension directory which are compatible with version %2 (<a href="%1">requested extensions from here</a>). If you want to install an extension which is not marked as compatible, you may be able to <a href="%3">download and install extensions manually</a> (depending on access to your web server).<br />', array(1 => $this->getRepositoryUrl(), 2 => $config->civiVersion, 3 => 'http://wiki.civicrm.org/confluence/display/CRMDOC/Extensions')), ts('No Extensions Available for this Version'), 'info');
245 }
246
247 ini_restore('allow_url_fopen');
248 ini_restore('default_socket_timeout');
249
250 restore_error_handler();
251
252 return $exts;
253 }
254
255 /**
256 * Given the key, retrieves the info XML from a remote server
257 * and stores locally, returning the contents.
258 *
259 * @access public
260 *
261 * @param string $key extension key
262 * @param boolean $cached whether to use cached data
263 *
264 * @return contents of info.xml, or null if info.xml cannot be retrieved or parsed
265 */
266 private function grabRemoteInfoFile($key, $cached = FALSE) {
267 $filename = $this->cacheDir . DIRECTORY_SEPARATOR . $key . '.xml';
268 $url = $this->getRepositoryUrl() . '/' . $key . '.xml';
269
270 if (!$cached || !file_exists($filename)) {
271 $fetchStatus = CRM_Utils_HttpClient::singleton()->fetch($url, $filename);
272 if ($fetchStatus != CRM_Utils_HttpClient::STATUS_OK) {
273 return NULL;
274 }
275 }
276
277 if (file_exists($filename)) {
278 $contents = file_get_contents($filename);
279
280 //parse just in case
281 $check = simplexml_load_string($contents);
282
283 if (!$check) {
284 foreach (libxml_get_errors() as $error) {
285 CRM_Core_Error::debug('xmlError', $error);
286 }
287 return;
288 }
289
290 return $contents;
291 }
292 }
293
294 private function getTsPath() {
295 return $this->cacheDir . DIRECTORY_SEPARATOR . 'timestamp.txt';
296 }
297
298 /**
299 * A dummy function required for suppressing download errors
300 */
301 public static function downloadError($errorNumber, $errorString) {
302 return;
303 }
304
305 }