dolibarr 24.0.3
externalModules.class.php
1<?php
2/*
3 * Copyright (C) 2025 Mohamed DAOUD <mdaoud@dolicloud.com>
4 * Copyright (C) 2025-2026 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
6 *
7 * This program is free software; you can redistribute it and/or modifyion 2.0 (the "License");
8 * it under the terms of the GNU General Public License as published bypliance with the License.
9 * the Free Software Foundation; either version 3 of the License, or
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 * or see https://www.gnu.org/
19 */
20
21include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
22
27{
31 public $no_page;
32
36 public $per_page;
40 public $categorie;
41
45 public $search;
46
47 // setups
55 public $file_source_url;
56
60 public $cache_file;
61
66 public $url;
70 public $shop_url; // the url of the shop
74 public $lang; // the integer representing the lang in the store
78 public $debug_api; // useful if no dialog
82 public $dolistore_api_url;
86 public $dolistore_api_key;
87
91 public $dolistoreApiStatus;
92
96 public $dolistoreApiError;
97
101 public $githubFileStatus;
102
106 public $githubFileError;
107
111 public $error;
112
116 public $numberOfProviders;
117
121 public $products;
122
126 public $numberTotalOfProducts;
127
131 public $numberTotalOfPages;
132
136 public $numberOfProducts;
137
143 public function __construct($debug = false)
144 {
145 global $langs;
146
147 $this->debug_api = $debug;
148
149 $this->url = DOL_URL_ROOT.'/admin/modules.php?mode=marketplace';
150
151 // For dolistore modules
152 $this->dolistore_api_url = getDolGlobalString('MAIN_MODULE_DOLISTORE_API_SRV', 'https://www.dolistore.com/api/'); // 'https://www.dolistore.com/api/', 'https://admin2.dolibarr.org/api/index.php/marketplace/'
153 $this->dolistore_api_key = getDolGlobalString('MAIN_MODULE_DOLISTORE_API_KEY', 'dolistorepublicapi');
154 $this->shop_url = getDolGlobalString('MAIN_MODULE_DOLISTORE_SHOP_URL', 'https://www.dolistore.com');
155
156 // For community modules
157 $this->file_source_url = "https://raw.githubusercontent.com/Dolibarr/dolibarr-community-modules/refs/heads/main/index.yaml";
158 $this->cache_file = DOL_DATA_ROOT.'/admin/temp/remote_github_modules_file.yaml';
159
160 $lang = $langs->defaultlang;
161 $lang_array = array('en_US', 'fr_FR', 'es_ES', 'it_IT', 'de_DE');
162 if (!in_array($lang, $lang_array)) {
163 $lang = 'en_US';
164 }
165 $this->lang = $lang;
166 }
167
174 public function loadRemoteSources($debug = false)
175 {
176 // Check access to Community repo
177 if (getDolGlobalString('MAIN_ENABLE_EXTERNALMODULES_COMMUNITY')) {
178 $cachedelayforgithubrepo = getDolGlobalInt('MAIN_REMOTE_GITHUBREPO_CACHE_DELAY', 86400);
179
180 $this->getRemoteYamlFile($this->file_source_url, $cachedelayforgithubrepo);
181
182 $this->githubFileError = $this->error;
183 $this->githubFileStatus = dol_is_file($this->cache_file) ? 1 : 0;
184 }
185
186 // Check access to Dolistore API /api/categories -> /api/index.php/marketplace/categories
187 if (getDolGlobalString('MAIN_ENABLE_EXTERNALMODULES_DOLISTORE')) {
188 $this->dolistoreApiStatus = $this->checkApiStatus();
189 }
190
191 // Count the number of online providers
192 $this->numberOfProviders = $this->dolistoreApiStatus + $this->githubFileStatus;
193 }
194
202 public function callApi($resource, $options = false)
203 {
204 // If no dolistore_api_key is set, we can't access the API
205 if (empty($this->dolistore_api_key) || empty($this->dolistore_api_url)) {
206 return array('status_code' => 0, 'response' => null);
207 }
208
209 // Add basic auth if needed
210 $basicAuthLogin = getDolGlobalString('MAIN_MODULE_DOLISTORE_BASIC_LOGIN');
211 $basicAuthPassword = getDolGlobalString('MAIN_MODULE_DOLISTORE_BASIC_PASSWORD');
212
213 $httpheader = array('DOLAPIKEY: '.$this->dolistore_api_key);
214 if ($basicAuthLogin) {
215 $httpheader[] = 'Authorization: Basic '.base64_encode($basicAuthLogin.':'.$basicAuthPassword);
216 }
217
218 $url = $this->dolistore_api_url . (preg_match('/\/$/', $this->dolistore_api_url) ? '' : '/') . $resource;
219
220 $options['apikey'] = $this->dolistore_api_key;
221
222 if ($options) {
223 $url .= '?' . http_build_query($options);
224 }
225
226 $response = getURLContent($url, 'GET', '', 1, $httpheader, array('https'), 0, -1, 5, 5);
227
228 $status_code = $response['http_code'];
229 $body = 'Error';
230
231 if ($status_code == 200) {
232 $body = $response['content'];
233 $body = json_decode($body, true);
234 $returnarray = array(
235 'status_code' => $status_code,
236 'response' => $body
237 );
238 } else {
239 $returnarray = array(
240 'status_code' => $status_code,
241 'response' => $body
242 );
243 if (!empty($response['curl_error_no'])) {
244 $returnarray['curl_error_no'] = $response['curl_error_no'];
245 }
246 if (!empty($response['curl_error_msg'])) {
247 $returnarray['curl_error_msg'] = $response['curl_error_msg'];
248 }
249 }
250
251 return $returnarray;
252 }
253
260 public function fetchModulesFromFile($options = array())
261 {
262 $modules = array();
263
264 if (!empty($this->cache_file) && file_exists($this->cache_file)) {
265 dol_syslog(__METHOD__ . " - Loading cache file: " . $this->cache_file, LOG_DEBUG);
266
267 $content = file_get_contents($this->cache_file);
268 if ($content !== false) {
269 $modules = $this->readYaml($content);
270 } else {
271 dol_syslog(__METHOD__ . " - Error reading cache file", LOG_ERR);
272 }
273 }
274
275 return $modules;
276 }
277
284 public function getCategories($active = 0)
285 {
286 $organized_tree = array();
287 $html = '';
288
289 $data = [
290 'lang' => $this->lang
291 ];
292
293 $current = $active;
294
295 $resCategories = $this->callApi('categories', $data);
296 if (isset($resCategories['response']) && is_array($resCategories['response'])) {
297 $organized_tree = $resCategories['response'];
298 } else {
299 return $html ;
300 }
301
302 $html = '';
303 foreach ($organized_tree as $key => $value) {
304 if ($value['label'] != "Versions" && $value['label'] != "Specials") {
305 $html .= '<li' . ($current == $value['rowid'] ? ' class="active"' : '') . '>';
306 $html .= '<a href="?mode=marketplace&categorie=' . $value['rowid'] . '">' . $value['label'] . '</a>';
307 if (isset($value['children'])) {
308 $html .= '<ul>';
309 usort($value['children'], $this->buildSorter('position'));
310 foreach ($value['children'] as $key_children => $value_children) {
311 $html .= '<li' . ($current == $value_children['rowid'] ? ' class="active"' : '') . '>';
312 $html .= '<a href="?mode=marketplace&categorie=' . $value_children['rowid'] . '" title="' . dol_escape_htmltag(strip_tags($value_children['description'])) . '">' . $value_children['label'] . '</a>';
313 $html .= '</li>';
314 }
315 $html .= '</ul>';
316 }
317 $html .= '</li>';
318 }
319 }
320 return $html;
321 }
322
330 public function getProducts($options, $modules = array())
331 {
332 global $langs;
333
334 $langs->load("products");
335
336 $html = "";
337 $last_month = dol_now() - (30 * 24 * 60 * 60);
338 $dolibarrversiontouse = DOL_VERSION; // full string with version
339
340 $this->products = array();
341
342 // Build a map of installed external module names to their versions (lowercase name => version)
343 $installedModules = array();
344 if (is_array($modules)) {
345 foreach ($modules as $objMod) {
346 if (is_object($objMod) && $objMod->isCoreOrExternalModule() != 'core') {
347 $moduleName = strtolower($objMod->name);
348 $moduleVersion = $objMod->getVersion(0);
349 $installedModules[$moduleName] = $moduleVersion;
350 }
351 }
352 }
353
354 $this->categorie = $options['categorie'] ?? 0;
355 $this->per_page = $options['per_page'] ?? 11;
356 $this->no_page = $options['no_page'] ?? 1;
357 $this->search = $options['search'] ?? '';
358
359 $this->per_page = 11; // We fix number of products per page to 11
360
361 // Length of $search must be at least 2 characters
362 if (!empty($this->search) && strlen(str_replace(' ', '', (string) $this->search)) < 2) {
363 $html .= '<tr class=""><td colspan="3" class="center">';
364 $html .= '<br><br>';
365 $html .= $langs->trans("SearchStringMinLength").'...';
366 $html .= '<br><br>';
367 $html .= '</td></tr>';
368 return $html;
369 }
370
371 $data = [
372 'categorieid' => $this->categorie,
373 'limit' => $this->per_page,
374 'page' => $this->no_page,
375 'search' => $this->search,
376 'lang' => $this->lang
377 ];
378
379
380 $this->numberTotalOfProducts = 0;
381
382 // Special case of category goodies
383 if ($this->categorie == 87) {
384 $html = '<div class="shop-container">
385 <div class="shop-image">
386 <a href="https://merch.dolibarr.org/" target="_blank">
387 <img src="https://www.dolistore.com/medias/image/marketplace/img/goodies-shop.jpg" width="50%" alt="DoliStore Merch and Gifts" />
388 <div class="shop-overlay">
389 <button target="new" class="shop-button">'.$langs->trans("GoodiesButtonTitle").' <i class="icon-chevron-right"></i></button>
390 </div>
391 </a>
392 </div>
393 </div>';
394
395 return $html;
396 }
397
398 // Fetch the products from Dolistore source
399
400 $dolistoreProducts = array();
401 $dolistoreProductsTotal = 0;
402 if ($this->dolistoreApiStatus > 0 && getDolGlobalInt('MAIN_ENABLE_EXTERNALMODULES_DOLISTORE')) {
403 $getDolistoreProducts = $this->callApi('products', $data);
404
405 if (!isset($getDolistoreProducts['response']) || !is_array($getDolistoreProducts['response']) || ($getDolistoreProducts['status_code'] != 200 && $getDolistoreProducts['status_code'] != 201)) {
406 $dolistoreProducts = array();
407 $dolistoreProductsTotal = 0;
408 } else {
409 $dolistoreProducts = $this->adaptData($getDolistoreProducts['response']['products'], 'dolistore');
410 $dolistoreProductsTotal = (int) $getDolistoreProducts['response']['total'];
411 $this->numberTotalOfProducts += $dolistoreProductsTotal;
412 }
413 }
414
415 // Fetch the products from the github repo
416
417 $fileProducts = array();
418 $fileProductsTotal = 0;
419 if (!empty($this->githubFileStatus) && getDolGlobalInt('MAIN_ENABLE_EXTERNALMODULES_COMMUNITY')) {
420 $fileProducts = $this->fetchModulesFromFile($data); // Return an array with all modules from the cache filecontent in $data
421
422 $fileProducts = $this->adaptData($fileProducts, 'githubcommunity');
423
424 $fileProducts = $this->applyFilters($fileProducts, $data);
425
426 $fileProductsTotal = $fileProducts['total'];
427
428 $this->numberTotalOfProducts += $fileProductsTotal;
429
430 $fileProducts = $fileProducts['data'];
431 }
432
433 // Number of pages
434 $this->numberTotalOfPages = (int) ceil(max($fileProductsTotal / $this->per_page, $dolistoreProductsTotal / $this->per_page));
435
436 // Merge both sources (github community modules have priority on dolistore).
437 $this->products = $dolistoreProducts;
438 foreach ($fileProducts as $fileProduct) {
439 $id = $fileProduct['id'];
440 if ($id > 0) {
441 if (empty($this->products[$id])) { // Not already present in array
442 array_unshift($this->products, $fileProduct);
443 } else {
444 $this->products[$id] = $fileProduct;
445 $this->products[$id]['category'] = $fileProduct['category'];
446 }
447 } else {
448 array_unshift($this->products, $fileProduct);
449 }
450 }
451
452
453 $i = 0;
454 foreach ($this->products as $product) {
455 $i++;
456
457 // check new product ?
458 $newapp = '';
459 if ($last_month < strtotime($product['datec']) && $product["status"] != 'soon' && $product["status"] != 'development' && $product["status"] != 'experimental') {
460 $newapp .= '<span class="newApp" title="'.$product['tms'].'">'.$langs->trans('New').'</span> ';
461 }
462
463 // check updated ?
464 if ($newapp == '' && $last_month < strtotime($product['tms']) && $product["status"] != 'soon' && $product["status"] != 'development' && $product["status"] != 'experimental') {
465 $newapp .= '<span class="updatedApp" title="'.$product['tms'].'">'.$langs->trans('UpdatedRecently').'</span> ';
466 }
467
468 // add image or default ?
469 if ($product["cover_photo_url"] != '' && $product["cover_photo_url"] != '#') {
470 $images = '<a href="'.$product["cover_photo_url"].'" class="documentpreview" target="_blank" rel="noopener noreferrer" mime="image/png" title="'.dol_escape_htmltag($product["label"].', '.$langs->trans('Version').' '.$product["module_version"]).'">';
471 $images .= '<img class="imgstore" src="'.$product["cover_photo_url"].'" alt="" /></a>';
472 } else {
473 $images = '<img class="imgstore" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" />';
474 }
475
476 // Set and check version
477 $version = '';
478 $compatible = '';
479 if ($product["status"] == 'soon' || $product["status"] == 'development' || $product["status"] == 'experimental') {
480 $version = '<span class="warning">'.$langs->trans("NotYetAvailable").' - '.$langs->trans("StillInDevelopment").'</span>';
481 $compatible = 'NotCompatible';
482 } else {
483 // A min or max version set to '', 'auto' or 'unknown' is an unknown version
484 $minknown = (!empty($product["dolibarr_min"]) && !in_array($product["dolibarr_min"], array('auto', 'unknown')));
485 $maxknown = (!empty($product["dolibarr_max"]) && !in_array($product["dolibarr_max"], array('auto', 'unknown')));
486
487 if ($minknown && $this->versionCompare($product["dolibarr_min"], $dolibarrversiontouse) > 0) {
488 // Need update of Dolibarr (current version is lower than min)
489 $version = '<span class="compatibleafterupdate">'.$langs->trans(
490 'CompatibleAfterUpdate',
491 $dolibarrversiontouse,
492 $product["dolibarr_min"],
493 $product["dolibarr_max"]
494 ).'</span>';
495 $compatible = 'NotCompatible';
496 } elseif ($maxknown && $this->versionCompare($product["dolibarr_max"], $dolibarrversiontouse) >= 0) {
497 // Compatible
498 $version = '<span class="compatible hideonsmartphone">'.$langs->trans(
499 'CompatibleUpTo',
500 $dolibarrversiontouse,
501 $product["dolibarr_min"],
502 $product["dolibarr_max"]
503 ).'</span>';
504 $compatible = '';
505 } else {
506 // Not compatible (current version is higher than max, or max is unknown)
507 $version = '<span class="warning">'.$langs->trans(
508 'NotCompatible',
509 $dolibarrversiontouse,
510 $product["dolibarr_min"],
511 $product["dolibarr_max"]
512 ).'</span>';
513 $compatible = 'NotCompatible';
514 }
515 }
516
517 // free or pay ?
518 $install_link = '';
519 if (array_key_exists('price_ht', $product) && price2num($product["price_ht"]) > 0) {
520 $price = '<h3>'.price(price2num($product["price_ht"], 'MT'), 0, $langs, 1, -1, -1, 'EUR').' '.$langs->trans("HT").'</h3>';
521
522 $download_link = '<a class="paddingleft paddingright valignmiddle" target="_blank" title="'.$langs->trans("View").'" href="'.$this->shop_url.'/product.php?id='.((int) $product['id']).'">';
523 $download_link .= img_picto('', 'url', 'class="size2x paddingright"');
524 $download_link .= '</a>';
525 } else {
526 $download_link = '#';
527 if ($product['source'] === 'dolistore') { // 0 on dolistore may mean 0 or a complementary fee to subscribe
528 $urlview = $this->shop_url.'/product.php?id='.((int) $product["id"]);
529 $price = '<h3><a href="'.$urlview.'" target="_blank">'.$langs->trans('SeeOnDoliStore').'</a></h3>';
530 } elseif ($product['source'] === 'githubcommunity') {
531 if (array_key_exists('price_ht', $product) && empty($product['price_ht'])) {
532 if ($product['status'] == 'soon') {
533 $price = '<h3>'.$langs->trans('StillInDevelopment').'</h3>';
534 } else {
535 $price = '<h3>'.$langs->trans('Free').'</h3>';
536 }
537 } else {
538 if ($product["dolistore-download"]) {
539 $price = '<h3><a href="'.$product["dolistore-download"].'" target="_blank">'.$langs->trans('SeeOnDoliStore').'</a></h3>';
540 } else {
541 $price = '<h3>'.$langs->trans('Unknown').'</h3>';
542 }
543 }
544 } else {
545 $price = '<h3>'.$langs->trans('Unknown').'</h3>';
546 }
547
548 if ($product['source'] === 'githubcommunity') {
549 $download_link = '<a class="paddingleft paddingright valignmiddle" target="_blank" title="'.$langs->trans("Sources").'" href="'.$product["link"].'">';
550 $download_link .= img_picto('', 'file-code', 'class="size2x paddingright colorgrey"');
551 $download_link .= '</a>';
552
553 $urlview = $product["dolistore-download"]; // View on Dolistore
554 if ($urlview) {
555 $download_link .= '<a class="paddingleft paddingright valignmiddle" target="_blank" title="'.$langs->trans("View").'" href="'.$urlview.'" rel="noopener noreferrer">';
556 $download_link .= img_picto('', 'url', 'class="size2x"');
557 $download_link .= '</a>';
558 }
559
560 if (!empty($product['direct-download']) && $product['direct-download'] == 'yes') {
561 $reg = array();
562 if (preg_match('/https:.*\?id=(\d+)$/', $urlview, $reg)) {
563 $urldownload = 'https://www.dolistore.com/_service_download.php?t=free&p='.$reg[1];
564 $download_link .= '<a class="paddingleft paddingright valignmiddle" target="_blank" title="'.$langs->trans("Download").'" href="'.$urldownload.'" rel="noopener noreferrer">';
565 $download_link .= img_picto('', 'download', 'class="size2x paddingright"');
566 //$download_link .= '<img width="32" src="'.DOL_URL_ROOT.'/admin/remotestore/img/download.png" />';
567 $download_link .= '</a>';
568 }
569 }
570 } elseif ($product['source'] === 'dolistore') {
571 $urlview = $this->shop_url.'/product.php?id='.((int) $product["id"]);
572 $urldownload = 'https://www.dolistore.com/_service_download.php?t=free&p=' . $product['id'];
573 $download_link = '<a class="paddingleft paddingright valignmiddle" target="_blank" title="'.$langs->trans("View").'" href="'.$urlview.'">';
574 $download_link .= img_picto('', 'url', 'class="size2x"');
575 $download_link .= '</a>';
576 $download_link .= '<a class="paddingleft paddingright valignmiddle" target="_blank" title="'.$langs->trans("Download").'" href="'.$urldownload.'" rel="noopener noreferrer">';
577 $download_link .= img_picto('', 'download', 'class="size2x paddingright"');
578 //$download_link .= '<img width="32" src="'.DOL_URL_ROOT.'/admin/remotestore/img/download.png" />';
579 $download_link .= '</a>';
580 }
581
582 // Direct install
583 if ((!empty($product['direct-download']) && in_array($product['direct-download'], array('yes', 'dolistore'))) || $product['source'] === 'dolistore') {
584 $urldownload = '';
585
586 if ($product['source'] === 'githubcommunity') {
587 $current_version = $product['module_version'] ?? '';
588 $module_name = strtolower(preg_replace('/@.*$/', '', $product['ref'] ?? ''));
589
590 // Remove "-" followed by current version at the end of the string if it exists
591 $module_name = preg_replace('/-' . preg_quote($current_version, '/') . '$/', '', $module_name);
592
593 $urldownload = 'https://github.com/Dolibarr/dolibarr-community-modules/raw/refs/heads/main/dev/build/bin/module_' . $module_name . '-' . $current_version . '.zip';
594
595 $reg = array();
596 $urlview = $product["dolistore-download"]; // View on Dolistore
597
598 // For community modules, we download from community repo.
599 // But we can force to download from dolistore if MAIN_DOWNLOAD_FROM_DOLISTORE_IN_PRIORITY is set (less reliable, less up to date)
600 if (($product["direct-download"] ?? '') == 'dolistore' || getDolGlobalString("MAIN_DOWNLOAD_FROM_DOLISTORE_IN_PRIORITY")) {
601 if (preg_match('/https:.*\?id=(\d+)$/', $urlview, $reg)) {
602 $urldownload = 'https://www.dolistore.com/_service_download.php?t=free&p='.$reg[1];
603 }
604 }
605 }
606 if ($product['source'] === 'dolistore') {
607 $urldownload = 'https://www.dolistore.com/_service_download.php?t=free&p=' . $product['id'];
608 }
609
610
611 $disableInstall = ($compatible === 'NotCompatible') && !getDolGlobalInt('MAIN_FEATURES_LEVEL');
612 // $disableInstall = false; // TODO: remove this.
613 $disableInfo = $disableInstall ? dol_string_nohtmltag($version) : '';
614 $fields = ['action' => 'install', 'token' => newToken()];
615 foreach ($product as $key => $value) {
616 $fields['producttoinstall['.$key.']'] = $value;
617 }
618
619 $installConfirmMessage = $langs->transnoentities(
620 "extModuleConfirmInstallText",
621 $product['label'] ?? '',
622 $product['module_version'] ?? '',
623 $product['ref'] ?? '',
624 !empty($product['tms']) ? dol_print_date($product['tms'], '%d/%m/%Y') : ''
625 );
626 $installConfirmMessage .= $langs->trans("Path").' : '.$urldownload;
627
628 // Check if module is already installed locally to show "Upgrade" or "Re-install" instead of "Install"
629 $buttonLabel = $langs->trans("Install");
630 $remoteVersion = $product['module_version'] ?? '';
631 $remoteModuleName = strtolower(preg_replace('/@.*$/', '', $product['ref'] ?? ''));
632 // Remove "-" followed by current version at the end of the string if it exists
633 $remoteModuleName = preg_replace('/-' . preg_quote($remoteVersion, '/') . '$/', '', $remoteModuleName);
634 if (!empty($installedModules[$remoteModuleName]) && $remoteVersion && $remoteVersion != 'unknown') {
635 $localVersion = $installedModules[$remoteModuleName];
636 // $localVersion is guaranteed non-empty here (see !empty() test above), so only the 'unknown' value must be excluded
637 if ($localVersion != 'unknown') {
638 $versionDiff = $this->versionCompare($localVersion, $remoteVersion);
639 if ($versionDiff < 0) {
640 $buttonLabel = $langs->trans("Upgrade");
641 } elseif ($versionDiff == 0) {
642 $buttonLabel = $langs->trans("ReInstall");
643 }
644 }
645 }
646
647 $install_link = '<button class="valignmiddle ' . ($disableInstall ? 'butActionRefused' : 'butAction') . ' paddingleft paddingright"'
648 . ($disableInfo ? ' title="' . dol_escape_htmltag($disableInfo) . '"' : '')
649 . (!$disableInstall ? ' data-confirm' : '')
650 . (!$disableInstall ? ' data-fields="' . dol_escape_htmltag(json_encode($fields)) . '"' : '')
651 . (!$disableInstall ? ' data-url="' . dol_escape_htmltag($this->url) . '"' : '')
652 . (!$disableInstall ? ' data-confirm-title="' . dol_escape_htmltag($langs->trans("extModuleConfirmInstallTitle")) . '"' : '')
653 . (!$disableInstall ? ' data-confirm-text="' . dol_escape_htmltag($installConfirmMessage) . '"' : '')
654 . (!$disableInstall ? ' data-confirm-label="' . dol_escape_htmltag($buttonLabel) . '"' : '')
655 . '>' . $buttonLabel . '</button>';
656 }
657 }
658
659 // Output the line
660 $html .= '<tr class="'.(getDolOptimizeSmallScreen() ? 'app' : 'app app2').' oddeven nohover '.dol_escape_htmltag($compatible).'">';
661
662 // Logo
663 $html .= '<td class="center width150"><div class="newAppParent">';
664 $html .= $newapp.$images; // No dol_escape_htmltag, it is already escape html
665 $html .= '</div></td>';
666
667 // Description
668 $html .= '<td class="margeCote minwidth400imp"><h2 class="appTitle">';
669 $html .= dolPrintHTML(dol_string_nohtmltag(ucfirst($product["label"])));
670 if (!empty($product['author']) && $product['author'] != 'unkownauthor') {
671 $html .= '<span class="small"> &nbsp; - &nbsp; '.img_picto('', 'company', 'class="pictofixedwidth"');
672 if (!empty($product['author_url'])) {
673 $html .= '<a href="'.$product['author_url'].'" target="_blank">'.$product['author'].'</a>';
674 } else {
675 $html .= $product['author'];
676 }
677 $html .= '</span>';
678 }
679 $html .= '<br><span class="small">';
680 $html .= $version; // Version Dolibarr. No dol_escape_htmltag, it is already escape html
681 $html .= '</span>';
682 $html .= '</h2>';
683
684 $html .= '<small class="appDateCreation appRef"> ';
685 if (empty($product['tms'])) {
686 $html .= img_picto($langs->trans('DateCreation'), 'calendar', 'class="pictofixedwidth"').'<span class="opacitymedium"><span class="hideonsmartphone">'.$langs->trans("DateCreation").': </span>';
687 $html .= (!empty($product['datec']) ? dol_print_date(dol_stringtotime($product['datec']), 'day') : $langs->trans("Unknown")).'</span>';
688 } else {
689 $html .= img_picto($langs->trans('DateModification'), 'calendar', 'class="pictofixedwidth"').'<span class="opacitymedium">'.dol_print_date(dol_stringtotime($product['tms']), 'day').'</span>';
690 }
691 $html .= ' &nbsp; &nbsp; ';
692
693 $html .= '<div class="appSource inline-block valigntop">';
694 if ($product["source"] == 'dolistore') {
695 $html .= '<img border="0" title="'.dolPrintHTML($langs->trans('Source').": DoliStore").'" class="imgautosize valignmiddle inline-block pictofixedwidth" style="height: 14px" src="'.DOL_URL_ROOT.'/theme/dolistore_squarred.svg">';
696 } elseif ($product["source"] == 'githubcommunity') {
697 $html .= img_picto($langs->trans('Source').': GitHub community repo', 'group', 'class="pictofixedwidth valignmiddle"');
698 } else {
699 $html .= img_picto($langs->trans('Source').': '.$langs->trans('Other'), 'generic', 'class="pictofixedwidth"');
700 }
701 $html .= '</div>';
702
703 $html .= $langs->trans('Ref').' '.dolPrintHTML(preg_replace('/@.*$/', '', $product["ref"]));
704 $html .= '</small><br>';
705
706
707 $html .= '&nbsp;';
708 if (!empty($product['phpmin']) && $product['phpmin'] != 'unknown') {
709 $html .= ' <span class="badge-secondary small" style="padding: 3px; border-radius: 5px">PHP min '.$product['phpmin'].'</span>';
710 }
711 if (!empty($product['phpmax']) && $product['phpmax'] != 'unknown') {
712 $html .= ' <span class="badge-secondary small" style="padding: 3px; border-radius: 5px">PHP max '.$product['phpmax'].'</span>';
713 }
714 $html .= '<br>';
715
716 $html .= '<br>';
717 $html .= '<div class="storedesc">'.dolPrintHTML(dol_string_nohtmltag($product["description"])).'</div>';
718 $html .= '</td>';
719
721 $html .= '</tr><tr class="app2 oddeven nohover borderbottom '.dol_escape_htmltag($compatible).'">';
722 }
723
724 // Price - do not load if display none
725 $html .= '<td class="margeCote center amount'.(getDolOptimizeSmallScreen() ? ' left" colspan="2"' : '"').'>';
726 $html .= $price;
727 if ((!empty($product['direct-download']) && in_array($product['direct-download'], array('yes', 'dolistore'))) || ($product['source'] === 'dolistore' && empty((float) $product['price_ht']))) {
728 if ($install_link) {
729 $html .= $install_link;
730 }
731 }
732
734 $html .= '</td>';
735 $html .= '<td class="margeCote nowraponall">';
736 }
737
738 // Links
739 $html .= $download_link;
740 $html .= '</td>';
741
742 $html .= '</tr>';
743 }
744
745 if (empty($this->products)) {
746 $colspan = (getDolOptimizeSmallScreen() ? 1 : 3);
747 $langs->load("website");
748
749 $html .= '<tr class=""><td colspan="'.$colspan.'" class="center">';
750 $html .= '<br><br>';
751 $html .= $langs->trans("noResultsWereFound").'...';
752 $html .= '<br><br>';
753 $html .= '</td></tr>';
754 }
755
756 // JS for confirm install
757 $confirmLabel = $langs->trans("Install");
758 $cancelLabel = $langs->trans("Cancel");
759 $html .= '<script>
760 $(document).on("click","[data-confirm]",function(){
761 var button = $(this);
762 var confirmTitle = button.data("confirm-title");
763 var confirmText = button.data("confirm-text");
764 var buttons = {};
765 buttons[button.data("confirm-label")||\'' . dol_escape_js($confirmLabel) . '\'] = function(){
766 var form = $("<form method=\'POST\' style=\'display:none\'>").attr("action", button.data("url"));
767 $.each(button.data("fields"), function(name, value){
768 form.append($("<input type=\'hidden\'>").attr("name", name).val(value));
769 });
770 $("body").append(form);
771 form.submit();
772 $(this).dialog("close");
773 };
774 buttons[\'' . dol_escape_js($cancelLabel) . '\'] = function(){$(this).dialog("close");};
775 $("<div>").html(confirmText).dialog({
776 title: confirmTitle,
777 minWidth: 580,
778 modal: true,
779 buttons: buttons
780 });
781 });
782 </script>';
783
784 $this->numberOfProducts = count($this->products);
785
786 return $html;
787 }
788
795 public function buildSorter(string $key): Closure
796 {
797 return
803 function (array $a, array $b) use ($key) {
804 $valA = isset($a[$key]) && is_scalar($a[$key]) ? (string) $a[$key] : '';
805 $valB = isset($b[$key]) && is_scalar($b[$key]) ? (string) $b[$key] : '';
806
807 return strnatcmp($valA, $valB);
808 };
809 }
810
818 public function versionCompare($v1, $v2)
819 {
820 // Clean v1 and v2
821 $v1 = str_replace(array('v', 'V'), '', $v1);
822 $v2 = str_replace(array('v', 'V'), '', $v2);
823
824 $v1 = explode('.', $v1);
825 $v2 = explode('.', $v2);
826 $ret = 0;
827 $level = 0;
828 $count1 = count($v1);
829 $count2 = count($v2);
830 $maxcount = max($count1, $count2);
831 while ($level < $maxcount) {
832 $operande1 = isset($v1[$level]) ? $v1[$level] : 'x';
833 $operande2 = isset($v2[$level]) ? $v2[$level] : 'x';
834 $level++;
835 if (strtoupper($operande1) == 'X' || strtoupper($operande2) == 'X' || $operande1 == '*' || $operande2 == '*') {
836 break;
837 }
838 if ($operande1 < $operande2) {
839 $ret = -$level;
840 break;
841 }
842 if ($operande1 > $operande2) {
843 $ret = $level;
844 break;
845 }
846 }
847 //print join('.',$versionarray1).'('.count($versionarray1).') / '.join('.',$versionarray2).'('.count($versionarray2).') => '.$ret.'<br>'."\n";
848 return $ret;
849 }
850
851 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
858 public function get_previous_link($text = '<<')
859 {
860 // phpcs:enable
861 return '<a href="'.$this->get_previous_url().'" class="button">'.dol_escape_htmltag($text).'</a>';
862 }
863
864 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
871 public function get_next_link($text = '>>')
872 {
873 // phpcs:enable
874 return '<a href="'.$this->get_next_url().'" class="button">'.dol_escape_htmltag($text).'</a>';
875 }
876
877 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
883 public function get_previous_url()
884 {
885 // phpcs:enable
886 $param_array = array();
887 if ($this->no_page > 1) {
888 $sub = 1;
889 } else {
890 $sub = 0;
891 }
892 if (!empty($this->search)) {
893 $param_array['search_keyword'] = $this->search;
894 }
895 $param_array['no_page'] = $this->no_page - $sub;
896 if ($this->categorie != 0) {
897 $param_array['categorie'] = $this->categorie;
898 }
899 $param = http_build_query($param_array);
900 return $this->url."&".$param;
901 }
902
903 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
909 public function get_next_url()
910 {
911 // phpcs:enable
912 $param_array = array();
913 if ($this->products !== null && count($this->products) < $this->per_page) {
914 $add = 0;
915 } else {
916 $add = 1;
917 }
918 if (!empty($this->search)) {
919 $param_array['search_keyword'] = $this->search;
920 }
921 $param_array['no_page'] = $this->no_page + $add;
922 if ($this->categorie != 0) {
923 $param_array['categorie'] = $this->categorie;
924 }
925 $param = http_build_query($param_array);
926 return $this->url."&".$param;
927 }
928
934 public function getPagination()
935 {
936
937 global $langs;
938
939 $page = $this->no_page;
940 $limit = $this->per_page;
941 $totalnboflines = $this->numberTotalOfProducts ?: 0;
942 $num = $this->numberOfProducts;
943
944 $html = "";
945
946 // Show navigation bar
947 $pagelist = '';
948 if ($page > 0 || $num > $limit) {
949 if ($totalnboflines) {
950 if ($limit > 0) {
951 $nbpages = $this->numberTotalOfPages;
952 } else {
953 $nbpages = 1;
954 }
955
956 // Show previous page
957 if ($page > 1) {
958 $pagelist .= '<li class="pagination paginationpage paginationpageleft"><a class="paginationprevious reposition" href="'.$this->get_previous_url().'"><i class="fa fa-chevron-left" title="'.dol_escape_htmltag($langs->trans("Previous")).'"></i></a></li>';
959 }
960
961 $pagelist .= '<li class="pagination">';
962 $pagelist .= '<label for="page_input">Page </label>';
963 if ($this->categorie != 0) {
964 $pagelist .= '<input type="hidden" name="categorie" value="' . $this->categorie . '">';
965 }
966 // URL to go to another page (without no_page). Used when pressing Enter into the page input field.
967 $param_array = array();
968 if (!empty($this->search)) {
969 $param_array['search_keyword'] = $this->search;
970 }
971 if ($this->categorie != 0) {
972 $param_array['categorie'] = $this->categorie;
973 }
974 $urlforpage = $this->url.($param_array ? '&'.http_build_query($param_array) : '');
975 $pagelist .= '<input type="text" id="page_input" name="no_page" value="'.($page).'" min="1" max="'.$nbpages.'" class="width40 page_input right" data-url="'.dol_escape_htmltag($urlforpage).'"';
976 $pagelist .= ' oninput="if(this.value > '.$nbpages.') this.value='.$nbpages.'"';
977 $pagelist .= ' onkeydown="if (event.key === \'Enter\') { event.preventDefault(); var p = parseInt(this.value, 10); if (isNaN(p) || p < 1) { p = 1; } window.location.href = this.dataset.url + \'&no_page=\' + p; }">';
978 $pagelist .= ' / '.$nbpages;
979 $pagelist .= '</li>';
980
981 // Show next page
982 if ($page < $nbpages) {
983 $pagelist .= '<li class="pagination paginationpage paginationpageright"><a class="paginationnext reposition" href="'.$this->get_next_url().'"><i class="fa fa-chevron-right" title="'.dol_escape_htmltag($langs->trans("Next")).'"></i></a></li>';
984 }
985 }
986 }
987
988 if ($limit || $pagelist) {
989 $html .= '<div class="pagination" style="padding: 7px;">';
990 $html .= '<ul>';
991 $html .= $pagelist;
992 $html .= '</ul>';
993 $html .= '</div>';
994 }
995
996 $html .= ajax_autoselect('.page_input');
997
998 return $html;
999 }
1000
1007 protected function checkStatusCode($request)
1008 {
1009 // Define error messages
1010 $error_messages = [
1011 204 => 'No content',
1012 400 => 'Bad Request',
1013 401 => 'Unauthorized',
1014 404 => 'Not Found',
1015 405 => 'Method Not Allowed',
1016 500 => 'Internal Server Error',
1017 ];
1018
1019 // If status code is 200 or 201, return an empty string
1020 if ($request['status_code'] === 200 || $request['status_code'] === 201) {
1021 return '';
1022 }
1023
1024 // Get the predefined error message or use a default one
1025 $error_message = $error_messages[$request['status_code']] ?? 'Unexpected HTTP status: ' . $request['status_code'];
1026
1027 // Append error details if available
1028 if (!empty($request['response']) && isset($request['response']['errors']) && is_array($request['response']['errors'])) {
1029 foreach ($request['response']['errors'] as $error) {
1030 $error_message .= ' - (Code ' . $error['code'] . '): ' . $error['message'];
1031 }
1032 }
1033
1034 if (!empty($request['curl_error_msg'])) {
1035 $error_message .= ' - ' . $request['curl_error_msg'];
1036 }
1037
1038 // Return the formatted error message
1039 return sprintf('This call to the API failed and returned an HTTP status of %d. That means: %s.', $request['status_code'], $error_message);
1040 }
1041
1049 public function getRemoteYamlFile($file_source_url, $cache_time)
1050 {
1051 $yaml = '';
1052 $cache_file = $this->cache_file;
1053 $cache_folder = dirname($cache_file);
1054
1055 // Check if cache directory exists
1056 if (!dol_is_dir($cache_folder)) {
1057 dol_mkdir($cache_folder, DOL_DATA_ROOT);
1058 }
1059
1060 if (!file_exists($cache_file) || filemtime($cache_file) < (dol_now() - $cache_time)) {
1061 // We get remote url
1062 $addheaders = array();
1063 $result = getURLContent($file_source_url, 'GET', '', 1, $addheaders); // TODO Force timeout to 5 s on both connect and response.
1064 if (!empty($result) && $result['http_code'] == 200) {
1065 $yaml = $result['content'];
1066 $result = file_put_contents($cache_file, $yaml);
1067 if ($result === false) {
1068 $this->error = 'Failed to create cache file: ' . $cache_file;
1069 } else {
1070 dolChmod($cache_file);
1071 }
1072 }
1073 } else {
1074 $yaml = file_get_contents($cache_file);
1075 }
1076
1077 return $yaml;
1078 }
1079
1080
1087 public function readYaml($yaml)
1088 {
1089 $data = [];
1090 $currentPackage = null;
1091 $currentSection = null;
1092
1093 foreach (explode("\n", trim($yaml)) as $line) {
1094 $trimmedLine = trim($line);
1095
1096 // Ignore empty lines and comments
1097 if ($trimmedLine === '' || strpos($trimmedLine, '#') === 0) {
1098 continue;
1099 }
1100
1101 // Match a new package entry (e.g., "- modulename: 'helloasso'") - Found a break in file.
1102 $matches = array();
1103 if (preg_match('/^\s*-\s*modulename:\s*["\']?(.*?)["\']?$/', $trimmedLine, $matches)) {
1104 if ($currentPackage !== null) {
1105 // Add the package to $data
1106 if (!empty($currentPackage['status']) && in_array($currentPackage['status'], array('enabled', 'soon'))) {
1107 $data[] = $currentPackage;
1108 }
1109 }
1110 $currentPackage = ['modulename' => $matches[1]];
1111 $currentSection = null;
1112 continue;
1113 }
1114
1115 // If the key doesn't start with fr, en, es, it, de, treat it as a section
1116 if (!preg_match('/^\s*(fr|en|es|it|de):\s*["\']?(.*?)["\']?$/', $trimmedLine)) {
1117 $currentSection = null;
1118 }
1119
1120 // Match a top-level key-value pair (e.g., "author: 'Dolicloud'")
1121 if (preg_match('/^(\w[\w-]*):\s*["\']?(.*?)["\']?$/', $trimmedLine, $matches)) {
1122 if ($currentPackage !== null) {
1123 if ($currentSection) {
1124 // Store in the sub section (language into label or description for example)
1125 $currentPackage[$currentSection][$matches[1]] = $matches[2] === '' ? null : $matches[2];
1126 } else {
1127 // Store as a normal key-value pair
1128 $currentPackage[$matches[1]] = $matches[2] === '' ? null : $matches[2];
1129 }
1130 }
1131
1132 // Match a nested section (e.g., "label:")
1133 if (preg_match('/^\s*(label|description):\s*$/', $trimmedLine, $matches)) {
1134 $currentSection = $matches[1];
1135 $currentPackage[$currentSection] = []; // Initialize as an empty array for nested sections
1136 }
1137
1138 continue;
1139 }
1140 }
1141
1142 // Add the last package if available
1143 if ($currentPackage !== null) {
1144 if (!empty($currentPackage['status']) && in_array($currentPackage['status'], array('enabled', 'soon'))) {
1145 $data[] = $currentPackage;
1146 }
1147 }
1148
1149 return $data;
1150 }
1151
1159 public function adaptData($data, $source)
1160 {
1161 $adaptedData = [];
1162
1163 if (!is_array($data) || empty($data) || empty($source)) {
1164 return $adaptedData;
1165 }
1166
1167 if ($source === 'githubcommunity') {
1168 foreach ($data as $package) {
1169 if (empty($package['modulename'])) {
1170 continue;
1171 }
1172
1173 // Check if there is a known ID
1174 $reg = array();
1175 $id = 0;
1176 if (!empty($package['dolistore-download']) && preg_match('/www\.dolistore\.com\/product\.php\?id=(\d+)/', (string) $package['dolistore-download'], $reg)) {
1177 $id = $reg[1];
1178 }
1179
1180 $adaptedPackage = [
1181 'id' => $id,
1182 'ref' => str_replace(' ', '', $package['modulename'] . '-' . $package['current_version'] . '@' .
1183 (array_key_exists('author', $package) ? $package['author'] : 'unkownauthor')),
1184 'label' => !empty($package['label'][substr($this->lang, 0, 2)])
1185 ? $package['label'][substr($this->lang, 0, 2)]
1186 : (!empty($package['label']['en']) ? $package['label']['en'] : $package['modulename']),
1187 'description' => !empty($package['description'][substr($this->lang, 0, 2)])
1188 ? $package['description'][substr($this->lang, 0, 2)]
1189 : (!empty($package['description']['en']) ? $package['description']['en'] : ''),
1190 'datec' => (!empty($package['created_at']) && is_string($package['created_at']))
1191 ? date('Y-m-d H:i:s', strtotime($package['created_at']))
1192 : '',
1193 'tms' => (!empty($package['last_updated_at']) && is_string($package['last_updated_at']))
1194 ? date('Y-m-d H:i:s', strtotime($package['last_updated_at']))
1195 : '',
1196 'author' => array_key_exists('author', $package) ? $package['author'] : '',
1197 'author_url' => array_key_exists('author_url', $package) ? $package['author_url'] : '',
1198 'dolibarr_min' => !empty($package['dolibarrmin'])
1199 ? $package['dolibarrmin']
1200 : 'unknown',
1201 'dolibarr_max' => !empty($package['dolibarrmax'])
1202 ? $package['dolibarrmax']
1203 : 'unknown',
1204 'phpmin' => !empty($package['phpmin'])
1205 ? $package['phpmin']
1206 : 'unknown',
1207 'phpmax' => !empty($package['phpmax'])
1208 ? $package['phpmax']
1209 : 'unknown',
1210 'module_version' => !empty($package['current_version'])
1211 ? $package['current_version']
1212 : 'unknown',
1213 'cover_photo_url' => !empty($package['cover'])
1214 ? $package['cover']
1215 : '#',
1216 'category' => (!empty($package['category']) && is_string($package['category']))
1217 ? explode(',', str_replace(' ', '', (string) $package['category']))
1218 : array(),
1219 'link' => !empty($package['git'])
1220 ? $package['git']
1221 : '#',
1222 'source' => 'githubcommunity',
1223 'status' => !empty($package['status']) ? $package['status'] : '',
1224 'direct-download' => !empty($package['direct-download'])
1225 ? $package['direct-download']
1226 : '',
1227 'dolistore-download' => !empty($package['dolistore-download'])
1228 ? $package['dolistore-download']
1229 : '',
1230 ];
1231
1232 // If a price entry exists
1233 if (array_key_exists('price', $package) && $package['price'] != null) {
1234 $adaptedPackage['price_ht'] = $package['price'];
1235 }
1236
1237 $adaptedData[] = $adaptedPackage;
1238 }
1239 }
1240
1241 if ($source === 'dolistore') {
1242 foreach ($data as $package) {
1243 $urlphoto = $this->shop_url.$package['cover_photo_url'];
1244
1245 if (preg_match('/^\/?wrapper\.php\?hashp=/', $package['cover_photo_url']) && !preg_match('/attachment=/', $package['cover_photo_url'])) {
1246 $urlphoto .= '&attachment=0';
1247 }
1248
1249 $adaptedPackage = [
1250 'id' => $package['id'],
1251 'ref' => $package['ref'],
1252 'label' => $package['label'],
1253 'description' => $package['description'],
1254 'datec' => $package['datec'],
1255 'tms' => $package['tms'],
1256 'author' => array_key_exists('author', $package) ? $package['author'] : '',
1257 'author_url' => array_key_exists('author_url', $package) ? $package['author_url'] : '',
1258 'price_ttc' => $package['price_ttc'],
1259 'price_ht' => $package['price_ht'],
1260 'dolibarr_min' => $package['dolibarr_min'],
1261 'dolibarr_max' => $package['dolibarr_max'],
1262 'phpmin' => empty($package['phpmin']) ? '' : $package['phpmin'],
1263 'phpmax' => empty($package['phpmax']) ? '' : $package['phpmax'],
1264 'module_version' => $package['module_version'],
1265 'cover_photo_url' => $urlphoto,
1266 'source' => 'dolistore',
1267 'status' => empty($package['status']) ? '' : $package['status'],
1268 'direct-download' => '',
1269 ];
1270
1271 $adaptedData[$package['id']] = $adaptedPackage;
1272 }
1273 }
1274
1275 return $adaptedData;
1276 }
1277
1285 public function applyFilters($list, $options)
1286 {
1287 $filteredData = $list;
1288
1289 // Sort products list by datec
1290 usort(
1291 $filteredData,
1299 static function ($a, $b) {
1300 return strtotime($b['datec'] ?? '0') - strtotime($a['datec'] ?? '0');
1301 }
1302 );
1303
1304 if (!empty($options['search'])) {
1305 $filteredData = array_filter(
1306 $filteredData,
1314 static function ($package) use ($options) {
1315 return stripos($package['label'], $options['search']) !== false || stripos($package['description'], $options['search']) !== false;
1316 }
1317 );
1318 }
1319
1320 if (!empty($options['categorieid'])) {
1321 $filteredData = array_filter(
1322 $filteredData,
1330 static function ($package) use ($options) {
1331 return in_array($options['categorieid'], $package['category']);
1332 }
1333 );
1334 }
1335
1336 $total = count($filteredData);
1337
1338 // Pagination
1339 $filteredData = array_values($filteredData);
1340 $filteredData = array_slice($filteredData, ($options['page'] - 1) * $options['limit'], $options['limit']);
1341
1342 return ['total' => $total, 'data' => $filteredData];
1343 }
1344
1350 public function checkApiStatus()
1351 {
1352 // Call remote API
1353 $testRequest = $this->callApi('categories');
1354
1355 if (!isset($testRequest['response']) || !is_array($testRequest['response']) || ($testRequest['status_code'] != 200 && $testRequest['status_code'] != 201)) {
1356 $this->dolistoreApiError = $this->checkStatusCode($testRequest);
1357 return 0;
1358 } else {
1359 return 1;
1360 }
1361 }
1362
1371 public function libStatus($status, $mode = 3, $moretext = '')
1372 {
1373 global $langs;
1374
1375 $statusType = 'status4';
1376 if ($status == 0) {
1377 $statusType = 'status3';
1378 }
1379
1380 $labelStatus = [];
1381 $labelStatusShort = [];
1382
1383 $labelStatus[0] = $langs->transnoentitiesnoconv("NotConnected");
1384 $labelStatus[1] = $langs->transnoentitiesnoconv("online");
1385 $labelStatusShort[0] = $langs->transnoentitiesnoconv("NotConnected");
1386 $labelStatusShort[1] = $langs->transnoentitiesnoconv("online");
1387
1388 return dolGetStatus($labelStatus[$status], $labelStatusShort[$status], '', $statusType, $mode, '', array('badgeParams' => array('attr' => array('class' => 'classfortooltip', 'title' => $labelStatusShort[$status].$moretext))));
1389 }
1390
1391
1398 public function getModuleZIP($producttoinstall = array())
1399 {
1400 global $conf;
1401
1402 // Check if cURL is available
1403 if (!function_exists('curl_init')) {
1404 dol_syslog(__METHOD__ . ': cURL is not available', LOG_ERR);
1405 return false;
1406 }
1407
1408 // Check required fields
1409 if (empty($producttoinstall['ref'])) {
1410 dol_syslog(__METHOD__ . ': Missing producttoinstall', LOG_ERR);
1411 return false;
1412 }
1413
1414 $current_version = $producttoinstall['module_version'] ?? '';
1415 $module_name = strtolower(preg_replace('/@.*$/', '', $producttoinstall['ref'] ?? ''));
1416
1417 // Remove "-" followed by current version at the end of the string if it exists
1418 $module_name = preg_replace('/-' . preg_quote($current_version, '/') . '$/', '', $module_name);
1419
1420 if (empty($module_name) || empty($current_version) || $current_version == 'unknown') {
1421 dol_syslog(__METHOD__ . ': Missing or unknown module name/version for product', LOG_ERR);
1422 return false;
1423 }
1424
1425 // Create a temporary directory for the download
1426 $tmpdir = $conf->admin->dir_temp . '/remotestoredl';
1427 dol_mkdir($tmpdir);
1428
1429 $downloaded = false;
1430 switch ($producttoinstall['source']) {
1431 case 'dolistore':
1432 if ($producttoinstall['id'] > 0) {
1433 $source_url = 'https://www.dolistore.com/_service_download.php?t=free&p=' . $producttoinstall['id'];
1434 $downloaded = $this->_downloadFile($source_url, $tmpdir);
1435 if (!$downloaded) {
1436 dol_syslog(__METHOD__ . ': Dolistore download failed: ' . $source_url, LOG_ERR);
1437 return false;
1438 }
1439 } else {
1440 dol_syslog(__METHOD__ . ': Invalid product ID for Dolistore download: ' . $producttoinstall['id'], LOG_ERR);
1441 return false;
1442 }
1443 break;
1444 case 'githubcommunity':
1445 if (!empty($producttoinstall['direct-download']) && in_array($producttoinstall['direct-download'], array('yes', 'dolistore'))) {
1446 $source_url = 'https://github.com/Dolibarr/dolibarr-community-modules/raw/refs/heads/main/dev/build/bin/module_' . $module_name . '-' . $current_version . '.zip';
1447 $downloaded = $this->_downloadFile($source_url, $tmpdir);
1448 if (!$downloaded) {
1449 dol_syslog(__METHOD__ . ': GitHub community module download failed: ' . $source_url . ', Try to find a Dolistore link', LOG_WARNING);
1450 if ($producttoinstall['id'] > 0) {
1451 $source_url = 'https://www.dolistore.com/_service_download.php?t=free&p=' . $producttoinstall['id'];
1452 $downloaded = $this->_downloadFile($source_url, $tmpdir);
1453 if (!$downloaded) {
1454 dol_syslog(__METHOD__ . ': Dolistore download failed: ' . $source_url, LOG_ERR);
1455 return false;
1456 }
1457 } else {
1458 dol_syslog(__METHOD__ . ': No direct download available for this GitHub community module', LOG_ERR);
1459 return false;
1460 }
1461 }
1462 } else {
1463 dol_syslog(__METHOD__ . ': No direct download available for this GitHub community module', LOG_ERR);
1464 return false;
1465 }
1466 break;
1467 default:
1468 dol_syslog(__METHOD__ . ': Unsupported source type: ' . $producttoinstall['source'], LOG_ERR);
1469 }
1470
1471
1472 dol_syslog(__METHOD__ . ': Module downloaded successfully to: ' . $downloaded, LOG_DEBUG);
1473 return $downloaded;
1474 }
1475
1476
1484 private function _downloadFile(string $url, string $dest_path)
1485 {
1486 // HEAD request to get real filename from Content-Disposition
1487 $filename = '';
1488 $head = getURLContent($url, 'HEAD');
1489 // Try to extract filename from Content-Disposition header
1490 if (!empty($head['header'])) {
1491 if (preg_match_all('/Content-Disposition:.*filename=["\']?([^"\';\r\n]+)/i', $head['header'], $m)) {
1492 $filename = trim(end($m[1]), " \t\"'");
1493 }
1494 }
1495
1496 // If filename is not found in headers, try to extract it from URL
1497 if (empty($filename)) {
1498 $filename = basename(parse_url($url, PHP_URL_PATH));
1499 }
1500
1501 // If filename is still empty or file name ne match the expected pattern (module_modulename-version.zip), log error and return false
1502 if (empty($filename) || !preg_match('/^module_[a-z0-9_]+-[0-9]+\.[0-9]+\.[0-9]+\.zip$/i', $filename)) {
1503 dol_syslog(__METHOD__ . ': Cannot determine filename from URL: ' . $url, LOG_ERR);
1504 return false;
1505 }
1506
1507 // Download the file
1508 $response = getURLContent($url, 'GET');
1509 if (empty($response['content']) || (isset($response['http_code']) && $response['http_code'] !== 200)) {
1510 dol_syslog(
1511 __METHOD__ . ': Download failed — HTTP ' . ($response['http_code'] ?? 'unknown') . ' — ' . $url,
1512 LOG_WARNING
1513 );
1514 return false;
1515 }
1516
1517 // Write to destination
1518 $dest_file = $dest_path . '/' . $filename;
1519 if (file_exists(dol_osencode($dest_file))) { // If file already exists, try to delete it first
1520 chmod(dol_osencode($dest_file), 0755);
1521 @unlink(dol_osencode($dest_file));
1522 }
1523 $writtenfile = file_put_contents(dol_osencode($dest_file), $response['content']);
1524 if ($writtenfile === false || $writtenfile === 0) {
1525 dol_syslog(__METHOD__ . ': Cannot write file: ' . $dest_file, LOG_ERR);
1526 @unlink(dol_osencode($dest_file));
1527 return false;
1528 }
1529
1530 dol_syslog(__METHOD__ . ': Downloaded successfully to: ' . $dest_file, LOG_DEBUG);
1531 return $dest_file;
1532 }
1533}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
Class ExternalModules.
__construct($debug=false)
Constructor.
libStatus($status, $mode=3, $moretext='')
Retrieve the status icon.
checkApiStatus()
Check if an Dolistore API is up.
getProducts($options, $modules=array())
Generate HTML for products.
versionCompare($v1, $v2)
version compare
getRemoteYamlFile($file_source_url, $cache_time)
Get YAML file from remote source and put it into the cache file.
buildSorter(string $key)
Sort an array by a key.
getModuleZIP($producttoinstall=array())
Download a Dolibarr module from a Git repository URL or Dolistore download URL.
getCategories($active=0)
Generate HTML for categories and their children.
applyFilters($list, $options)
Apply filters to the data.
fetchModulesFromFile($options=array())
Fetch modules from a cache YAML file.
_downloadFile(string $url, string $dest_path)
Download a remote URL to a local file using getURLContent (native Dolibarr).
readYaml($yaml)
Read a YAML string and convert it to an array.
callApi($resource, $options=false)
Test if we can access to remote Dolistore market place.
adaptData($data, $source)
Adapter data fetched from github remote source to the expected format.
loadRemoteSources($debug=false)
loadRemoteSources
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:451
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_is_file($pathoffile)
Return if path is a file.
dol_now($mode='gmt')
Return date for now.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dolPrintHTML($s, $allowiframe=0, $moreallowedtags=array())
Return a string (that can be on several lines) ready to be output on a HTML page.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
getDolOptimizeSmallScreen()
Return if render must be optimized for small screen.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
getURLContent($url, $postorget='GET', $param='', $followlocation=1, $addheaders=array(), $allowedschemes=array('http', 'https'), $localurl=0, $ssl_verifypeer=-1, $timeoutconnect=0, $timeoutresponse=0, $otherCurlOptions=array(), $morelogsuffix='')
Function to get a content from an URL (use proxy if proxy defined).
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:492
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:137
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:140