code syntax api directory

This commit is contained in:
Frédéric FRANCE 2021-02-23 17:44:43 +01:00
parent 2642e1d1b3
commit 9b48e1a649
No known key found for this signature in database
GPG Key ID: 06809324E4B2ABC1
7 changed files with 251 additions and 287 deletions

View File

@ -41,8 +41,7 @@ $langs->load("admin");
*/ */
// Enable and test if module Api is enabled // Enable and test if module Api is enabled
if (empty($conf->global->MAIN_MODULE_API)) if (empty($conf->global->MAIN_MODULE_API)) {
{
dol_syslog("Call Dolibarr API interfaces with module REST disabled"); dol_syslog("Call Dolibarr API interfaces with module REST disabled");
print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>';
print $langs->trans("ToActivateModule"); print $langs->trans("ToActivateModule");
@ -59,20 +58,16 @@ $api->r->addAuthenticationClass('DolibarrApiAccess', '');
$listofapis = array(); $listofapis = array();
$modulesdir = dolGetModulesDirs(); $modulesdir = dolGetModulesDirs();
foreach ($modulesdir as $dir) foreach ($modulesdir as $dir) {
{
/* /*
* Search available module * Search available module
*/ */
//dol_syslog("Scan directory ".$dir." for API modules"); //dol_syslog("Scan directory ".$dir." for API modules");
$handle = @opendir(dol_osencode($dir)); $handle = @opendir(dol_osencode($dir));
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false) if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) {
{
if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg))
{
$modulename = $reg[1]; $modulename = $reg[1];
// Defined if module is enabled // Defined if module is enabled
@ -96,7 +91,9 @@ foreach ($modulesdir as $dir)
$module = 'fichinter'; $module = 'fichinter';
} }
if (empty($conf->$module->enabled)) $enabled = false; if (empty($conf->$module->enabled)) {
$enabled = false;
}
if ($enabled) { if ($enabled) {
/* /*
@ -110,16 +107,12 @@ foreach ($modulesdir as $dir)
$dir_part = DOL_DOCUMENT_ROOT.'/'.$part.'/class/'; $dir_part = DOL_DOCUMENT_ROOT.'/'.$part.'/class/';
$handle_part = @opendir(dol_osencode($dir_part)); $handle_part = @opendir(dol_osencode($dir_part));
if (is_resource($handle_part)) if (is_resource($handle_part)) {
{ while (($file_searched = readdir($handle_part)) !== false) {
while (($file_searched = readdir($handle_part)) !== false) if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg)) {
{
if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg))
{
$classname = ucwords($reg[1]); $classname = ucwords($reg[1]);
require_once $dir_part.$file_searched; require_once $dir_part.$file_searched;
if (class_exists($classname)) if (class_exists($classname)) {
{
dol_syslog("Found API classname=".$classname." into ".$dir); dol_syslog("Found API classname=".$classname." into ".$dir);
$listofapis[] = $classname; $listofapis[] = $classname;
} }
@ -186,21 +179,23 @@ print '<br>';
$oldclass = ''; $oldclass = '';
print $langs->trans("ListOfAvailableAPIs").':<br>'; print $langs->trans("ListOfAvailableAPIs").':<br>';
foreach ($listofapis['v1'] as $key => $val) foreach ($listofapis['v1'] as $key => $val) {
{ if ($key == 'login') {
if ($key == 'login') continue; continue;
if ($key == 'index') continue; }
if ($key == 'index') {
continue;
}
if ($key) if ($key) {
{ foreach ($val as $method => $val2) {
foreach ($val as $method => $val2)
{
$newclass = $val2['className']; $newclass = $val2['className'];
if (preg_match('/restler/i', $newclass)) continue; if (preg_match('/restler/i', $newclass)) {
continue;
}
if ($oldclass != $newclass) if ($oldclass != $newclass) {
{
print "\n<br>\n".$langs->trans("Class").': '.$newclass.'<br>'."\n"; print "\n<br>\n".$langs->trans("Class").': '.$newclass.'<br>'."\n";
$oldclass = $newclass; $oldclass = $newclass;
} }

View File

@ -51,7 +51,9 @@ class DolibarrApi
{ {
global $conf, $dolibarr_main_url_root; global $conf, $dolibarr_main_url_root;
if (empty($cachedir)) $cachedir = $conf->api->dir_temp; if (empty($cachedir)) {
$cachedir = $conf->api->dir_temp;
}
Defaults::$cacheDirectory = $cachedir; Defaults::$cacheDirectory = $cachedir;
$this->db = $db; $this->db = $db;
@ -191,8 +193,7 @@ class DolibarrApi
// If object has lines, remove $db property // If object has lines, remove $db property
if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) { if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
$nboflines = count($object->lines); $nboflines = count($object->lines);
for ($i = 0; $i < $nboflines; $i++) for ($i = 0; $i < $nboflines; $i++) {
{
$this->_cleanObjectDatas($object->lines[$i]); $this->_cleanObjectDatas($object->lines[$i]);
unset($object->lines[$i]->contact); unset($object->lines[$i]->contact);
@ -284,12 +285,14 @@ class DolibarrApi
$ok = 0; $ok = 0;
$i = 0; $nb = strlen($tmp); $i = 0; $nb = strlen($tmp);
$counter = 0; $counter = 0;
while ($i < $nb) while ($i < $nb) {
{ if ($tmp[$i] == '(') {
if ($tmp[$i] == '(') $counter++; $counter++;
if ($tmp[$i] == ')') $counter--; }
if ($counter < 0) if ($tmp[$i] == ')') {
{ $counter--;
}
if ($counter < 0) {
$error = "Bad sqlfilters=".$sqlfilters; $error = "Bad sqlfilters=".$sqlfilters;
dol_syslog($error, LOG_WARNING); dol_syslog($error, LOG_WARNING);
return false; return false;
@ -313,14 +316,17 @@ class DolibarrApi
global $db; global $db;
//dol_syslog("Convert matches ".$matches[1]); //dol_syslog("Convert matches ".$matches[1]);
if (empty($matches[1])) return ''; if (empty($matches[1])) {
return '';
}
$tmp = explode(':', $matches[1]); $tmp = explode(':', $matches[1]);
if (count($tmp) < 3) return ''; if (count($tmp) < 3) {
return '';
}
$tmpescaped = $tmp[2]; $tmpescaped = $tmp[2];
$regbis = array(); $regbis = array();
if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
{
$tmpescaped = "'".$db->escape($regbis[1])."'"; $tmpescaped = "'".$db->escape($regbis[1])."'";
} else { } else {
$tmpescaped = $db->escape($tmpescaped); $tmpescaped = $db->escape($tmpescaped);

View File

@ -35,7 +35,6 @@ use \Luracast\Restler\Resources;
use \Luracast\Restler\Defaults; use \Luracast\Restler\Defaults;
use \Luracast\Restler\RestException; use \Luracast\Restler\RestException;
/** /**
* Dolibarr API access class * Dolibarr API access class
* *
@ -95,23 +94,19 @@ class DolibarrApiAccess implements iAuthenticate
// api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
$api_key = ''; $api_key = '';
if (isset($_GET['api_key'])) // For backward compatibility if (isset($_GET['api_key'])) { // For backward compatibility
{
// TODO Add option to disable use of api key on url. Return errors if used. // TODO Add option to disable use of api key on url. Return errors if used.
$api_key = $_GET['api_key']; $api_key = $_GET['api_key'];
} }
if (isset($_GET['DOLAPIKEY'])) if (isset($_GET['DOLAPIKEY'])) {
{
// TODO Add option to disable use of api key on url. Return errors if used. // TODO Add option to disable use of api key on url. Return errors if used.
$api_key = $_GET['DOLAPIKEY']; // With GET method $api_key = $_GET['DOLAPIKEY']; // With GET method
} }
if (isset($_SERVER['HTTP_DOLAPIKEY'])) // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY
{
$api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded) $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded)
} }
if ($api_key) if ($api_key) {
{
$userentity = 0; $userentity = 0;
$sql = "SELECT u.login, u.datec, u.api_key, "; $sql = "SELECT u.login, u.datec, u.api_key, ";
@ -121,17 +116,14 @@ class DolibarrApiAccess implements iAuthenticate
// TODO Check if 2 users has same API key. // TODO Check if 2 users has same API key.
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{ if ($this->db->num_rows($result)) {
if ($this->db->num_rows($result))
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$login = $obj->login; $login = $obj->login;
$stored_key = $obj->api_key; $stored_key = $obj->api_key;
$userentity = $obj->entity; $userentity = $obj->entity;
if (!defined("DOLENTITY") && $conf->entity != ($obj->entity ? $obj->entity : 1)) // If API was not forced with HTTP_DOLENTITY, and user is on another entity, so we reset entity to entity of user if (!defined("DOLENTITY") && $conf->entity != ($obj->entity ? $obj->entity : 1)) { // If API was not forced with HTTP_DOLENTITY, and user is on another entity, so we reset entity to entity of user
{
$conf->entity = ($obj->entity ? $obj->entity : 1); $conf->entity = ($obj->entity ? $obj->entity : 1);
// We must also reload global conf to get params from the entity // We must also reload global conf to get params from the entity
dol_syslog("Entity was not set on http header with HTTP_DOLAPIENTITY (recommanded for performance purpose), so we switch now on entity of user (".$conf->entity.") and we have to reload configuration.", LOG_WARNING); dol_syslog("Entity was not set on http header with HTTP_DOLAPIENTITY (recommanded for performance purpose), so we switch now on entity of user (".$conf->entity.") and we have to reload configuration.", LOG_WARNING);
@ -147,8 +139,7 @@ class DolibarrApiAccess implements iAuthenticate
return false; return false;
} }
if (!$login) if (!$login) {
{
throw new RestException(503, 'Error when searching login user from api key'); throw new RestException(503, 'Error when searching login user from api key');
} }
$fuser = new User($this->db); $fuser = new User($this->db);
@ -173,7 +164,9 @@ class DolibarrApiAccess implements iAuthenticate
$userClass::setCacheIdentifier(static::$role); $userClass::setCacheIdentifier(static::$role);
Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess'; Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
$requirefortest = static::$requires; $requirefortest = static::$requires;
if (!is_array($requirefortest)) $requirefortest = explode(',', $requirefortest); if (!is_array($requirefortest)) {
$requirefortest = explode(',', $requirefortest);
}
return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin'; return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
} }

View File

@ -20,7 +20,6 @@
use Luracast\Restler\RestException; use Luracast\Restler\RestException;
use Luracast\Restler\Format\UploadFormat; use Luracast\Restler\Format\UploadFormat;
require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
@ -36,7 +35,7 @@ class Documents extends DolibarrApi
/** /**
* @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object * @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object
*/ */
static $DOCUMENT_FIELDS = array( public static $DOCUMENT_FIELDS = array(
'modulepart' 'modulepart'
); );
@ -106,8 +105,7 @@ class Documents extends DolibarrApi
$filename = basename($original_file); $filename = basename($original_file);
$original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
if (!file_exists($original_file_osencoded)) if (!file_exists($original_file_osencoded)) {
{
dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING); dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
throw new RestException(404, 'File not found'); throw new RestException(404, 'File not found');
} }
@ -148,8 +146,7 @@ class Documents extends DolibarrApi
} }
$outputlangs = $langs; $outputlangs = $langs;
if ($langcode && $langs->defaultlang != $langcode) if ($langcode && $langs->defaultlang != $langcode) {
{
$outputlangs = new Translate('', $conf); $outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang($langcode); $outputlangs->setDefaultLang($langcode);
} }
@ -187,8 +184,7 @@ class Documents extends DolibarrApi
$templateused = ''; $templateused = '';
if ($modulepart == 'facture' || $modulepart == 'invoice') if ($modulepart == 'facture' || $modulepart == 'invoice') {
{
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
$this->invoice = new Facture($this->db); $this->invoice = new Facture($this->db);
$result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); $result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
@ -201,9 +197,7 @@ class Documents extends DolibarrApi
if ($result <= 0) { if ($result <= 0) {
throw new RestException(500, 'Error generating document'); throw new RestException(500, 'Error generating document');
} }
} } elseif ($modulepart == 'commande' || $modulepart == 'order') {
elseif ($modulepart == 'commande' || $modulepart == 'order')
{
require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
$this->order = new Commande($this->db); $this->order = new Commande($this->db);
$result = $this->order->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); $result = $this->order->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
@ -215,9 +209,7 @@ class Documents extends DolibarrApi
if ($result <= 0) { if ($result <= 0) {
throw new RestException(500, 'Error generating document'); throw new RestException(500, 'Error generating document');
} }
} } elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
elseif ($modulepart == 'propal' || $modulepart == 'proposal')
{
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
$this->propal = new Propal($this->db); $this->propal = new Propal($this->db);
$result = $this->propal->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); $result = $this->propal->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
@ -236,8 +228,7 @@ class Documents extends DolibarrApi
$filename = basename($original_file); $filename = basename($original_file);
$original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
if (!file_exists($original_file_osencoded)) if (!file_exists($original_file_osencoded)) {
{
throw new RestException(404, 'File not found'); throw new RestException(404, 'File not found');
} }
@ -278,8 +269,7 @@ class Documents extends DolibarrApi
$recursive = 0; $recursive = 0;
$type = 'files'; $type = 'files';
if ($modulepart == 'societe' || $modulepart == 'thirdparty') if ($modulepart == 'societe' || $modulepart == 'thirdparty') {
{
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
if (!DolibarrApiAccess::$user->rights->societe->lire) { if (!DolibarrApiAccess::$user->rights->societe->lire) {
@ -293,9 +283,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id; $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id;
} } elseif ($modulepart == 'user') {
elseif ($modulepart == 'user')
{
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
// Can get doc if has permission to read all user or if it is user itself // Can get doc if has permission to read all user or if it is user itself
@ -310,9 +298,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->user->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id; $upload_dir = $conf->user->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id;
} } elseif ($modulepart == 'adherent' || $modulepart == 'member') {
elseif ($modulepart == 'adherent' || $modulepart == 'member')
{
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
if (!DolibarrApiAccess::$user->rights->adherent->lire) { if (!DolibarrApiAccess::$user->rights->adherent->lire) {
@ -326,9 +312,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->adherent->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'member'); $upload_dir = $conf->adherent->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'member');
} } elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
elseif ($modulepart == 'propal' || $modulepart == 'proposal')
{
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
if (!DolibarrApiAccess::$user->rights->propal->lire) { if (!DolibarrApiAccess::$user->rights->propal->lire) {
@ -342,9 +326,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal'); $upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal');
} } elseif ($modulepart == 'commande' || $modulepart == 'order') {
elseif ($modulepart == 'commande' || $modulepart == 'order')
{
require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
if (!DolibarrApiAccess::$user->rights->commande->lire) { if (!DolibarrApiAccess::$user->rights->commande->lire) {
@ -358,9 +340,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande'); $upload_dir = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande');
} } elseif ($modulepart == 'shipment' || $modulepart == 'expedition') {
elseif ($modulepart == 'shipment' || $modulepart == 'expedition')
{
require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
if (!DolibarrApiAccess::$user->rights->expedition->lire) { if (!DolibarrApiAccess::$user->rights->expedition->lire) {
@ -374,9 +354,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment'); $upload_dir = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment');
} } elseif ($modulepart == 'facture' || $modulepart == 'invoice') {
elseif ($modulepart == 'facture' || $modulepart == 'invoice')
{
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
if (!DolibarrApiAccess::$user->rights->facture->lire) { if (!DolibarrApiAccess::$user->rights->facture->lire) {
@ -390,9 +368,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice'); $upload_dir = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice');
} } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
{
$modulepart = 'supplier_invoice'; $modulepart = 'supplier_invoice';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
@ -408,9 +384,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref); $upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref);
} } elseif ($modulepart == 'produit' || $modulepart == 'product') {
elseif ($modulepart == 'produit' || $modulepart == 'product')
{
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
if (!DolibarrApiAccess::$user->rights->produit->lire) { if (!DolibarrApiAccess::$user->rights->produit->lire) {
@ -426,9 +400,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product'); $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product');
} } elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event') {
elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event')
{
require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
if (!DolibarrApiAccess::$user->rights->agenda->myactions->read && !DolibarrApiAccess::$user->rights->agenda->allactions->read) { if (!DolibarrApiAccess::$user->rights->agenda->myactions->read && !DolibarrApiAccess::$user->rights->agenda->allactions->read) {
@ -442,9 +414,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref); $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref);
} } elseif ($modulepart == 'expensereport') {
elseif ($modulepart == 'expensereport')
{
require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
if (!DolibarrApiAccess::$user->rights->expensereport->read && !DolibarrApiAccess::$user->rights->expensereport->read) { if (!DolibarrApiAccess::$user->rights->expensereport->read && !DolibarrApiAccess::$user->rights->expensereport->read) {
@ -458,9 +428,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref); $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref);
} } elseif ($modulepart == 'categorie' || $modulepart == 'category') {
elseif ($modulepart == 'categorie' || $modulepart == 'category')
{
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
if (!DolibarrApiAccess::$user->rights->categorie->lire) { if (!DolibarrApiAccess::$user->rights->categorie->lire) {
@ -561,8 +529,7 @@ class Documents extends DolibarrApi
var_dump($filecontent); var_dump($filecontent);
exit;*/ exit;*/
if (empty($modulepart)) if (empty($modulepart)) {
{
throw new RestException(400, 'Modulepart not provided.'); throw new RestException(400, 'Modulepart not provided.');
} }
@ -571,41 +538,39 @@ class Documents extends DolibarrApi
} }
$newfilecontent = ''; $newfilecontent = '';
if (empty($fileencoding)) $newfilecontent = $filecontent; if (empty($fileencoding)) {
if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent); $newfilecontent = $filecontent;
}
if ($fileencoding == 'base64') {
$newfilecontent = base64_decode($filecontent);
}
$original_file = dol_sanitizeFileName($filename); $original_file = dol_sanitizeFileName($filename);
// Define $uploadir // Define $uploadir
$object = null; $object = null;
$entity = DolibarrApiAccess::$user->entity; $entity = DolibarrApiAccess::$user->entity;
if (empty($entity)) $entity = 1; if (empty($entity)) {
$entity = 1;
}
if ($ref) if ($ref) {
{
$tmpreldir = ''; $tmpreldir = '';
if ($modulepart == 'facture' || $modulepart == 'invoice') if ($modulepart == 'facture' || $modulepart == 'invoice') {
{
$modulepart = 'facture'; $modulepart = 'facture';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
$object = new Facture($this->db); $object = new Facture($this->db);
} } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
{
$modulepart = 'supplier_invoice'; $modulepart = 'supplier_invoice';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
$object = new FactureFournisseur($this->db); $object = new FactureFournisseur($this->db);
} } elseif ($modulepart == 'project') {
elseif ($modulepart == 'project')
{
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
$object = new Project($this->db); $object = new Project($this->db);
} } elseif ($modulepart == 'task' || $modulepart == 'project_task') {
elseif ($modulepart == 'task' || $modulepart == 'project_task')
{
$modulepart = 'project_task'; $modulepart = 'project_task';
require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
@ -614,36 +579,26 @@ class Documents extends DolibarrApi
$task_result = $object->fetch('', $ref); $task_result = $object->fetch('', $ref);
// Fetching the tasks project is required because its out_dir might be a sub-directory of the project // Fetching the tasks project is required because its out_dir might be a sub-directory of the project
if ($task_result > 0) if ($task_result > 0) {
{
$project_result = $object->fetch_projet(); $project_result = $object->fetch_projet();
if ($project_result >= 0) if ($project_result >= 0) {
{
$tmpreldir = dol_sanitizeFileName($object->project->ref).'/'; $tmpreldir = dol_sanitizeFileName($object->project->ref).'/';
} }
} else { } else {
throw new RestException(500, 'Error while fetching Task '.$ref); throw new RestException(500, 'Error while fetching Task '.$ref);
} }
} } elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') {
elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service')
{
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
$object = new Product($this->db); $object = new Product($this->db);
} } elseif ($modulepart == 'expensereport') {
elseif ($modulepart == 'expensereport')
{
require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
$object = new ExpenseReport($this->db); $object = new ExpenseReport($this->db);
} } elseif ($modulepart == 'adherent' || $modulepart == 'member') {
elseif ($modulepart == 'adherent' || $modulepart == 'member')
{
$modulepart = 'adherent'; $modulepart = 'adherent';
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
$object = new Adherent($this->db); $object = new Adherent($this->db);
} } elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale') {
elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale')
{
$modulepart = 'propale'; $modulepart = 'propale';
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
$object = new Propal($this->db); $object = new Propal($this->db);
@ -652,16 +607,12 @@ class Documents extends DolibarrApi
throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.'); throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
} }
if (is_object($object)) if (is_object($object)) {
{
$result = $object->fetch('', $ref); $result = $object->fetch('', $ref);
if ($result == 0) if ($result == 0) {
{
throw new RestException(404, "Object with ref '".$ref."' was not found."); throw new RestException(404, "Object with ref '".$ref."' was not found.");
} } elseif ($result < 0) {
elseif ($result < 0)
{
throw new RestException(500, 'Error while fetching object: '.$object->error); throw new RestException(500, 'Error while fetching object: '.$object->error);
} }
} }
@ -681,13 +632,16 @@ class Documents extends DolibarrApi
$tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write'); $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write');
$upload_dir = $tmp['original_file']; // No dirname here, tmp['original_file'] is already the dir because dol_check_secure_access_document was called with param original_file that is only the dir $upload_dir = $tmp['original_file']; // No dirname here, tmp['original_file'] is already the dir because dol_check_secure_access_document was called with param original_file that is only the dir
if (empty($upload_dir) || $upload_dir == '/') if (empty($upload_dir) || $upload_dir == '/') {
{
throw new RestException(500, 'This value of modulepart ('.$modulepart.') does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); throw new RestException(500, 'This value of modulepart ('.$modulepart.') does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.');
} }
} else { } else {
if ($modulepart == 'invoice') $modulepart = 'facture'; if ($modulepart == 'invoice') {
if ($modulepart == 'member') $modulepart = 'adherent'; $modulepart = 'facture';
}
if ($modulepart == 'member') {
$modulepart = 'adherent';
}
$relativefile = $subdir; $relativefile = $subdir;
$tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write'); $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
@ -794,8 +748,7 @@ class Documents extends DolibarrApi
$filename = basename($original_file); $filename = basename($original_file);
$original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
if (!file_exists($original_file_osencoded)) if (!file_exists($original_file_osencoded)) {
{
dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING); dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
throw new RestException(404, 'File not found'); throw new RestException(404, 'File not found');
} }
@ -825,8 +778,9 @@ class Documents extends DolibarrApi
// phpcs:enable // phpcs:enable
$result = array(); $result = array();
foreach (Documents::$DOCUMENT_FIELDS as $field) { foreach (Documents::$DOCUMENT_FIELDS as $field) {
if (!isset($data[$field])) if (!isset($data[$field])) {
throw new RestException(400, "$field field missing"); throw new RestException(400, "$field field missing");
}
$result[$field] = $data[$field]; $result[$field] = $data[$field];
} }
return $result; return $result;

View File

@ -61,14 +61,16 @@ class Login
// TODO Remove the API login. The token must be generated from backoffice only. // TODO Remove the API login. The token must be generated from backoffice only.
// Authentication mode // Authentication mode
if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'dolibarr'; if (empty($dolibarr_main_authentication)) {
$dolibarr_main_authentication = 'dolibarr';
}
// Authentication mode: forceuser // Authentication mode: forceuser
if ($dolibarr_main_authentication == 'forceuser') if ($dolibarr_main_authentication == 'forceuser') {
{ if (empty($dolibarr_auto_user)) {
if (empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto'; $dolibarr_auto_user = 'auto';
if ($dolibarr_auto_user != $login) }
{ if ($dolibarr_auto_user != $login) {
dol_syslog("Warning: your instance is set to use the automatic forced login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode."); dol_syslog("Warning: your instance is set to use the automatic forced login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode.");
throw new RestException(403, "Your instance is set to use the automatic login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode."); throw new RestException(403, "Your instance is set to use the automatic login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode.");
} }
@ -77,16 +79,16 @@ class Login
// Set authmode // Set authmode
$authmode = explode(',', $dolibarr_main_authentication); $authmode = explode(',', $dolibarr_main_authentication);
if ($entity != '' && !is_numeric($entity)) if ($entity != '' && !is_numeric($entity)) {
{
throw new RestException(403, "Bad value for entity, must be the numeric ID of company."); throw new RestException(403, "Bad value for entity, must be the numeric ID of company.");
} }
if ($entity == '') $entity = 1; if ($entity == '') {
$entity = 1;
}
include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$login = checkLoginPassEntity($login, $password, $entity, $authmode, 'api'); $login = checkLoginPassEntity($login, $password, $entity, $authmode, 'api');
if (empty($login)) if (empty($login)) {
{
throw new RestException(403, 'Access denied'); throw new RestException(403, 'Access denied');
} }
@ -94,17 +96,14 @@ class Login
$tmpuser = new User($this->db); $tmpuser = new User($this->db);
$tmpuser->fetch(0, $login, 0, 0, $entity); $tmpuser->fetch(0, $login, 0, 0, $entity);
if (empty($tmpuser->id)) if (empty($tmpuser->id)) {
{
throw new RestException(500, 'Failed to load user'); throw new RestException(500, 'Failed to load user');
} }
// Renew the hash // Renew the hash
if (empty($tmpuser->api_key) || $reset) if (empty($tmpuser->api_key) || $reset) {
{
$tmpuser->getrights(); $tmpuser->getrights();
if (empty($tmpuser->rights->user->self->creer)) if (empty($tmpuser->rights->user->self->creer)) {
{
throw new RestException(403, 'User need write permission on itself to reset its API token'); throw new RestException(403, 'User need write permission on itself to reset its API token');
} }
@ -118,8 +117,7 @@ class Login
dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log
$result = $this->db->query($sql); $result = $this->db->query($sql);
if (!$result) if (!$result) {
{
throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror()); throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror());
} }
} else { } else {

View File

@ -26,22 +26,42 @@
use Luracast\Restler\Format\UploadFormat; use Luracast\Restler\Format\UploadFormat;
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test if (!defined('NOCSRFCHECK')) {
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu }
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test
if (!defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) }
if (!defined("NOSESSION")) define("NOSESSION", '1'); if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library
}
if (!defined("NOLOGIN")) {
define("NOLOGIN", '1'); // If this page is public (can be called outside logged session)
}
if (!defined("NOSESSION")) {
define("NOSESSION", '1');
}
// Force entity if a value is provided into HTTP header. Otherwise, will use the entity of user of token used. // Force entity if a value is provided into HTTP header. Otherwise, will use the entity of user of token used.
if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']); if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) {
define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']);
}
$res = 0; $res = 0;
if (!$res && file_exists("../main.inc.php")) $res = include '../main.inc.php'; if (!$res && file_exists("../main.inc.php")) {
if (!$res) die("Include of main fails"); $res = include '../main.inc.php';
}
if (!$res) {
die("Include of main fails");
}
require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php'; require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
@ -61,14 +81,12 @@ if (preg_match('/api\/index\.php$/', $url)) { // sometimes $_SERVER['PHP_SELF']
$url = $_SERVER['PHP_SELF'].$_SERVER['PATH_INFO']; $url = $_SERVER['PHP_SELF'].$_SERVER['PATH_INFO'];
} }
// Fix for some NGINX setups (this should not be required even with NGINX, however setup of NGINX are often mysterious and this may help is such cases) // Fix for some NGINX setups (this should not be required even with NGINX, however setup of NGINX are often mysterious and this may help is such cases)
if (!empty($conf->global->MAIN_NGINX_FIX)) if (!empty($conf->global->MAIN_NGINX_FIX)) {
{
$url = (isset($_SERVER['SCRIPT_URI']) && $_SERVER["SCRIPT_URI"] !== null) ? $_SERVER["SCRIPT_URI"] : $_SERVER['PHP_SELF']; $url = (isset($_SERVER['SCRIPT_URI']) && $_SERVER["SCRIPT_URI"] !== null) ? $_SERVER["SCRIPT_URI"] : $_SERVER['PHP_SELF'];
} }
// Enable and test if module Api is enabled // Enable and test if module Api is enabled
if (empty($conf->global->MAIN_MODULE_API)) if (empty($conf->global->MAIN_MODULE_API)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr API interfaces with module REST disabled"); dol_syslog("Call Dolibarr API interfaces with module REST disabled");
print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>';
@ -78,8 +96,7 @@ if (empty($conf->global->MAIN_MODULE_API))
} }
// Test if explorer is not disabled // Test if explorer is not disabled
if (preg_match('/api\/index\.php\/explorer/', $url) && !empty($conf->global->API_EXPLORER_DISABLED)) if (preg_match('/api\/index\.php\/explorer/', $url) && !empty($conf->global->API_EXPLORER_DISABLED)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr API interfaces with module REST disabled"); dol_syslog("Call Dolibarr API interfaces with module REST disabled");
print $langs->trans("WarningAPIExplorerDisabled").'.<br><br>'; print $langs->trans("WarningAPIExplorerDisabled").'.<br><br>';
@ -112,8 +129,7 @@ preg_match('/index\.php\/([^\/]+)(.*)$/', $url, $reg);
// using the explorer. And when we make another call for another API, the API is not into the api/temp/routes.php and a 404 is returned. // using the explorer. And when we make another call for another API, the API is not into the api/temp/routes.php and a 404 is returned.
// So we force refresh to each call. // So we force refresh to each call.
$refreshcache = (empty($conf->global->API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE) ? true : false); $refreshcache = (empty($conf->global->API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE) ? true : false);
if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) {
{
$refreshcache = true; $refreshcache = true;
} }
@ -132,12 +148,10 @@ UploadFormat::$allowedMimeTypes = array('image/jpeg', 'image/png', 'text/plain',
// Restrict API to some IPs // Restrict API to some IPs
if (!empty($conf->global->API_RESTRICT_ON_IP)) if (!empty($conf->global->API_RESTRICT_ON_IP)) {
{
$allowedip = explode(' ', $conf->global->API_RESTRICT_ON_IP); $allowedip = explode(' ', $conf->global->API_RESTRICT_ON_IP);
$ipremote = getUserRemoteIP(); $ipremote = getUserRemoteIP();
if (!in_array($ipremote, $allowedip)) if (!in_array($ipremote, $allowedip)) {
{
dol_syslog('Remote ip is '.$ipremote.', not into list '.$conf->global->API_RESTRICT_ON_IP); dol_syslog('Remote ip is '.$ipremote.', not into list '.$conf->global->API_RESTRICT_ON_IP);
print 'APIs are not allowed from the IP '.$ipremote; print 'APIs are not allowed from the IP '.$ipremote;
header('HTTP/1.1 503 API not allowed from your IP '.$ipremote); header('HTTP/1.1 503 API not allowed from your IP '.$ipremote);
@ -148,65 +162,64 @@ if (!empty($conf->global->API_RESTRICT_ON_IP))
// Call Explorer file for all APIs definitions (this part is slow) // Call Explorer file for all APIs definitions (this part is slow)
if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) {
{
// Scan all API files to load them // Scan all API files to load them
$listofapis = array(); $listofapis = array();
$modulesdir = dolGetModulesDirs(); $modulesdir = dolGetModulesDirs();
foreach ($modulesdir as $dir) foreach ($modulesdir as $dir) {
{
// Search available module // Search available module
dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files"); dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files");
$handle = @opendir(dol_osencode($dir)); $handle = @opendir(dol_osencode($dir));
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false)
{
$regmod = array(); $regmod = array();
if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) {
{
$module = strtolower($regmod[1]); $module = strtolower($regmod[1]);
$moduledirforclass = getModuleDirForApiClass($module); $moduledirforclass = getModuleDirForApiClass($module);
$modulenameforenabled = $module; $modulenameforenabled = $module;
if ($module == 'propale') { $modulenameforenabled = 'propal'; } if ($module == 'propale') {
if ($module == 'supplierproposal') { $modulenameforenabled = 'supplier_proposal'; } $modulenameforenabled = 'propal';
if ($module == 'ficheinter') { $modulenameforenabled = 'ficheinter'; } }
if ($module == 'supplierproposal') {
$modulenameforenabled = 'supplier_proposal';
}
if ($module == 'ficheinter') {
$modulenameforenabled = 'ficheinter';
}
dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass); dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass);
// Defined if module is enabled // Defined if module is enabled
$enabled = true; $enabled = true;
if (empty($conf->$modulenameforenabled->enabled)) $enabled = false; if (empty($conf->$modulenameforenabled->enabled)) {
$enabled = false;
}
if ($enabled) if ($enabled) {
{
// If exists, load the API class for enable module // If exists, load the API class for enable module
// Search files named api_<object>.class.php into /htdocs/<module>/class directory // Search files named api_<object>.class.php into /htdocs/<module>/class directory
// @todo : use getElementProperties() function ? // @todo : use getElementProperties() function ?
$dir_part = dol_buildpath('/'.$moduledirforclass.'/class/'); $dir_part = dol_buildpath('/'.$moduledirforclass.'/class/');
$handle_part = @opendir(dol_osencode($dir_part)); $handle_part = @opendir(dol_osencode($dir_part));
if (is_resource($handle_part)) if (is_resource($handle_part)) {
{ while (($file_searched = readdir($handle_part)) !== false) {
while (($file_searched = readdir($handle_part)) !== false) if ($file_searched == 'api_access.class.php') {
{ continue;
if ($file_searched == 'api_access.class.php') continue; }
$regapi = array(); $regapi = array();
if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) {
{
$classname = ucwords($regapi[1]); $classname = ucwords($regapi[1]);
$classname = str_replace('_', '', $classname); $classname = str_replace('_', '', $classname);
require_once $dir_part.$file_searched; require_once $dir_part.$file_searched;
if (class_exists($classname.'Api')) if (class_exists($classname.'Api')) {
{
//dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched); //dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched);
$listofapis[strtolower($classname.'Api')] = $classname.'Api'; $listofapis[strtolower($classname.'Api')] = $classname.'Api';
} elseif (class_exists($classname)) } elseif (class_exists($classname)) {
{
//dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched); //dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched);
$listofapis[strtolower($classname)] = $classname; $listofapis[strtolower($classname)] = $classname;
} else { } else {
@ -224,8 +237,7 @@ if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $
// Sort the classes before adding them to Restler. // Sort the classes before adding them to Restler.
// The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted. // The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted.
asort($listofapis); asort($listofapis);
foreach ($listofapis as $apiname => $classname) foreach ($listofapis as $apiname => $classname) {
{
$api->r->addAPIClass($classname, $apiname); $api->r->addAPIClass($classname, $apiname);
} }
//var_dump($api->r); //var_dump($api->r);
@ -233,11 +245,9 @@ if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $
// Call one APIs or one definition of an API // Call one APIs or one definition of an API
$regbis = array(); $regbis = array();
if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && $reg[2] != '/resources.json' && preg_match('/^\/(swagger|resources)\.json\/(.+)$/', $reg[2], $regbis) && $regbis[2] != 'root'))) if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && $reg[2] != '/resources.json' && preg_match('/^\/(swagger|resources)\.json\/(.+)$/', $reg[2], $regbis) && $regbis[2] != 'root'))) {
{
$moduleobject = $reg[1]; $moduleobject = $reg[1];
if ($moduleobject == 'explorer') // If we call page to explore details of a service if ($moduleobject == 'explorer') { // If we call page to explore details of a service
{
$moduleobject = $regbis[2]; $moduleobject = $regbis[2];
} }
@ -248,21 +258,27 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' &&
dol_syslog("Load a dedicated API file moduleobject=".$moduleobject." moduledirforclass=".$moduledirforclass); dol_syslog("Load a dedicated API file moduleobject=".$moduleobject." moduledirforclass=".$moduledirforclass);
$tmpmodule = $moduleobject; $tmpmodule = $moduleobject;
if ($tmpmodule != 'api') if ($tmpmodule != 'api') {
$tmpmodule = preg_replace('/api$/i', '', $tmpmodule); $tmpmodule = preg_replace('/api$/i', '', $tmpmodule);
}
$classfile = str_replace('_', '', $tmpmodule); $classfile = str_replace('_', '', $tmpmodule);
// Special cases that does not match name rules conventions // Special cases that does not match name rules conventions
if ($moduleobject == 'supplierproposals') if ($moduleobject == 'supplierproposals') {
$classfile = 'supplier_proposals'; $classfile = 'supplier_proposals';
if ($moduleobject == 'supplierorders') }
if ($moduleobject == 'supplierorders') {
$classfile = 'supplier_orders'; $classfile = 'supplier_orders';
if ($moduleobject == 'supplierinvoices') }
if ($moduleobject == 'supplierinvoices') {
$classfile = 'supplier_invoices'; $classfile = 'supplier_invoices';
if ($moduleobject == 'ficheinter') }
if ($moduleobject == 'ficheinter') {
$classfile = 'interventions'; $classfile = 'interventions';
if ($moduleobject == 'interventions') }
if ($moduleobject == 'interventions') {
$classfile = 'interventions'; $classfile = 'interventions';
}
$dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2); $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2);
@ -271,8 +287,9 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' &&
dol_syslog('Search api file /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.' classname='.$classname); dol_syslog('Search api file /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.' classname='.$classname);
$res = false; $res = false;
if ($dir_part_file) if ($dir_part_file) {
$res = include_once $dir_part_file; $res = include_once $dir_part_file;
}
if (!$res) { if (!$res) {
dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING); dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING);
print 'API not found (failed to include API file)'; print 'API not found (failed to include API file)';
@ -281,9 +298,10 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' &&
exit(0); exit(0);
} }
if (class_exists($classname)) if (class_exists($classname)) {
$api->r->addAPIClass($classname); $api->r->addAPIClass($classname);
} }
}
//var_dump($api->r->apiVersionMap); //var_dump($api->r->apiVersionMap);