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
if (empty($conf->global->MAIN_MODULE_API))
{
if (empty($conf->global->MAIN_MODULE_API)) {
dol_syslog("Call Dolibarr API interfaces with module REST disabled");
print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>';
print $langs->trans("ToActivateModule");
@ -59,20 +58,16 @@ $api->r->addAuthenticationClass('DolibarrApiAccess', '');
$listofapis = array();
$modulesdir = dolGetModulesDirs();
foreach ($modulesdir as $dir)
{
foreach ($modulesdir as $dir) {
/*
* Search available module
*/
* Search available module
*/
//dol_syslog("Scan directory ".$dir." for API modules");
$handle = @opendir(dol_osencode($dir));
if (is_resource($handle))
{
while (($file = readdir($handle)) !== false)
{
if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg))
{
if (is_resource($handle)) {
while (($file = readdir($handle)) !== false) {
if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) {
$modulename = $reg[1];
// Defined if module is enabled
@ -96,60 +91,58 @@ foreach ($modulesdir as $dir)
$module = 'fichinter';
}
if (empty($conf->$module->enabled)) $enabled = false;
if (empty($conf->$module->enabled)) {
$enabled = false;
}
if ($enabled) {
/*
* If exists, load the API class for enable module
*
* Search files named api_<object>.class.php into /htdocs/<module>/class directory
*
* @todo : take care of externals module!
* @todo : use getElementProperties() function ?
*/
* If exists, load the API class for enable module
*
* Search files named api_<object>.class.php into /htdocs/<module>/class directory
*
* @todo : take care of externals module!
* @todo : use getElementProperties() function ?
*/
$dir_part = DOL_DOCUMENT_ROOT.'/'.$part.'/class/';
$handle_part = @opendir(dol_osencode($dir_part));
if (is_resource($handle_part))
{
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_resource($handle_part)) {
while (($file_searched = readdir($handle_part)) !== false) {
if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg)) {
$classname = ucwords($reg[1]);
require_once $dir_part.$file_searched;
if (class_exists($classname))
{
if (class_exists($classname)) {
dol_syslog("Found API classname=".$classname." into ".$dir);
$listofapis[] = $classname;
}
}
/*
if (is_readable($dir_part.$file_searched) && preg_match("/^(api_.*)\.class\.php$/i",$file_searched,$reg))
{
$classname=$reg[1];
$classname = str_replace('Api_','',ucwords($reg[1])).'Api';
//$classname = str_replace('Api_','',ucwords($reg[1]));
$classname = ucfirst($classname);
require_once $dir_part.$file_searched;
if (is_readable($dir_part.$file_searched) && preg_match("/^(api_.*)\.class\.php$/i",$file_searched,$reg))
{
$classname=$reg[1];
$classname = str_replace('Api_','',ucwords($reg[1])).'Api';
//$classname = str_replace('Api_','',ucwords($reg[1]));
$classname = ucfirst($classname);
require_once $dir_part.$file_searched;
// if (class_exists($classname))
// {
// dol_syslog("Found API classname=".$classname);
// $api->r->addAPIClass($classname,'');
// if (class_exists($classname))
// {
// dol_syslog("Found API classname=".$classname);
// $api->r->addAPIClass($classname,'');
// require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Routes.php';
// $tmpclass = new ReflectionClass($classname);
// try {
// $classMetadata = CommentParser::parse($tmpclass->getDocComment());
// } catch (Exception $e) {
// throw new RestException(500, "Error while parsing comments of `$classname` class. " . $e->getMessage());
// }
// require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Routes.php';
// $tmpclass = new ReflectionClass($classname);
// try {
// $classMetadata = CommentParser::parse($tmpclass->getDocComment());
// } catch (Exception $e) {
// throw new RestException(500, "Error while parsing comments of `$classname` class. " . $e->getMessage());
// }
// //$listofapis[]=array('classname'=>$classname, 'fullpath'=>$file_searched);
// }
}*/
// //$listofapis[]=array('classname'=>$classname, 'fullpath'=>$file_searched);
// }
}*/
}
}
}
@ -186,21 +179,23 @@ print '<br>';
$oldclass = '';
print $langs->trans("ListOfAvailableAPIs").':<br>';
foreach ($listofapis['v1'] as $key => $val)
{
if ($key == 'login') continue;
if ($key == 'index') continue;
foreach ($listofapis['v1'] as $key => $val) {
if ($key == 'login') {
continue;
}
if ($key == 'index') {
continue;
}
if ($key)
{
foreach ($val as $method => $val2)
{
if ($key) {
foreach ($val as $method => $val2) {
$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";
$oldclass = $newclass;
}

View File

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

View File

@ -35,7 +35,6 @@ use \Luracast\Restler\Resources;
use \Luracast\Restler\Defaults;
use \Luracast\Restler\RestException;
/**
* Dolibarr API access class
*
@ -90,28 +89,24 @@ class DolibarrApiAccess implements iAuthenticate
/*foreach ($_SERVER as $key => $val)
{
dol_syslog($key.' - '.$val);
dol_syslog($key.' - '.$val);
}*/
// api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
$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.
$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.
$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)
}
if ($api_key)
{
if ($api_key) {
$userentity = 0;
$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.
$result = $this->db->query($sql);
if ($result)
{
if ($this->db->num_rows($result))
{
if ($result) {
if ($this->db->num_rows($result)) {
$obj = $this->db->fetch_object($result);
$login = $obj->login;
$stored_key = $obj->api_key;
$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);
// 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);
@ -147,8 +139,7 @@ class DolibarrApiAccess implements iAuthenticate
return false;
}
if (!$login)
{
if (!$login) {
throw new RestException(503, 'Error when searching login user from api key');
}
$fuser = new User($this->db);
@ -173,7 +164,9 @@ class DolibarrApiAccess implements iAuthenticate
$userClass::setCacheIdentifier(static::$role);
Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
$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';
}

View File

@ -20,7 +20,6 @@
use Luracast\Restler\RestException;
use Luracast\Restler\Format\UploadFormat;
require_once DOL_DOCUMENT_ROOT.'/main.inc.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
*/
static $DOCUMENT_FIELDS = array(
public static $DOCUMENT_FIELDS = array(
'modulepart'
);
@ -106,8 +105,7 @@ class Documents extends DolibarrApi
$filename = basename($original_file);
$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);
throw new RestException(404, 'File not found');
}
@ -148,8 +146,7 @@ class Documents extends DolibarrApi
}
$outputlangs = $langs;
if ($langcode && $langs->defaultlang != $langcode)
{
if ($langcode && $langs->defaultlang != $langcode) {
$outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang($langcode);
}
@ -187,8 +184,7 @@ class Documents extends DolibarrApi
$templateused = '';
if ($modulepart == 'facture' || $modulepart == 'invoice')
{
if ($modulepart == 'facture' || $modulepart == 'invoice') {
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
$this->invoice = new Facture($this->db);
$result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
@ -201,9 +197,7 @@ class Documents extends DolibarrApi
if ($result <= 0) {
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';
$this->order = new Commande($this->db);
$result = $this->order->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
@ -215,9 +209,7 @@ class Documents extends DolibarrApi
if ($result <= 0) {
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';
$this->propal = new Propal($this->db);
$result = $this->propal->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
@ -236,8 +228,7 @@ class Documents extends DolibarrApi
$filename = basename($original_file);
$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');
}
@ -278,8 +269,7 @@ class Documents extends DolibarrApi
$recursive = 0;
$type = 'files';
if ($modulepart == 'societe' || $modulepart == 'thirdparty')
{
if ($modulepart == 'societe' || $modulepart == 'thirdparty') {
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
if (!DolibarrApiAccess::$user->rights->societe->lire) {
@ -293,9 +283,7 @@ class Documents extends DolibarrApi
}
$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';
// 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;
}
elseif ($modulepart == 'adherent' || $modulepart == 'member')
{
} elseif ($modulepart == 'adherent' || $modulepart == 'member') {
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
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');
}
elseif ($modulepart == 'propal' || $modulepart == 'proposal')
{
} elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
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');
}
elseif ($modulepart == 'commande' || $modulepart == 'order')
{
} elseif ($modulepart == 'commande' || $modulepart == 'order') {
require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
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');
}
elseif ($modulepart == 'shipment' || $modulepart == 'expedition')
{
} elseif ($modulepart == 'shipment' || $modulepart == 'expedition') {
require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
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');
}
elseif ($modulepart == 'facture' || $modulepart == 'invoice')
{
} elseif ($modulepart == 'facture' || $modulepart == 'invoice') {
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
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');
}
elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
{
} elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
$modulepart = 'supplier_invoice';
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);
}
elseif ($modulepart == 'produit' || $modulepart == 'product')
{
} elseif ($modulepart == 'produit' || $modulepart == 'product') {
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
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');
}
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';
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);
}
elseif ($modulepart == 'expensereport')
{
} elseif ($modulepart == 'expensereport') {
require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
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);
}
elseif ($modulepart == 'categorie' || $modulepart == 'category')
{
} elseif ($modulepart == 'categorie' || $modulepart == 'category') {
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
if (!DolibarrApiAccess::$user->rights->categorie->lire) {
@ -523,9 +491,9 @@ class Documents extends DolibarrApi
* @throws RestException
*/
/*
public function get($id) {
return array('note'=>'xxx');
}*/
public function get($id) {
return array('note'=>'xxx');
}*/
/**
@ -557,12 +525,11 @@ class Documents extends DolibarrApi
global $db, $conf;
/*var_dump($modulepart);
var_dump($filename);
var_dump($filecontent);
exit;*/
var_dump($filename);
var_dump($filecontent);
exit;*/
if (empty($modulepart))
{
if (empty($modulepart)) {
throw new RestException(400, 'Modulepart not provided.');
}
@ -571,41 +538,39 @@ class Documents extends DolibarrApi
}
$newfilecontent = '';
if (empty($fileencoding)) $newfilecontent = $filecontent;
if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent);
if (empty($fileencoding)) {
$newfilecontent = $filecontent;
}
if ($fileencoding == 'base64') {
$newfilecontent = base64_decode($filecontent);
}
$original_file = dol_sanitizeFileName($filename);
// Define $uploadir
$object = null;
$entity = DolibarrApiAccess::$user->entity;
if (empty($entity)) $entity = 1;
if (empty($entity)) {
$entity = 1;
}
if ($ref)
{
if ($ref) {
$tmpreldir = '';
if ($modulepart == 'facture' || $modulepart == 'invoice')
{
if ($modulepart == 'facture' || $modulepart == 'invoice') {
$modulepart = 'facture';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
$object = new Facture($this->db);
}
elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
{
} elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
$modulepart = 'supplier_invoice';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
$object = new FactureFournisseur($this->db);
}
elseif ($modulepart == 'project')
{
} elseif ($modulepart == 'project') {
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
$object = new Project($this->db);
}
elseif ($modulepart == 'task' || $modulepart == 'project_task')
{
} elseif ($modulepart == 'task' || $modulepart == 'project_task') {
$modulepart = 'project_task';
require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
@ -614,36 +579,26 @@ class Documents extends DolibarrApi
$task_result = $object->fetch('', $ref);
// 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();
if ($project_result >= 0)
{
if ($project_result >= 0) {
$tmpreldir = dol_sanitizeFileName($object->project->ref).'/';
}
} else {
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';
$object = new Product($this->db);
}
elseif ($modulepart == 'expensereport')
{
} elseif ($modulepart == 'expensereport') {
require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
$object = new ExpenseReport($this->db);
}
elseif ($modulepart == 'adherent' || $modulepart == 'member')
{
} elseif ($modulepart == 'adherent' || $modulepart == 'member') {
$modulepart = 'adherent';
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
$object = new Adherent($this->db);
}
elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale')
{
} elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale') {
$modulepart = 'propale';
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
$object = new Propal($this->db);
@ -652,22 +607,18 @@ class Documents extends DolibarrApi
throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
}
if (is_object($object))
{
if (is_object($object)) {
$result = $object->fetch('', $ref);
if ($result == 0)
{
if ($result == 0) {
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);
}
}
if (!($object->id > 0)) {
throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found.");
throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found.");
}
// Special cases that need to use get_exdir to get real dir of object
@ -681,13 +632,16 @@ class Documents extends DolibarrApi
$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
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.');
}
} else {
if ($modulepart == 'invoice') $modulepart = 'facture';
if ($modulepart == 'member') $modulepart = 'adherent';
if ($modulepart == 'invoice') {
$modulepart = 'facture';
}
if ($modulepart == 'member') {
$modulepart = 'adherent';
}
$relativefile = $subdir;
$tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
@ -771,12 +725,12 @@ class Documents extends DolibarrApi
// Special cases that need to use get_exdir to get real dir of object
// If future, all object should use this to define path of documents.
/*
$tmpreldir = '';
if ($modulepart == 'supplier_invoice') {
$tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
}
$tmpreldir = '';
if ($modulepart == 'supplier_invoice') {
$tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
}
$relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
$relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
$relativefile = $original_file;
$check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read');
@ -794,8 +748,7 @@ class Documents extends DolibarrApi
$filename = basename($original_file);
$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);
throw new RestException(404, 'File not found');
}
@ -825,8 +778,9 @@ class Documents extends DolibarrApi
// phpcs:enable
$result = array();
foreach (Documents::$DOCUMENT_FIELDS as $field) {
if (!isset($data[$field]))
if (!isset($data[$field])) {
throw new RestException(400, "$field field missing");
}
$result[$field] = $data[$field];
}
return $result;

View File

@ -61,14 +61,16 @@ class Login
// TODO Remove the API login. The token must be generated from backoffice only.
// Authentication mode
if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'dolibarr';
if (empty($dolibarr_main_authentication)) {
$dolibarr_main_authentication = 'dolibarr';
}
// Authentication mode: forceuser
if ($dolibarr_main_authentication == 'forceuser')
{
if (empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto';
if ($dolibarr_auto_user != $login)
{
if ($dolibarr_main_authentication == 'forceuser') {
if (empty($dolibarr_auto_user)) {
$dolibarr_auto_user = 'auto';
}
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.");
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
$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.");
}
if ($entity == '') $entity = 1;
if ($entity == '') {
$entity = 1;
}
include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$login = checkLoginPassEntity($login, $password, $entity, $authmode, 'api');
if (empty($login))
{
if (empty($login)) {
throw new RestException(403, 'Access denied');
}
@ -94,17 +96,14 @@ class Login
$tmpuser = new User($this->db);
$tmpuser->fetch(0, $login, 0, 0, $entity);
if (empty($tmpuser->id))
{
if (empty($tmpuser->id)) {
throw new RestException(500, 'Failed to load user');
}
// Renew the hash
if (empty($tmpuser->api_key) || $reset)
{
if (empty($tmpuser->api_key) || $reset) {
$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');
}
@ -118,8 +117,7 @@ class Login
dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log
$result = $this->db->query($sql);
if (!$result)
{
if (!$result) {
throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror());
}
} else {

View File

@ -310,7 +310,7 @@ class Setup extends DolibarrApi
* Get state by ID.
*
* @param int $id ID of state
* @return array Array of cleaned object properties
* @return array Array of cleaned object properties
*
* @url GET dictionary/states/{id}
*

View File

@ -26,22 +26,42 @@
use Luracast\Restler\Format\UploadFormat;
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not check anti POST 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('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');
if (!defined('NOCSRFCHECK')) {
define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test
}
if (!defined('NOTOKENRENEWAL')) {
define('NOTOKENRENEWAL', '1'); // Do not check anti POST 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('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.
if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']);
if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) {
define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']);
}
$res = 0;
if (!$res && file_exists("../main.inc.php")) $res = include '../main.inc.php';
if (!$res) die("Include of main fails");
if (!$res && file_exists("../main.inc.php")) {
$res = include '../main.inc.php';
}
if (!$res) {
die("Include of main fails");
}
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'];
}
// 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'];
}
// 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");
dol_syslog("Call Dolibarr API interfaces with module REST disabled");
print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>';
@ -78,8 +96,7 @@ if (empty($conf->global->MAIN_MODULE_API))
}
// 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");
dol_syslog("Call Dolibarr API interfaces with module REST disabled");
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.
// So we force refresh to each call.
$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;
}
@ -132,12 +148,10 @@ UploadFormat::$allowedMimeTypes = array('image/jpeg', 'image/png', 'text/plain',
// 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);
$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);
print 'APIs are not allowed from the 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)
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
$listofapis = array();
$modulesdir = dolGetModulesDirs();
foreach ($modulesdir as $dir)
{
foreach ($modulesdir as $dir) {
// Search available module
dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files");
$handle = @opendir(dol_osencode($dir));
if (is_resource($handle))
{
while (($file = readdir($handle)) !== false)
{
if (is_resource($handle)) {
while (($file = readdir($handle)) !== false) {
$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]);
$moduledirforclass = getModuleDirForApiClass($module);
$modulenameforenabled = $module;
if ($module == 'propale') { $modulenameforenabled = 'propal'; }
if ($module == 'supplierproposal') { $modulenameforenabled = 'supplier_proposal'; }
if ($module == 'ficheinter') { $modulenameforenabled = 'ficheinter'; }
if ($module == 'propale') {
$modulenameforenabled = 'propal';
}
if ($module == 'supplierproposal') {
$modulenameforenabled = 'supplier_proposal';
}
if ($module == 'ficheinter') {
$modulenameforenabled = 'ficheinter';
}
dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass);
// Defined if module is enabled
$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
// Search files named api_<object>.class.php into /htdocs/<module>/class directory
// @todo : use getElementProperties() function ?
$dir_part = dol_buildpath('/'.$moduledirforclass.'/class/');
$handle_part = @opendir(dol_osencode($dir_part));
if (is_resource($handle_part))
{
while (($file_searched = readdir($handle_part)) !== false)
{
if ($file_searched == 'api_access.class.php') continue;
if (is_resource($handle_part)) {
while (($file_searched = readdir($handle_part)) !== false) {
if ($file_searched == 'api_access.class.php') {
continue;
}
$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 = str_replace('_', '', $classname);
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);
$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);
$listofapis[strtolower($classname)] = $classname;
} else {
@ -224,8 +237,7 @@ if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $
// 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.
asort($listofapis);
foreach ($listofapis as $apiname => $classname)
{
foreach ($listofapis as $apiname => $classname) {
$api->r->addAPIClass($classname, $apiname);
}
//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
$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];
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];
}
@ -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);
$tmpmodule = $moduleobject;
if ($tmpmodule != 'api')
if ($tmpmodule != 'api') {
$tmpmodule = preg_replace('/api$/i', '', $tmpmodule);
}
$classfile = str_replace('_', '', $tmpmodule);
// Special cases that does not match name rules conventions
if ($moduleobject == 'supplierproposals')
if ($moduleobject == 'supplierproposals') {
$classfile = 'supplier_proposals';
if ($moduleobject == 'supplierorders')
}
if ($moduleobject == 'supplierorders') {
$classfile = 'supplier_orders';
if ($moduleobject == 'supplierinvoices')
}
if ($moduleobject == 'supplierinvoices') {
$classfile = 'supplier_invoices';
if ($moduleobject == 'ficheinter')
}
if ($moduleobject == 'ficheinter') {
$classfile = 'interventions';
if ($moduleobject == 'interventions')
}
if ($moduleobject == 'interventions') {
$classfile = 'interventions';
}
$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);
$res = false;
if ($dir_part_file)
if ($dir_part_file) {
$res = include_once $dir_part_file;
}
if (!$res) {
dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING);
print 'API not found (failed to include API file)';
@ -281,8 +298,9 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' &&
exit(0);
}
if (class_exists($classname))
if (class_exists($classname)) {
$api->r->addAPIClass($classname);
}
}