Merge remote-tracking branch 'origin/main'

This commit is contained in:
Michał Zieliński
2025-10-21 17:04:25 +02:00
17 changed files with 128 additions and 158 deletions

View File

@@ -236,7 +236,7 @@ $sugar_config = array (
'log_memory_usage' => false,
'logger' =>
array (
'level' => 'off',
'level' => 'bimit',
'file' =>
array (
'ext' => '.log',

View File

@@ -16,7 +16,6 @@ $sugar_config['stack_trace_errors'] = false;
$sugar_config['developerMode'] = false;
$sugar_config['list_max_entries_per_page'] = '100';
$sugar_config['other_group_tab_displayed'] = true;
$sugar_config['logger']['level'] = 'off';
$sugar_config['passwordsetting']['systexpiration'] = '2';
$sugar_config['passwordsetting']['systexpirationlogin'] = '1';
$sugar_config['passwordsetting']['systexpirationtime'] = '';

View File

@@ -68,7 +68,6 @@ $current_user->getSystemUser();
///////////////////////////////////////////////////////////////////////////////
//// PREP FOR SCHEDULER PID
$GLOBALS['log']->debug('--------------------------------------------> at cron.php <--------------------------------------------');
$cachePath = $GLOBALS['sugar_config']['cache_dir'].'modules/Schedulers';
$pid = 'pid.php';
@@ -79,14 +78,10 @@ if(!is_file($cachePath.'/'.$pid)) {
if(is_writable($cachePath)) { // the "file" does not yet exist
write_array_to_file('timestamp', array(strtotime(date('H:i'))) , $cachePath.'/'.$pid);
require_once($cachePath.'/'.$pid);
} else {
$GLOBALS['log']->fatal('Scheduler cannot write PID file. Please check permissions on '.$cachePath);
}
} else {
if(is_writable($cachePath.'/'.$pid)) {
require_once($cachePath.'/'.$pid);
} else {
$GLOBALS['log']->fatal('Scheduler cannot read the PID file. Please check permissions on '.$cachePath);
}
}
//// END PREP FOR SCHEDULER PID
@@ -102,11 +97,7 @@ if($timestamp[0] < strtotime(date('H:i'))) {
$s = new Scheduler();
$s->flushDeadJobs();
$s->checkPendingJobs();
} else {
$GLOBALS['log']->fatal('Scheduler cannot write PID file. Please check permissions on '.$cachePath);
}
} else {
$GLOBALS['log']->fatal('If you see a whole string of these, there is a chance someone is attacking your system.');
}
$exit_on_cleanup = true;
sugar_cleanup($exit_on_cleanup);

View File

@@ -65,6 +65,7 @@ class LoggerManager {
'error' => 25,
'fatal' => 10,
'security' => 5,
'bimit' => 2,
'off' => 0,
);

View File

@@ -182,10 +182,6 @@ class MssqlManager extends DBManager
}
}
if($this->checkError('Could Not Connect:', $dieOnError))
$GLOBALS['log']->info("connected to db");
$GLOBALS['log']->info("Connect:".$this->database);
}
/**
@@ -218,7 +214,6 @@ class MssqlManager extends DBManager
if (empty($app_strings) or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])) {
//ignore the message from sql-server if $app_strings array is empty. This will happen
//only if connection if made before languge is set.
$GLOBALS['log']->debug("Ignoring this database message: " . $sqlmsg);
$sqlmsg = '';
}
else {
@@ -229,7 +224,6 @@ class MssqlManager extends DBManager
}
if ( strlen($sqlmsg) > 2 ) {
$GLOBALS['log']->fatal("SQL Server error: " . $sqlmsg);
return true;
}
@@ -246,12 +240,8 @@ class MssqlManager extends DBManager
$suppress = false
)
{
// Flag if there are odd number of single quotes
if ((substr_count($sql, "'") & 1))
$GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
$this->countQuery($sql);
$GLOBALS['log']->info('Query:' . $sql);
$this->checkConnection();
$this->query_time = microtime(true);
@@ -268,7 +258,6 @@ class MssqlManager extends DBManager
$this->lastmysqlrow = -1;
$this->query_time = microtime(true) - $this->query_time;
$GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
$this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);
@@ -295,8 +284,6 @@ class MssqlManager extends DBManager
if ($start < 0)
$start=0;
$GLOBALS['log']->debug(print_r(func_get_args(),true));
$this->lastsql = $sql;
//change the casing to lower for easier string comparison, and trim whitespaces
@@ -392,7 +379,6 @@ class MssqlManager extends DBManager
else {
if ($start < 0)
$start = 0;
$GLOBALS['log']->debug(print_r(func_get_args(),true));
$this->lastsql = $sql;
$matches = array();
preg_match('/^(.*SELECT )(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
@@ -547,8 +533,6 @@ class MssqlManager extends DBManager
}
}
}
$GLOBALS['log']->debug('Limit Query: ' . $newSQL);
$result = $this->query($newSQL, $dieOnError, $msg);
$this->dump_slow_queries($newSQL);
return $result;
@@ -779,13 +763,11 @@ class MssqlManager extends DBManager
return $col_name;
}
//break out of here, log this
$GLOBALS['log']->debug("No match was found for order by, pass string back untouched as: $orig_order_match");
return $orig_order_match;
}
else {
//if found, then parse and return
//grab string up to the aliased column
$GLOBALS['log']->debug("order by found, process sql string");
$psql = (trim($this->getAliasFromSQL($sql, $orderMatch )));
if (empty($psql))
@@ -810,7 +792,6 @@ class MssqlManager extends DBManager
$col_name = $col_name. " ". $asc_desc;
//pass in new order by
$GLOBALS['log']->debug("order by being returned is " . $col_name);
return $col_name;
}
}
@@ -829,7 +810,6 @@ class MssqlManager extends DBManager
{
global $beanList, $beanFiles;
$GLOBALS['log']->debug("Module being processed is " . $module_str);
//get the right module files
//the module string exists in bean list, then process bean for correct table name
//note that we exempt the reports module from this, as queries from reporting module should be parsed for
@@ -847,14 +827,12 @@ class MssqlManager extends DBManager
$tbl_name = trim($tbl_name);
if(empty($tbl_name)){
$GLOBALS['log']->debug("Could not find table name for module $module_str. ");
$tbl_name = $module_str;
}
}
else {
//since the module does NOT exist in beanlist, then we have to parse the string
//and grab the table name from the passed in sql
$GLOBALS['log']->debug("Could not find table name from module in request, retrieve from passed in sql");
$tbl_name = $module_str;
$sql = strtolower($sql);
@@ -873,7 +851,6 @@ class MssqlManager extends DBManager
if ($next_space > 0) {
$tbl_name= substr($tableEnd,0, $next_space);
if(empty($tbl_name)){
$GLOBALS['log']->debug("Could not find table name sql either, return $module_str. ");
$tbl_name = $module_str;
}
}
@@ -911,7 +888,6 @@ class MssqlManager extends DBManager
}
}
//return table name
$GLOBALS['log']->debug("Table name for module $module_str is: ".$tbl_name);
return $tbl_name;
}
@@ -1066,7 +1042,6 @@ class MssqlManager extends DBManager
$tableName
)
{
$GLOBALS['log']->info("tableExists: $tableName");
$this->checkConnection();
$result = $this->query(
@@ -1135,7 +1110,6 @@ class MssqlManager extends DBManager
*/
public function getTablesArray()
{
$GLOBALS['log']->debug('MSSQL fetching table list');
if($this->getDatabase()) {
$tables = array();
@@ -1159,7 +1133,6 @@ class MssqlManager extends DBManager
*/
public function wakeupFTS()
{
$GLOBALS['log']->debug('MSSQL about to wakeup FTS');
if($this->getDatabase()) {
//create wakup catalog

View File

@@ -120,13 +120,10 @@ class MysqlManager extends DBManager
if (mysql_errno($this->getDatabase())) {
if ($this->dieOnError || $dieOnError){
$GLOBALS['log']->fatal("MySQL error ".mysql_errno($this->database).": ".mysql_error($this->database));
sugar_die ($msg."MySQL error ".mysql_errno($this->database).": ".mysql_error($this->database));
}
else {
$this->last_error = $msg."MySQL error ".mysql_errno($this->database).": ".mysql_error($this->database);
$GLOBALS['log']->error("MySQL error ".mysql_errno($this->database).": ".mysql_error($this->database));
}
return true;
}
@@ -152,7 +149,6 @@ class MysqlManager extends DBManager
)
{
parent::countQuery($sql);
$GLOBALS['log']->info('Query:' . $sql);
$this->checkConnection();
//$this->freeResult();
$this->query_time = microtime(true);
@@ -165,8 +161,6 @@ class MysqlManager extends DBManager
$this->lastmysqlrow = -1;
$this->query_time = microtime(true) - $this->query_time;
$GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
$this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);
if($autofree)
@@ -187,7 +181,6 @@ class MysqlManager extends DBManager
{
if ($start < 0)
$start = 0;
$GLOBALS['log']->debug('Limit Query:' . $sql. ' Start: ' .$start . ' count: ' . $count);
$sql = "$sql LIMIT $start,$count";
$this->lastsql = $sql;
@@ -226,19 +219,6 @@ class MysqlManager extends DBManager
if ( empty($badQuery) )
return true;
foreach($badQuery as $table=>$data ){
if(!empty($data)){
$warning = ' Table:' . $table . ' Data:' . $data;
if(!empty($GLOBALS['sugar_config']['check_query_log'])){
$GLOBALS['log']->fatal($sql);
$GLOBALS['log']->fatal('CHECK QUERY:' .$warning);
}
else{
$GLOBALS['log']->warn('CHECK QUERY:' .$warning);
}
}
}
return false;
}
@@ -331,7 +311,6 @@ class MysqlManager extends DBManager
public function getTablesArray()
{
global $sugar_config;
$GLOBALS['log']->debug('Fetching table list');
if ($this->getDatabase()) {
$tables = array();
@@ -363,7 +342,6 @@ class MysqlManager extends DBManager
$tableName
)
{
$GLOBALS['log']->info("tableExists: $tableName");
if ($this->getDatabase()) {
$result = $this->query("SHOW TABLES LIKE '".$tableName."'");
@@ -441,10 +419,6 @@ class MysqlManager extends DBManager
mysql_query($charset, $this->database); // no quotes around "[charset]"
mysql_query("SET NAMES 'utf8'", $this->database);
if($this->checkError('Could Not Connect:', $dieOnError))
$GLOBALS['log']->info("connected to db");
$GLOBALS['log']->info("Connect:".$this->database);
}
/**

View File

@@ -123,13 +123,10 @@ class MysqliManager extends MysqlManager
if (mysqli_errno($this->getDatabase())){
if($this->dieOnError || $dieOnError){
$GLOBALS['log']->fatal("MySQL error ".mysqli_errno($this->database).": ".mysqli_error($this->database));
sugar_die ($msg."MySQL error ".mysqli_errno($this->database).": ".mysqli_error($this->database));
}
else{
$this->last_error = $msg."MySQL error ".mysqli_errno($this->database).": ".mysqli_error($this->database);
$GLOBALS['log']->error("MySQL error ".mysqli_errno($this->database).": ".mysqli_error($this->database));
}
return true;
}
@@ -149,7 +146,6 @@ class MysqliManager extends MysqlManager
{
static $queryMD5 = array();
parent::countQuery($sql);
$GLOBALS['log']->info('Query:' . $sql);
$this->checkConnection();
//$this->freeResult();
$this->query_time = microtime(true);
@@ -166,8 +162,6 @@ class MysqliManager extends MysqlManager
$this->lastmysqlrow = -1;
$this->query_time = microtime(true) - $this->query_time;
$GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
$this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);
if($autofree)
@@ -318,9 +312,5 @@ class MysqliManager extends MysqlManager
mysqli_query($this->database,"SET CHARACTER SET utf8"); // no quotes around "[charset]"
mysqli_query($this->database,"SET NAMES 'utf8'");
if($this->checkError('Could Not Connect:', $dieOnError))
$GLOBALS['log']->info("connected to db");
}
}
?>

View File

@@ -504,7 +504,6 @@ function get_user_array($add_blank = true, $status = "Active", $assigned_user =
$query .= " OR id='$assigned_user'";
}
$query = $query . ' ORDER BY user_name ASC';
$GLOBALS['log']->debug("get_user_array query: $query");
$result = $db->query($query, true, "Error filling in user array: ");
if ($add_blank == true) {
@@ -623,7 +622,6 @@ function safe_map($request_var, & $focus, $always_copy = false) {
*/
function safe_map_named($request_var, & $focus, $member_var, $always_copy) {
if (isset($_REQUEST[$request_var]) && ($always_copy || is_null($focus->$member_var))) {
$GLOBALS['log']->debug("safe map named called assigning '{$_REQUEST[$request_var]}' to $member_var");
$focus->$member_var = $_REQUEST[$request_var];
}
}
@@ -688,32 +686,26 @@ function return_app_list_strings_language($language) {
if ($language_used != $default_language) {
if (file_exists("custom/application/Ext/Language/$default_language.lang.ext.php")) {
$app_list_strings = _mergeCustomAppListStrings("custom/application/Ext/Language/" . $default_language . ".lang.ext.php", $app_list_strings);
$GLOBALS['log']->info("Found extended language file: " . $default_language . ".lang.ext.php");
}
if (file_exists("custom/include/language/" . $default_language . ".lang.php")) {
include("custom/include/language/" . $default_language . ".lang.php");
$GLOBALS['log']->info("Found custom language file: " . $default_language . ".lang.php");
}
}
if (file_exists("custom/application/Ext/Language/" . $language . ".lang.ext.php")) {
$app_list_strings = _mergeCustomAppListStrings("custom/application/Ext/Language/" . $language . ".lang.ext.php", $app_list_strings);
$GLOBALS['log']->info("Found extended language file: " . $language . ".lang.ext.php");
}
if (file_exists("custom/include/language/" . $language . ".lang.php")) {
include("custom/include/language/" . $language . ".lang.php");
$GLOBALS['log']->info("Found custom language file: " . $language . ".lang.php");
}
if (!isset($app_list_strings)) {
$GLOBALS['log']->warn("Unable to find the application language file for language: " . $language);
$language_used = $default_language;
$app_list_strings = $en_app_list_strings;
}
if (!isset($app_list_strings)) {
$GLOBALS['log']->fatal("Unable to load the application language file for the selected language(" . $language . ") or the default language(" . $default_language . ")");
return null;
}
//add mz 2015-01-07
@@ -824,16 +816,13 @@ function return_application_language($language) {
}
if (file_exists("custom/application/Ext/Language/$language.lang.ext.php")) {
include("custom/application/Ext/Language/$language.lang.ext.php");
$GLOBALS['log']->info("Found extended language file: $language.lang.ext.php");
}
if (file_exists("custom/include/language/$language.lang.php")) {
include("custom/include/language/$language.lang.php");
$GLOBALS['log']->info("Found custom language file: $language.lang.php");
}
if (!isset($app_strings)) {
$GLOBALS['log']->warn("Unable to find the application language file for language: " . $language);
require("include/language/$default_language.lang.php");
if (file_exists("include/language/$default_language.lang.override.php")) {
include("include/language/$default_language.lang.override.php");
@@ -844,13 +833,11 @@ function return_application_language($language) {
if (file_exists("custom/application/Ext/Language/$default_language.lang.ext.php")) {
include("custom/application/Ext/Language/$default_language.lang.ext.php");
$GLOBALS['log']->info("Found extended language file: $default_language.lang.ext.php");
}
$language_used = $default_language;
}
if (!isset($app_strings)) {
$GLOBALS['log']->fatal("Unable to load the application language file for the selected language($language) or the default language($default_language)");
return null;
}
@@ -892,7 +879,6 @@ function return_module_language($language, $module, $refresh = false) {
// Jenny - Bug 8119: Need to check if $module is not empty
if (empty($module)) {
$stack = debug_backtrace();
$GLOBALS['log']->warn("Variable module is not in return_module_language " . var_export($stack, true));
return array();
}
@@ -991,7 +977,6 @@ function return_mod_list_strings_language($language, $module) {
// if we still don't have a language pack, then log an error
if (!isset($mod_list_strings)) {
$GLOBALS['log']->fatal("Unable to load the application list language file for the selected language($language) or the default language($default_language) for module({$module})");
return null;
}
@@ -1022,13 +1007,11 @@ function return_theme_language($language, $theme) {
include(SugarThemeRegistry::get($theme)->getFilePath() . "/language/$current_language.lang.php.override");
}
if (!isset($theme_strings)) {
$GLOBALS['log']->warn("Unable to find the theme file for language: " . $language . " and theme: " . $theme);
require(SugarThemeRegistry::get($theme)->getFilePath() . "/language/$default_language.lang.php");
$language_used = $default_language;
}
if (!isset($theme_strings)) {
$GLOBALS['log']->fatal("Unable to load the theme($theme) language file for the selected language($language) or the default language($default_language)");
return null;
}
@@ -1091,7 +1074,6 @@ function generate_where_statement($where_clauses) {
$where .= $clause;
}
$GLOBALS['log']->info("Here is the where clause for the list view: $where");
return $where;
}
@@ -1697,9 +1679,6 @@ function clean_string($str, $filter = "STANDARD") {
);
if (preg_match($filters[$filter], $str)) {
if (isset($GLOBALS['log']) && is_object($GLOBALS['log'])) {
$GLOBALS['log']->fatal("SECURITY: bad data passed in; string: {$str}");
}
die("Bad data passed in; <a href=\"{$sugar_config['site_url']}\">Return to Home</a>");
} else {
return $str;
@@ -2246,7 +2225,6 @@ function get_bean_select_array($add_blank = true, $bean_name, $display_columns,
$query .= ' order by ' . $order_by;
}
$GLOBALS['log']->debug("get_user_array query: $query");
$result = $db->query($query, true, "Error filling in user array: ");
if ($add_blank == true) {
@@ -3566,7 +3544,6 @@ function getJavascriptSiteURL() {
$site_url = preg_replace('/^http\:/', 'https:', $site_url);
}
}
$GLOBALS['log']->debug("getJavascriptSiteURL(), site_url=" . $site_url);
return $site_url;
}
@@ -4105,7 +4082,6 @@ function verify_image_file($path, $jpeg = false) {
$data = fread($fp, 4096);
fclose($fp);
if (preg_match("/<(html|!doctype|script|body|head|plaintext|table|img |pre(>| )|frameset|iframe|object|link|base|style|font|applet|meta|center|form|isindex)/i", $data, $m)) {
$GLOBALS['log']->info("Found {$m[0]} in $path, not allowing upload");
return false;
}
return true;

View File

@@ -2,8 +2,10 @@
$id = $_REQUEST['apilo_details'];
$apilo_config = loadApiloConfiguration();
brecho('halo');
brecho(loadApiloOrder($apilo_config['token'], $id));
function loadApiloOrder($token, $orderId) {
brecho($token);
$url = "https://twinpol.apilo.com/rest/api/orders/".$orderId."/";
$headers = [
'Authorization: Bearer ' . $token,
@@ -17,6 +19,7 @@ function loadApiloOrder($token, $orderId) {
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
brecho($response);
if ($httpCode !== 200) {
return false;
}

View File

@@ -0,0 +1,45 @@
<?php
$id = $_REQUEST['baselinker_details'];
brecho($id);
$baselinker_config = loadConfiguration();
$order = getOrder($baselinker_config['token'], $id);
brecho($order);
function loadConfiguration()
{
global $db;
$dbRes = $db->query("SELECT * FROM config WHERE category='baselinker'");
$config = [];
while ($row = $db->fetchByAssoc($dbRes)) {
$config[$row['name']] = $row['value'];
}
return $config;
}
function getOrder($token, $orderId)
{
$methodParams = '{
"order_id": ' . $orderId . '
}';
$apiParams = [
"method" => "getOrders",
"parameters" => $methodParams
];
$curl = curl_init("https://api.baselinker.com/connector.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["X-BLToken: " . $token]);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiParams));
$res = json_decode(curl_exec($curl));
if ($res->orders[0]->order_source != '') {
return $res->orders[0];
}
}
function brecho($msg)
{
echo '<br><pre>';
print_r($msg);
echo PHP_EOL;
echo '</pre><br>';
}

View File

@@ -109,6 +109,12 @@ function blockUI($msg) {
function copyToClipboard(text) {
navigator.clipboard.writeText(text);
}
function openDetails(id) {
function openDetails(id, origin) {
window.console.log(origin);
if (origin.startsWith('Apilo')) {
window.open("index.php?module=EcmInvoiceOuts&action=ecommerce&apilo_details="+id, "_blank");
} else {
window.open("index.php?module=EcmInvoiceOuts&action=ecommerce&baselinker_details="+id, "_blank");
}
}

View File

@@ -109,12 +109,17 @@
{$ROW.document_no}
{if $ROW.origin == 'amazon'}
<img src="modules/EcmSales/images/pdf.gif" onclick="copyToClipboard('{$ROW.url}')"
style="cursor:pointer;"></a>
style="cursor:pointer;"/>
{/if}
{if $ROW.origin == 'allegro'}
<img src="modules/EcmSales/images/pdf.gif"
onclick="window.open('https://panel-g.baselinker.com/printouts/printout_invoices.php?id={$ROW.id}')"
style="cursor:pointer;" {/if} </td>
style="cursor:pointer;"/>
{/if}
<img src="modules/EcmSales/images/convert.gif"
onclick="openDetails('{$ROW.order_no}', '{$ROW.origin}')"
style="cursor:pointer;"/>
</td>
<td>
<a target="_blank"
href="index.php?module=EcmStockDocOuts&action=DetailView&record={$ROW.wz_id}">{$ROW.wz_document_no}</a>
@@ -153,7 +158,7 @@
{$ROW.sum_by_products}
{math equation="abs(x-y)" x=$ROW.total_netto y=$ROW.sum_by_products assign="price_difference"}
{if $price_difference > 0.02}
<span style="color: red; font-weight: bold; cursor: pointer" onclick="openDetails('{$ROW.order_no}')">!!!</span>
<span style="color: red; font-weight: bold; cursor: pointer" onclick="openDetails('{$ROW.order_no}', '{$ROW.origin}')">!!!</span>
{/if}
</td>
<td>

View File

@@ -1,26 +1,31 @@
<?php
// enable error reporting
//error_reporting(LC_ALL);
//ini_set('display_errors', 1);
// ?XDEBUG_SESSION_START=PHPSTORM
//importApiloInvoices();
function importInvoices()
//importInvoices();
function apilo_importInvoices()
{
$apilo_config = loadApiloConfiguration();
$apilo_config = apilo_loadConfiguration();
$db = $GLOBALS['db'];
$dbRes = $db->query("SELECT COUNT(id) as last_id FROM ecommerce_invoices WHERE origin LIKE 'apilo%'");
$offset = intval($db->fetchByAssoc($dbRes)['last_id']);
$invoices = loadApiloInvoices($apilo_config['token'], $offset);
$invoices = apilo_loadInvoices($apilo_config['token'], $offset);
if (isset($invoices->error)) {
if (refreshApiloToken($apilo_config['refresh_token'], $apilo_config['client_id'], $apilo_config['client_secret']) == true) {
$apilo_config = loadApiloConfiguration();
$invoices = loadApiloInvoices($apilo_config['token'], $offset);
if (apilo_refreshToken($apilo_config['refreshToken'], $apilo_config['clientId'], $apilo_config['clientSecret']) == true) {
//$apilo_config = apilo_loadConfiguration();
//$invoices = apilo_loadInvoices($apilo_config['token'], $offset);
} else {
return false;
}
}
$platforms = loadApiloPlatformsList($apilo_config['token']);
$GLOBALS['log']->bimit('----- Importing invoices from Apilo, documents count', count($invoices->documents));
$platforms = apilo_loadPlatformsList($apilo_config['token']);
if (!$platforms) {
return false;
@@ -28,14 +33,15 @@ function importInvoices()
if (isset($invoices->documents) && count($invoices->documents) > 0) {
foreach ($invoices->documents as $invoice) {
addapiloInvoice($invoice, $platforms, $apilo_config['token']);
apilo_addInvoice($invoice, $platforms, $apilo_config['token']);
}
}
$GLOBALS['log']->bimit('----- Importing invoices from Apilo, all processed, return TRUE');
return true;
}
function loadApiloConfiguration()
function apilo_loadConfiguration()
{
global $db;
$db = $GLOBALS['db'];
$dbRes = $db->query("SELECT * FROM config WHERE category='apilo'");
$config = [];
while ($row = $db->fetchByAssoc($dbRes)) {
@@ -43,7 +49,7 @@ function loadApiloConfiguration()
}
return $config;
}
function loadApiloInvoices($token, $offset)
function apilo_loadInvoices($token, $offset)
{
$url = "https://twinpol.apilo.com/rest/api/finance/documents/";
$params = [
@@ -70,43 +76,44 @@ function loadApiloInvoices($token, $offset)
}
return json_decode($response);
}
function refreshApiloToken($refreshToken, $clientId, $clientSecret)
function apilo_refreshToken($refreshToken, $clientId, $clientSecret)
{
$url = "https://api.apilo.com/oauth/token";
$url = "https://twinpol.apilo.com/rest/auth/token/";
$data = [
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
'client_id' => $clientId,
'client_secret' => $clientSecret
'grantType' => 'refresh_token',
'token' => $refreshToken,
];
$headers = [
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic ' . base64_encode($clientId . ':' . $clientSecret),
'Content-Type: application/json',
'Accept: application/json'
];
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$err = curl_error($curl);
curl_close($curl);
brecho($response);
brecho($httpCode);
if ($httpCode !== 200) {
return false;
}
$tokenData = json_decode($response, true);
if (isset($tokenData['access_token'])) {
brecho($tokenData);
if (isset($tokenData['accessToken'])) {
global $db;
$db->query("UPDATE config SET value='" . $tokenData['access_token'] . "' WHERE category='apilo' AND name='access_token'");
if (isset($tokenData['refresh_token'])) {
$db->query("UPDATE config SET value='" . $tokenData['refresh_token'] . "' WHERE category='apilo' AND name='refresh_token'");
}
@@ -114,11 +121,11 @@ function refreshApiloToken($refreshToken, $clientId, $clientSecret)
}
return false;
}
function addApiloInvoice($invoice, $platforms, $token)
function apilo_addInvoice($invoice, $platforms, $token)
{
$db = $GLOBALS['db'];
$platformId = loadApiloOrderPlatformId($token, $invoice->orderId);
$platformId = apilo_loadOrderPlatformId($token, $invoice->orderId);
if (!$platformId) {
return false;
}
@@ -219,11 +226,12 @@ function addApiloInvoice($invoice, $platforms, $token)
if (isset($invoice->documentItems) && is_array($invoice->documentItems)) {
$db->query(sprintf("DELETE FROM ecommerce_invoices_products WHERE invoice_id='%s'", $db->quote($invoice->id)));
foreach ($invoice->documentItems as $item) {
addApiloInvoiceProduct($invoice->id, $item);
apilo_addInvoiceProduct($invoice->id, $item);
}
}
return true;
}
function addApiloInvoiceProduct($invoiceId, $item)
function apilo_addInvoiceProduct($invoiceId, $item)
{
$db = $GLOBALS['db'];
@@ -277,7 +285,7 @@ function addApiloInvoiceProduct($invoiceId, $item)
return false;
}
}
function loadApiloPlatformsList($token) {
function apilo_loadPlatformsList($token) {
$url = "https://twinpol.apilo.com/rest/api/orders/platform/map/";
$headers = [
'Authorization: Bearer ' . $token,
@@ -296,7 +304,7 @@ function loadApiloPlatformsList($token) {
}
return json_decode($response);
}
function loadApiloOrderPlatformId($token, $orderId) {
function apilo_loadOrderPlatformId($token, $orderId) {
$url = "https://twinpol.apilo.com/rest/api/orders/".$orderId."/";
$headers = [
'Authorization: Bearer ' . $token,

View File

@@ -21,6 +21,8 @@ if (isset($_REQUEST['import_baselinker'])) {
include_once(getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/importApiloInvoices.php');
} else if (isset($_REQUEST['apilo_details'])) {
include_once(getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/apiloInvoiceDetails.php');
} else if (isset($_REQUEST['baselinker_details'])) {
include_once(getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/baselinkerInvoiceDetails.php');
} else if (isset($_REQUEST['apilo_products'])) {
include_once(getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/checkApiloProducts.php');
} else {

View File

@@ -106,7 +106,6 @@ class Scheduler extends SugarBean {
*/
function fire() {
if(empty($this->job)) { // only execute when valid
$GLOBALS['log']->fatal('Scheduler tried to fire an empty job!!');
return false;
}
@@ -126,16 +125,18 @@ class Scheduler extends SugarBean {
$job->retrieve($jobId);
if($exJob[0] == 'function') {
$GLOBALS['log']->debug('----->Scheduler found a job of type FUNCTION');
require_once('modules/Schedulers/_AddJobsHere.php');
$job->setJobFlag(1);
$func = $exJob[1];
$GLOBALS['log']->debug('----->SchedulersJob firing '.$func);
$GLOBALS['log']->bimit('Starting function', $job->scheduler->id, $job->scheduler->name, $func);
$res = call_user_func($func);
if($res) {
$GLOBALS['log']->bimit('Setting JOB as finished', $job->scheduler->id, $job->scheduler->name, $res);
$job->setJobFlag(2);
$job->finishJob();
return true;
@@ -340,22 +341,15 @@ class Scheduler extends SugarBean {
$this->cleanJobLog();
$allSchedulers = $this->get_full_list('', 'schedulers.status=\'Active\'');
$GLOBALS['log']->info('-----> Scheduler found [ '.count($allSchedulers).' ] ACTIVE jobs');
if(!empty($allSchedulers)) {
foreach($allSchedulers as $focus) {
if($focus->fireQualified()) {
if($focus->fire()) {
$GLOBALS['log']->debug('----->Scheduler Job completed successfully');
} else {
$GLOBALS['log']->fatal('----->Scheduler Job FAILED');
$GLOBALS['log']->bimit('Starting job', $focus->id, $focus->name);
$res = $focus->fire();
$GLOBALS['log']->bimit('Finished job', $focus->id, $focus->name, $res);
}
}
}
} else {
$GLOBALS['log']->debug('----->No Schedulers found');
}
}
/**

View File

@@ -71,23 +71,33 @@ $job_strings = array(
function importApiloInvoices() {
try {
$GLOBALS['log']->bimit('_addJobsHere, importApiloInvoices started');
$GLOBALS['db']->query("USE preDb_0dcc87940d3655fa574b253df04ca1c3;");
$GLOBALS['log']->bimit('_addJobsHere, importApiloInvoices db query done');
require_once('modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/importApiloInvoices.php');
importInvoices();
$GLOBALS['log']->bimit('_addJobsHere, importApiloInvoices file loadded');
$GLOBALS['log']->bimit('_addJobsHere, importApiloInvoices importInvoices() fired');
$res = importInvoices();
$GLOBALS['log']->bimit('_addJobsHere, importApiloInvoices finished', $res);
return true;
} catch (Exception $e) {
$GLOBALS['log']->bimit('_addJobsHere, importApiloInvoices error', $e);
return false;
}
}
function importBaselinkerInvoices()
{
try {
$GLOBALS['log']->bimit('_addJobsHere, importBaselinkerInvoices started');
$GLOBALS['db']->query("USE preDb_0dcc87940d3655fa574b253df04ca1c3;");
require_once('modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/importBaselinkerInvoices.php');
importFV('7688'); // FV Polska
//importFV('15356'); // FV Polska (stare)
importFV('53096'); // FV Temu
$GLOBALS['log']->bimit('_addJobsHere, importBaselinkerInvoices finished');
return true;
} catch (Exception $e) {
$GLOBALS['log']->bimit('_addJobsHere, importBaselinkerInvoices error', $e);
return false;
}
}

View File

@@ -1,11 +1,4 @@
<?php
die();
require_once 'modules/Schedulers/Monitoring.php';
$EcmSysInfo = new EcmSysInfo ();
if ($EcmSysInfo->getDatabaseName () == 'preDb_7561b7965a2f9cebf2cbca60a9a07064') {
new Monitoring ();
}
return true;
?>
$logger = $GLOBALS['log'];
$logger->bimit('test');
echo 'test';