dolibarr 25.0.0-alpha
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
65 public $custom_sources = array();
66
71 public $url;
75 public $shop_url; // the url of the shop
79 public $lang; // the integer representing the lang in the store
83 public $debug_api; // useful if no dialog
87 public $dolistore_api_url;
91 public $dolistore_api_key;
92
96 public $dolistoreApiStatus;
97
101 public $dolistoreApiError;
102
106 public $githubFileStatus;
107
111 public $githubFileError;
112
116 public $error;
117
121 public $numberOfProviders;
122
126 public $products;
127
131 public $numberTotalOfProducts;
132
136 public $numberTotalOfPages;
137
141 public $numberOfProducts;
142
148 public function __construct($debug = false)
149 {
150 global $langs;
151
152 $this->debug_api = $debug;
153
154 $this->url = DOL_URL_ROOT.'/admin/modules.php?mode=marketplace';
155
156 // For dolistore modules
157 $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/'
158 $this->dolistore_api_key = getDolGlobalString('MAIN_MODULE_DOLISTORE_API_KEY', 'dolistorepublicapi');
159 $this->shop_url = getDolGlobalString('MAIN_MODULE_DOLISTORE_SHOP_URL', 'https://www.dolistore.com');
160
161 // For community modules
162 $this->file_source_url = "https://raw.githubusercontent.com/Dolibarr/dolibarr-community-modules/refs/heads/main/index.yaml";
163 $this->cache_file = DOL_DATA_ROOT.'/admin/temp/remote_github_modules_file.yaml';
164
165 // For the additional modules repositories (GitHub mono repositories with same structure than the community repository)
166 // MAIN_ADD_EXTERNAL_MODULES_SOURCE is a comma separated list of 'URL[:branch]'
167 // Example: 'https://github.com/DoliCloud/dolimods:master,https://github.com/owner/repo:develop'
168 // If the branch is not provided, 'main' is used.
169 $i = 0;
170 foreach (explode(',', getDolGlobalString('MAIN_ADD_EXTERNAL_MODULES_SOURCE')) as $customsource) {
171 $customsource = trim($customsource);
172 if ($customsource === '') {
173 continue;
174 }
175 $i++;
176
177 $url = $customsource;
178 $branch = '';
179 $reg = array();
180 // A ':' followed by a string with no '/' at the end is the branch (the ':' of 'https:' is never followed by such a string)
181 if (preg_match('/^(.+):([\w.\/-]+)$/', $customsource, $reg) && strpos($reg[2], '/') === false) {
182 $url = $reg[1];
183 $branch = $reg[2];
184 }
185 $url = preg_replace('/\/+$/', '', $url);
186
187 $owner = '';
188 $repo = '';
189 // Accept 'https://github.com/owner/repo', 'https://github.com/owner/repo.git' or 'https://github.com/owner/repo/tree/branch'
190 if (preg_match('/^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/tree\/([\w.\/-]+))?$/', $url, $reg)) {
191 $owner = $reg[1];
192 $repo = $reg[2];
193 if (empty($branch)) {
194 $branch = empty($reg[3]) ? 'main' : $reg[3];
195 }
196 }
197
198 // The key is used to build the name of the constant to enable the source, so it must be stable
199 $key = ($owner ? strtoupper(preg_replace('/[^a-zA-Z0-9]/', '_', $owner.'_'.$repo)) : 'INVALID'.$i);
200
201 $this->custom_sources[$key] = array(
202 'url' => $url,
203 'branch' => $branch,
204 'const_enable' => 'MAIN_ENABLE_EXTERNALMODULES_CUSTOM_'.$key,
205 'raw_base_url' => ($owner ? 'https://github.com/'.$owner.'/'.$repo.'/raw/refs/heads/'.$branch : ''),
206 'file_source_url' => ($owner ? 'https://raw.githubusercontent.com/'.$owner.'/'.$repo.'/refs/heads/'.$branch.'/index.yaml' : ''),
207 'cache_file' => DOL_DATA_ROOT.'/admin/temp/remote_github_custom_modules_file_'.strtolower($key).'.yaml',
208 'status' => 0,
209 'error' => '',
210 );
211 }
212
213 $lang = $langs->defaultlang;
214 $lang_array = array('en_US', 'fr_FR', 'es_ES', 'it_IT', 'de_DE');
215 if (!in_array($lang, $lang_array)) {
216 $lang = 'en_US';
217 }
218 $this->lang = $lang;
219 }
220
227 public function loadRemoteSources($debug = false)
228 {
229 // Check access to Community repo
230 if (getDolGlobalString('MAIN_ENABLE_EXTERNALMODULES_COMMUNITY')) {
231 $cachedelayforgithubrepo = getDolGlobalInt('MAIN_REMOTE_GITHUBREPO_CACHE_DELAY', 86400);
232
233 $this->getRemoteYamlFile($this->file_source_url, $cachedelayforgithubrepo);
234
235 $this->githubFileError = $this->error;
236 $this->githubFileStatus = dol_is_file($this->cache_file) ? 1 : 0;
237 }
238
239 // Check access to the additional repos
240 $nbcustomsourcesok = 0;
241 foreach ($this->custom_sources as $key => $customsource) {
242 if (!getDolGlobalString($customsource['const_enable'])) {
243 continue;
244 }
245 if ($customsource['file_source_url']) {
246 $cachedelayforgithubrepo = getDolGlobalInt('MAIN_REMOTE_GITHUBREPO_CACHE_DELAY', 86400);
247
248 $this->error = '';
249 $this->getRemoteYamlFile($customsource['file_source_url'], $cachedelayforgithubrepo, $customsource['cache_file']);
250
251 $this->custom_sources[$key]['error'] = (string) $this->error;
252 $this->custom_sources[$key]['status'] = dol_is_file($customsource['cache_file']) ? 1 : 0;
253 $nbcustomsourcesok += $this->custom_sources[$key]['status'];
254 } else {
255 $this->custom_sources[$key]['error'] = 'Each value of MAIN_ADD_EXTERNAL_MODULES_SOURCE must be a GitHub repository URL like https://github.com/owner/repo or https://github.com/owner/repo:branch';
256 }
257 }
258
259 // Check access to Dolistore API /api/categories -> /api/index.php/marketplace/categories
260 if (getDolGlobalString('MAIN_ENABLE_EXTERNALMODULES_DOLISTORE')) {
261 $this->dolistoreApiStatus = $this->checkApiStatus();
262 }
263
264 // Count the number of online providers
265 $this->numberOfProviders = (int) $this->dolistoreApiStatus + (int) $this->githubFileStatus + $nbcustomsourcesok;
266 }
267
275 public function callApi($resource, $options = false)
276 {
277 // If no dolistore_api_key is set, we can't access the API
278 if (empty($this->dolistore_api_key) || empty($this->dolistore_api_url)) {
279 return array('status_code' => 0, 'response' => null);
280 }
281
282 // Add basic auth if needed
283 $basicAuthLogin = getDolGlobalString('MAIN_MODULE_DOLISTORE_BASIC_LOGIN');
284 $basicAuthPassword = getDolGlobalString('MAIN_MODULE_DOLISTORE_BASIC_PASSWORD');
285
286 $httpheader = array('DOLAPIKEY: '.$this->dolistore_api_key);
287 if ($basicAuthLogin) {
288 $httpheader[] = 'Authorization: Basic '.base64_encode($basicAuthLogin.':'.$basicAuthPassword);
289 }
290
291 $url = $this->dolistore_api_url . (preg_match('/\/$/', $this->dolistore_api_url) ? '' : '/') . $resource;
292
293 $options['apikey'] = $this->dolistore_api_key;
294
295 if ($options) {
296 $url .= '?' . http_build_query($options);
297 }
298
299 $response = getURLContent($url, 'GET', '', 1, $httpheader, array('https'), 0, -1, 5, 5);
300
301 $status_code = $response['http_code'];
302 $body = 'Error';
303
304 if ($status_code == 200) {
305 $body = $response['content'];
306 $body = json_decode($body, true);
307 $returnarray = array(
308 'status_code' => $status_code,
309 'response' => $body
310 );
311 } else {
312 $returnarray = array(
313 'status_code' => $status_code,
314 'response' => $body
315 );
316 if (!empty($response['curl_error_no'])) {
317 $returnarray['curl_error_no'] = $response['curl_error_no'];
318 }
319 if (!empty($response['curl_error_msg'])) {
320 $returnarray['curl_error_msg'] = $response['curl_error_msg'];
321 }
322 }
323
324 return $returnarray;
325 }
326
334 public function fetchModulesFromFile($options = array(), $cache_file = '')
335 {
336 $modules = array();
337
338 if (empty($cache_file)) {
339 $cache_file = $this->cache_file;
340 }
341
342 if (!empty($cache_file) && file_exists($cache_file)) {
343 dol_syslog(__METHOD__ . " - Loading cache file: " . $cache_file, LOG_DEBUG);
344
345 $content = file_get_contents($cache_file);
346 if ($content !== false) {
347 $modules = $this->readYaml($content);
348 } else {
349 dol_syslog(__METHOD__ . " - Error reading cache file", LOG_ERR);
350 }
351 }
352
353 return $modules;
354 }
355
362 public function getCategories($active = 0)
363 {
364 $organized_tree = array();
365 $html = '';
366
367 $data = [
368 'lang' => $this->lang
369 ];
370
371 $current = $active;
372
373 $resCategories = $this->callApi('categories', $data);
374 if (isset($resCategories['response']) && is_array($resCategories['response'])) {
375 $organized_tree = $resCategories['response'];
376 } else {
377 return $html ;
378 }
379
380 $html = '';
381 foreach ($organized_tree as $key => $value) {
382 if ($value['label'] != "Versions" && $value['label'] != "Specials") {
383 $html .= '<li' . ($current == $value['rowid'] ? ' class="active"' : '') . '>';
384 $html .= '<a href="?mode=marketplace&categorie=' . $value['rowid'] . '">' . $value['label'] . '</a>';
385 if (isset($value['children'])) {
386 $html .= '<ul>';
387 usort($value['children'], $this->buildSorter('position'));
388 foreach ($value['children'] as $key_children => $value_children) {
389 $html .= '<li' . ($current == $value_children['rowid'] ? ' class="active"' : '') . '>';
390 $html .= '<a href="?mode=marketplace&categorie=' . $value_children['rowid'] . '" title="' . dol_escape_htmltag(strip_tags($value_children['description'])) . '">' . $value_children['label'] . '</a>';
391 $html .= '</li>';
392 }
393 $html .= '</ul>';
394 }
395 $html .= '</li>';
396 }
397 }
398 return $html;
399 }
400
408 public function getProducts($options, $modules = array())
409 {
410 global $langs;
411
412 $langs->load("products");
413
414 $html = "";
415 $last_month = dol_now() - (30 * 24 * 60 * 60);
416 $dolibarrversiontouse = DOL_VERSION; // full string with version
417
418 $this->products = array();
419
420 // Build a map of installed external module names to their versions (lowercase name => version)
421 $installedModules = array();
422 if (is_array($modules)) {
423 foreach ($modules as $objMod) {
424 if (is_object($objMod) && $objMod->isCoreOrExternalModule() != 'core') {
425 $moduleName = strtolower($objMod->name);
426 $moduleVersion = $objMod->getVersion(0);
427 $installedModules[$moduleName] = $moduleVersion;
428 }
429 }
430 }
431
432 $this->categorie = $options['categorie'] ?? 0;
433 $this->per_page = $options['per_page'] ?? 11;
434 $this->no_page = $options['no_page'] ?? 1;
435 $this->search = $options['search'] ?? '';
436
437 $this->per_page = 11; // We fix number of products per page to 11
438
439 // Length of $search must be at least 2 characters
440 if (!empty($this->search) && strlen(str_replace(' ', '', (string) $this->search)) < 2) {
441 $html .= '<tr class=""><td colspan="3" class="center">';
442 $html .= '<br><br>';
443 $html .= $langs->trans("SearchStringMinLength").'...';
444 $html .= '<br><br>';
445 $html .= '</td></tr>';
446 return $html;
447 }
448
449 $data = [
450 'categorieid' => $this->categorie,
451 'limit' => $this->per_page,
452 'page' => $this->no_page,
453 'search' => $this->search,
454 'lang' => $this->lang
455 ];
456
457
458 $this->numberTotalOfProducts = 0;
459
460 // Special case of category goodies
461 if ($this->categorie == 87) {
462 $html = '<div class="shop-container">
463 <div class="shop-image">
464 <a href="https://merch.dolibarr.org/" target="_blank">
465 <img src="https://www.dolistore.com/medias/image/marketplace/img/goodies-shop.jpg" width="50%" alt="DoliStore Merch and Gifts" />
466 <div class="shop-overlay">
467 <button target="new" class="shop-button">'.$langs->trans("GoodiesButtonTitle").' <i class="icon-chevron-right"></i></button>
468 </div>
469 </a>
470 </div>
471 </div>';
472
473 return $html;
474 }
475
476 // Fetch the products from Dolistore source
477
478 $dolistoreProducts = array();
479 $dolistoreProductsTotal = 0;
480 if ($this->dolistoreApiStatus > 0 && getDolGlobalInt('MAIN_ENABLE_EXTERNALMODULES_DOLISTORE')) {
481 $getDolistoreProducts = $this->callApi('products', $data);
482
483 if (!isset($getDolistoreProducts['response']) || !is_array($getDolistoreProducts['response']) || ($getDolistoreProducts['status_code'] != 200 && $getDolistoreProducts['status_code'] != 201)) {
484 $dolistoreProducts = array();
485 $dolistoreProductsTotal = 0;
486 } else {
487 $dolistoreProducts = $this->adaptData($getDolistoreProducts['response']['products'], 'dolistore');
488 $dolistoreProductsTotal = (int) $getDolistoreProducts['response']['total'];
489 $this->numberTotalOfProducts += $dolistoreProductsTotal;
490 }
491 }
492
493 // Fetch the products from the github repo
494
495 $fileProducts = array();
496 $fileProductsTotal = 0;
497 if (!empty($this->githubFileStatus) && getDolGlobalInt('MAIN_ENABLE_EXTERNALMODULES_COMMUNITY')) {
498 $fileProducts = $this->fetchModulesFromFile($data); // Return an array with all modules from the cache filecontent in $data
499
500 $fileProducts = $this->adaptData($fileProducts, 'githubcommunity');
501
502 $fileProducts = $this->applyFilters($fileProducts, $data);
503
504 $fileProductsTotal = $fileProducts['total'];
505
506 $this->numberTotalOfProducts += $fileProductsTotal;
507
508 $fileProducts = $fileProducts['data'];
509 }
510
511 // Fetch the products from the additional github repos
512
513 $customFileProducts = array();
514 $customFileProductsTotalMax = 0;
515 foreach ($this->custom_sources as $key => $customsource) {
516 if (empty($customsource['status']) || !getDolGlobalInt($customsource['const_enable'])) {
517 continue;
518 }
519 $tmpProducts = $this->fetchModulesFromFile($data, $customsource['cache_file']);
520
521 $tmpProducts = $this->adaptData($tmpProducts, 'githubcustom', $key);
522
523 $tmpProducts = $this->applyFilters($tmpProducts, $data);
524
525 $customFileProductsTotalMax = max($customFileProductsTotalMax, $tmpProducts['total']);
526
527 $this->numberTotalOfProducts += $tmpProducts['total'];
528
529 $customFileProducts = array_merge($customFileProducts, $tmpProducts['data']);
530 }
531
532 // Number of pages
533 $this->numberTotalOfPages = (int) ceil(max($fileProductsTotal / $this->per_page, $customFileProductsTotalMax / $this->per_page, $dolistoreProductsTotal / $this->per_page));
534
535 // Merge all sources (github modules have priority on dolistore, the additional repos have priority on the community repo).
536 $this->products = $dolistoreProducts;
537 foreach (array_merge($fileProducts, $customFileProducts) as $fileProduct) {
538 $id = $fileProduct['id'];
539 if ($id > 0) {
540 if (empty($this->products[$id])) { // Not already present in array
541 array_unshift($this->products, $fileProduct);
542 } else {
543 $this->products[$id] = $fileProduct;
544 $this->products[$id]['category'] = $fileProduct['category'];
545 }
546 } else {
547 array_unshift($this->products, $fileProduct);
548 }
549 }
550
551
552 $i = 0;
553 foreach ($this->products as $product) {
554 $i++;
555
556 // check new product ?
557 $newapp = '';
558 if ($last_month < strtotime($product['datec']) && $product["status"] != 'soon' && $product["status"] != 'development' && $product["status"] != 'experimental') {
559 $newapp .= '<span class="newApp" title="'.$product['tms'].'">'.$langs->trans('New').'</span> ';
560 }
561
562 // check updated ?
563 if ($newapp == '' && $last_month < strtotime($product['tms']) && $product["status"] != 'soon' && $product["status"] != 'development' && $product["status"] != 'experimental') {
564 $newapp .= '<span class="updatedApp" title="'.$product['tms'].'">'.$langs->trans('UpdatedRecently').'</span> ';
565 }
566
567 // add image or default ?
568 if ($product["cover_photo_url"] != '' && $product["cover_photo_url"] != '#') {
569 $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"]).'">';
570 $images .= '<img class="imgstore" src="'.$product["cover_photo_url"].'" alt="" /></a>';
571 } else {
572 $images = '<img class="imgstore" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" />';
573 }
574
575 // Set and check version
576 $version = '';
577 $compatible = '';
578 if ($product["status"] == 'soon' || $product["status"] == 'development' || $product["status"] == 'experimental') {
579 $version = '<span class="warning">'.$langs->trans("NotYetAvailable").' - '.$langs->trans("StillInDevelopment").'</span>';
580 $compatible = 'NotCompatible';
581 } else {
582 // A min or max version set to '', 'auto' or 'unknown' is an unknown version
583 $minknown = (!empty($product["dolibarr_min"]) && !in_array($product["dolibarr_min"], array('auto', 'unknown')));
584 $maxknown = (!empty($product["dolibarr_max"]) && !in_array($product["dolibarr_max"], array('auto', 'unknown')));
585
586 if ($minknown && $this->versionCompare($product["dolibarr_min"], $dolibarrversiontouse) > 0) {
587 // Need update of Dolibarr (current version is lower than min)
588 $version = '<span class="compatibleafterupdate">'.$langs->trans(
589 'CompatibleAfterUpdate',
590 $dolibarrversiontouse,
591 $product["dolibarr_min"],
592 $product["dolibarr_max"]
593 ).'</span>';
594 $compatible = 'NotCompatible';
595 } elseif ($maxknown && $this->versionCompare($product["dolibarr_max"], $dolibarrversiontouse) >= 0) {
596 // Compatible
597 $version = '<span class="compatible hideonsmartphone">'.$langs->trans(
598 'CompatibleUpTo',
599 $dolibarrversiontouse,
600 $product["dolibarr_min"],
601 $product["dolibarr_max"]
602 ).'</span>';
603 $compatible = '';
604 } else {
605 // Not compatible (current version is higher than max, or max is unknown)
606 $version = '<span class="warning">'.$langs->trans(
607 'NotCompatible',
608 $dolibarrversiontouse,
609 $product["dolibarr_min"],
610 $product["dolibarr_max"]
611 ).'</span>';
612 $compatible = 'NotCompatible';
613 }
614 }
615
616 // free or pay ?
617 $install_link = '';
618 if (array_key_exists('price_ht', $product) && price2num($product["price_ht"]) > 0) {
619 $price = '<h3>'.price(price2num($product["price_ht"], 'MT'), 0, $langs, 1, -1, -1, 'EUR').' '.$langs->trans("HT").'</h3>';
620
621 $download_link = '<a class="paddingleft paddingright valignmiddle" target="_blank" title="'.$langs->trans("View").'" href="'.$this->shop_url.'/product.php?id='.((int) $product['id']).'">';
622 $download_link .= img_picto('', 'url', 'class="size2x paddingright"');
623 $download_link .= '</a>';
624 } else {
625 $download_link = '#';
626 if ($product['source'] === 'dolistore') { // 0 on dolistore may mean 0 or a complementary fee to subscribe
627 $urlview = $this->shop_url.'/product.php?id='.((int) $product["id"]);
628 $price = '<h3><a href="'.$urlview.'" target="_blank">'.$langs->trans('SeeOnDoliStore').'</a></h3>';
629 } elseif (in_array($product['source'], array('githubcommunity', 'githubcustom'))) {
630 if (array_key_exists('price_ht', $product) && empty($product['price_ht'])) {
631 if ($product['status'] == 'soon') {
632 $price = '<h3>'.$langs->trans('StillInDevelopment').'</h3>';
633 } else {
634 $price = '<h3>'.$langs->trans('Free').'</h3>';
635 }
636 } else {
637 if ($product["dolistore-download"]) {
638 $price = '<h3><a href="'.$product["dolistore-download"].'" target="_blank">'.$langs->trans('SeeOnDoliStore').'</a></h3>';
639 } else {
640 $price = '<h3>'.$langs->trans('Unknown').'</h3>';
641 }
642 }
643 } else {
644 $price = '<h3>'.$langs->trans('Unknown').'</h3>';
645 }
646
647 if (in_array($product['source'], array('githubcommunity', 'githubcustom'))) {
648 $download_link = '<a class="paddingleft paddingright valignmiddle" target="_blank" title="'.$langs->trans("Sources").'" href="'.$product["link"].'">';
649 $download_link .= img_picto('', 'file-code', 'class="size2x paddingright colorgrey"');
650 $download_link .= '</a>';
651
652 $urlview = $product["dolistore-download"]; // View on Dolistore
653 if ($urlview) {
654 $download_link .= '<a class="paddingleft paddingright valignmiddle" target="_blank" title="'.$langs->trans("View").'" href="'.$urlview.'" rel="noopener noreferrer">';
655 $download_link .= img_picto('', 'url', 'class="size2x"');
656 $download_link .= '</a>';
657 }
658
659 if (!empty($product['direct-download']) && $product['direct-download'] == 'yes') {
660 $reg = array();
661 if (preg_match('/https:.*\?id=(\d+)$/', $urlview, $reg)) {
662 $urldownload = 'https://www.dolistore.com/_service_download.php?t=free&p='.$reg[1];
663 $download_link .= '<a class="paddingleft paddingright valignmiddle" target="_blank" title="'.$langs->trans("Download").'" href="'.$urldownload.'" rel="noopener noreferrer">';
664 $download_link .= img_picto('', 'download', 'class="size2x paddingright"');
665 $download_link .= '</a>';
666 }
667 }
668 } elseif ($product['source'] === 'dolistore') {
669 $urlview = $this->shop_url.'/product.php?id='.((int) $product["id"]);
670 $urldownload = 'https://www.dolistore.com/_service_download.php?t=free&p=' . $product['id'];
671 $download_link = '<a class="paddingleft paddingright valignmiddle" target="_blank" title="'.$langs->trans("View").'" href="'.$urlview.'">';
672 $download_link .= img_picto('', 'url', 'class="size2x"');
673 $download_link .= '</a>';
674 $download_link .= '<a class="paddingleft paddingright valignmiddle" target="_blank" title="'.$langs->trans("Download").'" href="'.$urldownload.'" rel="noopener noreferrer">';
675 $download_link .= img_picto('', 'download', 'class="size2x paddingright"');
676 $download_link .= '</a>';
677 }
678
679 // Direct install
680 if ((!empty($product['direct-download']) && in_array($product['direct-download'], array('yes', 'dolistore'))) || $product['source'] === 'dolistore') {
681 $urldownload = '';
682
683 if (in_array($product['source'], array('githubcommunity', 'githubcustom'))) {
684 $current_version = $product['module_version'] ?? '';
685 $module_name = strtolower(preg_replace('/@.*$/', '', $product['ref'] ?? ''));
686
687 // Remove "-" followed by current version at the end of the string if it exists
688 $module_name = preg_replace('/-' . preg_quote($current_version, '/') . '$/', '', $module_name);
689
690 $urldownload = $this->getGithubRawBaseUrl($product['source'], $product['custom_source_key'] ?? '').'/dev/build/bin/module_' . $module_name . '-' . $current_version . '.zip';
691
692 $reg = array();
693 $urlview = $product["dolistore-download"]; // View on Dolistore
694
695 // For community modules, we download from community repo.
696 // But we can force to download from dolistore if MAIN_DOWNLOAD_FROM_DOLISTORE_IN_PRIORITY is set (less reliable, less up to date)
697 if (($product["direct-download"] ?? '') == 'dolistore' || getDolGlobalString("MAIN_DOWNLOAD_FROM_DOLISTORE_IN_PRIORITY")) {
698 if (preg_match('/https:.*\?id=(\d+)$/', $urlview, $reg)) {
699 $urldownload = 'https://www.dolistore.com/_service_download.php?t=free&p='.$reg[1];
700 }
701 }
702 }
703 if ($product['source'] === 'dolistore') {
704 $urldownload = 'https://www.dolistore.com/_service_download.php?t=free&p=' . $product['id'];
705 }
706
707
708 $disableInstall = ($compatible === 'NotCompatible') && !getDolGlobalInt('MAIN_FEATURES_LEVEL');
709 // $disableInstall = false; // TODO: remove this.
710 $disableInfo = $disableInstall ? dol_string_nohtmltag($version) : '';
711 $fields = ['action' => 'install', 'token' => newToken()];
712 foreach ($product as $key => $value) {
713 $fields['producttoinstall['.$key.']'] = $value;
714 }
715
716 $installConfirmMessage = $langs->transnoentities(
717 "extModuleConfirmInstallText",
718 $product['label'] ?? '',
719 $product['module_version'] ?? '',
720 $product['ref'] ?? '',
721 !empty($product['tms']) ? dol_print_date($product['tms'], '%d/%m/%Y') : ''
722 );
723 $installConfirmMessage .= $langs->trans("Path").' : '.$urldownload;
724
725 // Check if module is already installed locally to show "Upgrade" or "Re-install" instead of "Install"
726 $buttonLabel = $langs->trans("Install");
727 $remoteVersion = $product['module_version'] ?? '';
728 $remoteModuleName = strtolower(preg_replace('/@.*$/', '', $product['ref'] ?? ''));
729 // Remove "-" followed by current version at the end of the string if it exists
730 $remoteModuleName = preg_replace('/-' . preg_quote($remoteVersion, '/') . '$/', '', $remoteModuleName);
731 if (!empty($installedModules[$remoteModuleName]) && $remoteVersion && $remoteVersion != 'unknown') {
732 $localVersion = $installedModules[$remoteModuleName];
733 // $localVersion is guaranteed non-empty here (see !empty() test above), so only the 'unknown' value must be excluded
734 if ($localVersion != 'unknown') {
735 $versionDiff = $this->versionCompare($localVersion, $remoteVersion);
736 if ($versionDiff < 0) {
737 $buttonLabel = $langs->trans("Upgrade");
738 } elseif ($versionDiff == 0) {
739 $buttonLabel = $langs->trans("ReInstall");
740 }
741 }
742 }
743
744 $install_link = '<button class="valignmiddle ' . ($disableInstall ? 'butActionRefused' : 'butAction') . ' paddingleft paddingright"'
745 . ($disableInfo ? ' title="' . dol_escape_htmltag($disableInfo) . '"' : '')
746 . (!$disableInstall ? ' data-confirm' : '')
747 . (!$disableInstall ? ' data-fields="' . dol_escape_htmltag(json_encode($fields)) . '"' : '')
748 . (!$disableInstall ? ' data-url="' . dol_escape_htmltag($this->url) . '"' : '')
749 . (!$disableInstall ? ' data-confirm-title="' . dol_escape_htmltag($langs->trans("extModuleConfirmInstallTitle")) . '"' : '')
750 . (!$disableInstall ? ' data-confirm-text="' . dol_escape_htmltag($installConfirmMessage) . '"' : '')
751 . (!$disableInstall ? ' data-confirm-label="' . dol_escape_htmltag($buttonLabel) . '"' : '')
752 . '>' . $buttonLabel . '</button>';
753 }
754 }
755
756 // Output the line
757 $html .= '<tr class="'.(getDolOptimizeSmallScreen() ? 'app' : 'app app2').' oddeven nohover '.dol_escape_htmltag($compatible).'">';
758
759 // Logo
760 $html .= '<td class="center width150"><div class="newAppParent">';
761 $html .= $newapp.$images; // No dol_escape_htmltag, it is already escape html
762 $html .= '</div></td>';
763
764 // Description
765 $html .= '<td class="margeCote minwidth400imp"><h2 class="appTitle">';
766 $html .= dolPrintHTML(dol_string_nohtmltag(ucfirst($product["label"])));
767 if (!empty($product['author']) && $product['author'] != 'unkownauthor') {
768 $html .= '<span class="small"> &nbsp; - &nbsp; '.img_picto('', 'company', 'class="pictofixedwidth"');
769 if (!empty($product['author_url'])) {
770 $html .= '<a href="'.$product['author_url'].'" target="_blank">'.$product['author'].'</a>';
771 } else {
772 $html .= $product['author'];
773 }
774 $html .= '</span>';
775 }
776 $html .= '<br><span class="small">';
777 $html .= $version; // Version Dolibarr. No dol_escape_htmltag, it is already escape html
778 $html .= '</span>';
779 $html .= '</h2>';
780
781 $html .= '<small class="appDateCreation appRef"> ';
782 if (empty($product['tms'])) {
783 $html .= img_picto($langs->trans('DateCreation'), 'calendar', 'class="pictofixedwidth"').'<span class="opacitymedium"><span class="hideonsmartphone">'.$langs->trans("DateCreation").': </span>';
784 $html .= (!empty($product['datec']) ? dol_print_date(dol_stringtotime($product['datec']), 'day') : $langs->trans("Unknown")).'</span>';
785 } else {
786 $html .= img_picto($langs->trans('DateModification'), 'calendar', 'class="pictofixedwidth"').'<span class="opacitymedium">'.dol_print_date(dol_stringtotime($product['tms']), 'day').'</span>';
787 }
788 $html .= ' &nbsp; &nbsp; ';
789
790 $html .= '<div class="appSource inline-block valigntop">';
791 if ($product["source"] == 'dolistore') {
792 $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">';
793 } elseif ($product["source"] == 'githubcommunity') {
794 $html .= img_picto($langs->trans('Source').': GitHub community repo', 'group', 'class="pictofixedwidth valignmiddle"');
795 } elseif ($product["source"] == 'githubcustom') {
796 $html .= img_picto($langs->trans('Source').': '.($this->custom_sources[$product['custom_source_key']]['url'] ?? ''), 'fa-code-branch', 'class="pictofixedwidth valignmiddle"');
797 } else {
798 $html .= img_picto($langs->trans('Source').': '.$langs->trans('Other'), 'generic', 'class="pictofixedwidth"');
799 }
800 $html .= '</div>';
801
802 $html .= $langs->trans('Ref').' '.dolPrintHTML(preg_replace('/@.*$/', '', $product["ref"]));
803 $html .= '</small><br>';
804
805
806 $html .= '&nbsp;';
807 if (!empty($product['phpmin']) && $product['phpmin'] != 'unknown') {
808 $html .= ' <span class="badge-secondary small" style="padding: 3px; border-radius: 5px">PHP min '.$product['phpmin'].'</span>';
809 }
810 if (!empty($product['phpmax']) && $product['phpmax'] != 'unknown') {
811 $html .= ' <span class="badge-secondary small" style="padding: 3px; border-radius: 5px">PHP max '.$product['phpmax'].'</span>';
812 }
813 $html .= '<br>';
814
815 $html .= '<br>';
816 $html .= '<div class="storedesc">'.dolPrintHTML(dol_string_nohtmltag($product["description"])).'</div>';
817 $html .= '</td>';
818
820 $html .= '</tr><tr class="app2 oddeven nohover borderbottom '.dol_escape_htmltag($compatible).'">';
821 }
822
823 // Price - do not load if display none
824 $html .= '<td class="margeCote center amount'.(getDolOptimizeSmallScreen() ? ' left" colspan="2"' : '"').'>';
825 $html .= $price;
826 if ((!empty($product['direct-download']) && in_array($product['direct-download'], array('yes', 'dolistore'))) || ($product['source'] === 'dolistore' && empty((float) $product['price_ht']))) {
827 if ($install_link) {
828 $html .= $install_link;
829 }
830 }
831
833 $html .= '</td>';
834 $html .= '<td class="margeCote nowraponall">';
835 }
836
837 // Links
838 $html .= $download_link;
839 $html .= '</td>';
840
841 $html .= '</tr>';
842 }
843
844 if (empty($this->products)) {
845 $colspan = (getDolOptimizeSmallScreen() ? 1 : 3);
846 $langs->load("website");
847
848 $html .= '<tr class=""><td colspan="'.$colspan.'" class="center">';
849 $html .= '<br><br>';
850 $html .= $langs->trans("noResultsWereFound").'...';
851 $html .= '<br><br>';
852 $html .= '</td></tr>';
853 }
854
855 // JS for confirm install
856 $confirmLabel = $langs->trans("Install");
857 $cancelLabel = $langs->trans("Cancel");
858 $html .= '<script>
859 $(document).on("click","[data-confirm]",function(){
860 var button = $(this);
861 var confirmTitle = button.data("confirm-title");
862 var confirmText = button.data("confirm-text");
863 var buttons = {};
864 buttons[button.data("confirm-label")||\'' . dol_escape_js($confirmLabel) . '\'] = function(){
865 var form = $("<form method=\'POST\' style=\'display:none\'>").attr("action", button.data("url"));
866 $.each(button.data("fields"), function(name, value){
867 form.append($("<input type=\'hidden\'>").attr("name", name).val(value));
868 });
869 $("body").append(form);
870 form.submit();
871 $(this).dialog("close");
872 };
873 buttons[\'' . dol_escape_js($cancelLabel) . '\'] = function(){$(this).dialog("close");};
874 $("<div>").html(confirmText).dialog({
875 title: confirmTitle,
876 minWidth: 580,
877 modal: true,
878 buttons: buttons
879 });
880 });
881 </script>';
882
883 $this->numberOfProducts = count($this->products);
884
885 return $html;
886 }
887
894 public function buildSorter(string $key): Closure
895 {
896 return
902 function (array $a, array $b) use ($key) {
903 $valA = isset($a[$key]) && is_scalar($a[$key]) ? (string) $a[$key] : '';
904 $valB = isset($b[$key]) && is_scalar($b[$key]) ? (string) $b[$key] : '';
905
906 return strnatcmp($valA, $valB);
907 };
908 }
909
917 public function versionCompare($v1, $v2)
918 {
919 // Clean v1 and v2
920 $v1 = str_replace(array('v', 'V'), '', $v1);
921 $v2 = str_replace(array('v', 'V'), '', $v2);
922
923 $v1 = explode('.', $v1);
924 $v2 = explode('.', $v2);
925 $ret = 0;
926 $level = 0;
927 $count1 = count($v1);
928 $count2 = count($v2);
929 $maxcount = max($count1, $count2);
930 while ($level < $maxcount) {
931 $operande1 = isset($v1[$level]) ? $v1[$level] : 'x';
932 $operande2 = isset($v2[$level]) ? $v2[$level] : 'x';
933 $level++;
934 if (strtoupper($operande1) == 'X' || strtoupper($operande2) == 'X' || $operande1 == '*' || $operande2 == '*') {
935 break;
936 }
937 if ($operande1 < $operande2) {
938 $ret = -$level;
939 break;
940 }
941 if ($operande1 > $operande2) {
942 $ret = $level;
943 break;
944 }
945 }
946 //print join('.',$versionarray1).'('.count($versionarray1).') / '.join('.',$versionarray2).'('.count($versionarray2).') => '.$ret.'<br>'."\n";
947 return $ret;
948 }
949
950 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
957 public function get_previous_link($text = '<<')
958 {
959 // phpcs:enable
960 return '<a href="'.$this->get_previous_url().'" class="button">'.dol_escape_htmltag($text).'</a>';
961 }
962
963 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
970 public function get_next_link($text = '>>')
971 {
972 // phpcs:enable
973 return '<a href="'.$this->get_next_url().'" class="button">'.dol_escape_htmltag($text).'</a>';
974 }
975
976 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
982 public function get_previous_url()
983 {
984 // phpcs:enable
985 $param_array = array();
986 if ($this->no_page > 1) {
987 $sub = 1;
988 } else {
989 $sub = 0;
990 }
991 if (!empty($this->search)) {
992 $param_array['search_keyword'] = $this->search;
993 }
994 $param_array['no_page'] = $this->no_page - $sub;
995 if ($this->categorie != 0) {
996 $param_array['categorie'] = $this->categorie;
997 }
998 $param = http_build_query($param_array);
999 return $this->url."&".$param;
1000 }
1001
1002 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1008 public function get_next_url()
1009 {
1010 // phpcs:enable
1011 $param_array = array();
1012 if ($this->products !== null && count($this->products) < $this->per_page) {
1013 $add = 0;
1014 } else {
1015 $add = 1;
1016 }
1017 if (!empty($this->search)) {
1018 $param_array['search_keyword'] = $this->search;
1019 }
1020 $param_array['no_page'] = $this->no_page + $add;
1021 if ($this->categorie != 0) {
1022 $param_array['categorie'] = $this->categorie;
1023 }
1024 $param = http_build_query($param_array);
1025 return $this->url."&".$param;
1026 }
1027
1033 public function getPagination()
1034 {
1035
1036 global $langs;
1037
1038 $page = $this->no_page;
1039 $limit = $this->per_page;
1040 $totalnboflines = $this->numberTotalOfProducts ?: 0;
1041 $num = $this->numberOfProducts;
1042
1043 $html = "";
1044
1045 // Show navigation bar
1046 $pagelist = '';
1047 if ($page > 0 || $num > $limit) {
1048 if ($totalnboflines) {
1049 if ($limit > 0) {
1050 $nbpages = $this->numberTotalOfPages;
1051 } else {
1052 $nbpages = 1;
1053 }
1054
1055 // Show previous page
1056 if ($page > 1) {
1057 $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>';
1058 }
1059
1060 $pagelist .= '<li class="pagination">';
1061 $pagelist .= '<label for="page_input">Page </label>';
1062 if ($this->categorie != 0) {
1063 $pagelist .= '<input type="hidden" name="categorie" value="' . $this->categorie . '">';
1064 }
1065 // URL to go to another page (without no_page). Used when pressing Enter into the page input field.
1066 $param_array = array();
1067 if (!empty($this->search)) {
1068 $param_array['search_keyword'] = $this->search;
1069 }
1070 if ($this->categorie != 0) {
1071 $param_array['categorie'] = $this->categorie;
1072 }
1073 $urlforpage = $this->url.($param_array ? '&'.http_build_query($param_array) : '');
1074 $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).'"';
1075 $pagelist .= ' oninput="if(this.value > '.$nbpages.') this.value='.$nbpages.'"';
1076 $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; }">';
1077 $pagelist .= ' / '.$nbpages;
1078 $pagelist .= '</li>';
1079
1080 // Show next page
1081 if ($page < $nbpages) {
1082 $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>';
1083 }
1084 }
1085 }
1086
1087 if ($limit || $pagelist) {
1088 $html .= '<div class="pagination" style="padding: 7px;">';
1089 $html .= '<ul>';
1090 $html .= $pagelist;
1091 $html .= '</ul>';
1092 $html .= '</div>';
1093 }
1094
1095 $html .= ajax_autoselect('.page_input');
1096
1097 return $html;
1098 }
1099
1106 protected function checkStatusCode($request)
1107 {
1108 // Define error messages
1109 $error_messages = [
1110 204 => 'No content',
1111 400 => 'Bad Request',
1112 401 => 'Unauthorized',
1113 404 => 'Not Found',
1114 405 => 'Method Not Allowed',
1115 500 => 'Internal Server Error',
1116 ];
1117
1118 // If status code is 200 or 201, return an empty string
1119 if ($request['status_code'] === 200 || $request['status_code'] === 201) {
1120 return '';
1121 }
1122
1123 // Get the predefined error message or use a default one
1124 $error_message = $error_messages[$request['status_code']] ?? 'Unexpected HTTP status: ' . $request['status_code'];
1125
1126 // Append error details if available
1127 if (!empty($request['response']) && isset($request['response']['errors']) && is_array($request['response']['errors'])) {
1128 foreach ($request['response']['errors'] as $error) {
1129 $error_message .= ' - (Code ' . $error['code'] . '): ' . $error['message'];
1130 }
1131 }
1132
1133 if (!empty($request['curl_error_msg'])) {
1134 $error_message .= ' - ' . $request['curl_error_msg'];
1135 }
1136
1137 // Return the formatted error message
1138 return sprintf('This call to the API failed and returned an HTTP status of %d. That means: %s.', $request['status_code'], $error_message);
1139 }
1140
1148 public function getGithubRawBaseUrl($source, $sourcekey = '')
1149 {
1150 if ($source === 'githubcustom') {
1151 return $this->custom_sources[$sourcekey]['raw_base_url'] ?? '';
1152 }
1153
1154 return 'https://github.com/Dolibarr/dolibarr-community-modules/raw/refs/heads/main';
1155 }
1156
1165 public function getRemoteYamlFile($file_source_url, $cache_time, $cache_file = '')
1166 {
1167 $yaml = '';
1168 if (empty($cache_file)) {
1169 $cache_file = $this->cache_file;
1170 }
1171 $cache_folder = dirname($cache_file);
1172
1173 // Check if cache directory exists
1174 if (!dol_is_dir($cache_folder)) {
1175 dol_mkdir($cache_folder, DOL_DATA_ROOT);
1176 }
1177
1178 if (!file_exists($cache_file) || filemtime($cache_file) < (dol_now() - $cache_time)) {
1179 // We get remote url
1180 $addheaders = array();
1181 $result = getURLContent($file_source_url, 'GET', '', 1, $addheaders); // TODO Force timeout to 5 s on both connect and response.
1182 if (!empty($result) && $result['http_code'] == 200) {
1183 $yaml = $result['content'];
1184 $result = file_put_contents($cache_file, $yaml);
1185 if ($result === false) {
1186 $this->error = 'Failed to create cache file: ' . $cache_file;
1187 } else {
1188 dolChmod($cache_file);
1189 }
1190 }
1191 } else {
1192 $yaml = file_get_contents($cache_file);
1193 }
1194
1195 return $yaml;
1196 }
1197
1198
1205 public function readYaml($yaml)
1206 {
1207 $data = [];
1208 $currentPackage = null;
1209 $currentSection = null;
1210
1211 foreach (explode("\n", trim($yaml)) as $line) {
1212 $trimmedLine = trim($line);
1213
1214 // Ignore empty lines and comments
1215 if ($trimmedLine === '' || strpos($trimmedLine, '#') === 0) {
1216 continue;
1217 }
1218
1219 // Match a new package entry (e.g., "- modulename: 'helloasso'") - Found a break in file.
1220 $matches = array();
1221 if (preg_match('/^\s*-\s*modulename:\s*["\']?(.*?)["\']?$/', $trimmedLine, $matches)) {
1222 if ($currentPackage !== null) {
1223 // Add the package to $data
1224 if (!empty($currentPackage['status']) && in_array($currentPackage['status'], array('enabled', 'soon'))) {
1225 $data[] = $currentPackage;
1226 }
1227 }
1228 $currentPackage = ['modulename' => $matches[1]];
1229 $currentSection = null;
1230 continue;
1231 }
1232
1233 // If the key doesn't start with fr, en, es, it, de, treat it as a section
1234 if (!preg_match('/^\s*(fr|en|es|it|de):\s*["\']?(.*?)["\']?$/', $trimmedLine)) {
1235 $currentSection = null;
1236 }
1237
1238 // Match a top-level key-value pair (e.g., "author: 'Dolicloud'")
1239 if (preg_match('/^(\w[\w-]*):\s*["\']?(.*?)["\']?$/', $trimmedLine, $matches)) {
1240 if ($currentPackage !== null) {
1241 if ($currentSection) {
1242 // Store in the sub section (language into label or description for example)
1243 $currentPackage[$currentSection][$matches[1]] = $matches[2] === '' ? null : $matches[2];
1244 } else {
1245 // Store as a normal key-value pair
1246 $currentPackage[$matches[1]] = $matches[2] === '' ? null : $matches[2];
1247 }
1248 }
1249
1250 // Match a nested section (e.g., "label:")
1251 if (preg_match('/^\s*(label|description):\s*$/', $trimmedLine, $matches)) {
1252 $currentSection = $matches[1];
1253 $currentPackage[$currentSection] = []; // Initialize as an empty array for nested sections
1254 }
1255
1256 continue;
1257 }
1258 }
1259
1260 // Add the last package if available
1261 if ($currentPackage !== null) {
1262 if (!empty($currentPackage['status']) && in_array($currentPackage['status'], array('enabled', 'soon'))) {
1263 $data[] = $currentPackage;
1264 }
1265 }
1266
1267 return $data;
1268 }
1269
1278 public function adaptData($data, $source, $sourcekey = '')
1279 {
1280 $adaptedData = [];
1281
1282 if (!is_array($data) || empty($data) || empty($source)) {
1283 return $adaptedData;
1284 }
1285
1286 if (in_array($source, array('githubcommunity', 'githubcustom'))) {
1287 foreach ($data as $package) {
1288 if (empty($package['modulename'])) {
1289 continue;
1290 }
1291
1292 // Check if there is a known ID
1293 $reg = array();
1294 $id = 0;
1295 if (!empty($package['dolistore-download']) && preg_match('/www\.dolistore\.com\/product\.php\?id=(\d+)/', (string) $package['dolistore-download'], $reg)) {
1296 $id = $reg[1];
1297 }
1298
1299 $adaptedPackage = [
1300 'id' => $id,
1301 'ref' => str_replace(' ', '', $package['modulename'] . '-' . $package['current_version'] . '@' .
1302 (array_key_exists('author', $package) ? $package['author'] : 'unkownauthor')),
1303 'label' => !empty($package['label'][substr($this->lang, 0, 2)])
1304 ? $package['label'][substr($this->lang, 0, 2)]
1305 : (!empty($package['label']['en']) ? $package['label']['en'] : $package['modulename']),
1306 'description' => !empty($package['description'][substr($this->lang, 0, 2)])
1307 ? $package['description'][substr($this->lang, 0, 2)]
1308 : (!empty($package['description']['en']) ? $package['description']['en'] : ''),
1309 'datec' => (!empty($package['created_at']) && is_string($package['created_at']))
1310 ? date('Y-m-d H:i:s', strtotime($package['created_at']))
1311 : '',
1312 'tms' => (!empty($package['last_updated_at']) && is_string($package['last_updated_at']))
1313 ? date('Y-m-d H:i:s', strtotime($package['last_updated_at']))
1314 : '',
1315 'author' => array_key_exists('author', $package) ? $package['author'] : '',
1316 'author_url' => array_key_exists('author_url', $package) ? $package['author_url'] : '',
1317 'dolibarr_min' => !empty($package['dolibarrmin'])
1318 ? $package['dolibarrmin']
1319 : 'unknown',
1320 'dolibarr_max' => !empty($package['dolibarrmax'])
1321 ? $package['dolibarrmax']
1322 : 'unknown',
1323 'phpmin' => !empty($package['phpmin'])
1324 ? $package['phpmin']
1325 : 'unknown',
1326 'phpmax' => !empty($package['phpmax'])
1327 ? $package['phpmax']
1328 : 'unknown',
1329 'module_version' => !empty($package['current_version'])
1330 ? $package['current_version']
1331 : 'unknown',
1332 'cover_photo_url' => !empty($package['cover'])
1333 ? $package['cover']
1334 : '#',
1335 'category' => (!empty($package['category']) && is_string($package['category']))
1336 ? explode(',', str_replace(' ', '', (string) $package['category']))
1337 : array(),
1338 'link' => !empty($package['git'])
1339 ? $package['git']
1340 : '#',
1341 'source' => $source,
1342 'custom_source_key' => $sourcekey,
1343 'status' => !empty($package['status']) ? $package['status'] : '',
1344 'direct-download' => !empty($package['direct-download'])
1345 ? $package['direct-download']
1346 : '',
1347 'dolistore-download' => !empty($package['dolistore-download'])
1348 ? $package['dolistore-download']
1349 : '',
1350 ];
1351
1352 // If a price entry exists
1353 if (array_key_exists('price', $package) && $package['price'] != null) {
1354 $adaptedPackage['price_ht'] = $package['price'];
1355 }
1356
1357 $adaptedData[] = $adaptedPackage;
1358 }
1359 }
1360
1361 if ($source === 'dolistore') {
1362 foreach ($data as $package) {
1363 $urlphoto = $this->shop_url.$package['cover_photo_url'];
1364
1365 if (preg_match('/^\/?wrapper\.php\?hashp=/', $package['cover_photo_url']) && !preg_match('/attachment=/', $package['cover_photo_url'])) {
1366 $urlphoto .= '&attachment=0';
1367 }
1368
1369 $adaptedPackage = [
1370 'id' => $package['id'],
1371 'ref' => $package['ref'],
1372 'label' => $package['label'],
1373 'description' => $package['description'],
1374 'datec' => $package['datec'],
1375 'tms' => $package['tms'],
1376 'author' => array_key_exists('author', $package) ? $package['author'] : '',
1377 'author_url' => array_key_exists('author_url', $package) ? $package['author_url'] : '',
1378 'price_ttc' => $package['price_ttc'],
1379 'price_ht' => $package['price_ht'],
1380 'dolibarr_min' => $package['dolibarr_min'],
1381 'dolibarr_max' => $package['dolibarr_max'],
1382 'phpmin' => empty($package['phpmin']) ? '' : $package['phpmin'],
1383 'phpmax' => empty($package['phpmax']) ? '' : $package['phpmax'],
1384 'module_version' => $package['module_version'],
1385 'cover_photo_url' => $urlphoto,
1386 'source' => 'dolistore',
1387 'status' => empty($package['status']) ? '' : $package['status'],
1388 'direct-download' => '',
1389 ];
1390
1391 $adaptedData[$package['id']] = $adaptedPackage;
1392 }
1393 }
1394
1395 return $adaptedData;
1396 }
1397
1405 public function applyFilters($list, $options)
1406 {
1407 $filteredData = $list;
1408
1409 // Sort products list by datec
1410 usort(
1411 $filteredData,
1419 static function ($a, $b) {
1420 return strtotime($b['datec'] ?? '0') - strtotime($a['datec'] ?? '0');
1421 }
1422 );
1423
1424 if (!empty($options['search'])) {
1425 $filteredData = array_filter(
1426 $filteredData,
1434 static function ($package) use ($options) {
1435 return stripos($package['label'], $options['search']) !== false || stripos($package['description'], $options['search']) !== false;
1436 }
1437 );
1438 }
1439
1440 if (!empty($options['categorieid'])) {
1441 $filteredData = array_filter(
1442 $filteredData,
1450 static function ($package) use ($options) {
1451 return in_array($options['categorieid'], $package['category']);
1452 }
1453 );
1454 }
1455
1456 $total = count($filteredData);
1457
1458 // Pagination
1459 $filteredData = array_values($filteredData);
1460 $filteredData = array_slice($filteredData, ($options['page'] - 1) * $options['limit'], $options['limit']);
1461
1462 return ['total' => $total, 'data' => $filteredData];
1463 }
1464
1470 public function checkApiStatus()
1471 {
1472 // Call remote API
1473 $testRequest = $this->callApi('categories');
1474
1475 if (!isset($testRequest['response']) || !is_array($testRequest['response']) || ($testRequest['status_code'] != 200 && $testRequest['status_code'] != 201)) {
1476 $this->dolistoreApiError = $this->checkStatusCode($testRequest);
1477 return 0;
1478 } else {
1479 return 1;
1480 }
1481 }
1482
1491 public function libStatus($status, $mode = 3, $moretext = '')
1492 {
1493 global $langs;
1494
1495 $statusType = 'status4';
1496 if ($status == 0) {
1497 $statusType = 'status3';
1498 }
1499
1500 $labelStatus = [];
1501 $labelStatusShort = [];
1502
1503 $labelStatus[0] = $langs->transnoentitiesnoconv("NotConnected");
1504 $labelStatus[1] = $langs->transnoentitiesnoconv("online");
1505 $labelStatusShort[0] = $langs->transnoentitiesnoconv("NotConnected");
1506 $labelStatusShort[1] = $langs->transnoentitiesnoconv("online");
1507
1508 return dolGetStatus($labelStatus[$status], $labelStatusShort[$status], '', $statusType, $mode, '', array('badgeParams' => array('attr' => array('class' => 'classfortooltip', 'title' => $labelStatusShort[$status].$moretext))));
1509 }
1510
1511
1518 public function getModuleZIP($producttoinstall = array())
1519 {
1520 global $conf;
1521
1522 // Check if cURL is available
1523 if (!function_exists('curl_init')) {
1524 dol_syslog(__METHOD__ . ': cURL is not available', LOG_ERR);
1525 return false;
1526 }
1527
1528 // Check required fields
1529 if (empty($producttoinstall['ref'])) {
1530 dol_syslog(__METHOD__ . ': Missing producttoinstall', LOG_ERR);
1531 return false;
1532 }
1533
1534 $current_version = $producttoinstall['module_version'] ?? '';
1535 $module_name = strtolower(preg_replace('/@.*$/', '', $producttoinstall['ref'] ?? ''));
1536
1537 // Remove "-" followed by current version at the end of the string if it exists
1538 $module_name = preg_replace('/-' . preg_quote($current_version, '/') . '$/', '', $module_name);
1539
1540 if (empty($module_name) || empty($current_version) || $current_version == 'unknown') {
1541 dol_syslog(__METHOD__ . ': Missing or unknown module name/version for product', LOG_ERR);
1542 return false;
1543 }
1544
1545 // Create a temporary directory for the download
1546 $tmpdir = $conf->admin->dir_temp . '/remotestoredl';
1547 dol_mkdir($tmpdir);
1548
1549 $downloaded = false;
1550 switch ($producttoinstall['source']) {
1551 case 'dolistore':
1552 if ($producttoinstall['id'] > 0) {
1553 $source_url = 'https://www.dolistore.com/_service_download.php?t=free&p=' . $producttoinstall['id'];
1554 $downloaded = $this->_downloadFile($source_url, $tmpdir);
1555 if (!$downloaded) {
1556 dol_syslog(__METHOD__ . ': Dolistore download failed: ' . $source_url, LOG_ERR);
1557 return false;
1558 }
1559 } else {
1560 dol_syslog(__METHOD__ . ': Invalid product ID for Dolistore download: ' . $producttoinstall['id'], LOG_ERR);
1561 return false;
1562 }
1563 break;
1564 case 'githubcommunity':
1565 case 'githubcustom':
1566 $sourcekey = (string) ($producttoinstall['custom_source_key'] ?? '');
1567 if ($producttoinstall['source'] == 'githubcustom' && (empty($this->custom_sources[$sourcekey]['raw_base_url']) || !getDolGlobalString($this->custom_sources[$sourcekey]['const_enable']))) {
1568 dol_syslog(__METHOD__ . ': The additional modules repository '.$sourcekey.' is not enabled or not valid into MAIN_ADD_EXTERNAL_MODULES_SOURCE', LOG_ERR);
1569 return false;
1570 }
1571 if (!empty($producttoinstall['direct-download']) && in_array($producttoinstall['direct-download'], array('yes', 'dolistore'))) {
1572 $source_url = $this->getGithubRawBaseUrl($producttoinstall['source'], $sourcekey).'/dev/build/bin/module_' . $module_name . '-' . $current_version . '.zip';
1573 $downloaded = $this->_downloadFile($source_url, $tmpdir);
1574 if (!$downloaded) {
1575 dol_syslog(__METHOD__ . ': GitHub community module download failed: ' . $source_url . ', Try to find a Dolistore link', LOG_WARNING);
1576 if ($producttoinstall['id'] > 0) {
1577 $source_url = 'https://www.dolistore.com/_service_download.php?t=free&p=' . $producttoinstall['id'];
1578 $downloaded = $this->_downloadFile($source_url, $tmpdir);
1579 if (!$downloaded) {
1580 dol_syslog(__METHOD__ . ': Dolistore download failed: ' . $source_url, LOG_ERR);
1581 return false;
1582 }
1583 } else {
1584 dol_syslog(__METHOD__ . ': No direct download available for this GitHub community module', LOG_ERR);
1585 return false;
1586 }
1587 }
1588 } else {
1589 dol_syslog(__METHOD__ . ': No direct download available for this GitHub community module', LOG_ERR);
1590 return false;
1591 }
1592 break;
1593 default:
1594 dol_syslog(__METHOD__ . ': Unsupported source type: ' . $producttoinstall['source'], LOG_ERR);
1595 }
1596
1597
1598 dol_syslog(__METHOD__ . ': Module downloaded successfully to: ' . $downloaded, LOG_DEBUG);
1599 return $downloaded;
1600 }
1601
1602
1610 private function _downloadFile(string $url, string $dest_path)
1611 {
1612 // HEAD request to get real filename from Content-Disposition
1613 $filename = '';
1614 $head = getURLContent($url, 'HEAD');
1615 // Try to extract filename from Content-Disposition header
1616 if (!empty($head['header'])) {
1617 if (preg_match_all('/Content-Disposition:.*filename=["\']?([^"\';\r\n]+)/i', $head['header'], $m)) {
1618 $filename = trim(end($m[1]), " \t\"'");
1619 }
1620 }
1621
1622 // If filename is not found in headers, try to extract it from URL
1623 if (empty($filename)) {
1624 $filename = basename(parse_url($url, PHP_URL_PATH));
1625 }
1626
1627 // If filename is still empty or file name ne match the expected pattern (module_modulename-version.zip), log error and return false
1628 if (empty($filename) || !preg_match('/^module_[a-z0-9_]+-[0-9]+\.[0-9]+\.[0-9]+\.zip$/i', $filename)) {
1629 dol_syslog(__METHOD__ . ': Cannot determine filename from URL: ' . $url, LOG_ERR);
1630 return false;
1631 }
1632
1633 // Download the file
1634 $response = getURLContent($url, 'GET');
1635 if (empty($response['content']) || (isset($response['http_code']) && $response['http_code'] !== 200)) {
1636 dol_syslog(
1637 __METHOD__ . ': Download failed — HTTP ' . ($response['http_code'] ?? 'unknown') . ' — ' . $url,
1638 LOG_WARNING
1639 );
1640 return false;
1641 }
1642
1643 // Write to destination
1644 $dest_file = $dest_path . '/' . $filename;
1645 if (file_exists(dol_osencode($dest_file))) { // If file already exists, try to delete it first
1646 chmod(dol_osencode($dest_file), 0755);
1647 @unlink(dol_osencode($dest_file));
1648 }
1649 $writtenfile = file_put_contents(dol_osencode($dest_file), $response['content']);
1650 if ($writtenfile === false || $writtenfile === 0) {
1651 dol_syslog(__METHOD__ . ': Cannot write file: ' . $dest_file, LOG_ERR);
1652 @unlink(dol_osencode($dest_file));
1653 return false;
1654 }
1655
1656 dol_syslog(__METHOD__ . ': Downloaded successfully to: ' . $dest_file, LOG_DEBUG);
1657 return $dest_file;
1658 }
1659}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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
getGithubRawBaseUrl($source, $sourcekey='')
Return the base URL to get raw files of a GitHub modules repository.
fetchModulesFromFile($options=array(), $cache_file='')
Fetch modules from a cache YAML 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.
checkStatusCode($request)
Check the status code of the request.
_downloadFile(string $url, string $dest_path)
Download a remote URL to a local file using getURLContent (native Dolibarr).
getRemoteYamlFile($file_source_url, $cache_time, $cache_file='')
Get YAML file from remote source and put it into the cache file.
adaptData($data, $source, $sourcekey='')
Adapter data fetched from github remote source to the expected format.
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.
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, $processnotimeasnoon=0)
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:452
dol_is_file($pathoffile)
Return if path is a file.
dol_is_dir($folder)
Test if filename is a directory.
dol_now($mode='gmt')
Return date for now.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
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.
getDolOptimizeSmallScreen()
Return if render must be optimized for small screen.
dolChmod($filepath, $newmask='')
Change mod of a file.
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'.
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)
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).
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
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
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button