Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into

develop

Conflicts:
	htdocs/adherents/subscription/list.php
	htdocs/societe/canvas/company/tpl/card_create.tpl.php
	htdocs/societe/canvas/individual/tpl/card_create.tpl.php
	htdocs/societe/card.php
This commit is contained in:
Laurent Destailleur 2021-03-01 17:46:36 +01:00
commit 1cdea45707
251 changed files with 16079 additions and 12496 deletions

View File

@ -22,7 +22,9 @@
* \brief This script create a xml checksum file * \brief This script create a xml checksum file
*/ */
if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db if (! defined('NOREQUIREDB')) {
define('NOREQUIREDB', '1'); // Do not create database handler $db
}
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
@ -54,7 +56,9 @@ parse_str($argv[1]);
$i=0; $i=0;
while ($i < $argc) { while ($i < $argc) {
if (! empty($argv[$i])) parse_str($argv[$i]); if (! empty($argv[$i])) {
parse_str($argv[$i]);
}
if (preg_match('/includeconstant=/', $argv[$i])) { if (preg_match('/includeconstant=/', $argv[$i])) {
$tmp=explode(':', $includeconstant, 3); $tmp=explode(':', $includeconstant, 3);
if (count($tmp) != 3) { if (count($tmp) != 3) {
@ -78,7 +82,9 @@ $savrelease = $release;
$tmpver=explode('-', $release, 2); $tmpver=explode('-', $release, 2);
if ($tmpver[0] == 'auto' || $tmpver[0] == 'autostable') { if ($tmpver[0] == 'auto' || $tmpver[0] == 'autostable') {
$release=DOL_VERSION; $release=DOL_VERSION;
if ($tmpver[1] && $tmpver[0] == 'auto') $release.='-'.$tmpver[1]; if ($tmpver[1] && $tmpver[0] == 'auto') {
$release.='-'.$tmpver[1];
}
} }
if (empty($includecustom)) { if (empty($includecustom)) {
@ -205,8 +211,9 @@ foreach ($files as $filetmp) {
$newdir = str_replace(DOL_DOCUMENT_ROOT, '', dirname($file)); $newdir = str_replace(DOL_DOCUMENT_ROOT, '', dirname($file));
$newdir = str_replace(dirname(__FILE__).'/../scripts', '', dirname($file)); $newdir = str_replace(dirname(__FILE__).'/../scripts', '', dirname($file));
if ($newdir!=$dir) { if ($newdir!=$dir) {
if ($needtoclose) if ($needtoclose) {
fputs($fp, ' </dir>'."\n"); fputs($fp, ' </dir>'."\n");
}
fputs($fp, ' <dir name="'.$newdir.'" >'."\n"); fputs($fp, ' <dir name="'.$newdir.'" >'."\n");
$dir = $newdir; $dir = $newdir;
$needtoclose=1; $needtoclose=1;

View File

@ -131,13 +131,16 @@ $fields = implode(',', $fieldArray);
//var_dump($fieldArray);die(); //var_dump($fieldArray);die();
$maxLength = 0; $maxLength = 0;
for ($i = 1; $i <= $record_numbers; $i++) { for ($i = 1; $i <= $record_numbers; $i++) {
if ($startlinenb && $i < $startlinenb) if ($startlinenb && $i < $startlinenb) {
continue; continue;
if ($endlinenb && $i > $endlinenb) }
if ($endlinenb && $i > $endlinenb) {
continue; continue;
}
$row = dbase_get_record_with_names($fhandle, $i); $row = dbase_get_record_with_names($fhandle, $i);
if ($row === false || (isset($row["deleted"]) && $row["deleted"] == '1')) if ($row === false || (isset($row["deleted"]) && $row["deleted"] == '1')) {
continue; continue;
}
$sqlInsert = "INSERT INTO `$table_name`($fields) VALUES (null,"; $sqlInsert = "INSERT INTO `$table_name`($fields) VALUES (null,";
array_shift($row); // remove delete column array_shift($row); // remove delete column
foreach ($row as $value) { foreach ($row as $value) {

View File

@ -88,25 +88,29 @@ if (!$ret > 0) {
$sql = "SELECT * FROM `$table` WHERE 1"; $sql = "SELECT * FROM `$table` WHERE 1";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
while ($fields = $db->fetch_array($resql)) { while ($fields = $db->fetch_array($resql)) {
$errorrecord = 0; $errorrecord = 0;
if ($fields === false) if ($fields === false) {
continue; continue;
}
$nboflines++; $nboflines++;
$produit = new Product($db); $produit = new Product($db);
$produit->type = 0; $produit->type = 0;
$produit->status = 1; $produit->status = 1;
$produit->ref = trim($fields['REF']); $produit->ref = trim($fields['REF']);
if ($produit->ref == '') if ($produit->ref == '') {
continue; continue;
}
print "Process line nb " . $j . ", ref " . $produit->ref; print "Process line nb " . $j . ", ref " . $produit->ref;
$produit->label = trim($fields['LIBELLE']); $produit->label = trim($fields['LIBELLE']);
if ($produit->label == '') if ($produit->label == '') {
$produit->label = $produit->ref; $produit->label = $produit->ref;
if (empty($produit->label)) }
if (empty($produit->label)) {
continue; continue;
}
//$produit->description = trim($fields[4] . "\n" . ($fields[5] ? $fields[5] . ' x ' . $fields[6] . ' x ' . $fields[7] : '')); //$produit->description = trim($fields[4] . "\n" . ($fields[5] ? $fields[5] . ' x ' . $fields[6] . ' x ' . $fields[7] : ''));
// $produit->volume = price2num($fields[8]); // $produit->volume = price2num($fields[8]);
// $produit->volume_unit = 0; // $produit->volume_unit = 0;
@ -166,8 +170,9 @@ while ($fields = $db->fetch_array($resql)) {
//$ret1 = $produit->updatePrice($produit->price_ttc, $produit->price_base_type, $user, $produit->tva_tx, $produit->price_min, 1, $produit->tva_npr, 0, 0, array()); //$ret1 = $produit->updatePrice($produit->price_ttc, $produit->price_base_type, $user, $produit->tva_tx, $produit->price_min, 1, $produit->tva_npr, 0, 0, array());
$ret1 = false; $ret1 = false;
for ($i = 0; $i < 10; $i++) { for ($i = 0; $i < 10; $i++) {
if ($fields['TARIF' . ($i)] == 0) if ($fields['TARIF' . ($i)] == 0) {
continue; continue;
}
$ret1 = $ret1 || $produit->updatePrice(price2num($fields['TARIF' . ($i)]), 'HT', $user, $produit->tva_tx, $produit->price_min, $i + 1, $produit->tva_npr, 0, 0, array()) < 0; $ret1 = $ret1 || $produit->updatePrice(price2num($fields['TARIF' . ($i)]), 'HT', $user, $produit->tva_tx, $produit->price_min, $i + 1, $produit->tva_npr, 0, 0, array()) < 0;
} }
if ($ret1) { if ($ret1) {
@ -227,7 +232,10 @@ while ($fields = $db->fetch_array($resql)) {
$error++; // $errorrecord will be reset $error++; // $errorrecord will be reset
} }
$j++; $j++;
} else die("error : $sql"); }
} else {
die("error : $sql");
}

View File

@ -144,15 +144,17 @@ if (!$ret > 0) {
$sql = "SELECT * FROM `$table` WHERE 1 "; //ORDER BY REMISE DESC,`LCIVIL` DESC"; $sql = "SELECT * FROM `$table` WHERE 1 "; //ORDER BY REMISE DESC,`LCIVIL` DESC";
$resql = $db->query($sql); $resql = $db->query($sql);
//$db->begin(); //$db->begin();
if ($resql) if ($resql) {
while ($fields = $db->fetch_array($resql)) { while ($fields = $db->fetch_array($resql)) {
$i++; $i++;
$errorrecord = 0; $errorrecord = 0;
if ($startlinenb && $i < $startlinenb) if ($startlinenb && $i < $startlinenb) {
continue; continue;
if ($endlinenb && $i > $endlinenb) }
if ($endlinenb && $i > $endlinenb) {
continue; continue;
}
$nboflines++; $nboflines++;
@ -170,16 +172,20 @@ while ($fields = $db->fetch_array($resql)) {
$object->address = trim($fields['FADR1']); $object->address = trim($fields['FADR1']);
if ($fields['FADR2']) if ($fields['FADR2']) {
$object->address .= "\n" . trim($fields['FADR2']); $object->address .= "\n" . trim($fields['FADR2']);
if ($fields['FADR3']) }
if ($fields['FADR3']) {
$object->address .= "\n" . trim($fields['FADR3']); $object->address .= "\n" . trim($fields['FADR3']);
}
$object->zip = trim($fields['FPOSTE']); $object->zip = trim($fields['FPOSTE']);
$object->town = trim($fields['FVILLE']); $object->town = trim($fields['FVILLE']);
if ($fields['FPAYS']) if ($fields['FPAYS']) {
$object->country_id = dol_getIdFromCode($db, trim(ucwords(strtolower($fields['FPAYS']))), 'c_country', 'label', 'rowid'); $object->country_id = dol_getIdFromCode($db, trim(ucwords(strtolower($fields['FPAYS']))), 'c_country', 'label', 'rowid');
else $object->country_id = 1; } else {
$object->country_id = 1;
}
$object->phone = trim($fields['FTEL']) ? trim($fields['FTEL']) : trim($fields['FCONTACT']); $object->phone = trim($fields['FTEL']) ? trim($fields['FTEL']) : trim($fields['FCONTACT']);
$object->phone = substr($object->phone, 0, 20); $object->phone = substr($object->phone, 0, 20);
$object->fax = trim($fields['FFAX']) ? trim($fields['FFAX']) : trim($fields['FCONTACT']); $object->fax = trim($fields['FFAX']) ? trim($fields['FFAX']) : trim($fields['FCONTACT']);
@ -289,16 +295,20 @@ while ($fields = $db->fetch_array($resql)) {
$contact->lastname = $fields['LCIVIL'] . " " . $fields['LNOM']; $contact->lastname = $fields['LCIVIL'] . " " . $fields['LNOM'];
} }
$contact->address = trim($fields['LADR1']); $contact->address = trim($fields['LADR1']);
if ($fields['LADR2']) if ($fields['LADR2']) {
$contact->address .= "\n" . trim($fields['LADR2']); $contact->address .= "\n" . trim($fields['LADR2']);
if ($fields['LADR3']) }
if ($fields['LADR3']) {
$contact->address .= "\n" . trim($fields['LADR3']); $contact->address .= "\n" . trim($fields['LADR3']);
}
$contact->zip = trim($fields['LPOSTE']); $contact->zip = trim($fields['LPOSTE']);
$contact->town = trim($fields['LVILLE']); $contact->town = trim($fields['LVILLE']);
if ($fields['FPAYS']) if ($fields['FPAYS']) {
$contact->country_id = dol_getIdFromCode($db, trim(ucwords(strtolower($fields['LPAYS']))), 'c_country', 'label', 'rowid'); $contact->country_id = dol_getIdFromCode($db, trim(ucwords(strtolower($fields['LPAYS']))), 'c_country', 'label', 'rowid');
else $contact->country_id = 1; } else {
$contact->country_id = 1;
}
$contact->email = $fields['LMAIL']; $contact->email = $fields['LMAIL'];
$contact->phone = trim($fields['LTEL']) ? trim($fields['LTEL']) : trim($fields['LCONTACT']); $contact->phone = trim($fields['LTEL']) ? trim($fields['LTEL']) : trim($fields['LCONTACT']);
$contact->fax = trim($fields['LFAX']) ? trim($fields['LFAX']) : trim($fields['LCONTACT']); $contact->fax = trim($fields['LFAX']) ? trim($fields['LFAX']) : trim($fields['LCONTACT']);
@ -338,7 +348,10 @@ while ($fields = $db->fetch_array($resql)) {
$error++; // $errorrecord will be reset $error++; // $errorrecord will be reset
} }
$j++; $j++;
} else die("error : $sql"); }
} else {
die("error : $sql");
}
$db->commit(); $db->commit();

View File

@ -25,27 +25,42 @@ class DBase
private $recordLength = 0; private $recordLength = 0;
private $recordCount = 0; private $recordCount = 0;
//resource dbase_open ( string $filename , int $mode ) /**
* resource dbase_open
* @param string $filename filename
* @param int $mode mode
* @return DBase
*/
public static function open($filename, $mode) public static function open($filename, $mode)
{ {
if (!file_exists($filename)) if (!file_exists($filename)) {
return false; return false;
}
$modes = array('r', 'w', 'r+'); $modes = array('r', 'w', 'r+');
$mode = $modes[$mode]; $mode = $modes[$mode];
$fd = fopen($filename, $mode); $fd = fopen($filename, $mode);
if (!$fd) if (!$fd) {
return false; return false;
}
return new DBase($fd); return new DBase($fd);
} }
//resource dbase_create ( string $filename , array $fields [, int $type = DBASE_TYPE_DBASE ] ) /**
* resource dbase_create
* @param string $filename filename
* @param array $fields fields
* @param int $type DBASE_TYPE_DBASE
* @return DBase
*/
public static function create($filename, $fields, $type = DBASE_TYPE_DBASE) public static function create($filename, $fields, $type = DBASE_TYPE_DBASE)
{ {
if (file_exists($filename)) if (file_exists($filename)) {
return false; return false;
}
$fd = fopen($filename, 'c+'); $fd = fopen($filename, 'c+');
if (!$fd) if (!$fd) {
return false; return false;
}
// Byte 0 (1 byte): Valid dBASE for DOS file; bits 0-2 indicate version number, bit 3 // Byte 0 (1 byte): Valid dBASE for DOS file; bits 0-2 indicate version number, bit 3
// indicates the presence of a dBASE for DOS memo file, bits 4-6 indicate the // indicates the presence of a dBASE for DOS memo file, bits 4-6 indicate the
// presence of a SQL table, bit 7 indicates the presence of any memo file // presence of a SQL table, bit 7 indicates the presence of any memo file
@ -62,8 +77,9 @@ class DBase
// Byte 10-11 (16-bit number): Number of bytes in record. // Byte 10-11 (16-bit number): Number of bytes in record.
// Make sure the include the byte for deleted flag // Make sure the include the byte for deleted flag
$len = 1; $len = 1;
foreach ($fields as &$field) foreach ($fields as &$field) {
$len += self::length($field); $len += self::length($field);
}
self::putInt16($fd, $len); self::putInt16($fd, $len);
// Byte 12-13 (2 bytes): Reserved, 0 filled. // Byte 12-13 (2 bytes): Reserved, 0 filled.
self::putInt16($fd, 0); self::putInt16($fd, 0);
@ -102,7 +118,11 @@ class DBase
return new DBase($fd); return new DBase($fd);
} }
// Create DBase instance /**
* Create DBase instance
* @param mixed $fd file descriptor
* @return void
*/
private function __construct($fd) private function __construct($fd)
{ {
$this->fd = $fd; $this->fd = $fd;
@ -126,75 +146,120 @@ class DBase
} }
} }
//bool dbase_close ( resource $dbase_identifier ) /**
* dbase_close
* @return void
*/
public function close() public function close()
{ {
fclose($this->fd); fclose($this->fd);
} }
//array dbase_get_header_info ( resource $dbase_identifier ) // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* dbase_get_header_info
* @return array
*/
public function get_header_info() public function get_header_info()
{ {
// phpcs:disable
return $this->fields; return $this->fields;
} }
//int dbase_numfields ( resource $dbase_identifier ) /**
* dbase_numfields
* @return int
*/
public function numfields() public function numfields()
{ {
return $this->fieldCount; return $this->fieldCount;
} }
//int dbase_numrecords ( resource $dbase_identifier ) /**
* dbase_numrecords
* @return int
*/
public function numrecords() public function numrecords()
{ {
return $this->recordCount; return $this->recordCount;
} }
//bool dbase_add_record ( resource $dbase_identifier , array $record ) // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* dbase_add_record
* @param array $record record
* @return bool
*/
public function add_record($record) public function add_record($record)
{ {
if (count($record) != $this->fieldCount) // phpcs:enable
if (count($record) != $this->fieldCount) {
return false; return false;
}
// Seek to end of file, minus the end of file marker // Seek to end of file, minus the end of file marker
fseek($this->fd, 0, SEEK_END); fseek($this->fd, 0, SEEK_END);
// Put the deleted flag // Put the deleted flag
self::putChar8($this->fd, 0x20); self::putChar8($this->fd, 0x20);
// Put the record // Put the record
if (!$this->putRecord($record)) if (!$this->putRecord($record)) {
return false; return false;
}
// Update the record count // Update the record count
fseek($this->fd, 4); fseek($this->fd, 4);
self::putInt32($this->fd, ++$this->recordCount); self::putInt32($this->fd, ++$this->recordCount);
return true; return true;
} }
//bool dbase_replace_record ( resource $dbase_identifier , array $record , int $record_number ) // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* dbase_replace_record
* @param array $record record
* @param int $record_number record number
* @return bool
*/
public function replace_record($record, $record_number) public function replace_record($record, $record_number)
{ {
if (count($record) != $this->fieldCount) // phpcs:enable
if (count($record) != $this->fieldCount) {
return false; return false;
if ($record_number < 1 || $record_number > $this->recordCount) }
if ($record_number < 1 || $record_number > $this->recordCount) {
return false; return false;
}
// Skip to the record location, plus the 1 byte for the deleted flag // Skip to the record location, plus the 1 byte for the deleted flag
fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1)) + 1); fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1)) + 1);
return $this->putRecord($record); return $this->putRecord($record);
} }
//bool dbase_delete_record ( resource $dbase_identifier , int $record_number ) // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* dbase_delete_record
* @param int $record_number record number
* @return bool
*/
public function delete_record($record_number) public function delete_record($record_number)
{ {
if ($record_number < 1 || $record_number > $this->recordCount) // phpcs:enable
if ($record_number < 1 || $record_number > $this->recordCount) {
return false; return false;
}
fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1))); fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1)));
self::putChar8($this->fd, 0x2A); self::putChar8($this->fd, 0x2A);
return true; return true;
} }
//array dbase_get_record ( resource $dbase_identifier , int $record_number ) // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* dbase_get_record
* @param int $record_number record number
* @return array
*/
public function get_record($record_number) public function get_record($record_number)
{ {
if ($record_number < 1 || $record_number > $this->recordCount) // phpcs:enable
if ($record_number < 1 || $record_number > $this->recordCount) {
return false; return false;
}
fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1))); fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1)));
$record = array( $record = array(
'deleted' => self::getChar8($this->fd) == 0x2A ? 1 : 0 'deleted' => self::getChar8($this->fd) == 0x2A ? 1 : 0
@ -203,22 +268,31 @@ class DBase
$value = trim(fread($this->fd, $field['length'])); $value = trim(fread($this->fd, $field['length']));
if ($field['type'] == 'L') { if ($field['type'] == 'L') {
$value = strtolower($value); $value = strtolower($value);
if ($value == 't' || $value == 'y') if ($value == 't' || $value == 'y') {
$value = true; $value = true;
elseif ($value == 'f' || $value == 'n') } elseif ($value == 'f' || $value == 'n') {
$value = false; $value = false;
else $value = null; } else {
$value = null;
}
} }
$record[$i] = $value; $record[$i] = $value;
} }
return $record; return $record;
} }
//array dbase_get_record_with_names ( resource $dbase_identifier , int $record_number ) // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* dbase_get_record_with_names
* @param int $record_number record number
* @return array
*/
public function get_record_with_names($record_number) public function get_record_with_names($record_number)
{ {
if ($record_number < 1 || $record_number > $this->recordCount) // phpcs:enable
if ($record_number < 1 || $record_number > $this->recordCount) {
return false; return false;
}
$record = $this->get_record($record_number); $record = $this->get_record($record_number);
foreach ($this->fields as $i => &$field) { foreach ($this->fields as $i => &$field) {
$record[$field['name']] = $record[$i]; $record[$field['name']] = $record[$i];
@ -227,7 +301,10 @@ class DBase
return $record; return $record;
} }
//bool dbase_pack ( resource $dbase_identifier ) /**
* dbase_pack
* @return void
*/
public function pack() public function pack()
{ {
$in_offset = $out_offset = $this->headerLength; $in_offset = $out_offset = $this->headerLength;
@ -256,6 +333,10 @@ class DBase
* A few utilitiy functions * A few utilitiy functions
*/ */
/**
* @param string $field field
* @return int
*/
private static function length($field) private static function length($field)
{ {
switch ($field[1]) { switch ($field[1]) {
@ -278,49 +359,100 @@ class DBase
* Functions for reading and writing bytes * Functions for reading and writing bytes
*/ */
/**
* getChar8
* @param mixed $fd file descriptor
* @return int
*/
private static function getChar8($fd) private static function getChar8($fd)
{ {
return ord(fread($fd, 1)); return ord(fread($fd, 1));
} }
/**
* putChar8
* @param mixed $fd file descriptor
* @param mixed $value value
* @return bool
*/
private static function putChar8($fd, $value) private static function putChar8($fd, $value)
{ {
return fwrite($fd, chr($value)); return fwrite($fd, chr($value));
} }
/**
* getInt16
* @param mixed $fd file descriptor
* @param int $n n
* @return bool
*/
private static function getInt16($fd, $n = 1) private static function getInt16($fd, $n = 1)
{ {
$data = fread($fd, 2 * $n); $data = fread($fd, 2 * $n);
$i = unpack("S$n", $data); $i = unpack("S$n", $data);
if ($n == 1) if ($n == 1) {
return (int) $i[1]; return (int) $i[1];
else return array_merge($i); } else {
return array_merge($i);
}
} }
/**
* putInt16
* @param mixed $fd file descriptor
* @param mixed $value value
* @return bool
*/
private static function putInt16($fd, $value) private static function putInt16($fd, $value)
{ {
return fwrite($fd, pack('S', $value)); return fwrite($fd, pack('S', $value));
} }
/**
* getInt32
* @param mixed $fd file descriptor
* @param int $n n
* @return bool
*/
private static function getInt32($fd, $n = 1) private static function getInt32($fd, $n = 1)
{ {
$data = fread($fd, 4 * $n); $data = fread($fd, 4 * $n);
$i = unpack("L$n", $data); $i = unpack("L$n", $data);
if ($n == 1) if ($n == 1) {
return (int) $i[1]; return (int) $i[1];
else return array_merge($i); } else {
return array_merge($i);
}
} }
/**
* putint32
* @param mixed $fd file descriptor
* @param mixed $value value
* @return bool
*/
private static function putInt32($fd, $value) private static function putInt32($fd, $value)
{ {
return fwrite($fd, pack('L', $value)); return fwrite($fd, pack('L', $value));
} }
/**
* putString
* @param mixed $fd file descriptor
* @param mixed $value value
* @param int $length length
* @return bool
*/
private static function putString($fd, $value, $length = 254) private static function putString($fd, $value, $length = 254)
{ {
$ret = fwrite($fd, pack('A' . $length, $value)); $ret = fwrite($fd, pack('A' . $length, $value));
} }
/**
* putRecord
* @param mixed $record record
* @return bool
*/
private function putRecord($record) private function putRecord($record)
{ {
foreach ($this->fields as $i => &$field) { foreach ($this->fields as $i => &$field) {
@ -336,62 +468,130 @@ class DBase
} }
if (!function_exists('dbase_open')) { if (!function_exists('dbase_open')) {
/**
* dbase_open
* @param string $filename filename
* @param int $mode mode
* @return DBase
*/
function dbase_open($filename, $mode) function dbase_open($filename, $mode)
{ {
return DBase::open($filename, $mode); return DBase::open($filename, $mode);
} }
/**
* dbase_create
* @param string $filename filename
* @param array $fields fields
* @param int $type type
* @return DBase
*/
function dbase_create($filename, $fields, $type = DBASE_TYPE_DBASE) function dbase_create($filename, $fields, $type = DBASE_TYPE_DBASE)
{ {
return DBase::create($filename, $fields, $type); return DBase::create($filename, $fields, $type);
} }
/**
* dbase_close
* @param Resource $dbase_identifier dbase identifier
* @return bool
*/
function dbase_close($dbase_identifier) function dbase_close($dbase_identifier)
{ {
return $dbase_identifier->close(); return $dbase_identifier->close();
} }
/**
* dbase_get_header_info
* @param Resource $dbase_identifier dbase identifier
* @return string
*/
function dbase_get_header_info($dbase_identifier) function dbase_get_header_info($dbase_identifier)
{ {
return $dbase_identifier->get_header_info(); return $dbase_identifier->get_header_info();
} }
/**
* dbase_numfields
* @param Resource $dbase_identifier dbase identifier
* @return int
*/
function dbase_numfields($dbase_identifier) function dbase_numfields($dbase_identifier)
{ {
$dbase_identifier->numfields(); $dbase_identifier->numfields();
} }
/**
* dbase_numrecords
* @param Resource $dbase_identifier dbase identifier
* @return int
*/
function dbase_numrecords($dbase_identifier) function dbase_numrecords($dbase_identifier)
{ {
return $dbase_identifier->numrecords(); return $dbase_identifier->numrecords();
} }
/**
* dbase_add_record
* @param Resource $dbase_identifier dbase identifier
* @param array $record record
* @return bool
*/
function dbase_add_record($dbase_identifier, $record) function dbase_add_record($dbase_identifier, $record)
{ {
return $dbase_identifier->add_record($record); return $dbase_identifier->add_record($record);
} }
/**
* dbase_delete_record
* @param Resource $dbase_identifier dbase identifier
* @param int $record_number record number
* @return bool
*/
function dbase_delete_record($dbase_identifier, $record_number) function dbase_delete_record($dbase_identifier, $record_number)
{ {
return $dbase_identifier->delete_record($record_number); return $dbase_identifier->delete_record($record_number);
} }
/**
* dbase_replace_record
* @param Resource $dbase_identifier dbase identifier
* @param array $record record
* @param int $record_number record number
* @return bool
*/
function dbase_replace_record($dbase_identifier, $record, $record_number) function dbase_replace_record($dbase_identifier, $record, $record_number)
{ {
return $dbase_identifier->replace_record($record, $record_number); return $dbase_identifier->replace_record($record, $record_number);
} }
/**
* dbase_get_record
* @param Resource $dbase_identifier dbase identifier
* @param int $record_number record number
* @return bool
*/
function dbase_get_record($dbase_identifier, $record_number) function dbase_get_record($dbase_identifier, $record_number)
{ {
return $dbase_identifier->get_record($record_number); return $dbase_identifier->get_record($record_number);
} }
/**
* dbase_get_record_with_names
* @param Resource $dbase_identifier dbase identifier
* @param int $record_number record number
* @return bool
*/
function dbase_get_record_with_names($dbase_identifier, $record_number) function dbase_get_record_with_names($dbase_identifier, $record_number)
{ {
return $dbase_identifier->get_record_with_names($record_number); return $dbase_identifier->get_record_with_names($record_number);
} }
/**
* dbase_pack
* @param Resource $dbase_identifier dbase identifier
* @return bool
*/
function dbase_pack($dbase_identifier) function dbase_pack($dbase_identifier)
{ {
return $dbase_identifier->pack(); return $dbase_identifier->pack();

View File

@ -100,8 +100,7 @@ $dates = array (mktime(12, 0, 0, 1, 3, $year),
); );
$ret=$user->fetch('', 'admin'); $ret=$user->fetch('', 'admin');
if (! $ret > 0) if (! $ret > 0) {
{
print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
exit; exit;
} }
@ -111,12 +110,10 @@ $user->getrights();
$socids = array(); $socids = array();
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE client in (1, 3)"; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE client in (1, 3)";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num_thirdparties = $db->num_rows($resql); $num_thirdparties = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num_thirdparties) while ($i < $num_thirdparties) {
{
$i++; $i++;
$row = $db->fetch_row($resql); $row = $db->fetch_row($resql);
$socids[$i] = $row[0]; $socids[$i] = $row[0];
@ -126,12 +123,10 @@ if ($resql)
$prodids = array(); $prodids = array();
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tosell=1"; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tosell=1";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num_prods = $db->num_rows($resql); $num_prods = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num_prods) while ($i < $num_prods) {
{
$i++; $i++;
$row = $db->fetch_row($resql); $row = $db->fetch_row($resql);
$prodids[$i] = $row[0]; $prodids[$i] = $row[0];
@ -140,8 +135,7 @@ if ($resql)
$i=0; $i=0;
$result=0; $result=0;
while ($i < GEN_NUMBER_FACTURE && $result >= 0) while ($i < GEN_NUMBER_FACTURE && $result >= 0) {
{
$i++; $i++;
$socid = mt_rand(1, $num_thirdparties); $socid = mt_rand(1, $num_thirdparties);
@ -158,26 +152,22 @@ while ($i < GEN_NUMBER_FACTURE && $result >= 0)
$fuser->getRights(); $fuser->getRights();
$result=$object->create($fuser); $result=$object->create($fuser);
if ($result >= 0) if ($result >= 0) {
{
$nbp = mt_rand(2, 5); $nbp = mt_rand(2, 5);
$xnbp = 0; $xnbp = 0;
while ($xnbp < $nbp) while ($xnbp < $nbp) {
{
$prodid = mt_rand(1, $num_prods); $prodid = mt_rand(1, $num_prods);
$product=new Product($db); $product=new Product($db);
$result=$product->fetch($prodids[$prodid]); $result=$product->fetch($prodids[$prodid]);
$result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0, '', '', 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type); $result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0, '', '', 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type);
if ($result < 0) if ($result < 0) {
{
dol_print_error($db, $propal->error); dol_print_error($db, $propal->error);
} }
$xnbp++; $xnbp++;
} }
$result=$object->validate($fuser); $result=$object->validate($fuser);
if ($result) if ($result) {
{
print " OK with ref ".$object->ref."\n";; print " OK with ref ".$object->ref."\n";;
} else { } else {
dol_print_error($db, $object->error); dol_print_error($db, $object->error);

View File

@ -106,8 +106,7 @@ $dates = array (mktime(12, 0, 0, 1, 3, $year),
); );
$ret=$user->fetch('', 'admin'); $ret=$user->fetch('', 'admin');
if ($ret <= 0) if ($ret <= 0) {
{
print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
exit; exit;
} }
@ -124,7 +123,9 @@ if ($resql) {
$row = $db->fetch_row($resql); $row = $db->fetch_row($resql);
$societesid[$i] = $row[0]; $societesid[$i] = $row[0];
} }
} else { print "err"; } } else {
print "err";
}
$commandesid = array(); $commandesid = array();
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande"; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande";
@ -137,7 +138,9 @@ if ($resql) {
$row = $db->fetch_row($resql); $row = $db->fetch_row($resql);
$commandesid[$i] = $row[0]; $commandesid[$i] = $row[0];
} }
} else { print "err"; } } else {
print "err";
}
$prodids = array(); $prodids = array();
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tosell=1"; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tosell=1";
@ -156,8 +159,7 @@ if ($resql) {
print "Build ".GEN_NUMBER_COMMANDE." orders\n"; print "Build ".GEN_NUMBER_COMMANDE." orders\n";
for ($s = 0 ; $s < GEN_NUMBER_COMMANDE ; $s++) for ($s = 0; $s < GEN_NUMBER_COMMANDE; $s++) {
{
print "Process order ".$s."\n"; print "Process order ".$s."\n";
$object = new Commande($db); $object = new Commande($db);
@ -182,26 +184,22 @@ for ($s = 0 ; $s < GEN_NUMBER_COMMANDE ; $s++)
$db->begin(); $db->begin();
$result=$object->create($fuser); $result=$object->create($fuser);
if ($result >= 0) if ($result >= 0) {
{
$nbp = mt_rand(2, 5); $nbp = mt_rand(2, 5);
$xnbp = 0; $xnbp = 0;
while ($xnbp < $nbp) while ($xnbp < $nbp) {
{
$prodid = mt_rand(1, $num_prods); $prodid = mt_rand(1, $num_prods);
$product=new Product($db); $product=new Product($db);
$result=$product->fetch($prodids[$prodid]); $result=$product->fetch($prodids[$prodid]);
$result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0, 0, 0, $product->price_base_type, $product->price_ttc, '', '', $product->type); $result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0, 0, 0, $product->price_base_type, $product->price_ttc, '', '', $product->type);
if ($result <= 0) if ($result <= 0) {
{
dol_print_error($db, $object->error); dol_print_error($db, $object->error);
} }
$xnbp++; $xnbp++;
} }
$result=$object->valid($fuser); $result=$object->valid($fuser);
if ($result > 0) if ($result > 0) {
{
$db->commit(); $db->commit();
print " OK with ref ".$object->ref."\n"; print " OK with ref ".$object->ref."\n";
} else { } else {

View File

@ -54,8 +54,7 @@ define(GEN_NUMBER_PRODUIT, 100000);
$ret=$user->fetch('', 'admin'); $ret=$user->fetch('', 'admin');
if (! $ret > 0) if (! $ret > 0) {
{
print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
exit; exit;
} }
@ -66,27 +65,36 @@ $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product"; $productsid = array();
$resql=$db->query($sql); $resql=$db->query($sql);
if ($resql) { if ($resql) {
$num = $db->num_rows($resql); $i = 0; $num = $db->num_rows($resql); $i = 0;
while ($i < $num) { $row = $db->fetch_row($resql); $productsid[$i] = $row[0]; $i++; } while ($i < $num) {
$row = $db->fetch_row($resql); $productsid[$i] = $row[0]; $i++;
}
} }
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe"; $societesid = array(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe"; $societesid = array();
$resql=$db->query($sql); $resql=$db->query($sql);
if ($resql) { if ($resql) {
$num = $db->num_rows($resql); $i = 0; $num = $db->num_rows($resql); $i = 0;
while ($i < $num) { $row = $db->fetch_row($resql); $societesid[$i] = $row[0]; $i++; } while ($i < $num) {
} else { print "err"; } $row = $db->fetch_row($resql); $societesid[$i] = $row[0]; $i++;
}
} else {
print "err";
}
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande"; $commandesid = array(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande"; $commandesid = array();
$resql=$db->query($sql); $resql=$db->query($sql);
if ($resql) { if ($resql) {
$num = $db->num_rows($resql); $i = 0; $num = $db->num_rows($resql); $i = 0;
while ($i < $num) { $row = $db->fetch_row($resql); $commandesid[$i] = $row[0]; $i++; } while ($i < $num) {
} else { print "err"; } $row = $db->fetch_row($resql); $commandesid[$i] = $row[0]; $i++;
}
} else {
print "err";
}
print "Generates ".GEN_NUMBER_PRODUIT." products\n"; print "Generates ".GEN_NUMBER_PRODUIT." products\n";
for ($s = 0 ; $s < GEN_NUMBER_PRODUIT ; $s++) for ($s = 0; $s < GEN_NUMBER_PRODUIT; $s++) {
{
print "Product ".$s; print "Product ".$s;
$produit = new Product($db); $produit = new Product($db);
$produit->type = mt_rand(0, 1); $produit->type = mt_rand(0, 1);
@ -97,6 +105,9 @@ for ($s = 0 ; $s < GEN_NUMBER_PRODUIT ; $s++)
$produit->price = mt_rand(1, 1000); $produit->price = mt_rand(1, 1000);
$produit->tva_tx = "19.6"; $produit->tva_tx = "19.6";
$ret=$produit->create($user); $ret=$produit->create($user);
if ($ret < 0) print "Error $ret - ".$produit->error."\n"; if ($ret < 0) {
else print " OK with ref ".$produit->ref."\n"; print "Error $ret - ".$produit->error."\n";
} else {
print " OK with ref ".$produit->ref."\n";
}
} }

View File

@ -102,8 +102,7 @@ $dates = array (mktime(12, 0, 0, 1, 3, $year),
); );
$ret=$user->fetch('', 'admin'); $ret=$user->fetch('', 'admin');
if (! $ret > 0) if (! $ret > 0) {
{
print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
exit; exit;
} }
@ -113,12 +112,10 @@ $user->getrights();
$socids = array(); $socids = array();
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE client in (1,3)"; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE client in (1,3)";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num_thirdparties = $db->num_rows($resql); $num_thirdparties = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num_thirdparties) while ($i < $num_thirdparties) {
{
$i++; $i++;
$row = $db->fetch_row($resql); $row = $db->fetch_row($resql);
$socids[$i] = $row[0]; $socids[$i] = $row[0];
@ -128,12 +125,10 @@ if ($resql)
$contids = array(); $contids = array();
$sql = "SELECT rowid, fk_soc FROM ".MAIN_DB_PREFIX."socpeople"; $sql = "SELECT rowid, fk_soc FROM ".MAIN_DB_PREFIX."socpeople";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num_conts = $db->num_rows($resql); $num_conts = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num_conts) while ($i < $num_conts) {
{
$i++; $i++;
$row = $db->fetch_row($resql); $row = $db->fetch_row($resql);
$contids[$row[1]][0] = $row[0]; // A ameliorer $contids[$row[1]][0] = $row[0]; // A ameliorer
@ -143,12 +138,10 @@ if ($resql)
$prodids = array(); $prodids = array();
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tosell=1"; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tosell=1";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num_prods = $db->num_rows($resql); $num_prods = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num_prods) while ($i < $num_prods) {
{
$i++; $i++;
$row = $db->fetch_row($resql); $row = $db->fetch_row($resql);
$prodids[$i] = $row[0]; $prodids[$i] = $row[0];
@ -159,15 +152,13 @@ $user->rights->propal->creer=1;
$user->rights->propal->propal_advance->validate=1; $user->rights->propal->propal_advance->validate=1;
if (! empty($conf->global->PROPALE_ADDON) && is_readable(DOL_DOCUMENT_ROOT ."/core/modules/propale/".$conf->global->PROPALE_ADDON.".php")) if (! empty($conf->global->PROPALE_ADDON) && is_readable(DOL_DOCUMENT_ROOT ."/core/modules/propale/".$conf->global->PROPALE_ADDON.".php")) {
{
require_once DOL_DOCUMENT_ROOT ."/core/modules/propale/".$conf->global->PROPALE_ADDON.".php"; require_once DOL_DOCUMENT_ROOT ."/core/modules/propale/".$conf->global->PROPALE_ADDON.".php";
} }
$i=0; $i=0;
$result=0; $result=0;
while ($i < GEN_NUMBER_PROPAL && $result >= 0) while ($i < GEN_NUMBER_PROPAL && $result >= 0) {
{
$i++; $i++;
$socid = mt_rand(1, $num_thirdparties); $socid = mt_rand(1, $num_thirdparties);
print "Proposal ".$i." for socid ".$socid; print "Proposal ".$i." for socid ".$socid;
@ -188,26 +179,22 @@ while ($i < GEN_NUMBER_PROPAL && $result >= 0)
$object->mode_reglement_id = 3; $object->mode_reglement_id = 3;
$result=$object->create($fuser); $result=$object->create($fuser);
if ($result >= 0) if ($result >= 0) {
{
$nbp = mt_rand(2, 5); $nbp = mt_rand(2, 5);
$xnbp = 0; $xnbp = 0;
while ($xnbp < $nbp) while ($xnbp < $nbp) {
{
$prodid = mt_rand(1, $num_prods); $prodid = mt_rand(1, $num_prods);
$product=new Product($db); $product=new Product($db);
$result=$product->fetch($prodids[$prodid]); $result=$product->fetch($prodids[$prodid]);
$result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0); $result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0);
if ($result < 0) if ($result < 0) {
{
dol_print_error($db, $object->error); dol_print_error($db, $object->error);
} }
$xnbp++; $xnbp++;
} }
$result=$object->valid($fuser); $result=$object->valid($fuser);
if ($result > 0) if ($result > 0) {
{
$db->commit(); $db->commit();
print " OK with ref ".$object->ref."\n"; print " OK with ref ".$object->ref."\n";
} else { } else {

View File

@ -57,8 +57,7 @@ define(GEN_NUMBER_SOCIETE, 10);
$ret=$user->fetch('', 'admin'); $ret=$user->fetch('', 'admin');
if (! $ret > 0) if (! $ret > 0) {
{
print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
exit; exit;
} }
@ -85,7 +84,9 @@ if ($resql) {
$societesid[$i] = $row[0]; $societesid[$i] = $row[0];
$i++; $i++;
} }
} else { print "err"; } } else {
print "err";
}
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande"; $commandesid = array(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande"; $commandesid = array();
$resql=$db->query($sql); $resql=$db->query($sql);
@ -96,13 +97,14 @@ if ($resql) {
$commandesid[$i] = $row[0]; $commandesid[$i] = $row[0];
$i++; $i++;
} }
} else { print "err"; } } else {
print "err";
}
print "Generates ".GEN_NUMBER_SOCIETE." companies\n"; print "Generates ".GEN_NUMBER_SOCIETE." companies\n";
for ($s = 0 ; $s < GEN_NUMBER_SOCIETE ; $s++) for ($s = 0; $s < GEN_NUMBER_SOCIETE; $s++) {
{
print "Company $s\n"; print "Company $s\n";
$soc = new Societe($db); $soc = new Societe($db);
$soc->name = "Company num ".time()."$s"; $soc->name = "Company num ".time()."$s";
@ -115,23 +117,22 @@ for ($s = 0 ; $s < GEN_NUMBER_SOCIETE ; $s++)
$soc->country_id=1; $soc->country_id=1;
$soc->country_code='FR'; $soc->country_code='FR';
// Un client sur 3 a une remise de 5% // Un client sur 3 a une remise de 5%
$user_remise=mt_rand(1, 3); if ($user_remise==3) $soc->remise_percent=5; $user_remise=mt_rand(1, 3); if ($user_remise==3) {
$soc->remise_percent=5;
}
print "> client=".$soc->client.", fournisseur=".$soc->fournisseur.", remise=".$soc->remise_percent."\n"; print "> client=".$soc->client.", fournisseur=".$soc->fournisseur.", remise=".$soc->remise_percent."\n";
$soc->note_private = 'Company created by the script generate-societe.php'; $soc->note_private = 'Company created by the script generate-societe.php';
$socid = $soc->create(); $socid = $soc->create();
if ($socid >= 0) if ($socid >= 0) {
{
$rand = mt_rand(1, 4); $rand = mt_rand(1, 4);
print "> Generates $rand contact(s)\n"; print "> Generates $rand contact(s)\n";
for ($c = 0 ; $c < $rand ; $c++) for ($c = 0; $c < $rand; $c++) {
{
$contact = new Contact($db); $contact = new Contact($db);
$contact->socid = $soc->id; $contact->socid = $soc->id;
$contact->lastname = "Lastname".$c; $contact->lastname = "Lastname".$c;
$contact->firstname = $listoflastname[mt_rand(0, count($listoflastname)-1)]; $contact->firstname = $listoflastname[mt_rand(0, count($listoflastname)-1)];
if ( $contact->create($user) ) if ($contact->create($user)) {
{
} }
} }

View File

@ -79,30 +79,26 @@ if (! file_exists($filepath)) {
} }
$ret=$user->fetch('', 'admin'); $ret=$user->fetch('', 'admin');
if (! $ret > 0) if (! $ret > 0) {
{
print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
exit; exit;
} }
$user->getrights(); $user->getrights();
// Ask confirmation // Ask confirmation
if (! $confirmed) if (! $confirmed) {
{
print "Hit Enter to continue or CTRL+C to stop...\n"; print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN)); $input = trim(fgets(STDIN));
} }
// Open input and output files // Open input and output files
$fhandle = fopen($filepath, 'r'); $fhandle = fopen($filepath, 'r');
if (! $fhandle) if (! $fhandle) {
{
print 'Error: Failed to open file '.$filepath."\n"; print 'Error: Failed to open file '.$filepath."\n";
exit(1); exit(1);
} }
$fhandleerr = fopen($filepatherr, 'w'); $fhandleerr = fopen($filepatherr, 'w');
if (! $fhandleerr) if (! $fhandleerr) {
{
print 'Error: Failed to open file '.$filepatherr."\n"; print 'Error: Failed to open file '.$filepatherr."\n";
exit(1); exit(1);
} }
@ -114,13 +110,16 @@ $db->begin();
$i=0; $i=0;
$nboflines++; $nboflines++;
while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) {
{
$i++; $i++;
$errorrecord=0; $errorrecord=0;
if ($startlinenb && $i < $startlinenb) continue; if ($startlinenb && $i < $startlinenb) {
if ($endlinenb && $i > $endlinenb) continue; continue;
}
if ($endlinenb && $i > $endlinenb) {
continue;
}
$nboflines++; $nboflines++;
@ -159,8 +158,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
$produit->array_options['options_ecotaxdeee']=price2num($fields[17]); $produit->array_options['options_ecotaxdeee']=price2num($fields[17]);
$ret=$produit->create($user); $ret=$produit->create($user);
if ($ret < 0) if ($ret < 0) {
{
print " - Error in create result code = ".$ret." - ".$produit->errorsToString(); print " - Error in create result code = ".$ret." - ".$produit->errorsToString();
$errorrecord++; $errorrecord++;
} else { } else {
@ -170,12 +168,10 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
dol_syslog("Add prices"); dol_syslog("Add prices");
// If we use price level, insert price for each level // If we use price level, insert price for each level
if (! $errorrecord && 1) if (! $errorrecord && 1) {
{
$ret1=$produit->updatePrice($produit->price_ttc, $produit->price_base_type, $user, $produit->tva_tx, $produit->price_min, 1, $produit->tva_npr, 0, 0, array()); $ret1=$produit->updatePrice($produit->price_ttc, $produit->price_base_type, $user, $produit->tva_tx, $produit->price_min, 1, $produit->tva_npr, 0, 0, array());
$ret2=$produit->updatePrice(price2num($fields[14]), 'HT', $user, $produit->tva_tx, $produit->price_min, 2, $produit->tva_npr, 0, 0, array()); $ret2=$produit->updatePrice(price2num($fields[14]), 'HT', $user, $produit->tva_tx, $produit->price_min, 2, $produit->tva_npr, 0, 0, array());
if ($ret1 < 0 || $ret2 < 0) if ($ret1 < 0 || $ret2 < 0) {
{
print " - Error in updatePrice result code = ".$ret1." ".$ret2." - ".$produit->errorsToString(); print " - Error in updatePrice result code = ".$ret1." ".$ret2." - ".$produit->errorsToString();
$errorrecord++; $errorrecord++;
} else { } else {
@ -186,14 +182,12 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
dol_syslog("Add multilangs"); dol_syslog("Add multilangs");
// Add alternative languages // Add alternative languages
if (! $errorrecord && 1) if (! $errorrecord && 1) {
{
$produit->multilangs['fr_FR']=array('label'=>$produit->label, 'description'=>$produit->description, 'note'=>$produit->note_private); $produit->multilangs['fr_FR']=array('label'=>$produit->label, 'description'=>$produit->description, 'note'=>$produit->note_private);
$produit->multilangs['en_US']=array('label'=>$fields[3], 'description'=>$produit->description, 'note'=>$produit->note_private); $produit->multilangs['en_US']=array('label'=>$fields[3], 'description'=>$produit->description, 'note'=>$produit->note_private);
$ret=$produit->setMultiLangs($user); $ret=$produit->setMultiLangs($user);
if ($ret < 0) if ($ret < 0) {
{
print " - Error in setMultiLangs result code = ".$ret." - ".$produit->errorsToString(); print " - Error in setMultiLangs result code = ".$ret." - ".$produit->errorsToString();
$errorrecord++; $errorrecord++;
} else { } else {
@ -203,8 +197,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
print "\n"; print "\n";
if ($errorrecord) if ($errorrecord) {
{
fwrite($fhandleerr, 'Error on record nb '.$i." - ".$produit->errorsToString()."\n"); fwrite($fhandleerr, 'Error on record nb '.$i." - ".$produit->errorsToString()."\n");
$error++; // $errorrecord will be reset $error++; // $errorrecord will be reset
} }
@ -217,8 +210,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
// commit or rollback // commit or rollback
print "Nb of lines qualified: ".$nboflines."\n"; print "Nb of lines qualified: ".$nboflines."\n";
print "Nb of errors: ".$error."\n"; print "Nb of errors: ".$error."\n";
if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) {
{
print "Rollback any changes.\n"; print "Rollback any changes.\n";
$db->rollback(); $db->rollback();
} else { } else {

View File

@ -79,30 +79,26 @@ if (! file_exists($filepath)) {
} }
$ret=$user->fetch('', 'admin'); $ret=$user->fetch('', 'admin');
if (! $ret > 0) if (! $ret > 0) {
{
print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
exit; exit;
} }
$user->getrights(); $user->getrights();
// Ask confirmation // Ask confirmation
if (! $confirmed) if (! $confirmed) {
{
print "Hit Enter to continue or CTRL+C to stop...\n"; print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN)); $input = trim(fgets(STDIN));
} }
// Open input and output files // Open input and output files
$fhandle = fopen($filepath, 'r'); $fhandle = fopen($filepath, 'r');
if (! $fhandle) if (! $fhandle) {
{
print 'Error: Failed to open file '.$filepath."\n"; print 'Error: Failed to open file '.$filepath."\n";
exit(1); exit(1);
} }
$fhandleerr = fopen($filepatherr, 'w'); $fhandleerr = fopen($filepatherr, 'w');
if (! $fhandleerr) if (! $fhandleerr) {
{
print 'Error: Failed to open file '.$filepatherr."\n"; print 'Error: Failed to open file '.$filepatherr."\n";
exit(1); exit(1);
} }
@ -114,13 +110,16 @@ $db->begin();
$i=0; $i=0;
$nboflines=0; $nboflines=0;
while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) {
{
$i++; $i++;
$errorrecord=0; $errorrecord=0;
if ($startlinenb && $i < $startlinenb) continue; if ($startlinenb && $i < $startlinenb) {
if ($endlinenb && $i > $endlinenb) continue; continue;
}
if ($endlinenb && $i > $endlinenb) {
continue;
}
$nboflines++; $nboflines++;
@ -144,14 +143,16 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
$object->default_lang = trim($fields[43]); $object->default_lang = trim($fields[43]);
//$condpayment = dol_string_unaccent(trim($fields[36])); //$condpayment = dol_string_unaccent(trim($fields[36]));
if ($fields[36]) if ($fields[36]) {
{
$condpayment = trim($fields[36]); $condpayment = trim($fields[36]);
if ($condpayment == 'A la commande') $condpayment = 'A réception de commande'; if ($condpayment == 'A la commande') {
if ($condpayment == 'A reception facture') $condpayment = 'Réception de facture'; $condpayment = 'A réception de commande';
}
if ($condpayment == 'A reception facture') {
$condpayment = 'Réception de facture';
}
$object->cond_reglement_id = dol_getIdFromCode($db, $condpayment, 'c_payment_term', 'libelle_facture', 'rowid', 1); $object->cond_reglement_id = dol_getIdFromCode($db, $condpayment, 'c_payment_term', 'libelle_facture', 'rowid', 1);
if (empty($object->cond_reglement_id)) if (empty($object->cond_reglement_id)) {
{
print " - Error cant find payment mode for ".$condpayment."\n"; print " - Error cant find payment mode for ".$condpayment."\n";
$errorrecord++; $errorrecord++;
} }
@ -165,7 +166,9 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
// Set price level // Set price level
$object->price_level = 1; $object->price_level = 1;
if ($labeltype == 'Revendeur') $object->price_level = 2; if ($labeltype == 'Revendeur') {
$object->price_level = 2;
}
print "Process line nb ".$i.", name ".$object->name; print "Process line nb ".$i.", name ".$object->name;
@ -174,11 +177,9 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
$object->array_options['options_anastate']=price2num($fields[20]); $object->array_options['options_anastate']=price2num($fields[20]);
$object->array_options['options_anaregion']=price2num($fields[17]); $object->array_options['options_anaregion']=price2num($fields[17]);
if (! $errorrecord) if (! $errorrecord) {
{
$ret=$object->create($user); $ret=$object->create($user);
if ($ret < 0) if ($ret < 0) {
{
print " - Error in create result code = ".$ret." - ".$object->errorsToString(); print " - Error in create result code = ".$ret." - ".$object->errorsToString();
$errorrecord++; $errorrecord++;
} else { } else {
@ -186,28 +187,28 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
} }
} }
if (! $errorrecord) if (! $errorrecord) {
{
dol_syslog("Set price level"); dol_syslog("Set price level");
$object->set_price_level($object->price_level, $user); $object->set_price_level($object->price_level, $user);
} }
// Assign sales representative // Assign sales representative
if (! $errorrecord && $fields[3]) if (! $errorrecord && $fields[3]) {
{
$salesrep=new User($db); $salesrep=new User($db);
$tmp=explode(' ', $fields[3], 2); $tmp=explode(' ', $fields[3], 2);
$salesrep->firstname = trim($tmp[0]); $salesrep->firstname = trim($tmp[0]);
$salesrep->lastname = trim($tmp[1]); $salesrep->lastname = trim($tmp[1]);
if ($salesrep->lastname) $salesrep->login = strtolower(substr($salesrep->firstname, 0, 1)) . strtolower(substr($salesrep->lastname, 0)); if ($salesrep->lastname) {
else $salesrep->login=strtolower($salesrep->firstname); $salesrep->login = strtolower(substr($salesrep->firstname, 0, 1)) . strtolower(substr($salesrep->lastname, 0));
} else {
$salesrep->login=strtolower($salesrep->firstname);
}
$salesrep->login=preg_replace('/ /', '', $salesrep->login); $salesrep->login=preg_replace('/ /', '', $salesrep->login);
$salesrep->fetch(0, $salesrep->login); $salesrep->fetch(0, $salesrep->login);
$result = $object->add_commercial($user, $salesrep->id); $result = $object->add_commercial($user, $salesrep->id);
if ($result < 0) if ($result < 0) {
{
print " - Error in create link with sale representative result code = ".$result." - ".$object->errorsToString(); print " - Error in create link with sale representative result code = ".$result." - ".$object->errorsToString();
$errorrecord++; $errorrecord++;
} else { } else {
@ -217,8 +218,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
dol_syslog("Add invoice contacts"); dol_syslog("Add invoice contacts");
// Insert an invoice contact if there is an invoice email != standard email // Insert an invoice contact if there is an invoice email != standard email
if (! $errorrecord && $fields[27] && $fields[26] != $fields[27]) if (! $errorrecord && $fields[27] && $fields[26] != $fields[27]) {
{
$ret1=$ret2=0; $ret1=$ret2=0;
$contact = new Contact($db); $contact = new Contact($db);
@ -231,12 +231,10 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
$contact->socid=$object->id; $contact->socid=$object->id;
$ret1=$contact->create($user); $ret1=$contact->create($user);
if ($ret1 > 0) if ($ret1 > 0) {
{
//$ret2=$contact->add_contact($object->id, 'BILLING'); //$ret2=$contact->add_contact($object->id, 'BILLING');
} }
if ($ret1 < 0 || $ret2 < 0) if ($ret1 < 0 || $ret2 < 0) {
{
print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString(); print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString();
$errorrecord++; $errorrecord++;
} else { } else {
@ -246,8 +244,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
dol_syslog("Add delivery contacts"); dol_syslog("Add delivery contacts");
// Insert a delivery contact // Insert a delivery contact
if (! $errorrecord && $fields[47]) if (! $errorrecord && $fields[47]) {
{
$ret1=$ret2=0; $ret1=$ret2=0;
$contact2 = new Contact($db); $contact2 = new Contact($db);
@ -263,12 +260,10 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
$contact2->array_options['options_anazoneliv']=price2num($fields[53]); $contact2->array_options['options_anazoneliv']=price2num($fields[53]);
$ret1=$contact2->create($user); $ret1=$contact2->create($user);
if ($ret1 > 0) if ($ret1 > 0) {
{
//$ret2=$contact2->add_contact($object->id, 'SHIPPING'); //$ret2=$contact2->add_contact($object->id, 'SHIPPING');
} }
if ($ret1 < 0 || $ret2 < 0) if ($ret1 < 0 || $ret2 < 0) {
{
print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString(); print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString();
$errorrecord++; $errorrecord++;
} else { } else {
@ -279,8 +274,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
print "\n"; print "\n";
if ($errorrecord) if ($errorrecord) {
{
fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n"); fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n");
$error++; // $errorrecord will be reset $error++; // $errorrecord will be reset
} }
@ -293,8 +287,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
// commit or rollback // commit or rollback
print "Nb of lines qualified: ".$nboflines."\n"; print "Nb of lines qualified: ".$nboflines."\n";
print "Nb of errors: ".$error."\n"; print "Nb of errors: ".$error."\n";
if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) {
{
print "Rollback any changes.\n"; print "Rollback any changes.\n";
$db->rollback(); $db->rollback();
} else { } else {

View File

@ -79,30 +79,26 @@ if (! file_exists($filepath)) {
} }
$ret=$user->fetch('', 'admin'); $ret=$user->fetch('', 'admin');
if (! $ret > 0) if (! $ret > 0) {
{
print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
exit; exit;
} }
$user->getrights(); $user->getrights();
// Ask confirmation // Ask confirmation
if (! $confirmed) if (! $confirmed) {
{
print "Hit Enter to continue or CTRL+C to stop...\n"; print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN)); $input = trim(fgets(STDIN));
} }
// Open input and output files // Open input and output files
$fhandle = fopen($filepath, 'r'); $fhandle = fopen($filepath, 'r');
if (! $fhandle) if (! $fhandle) {
{
print 'Error: Failed to open file '.$filepath."\n"; print 'Error: Failed to open file '.$filepath."\n";
exit(1); exit(1);
} }
$fhandleerr = fopen($filepatherr, 'w'); $fhandleerr = fopen($filepatherr, 'w');
if (! $fhandleerr) if (! $fhandleerr) {
{
print 'Error: Failed to open file '.$filepatherr."\n"; print 'Error: Failed to open file '.$filepatherr."\n";
exit(1); exit(1);
} }
@ -114,13 +110,16 @@ $db->begin();
$i=0; $i=0;
$nboflines=0; $nboflines=0;
while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) {
{
$i++; $i++;
$errorrecord=0; $errorrecord=0;
if ($startlinenb && $i < $startlinenb) continue; if ($startlinenb && $i < $startlinenb) {
if ($endlinenb && $i > $endlinenb) continue; continue;
}
if ($endlinenb && $i > $endlinenb) {
continue;
}
$nboflines++; $nboflines++;
@ -130,16 +129,18 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
$tmp=explode(' ', $fields[3], 2); $tmp=explode(' ', $fields[3], 2);
$object->firstname = trim($tmp[0]); $object->firstname = trim($tmp[0]);
$object->lastname = trim($tmp[1]); $object->lastname = trim($tmp[1]);
if ($object->lastname) $object->login = strtolower(substr($object->firstname, 0, 1)) . strtolower(substr($object->lastname, 0)); if ($object->lastname) {
else $object->login=strtolower($object->firstname); $object->login = strtolower(substr($object->firstname, 0, 1)) . strtolower(substr($object->lastname, 0));
} else {
$object->login=strtolower($object->firstname);
}
$object->login=preg_replace('/ /', '', $object->login); $object->login=preg_replace('/ /', '', $object->login);
$object->password = 'init'; $object->password = 'init';
print "Process line nb ".$i.", login ".$object->login; print "Process line nb ".$i.", login ".$object->login;
$ret=$object->create($user); $ret=$object->create($user);
if ($ret < 0) if ($ret < 0) {
{
print " - Error in create result code = ".$ret." - ".$object->errorsToString(); print " - Error in create result code = ".$ret." - ".$object->errorsToString();
$errorrecord++; $errorrecord++;
} else { } else {
@ -148,8 +149,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
print "\n"; print "\n";
if ($errorrecord) if ($errorrecord) {
{
fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n"); fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n");
$error++; // $errorrecord will be reset $error++; // $errorrecord will be reset
} }
@ -162,8 +162,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
// commit or rollback // commit or rollback
print "Nb of lines qualified: ".$nboflines."\n"; print "Nb of lines qualified: ".$nboflines."\n";
print "Nb of errors: ".$error."\n"; print "Nb of errors: ".$error."\n";
if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) {
{
print "Rollback any changes.\n"; print "Rollback any changes.\n";
$db->rollback(); $db->rollback();
} else { } else {

View File

@ -188,18 +188,15 @@ if (empty($mode) || ! in_array($mode, array('test','confirm'))) {
print "option can be ".implode(',', array_keys($sqls))."\n"; print "option can be ".implode(',', array_keys($sqls))."\n";
exit(-1); exit(-1);
} }
if (empty($option)) if (empty($option)) {
{
print "Usage: $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; print "Usage: $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n";
print "\n"; print "\n";
print "option must be defined with a value in list ".implode(',', array_keys($sqls))."\n"; print "option must be defined with a value in list ".implode(',', array_keys($sqls))."\n";
exit(-1); exit(-1);
} }
if ($option != 'all') if ($option != 'all') {
{
$listofoptions=explode(',', $option); $listofoptions=explode(',', $option);
foreach ($listofoptions as $cursoroption) foreach ($listofoptions as $cursoroption) {
{
if (! in_array($cursoroption, array_keys($sqls))) { if (! in_array($cursoroption, array_keys($sqls))) {
print "Usage: $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; print "Usage: $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n";
print "\n"; print "\n";
@ -216,11 +213,12 @@ if (empty($date) || (! preg_match('/\d\d\d\d\-\d\d\-\d\d$/', $date) && $date !=
exit(-1); exit(-1);
} }
if ($date == 'all') $date = '2199-01-01'; if ($date == 'all') {
$date = '2199-01-01';
}
// Replace database handler // Replace database handler
if (! empty($argv[4])) if (! empty($argv[4])) {
{
$db->close(); $db->close();
unset($db); unset($db);
$db=getDoliDBInstance($argv[4], $argv[5], $argv[6], $argv[7], $argv[8], $argv[9]); $db=getDoliDBInstance($argv[4], $argv[5], $argv[6], $argv[7], $argv[8], $argv[9]);
@ -229,8 +227,7 @@ if (! empty($argv[4]))
//var_dump($user->db->database_name); //var_dump($user->db->database_name);
$ret=$user->fetch('', 'admin'); $ret=$user->fetch('', 'admin');
if (! $ret > 0) if (! $ret > 0) {
{
print 'An admin user with login "admin" must exists to use this script.'."\n"; print 'An admin user with login "admin" must exists to use this script.'."\n";
exit; exit;
} }
@ -245,8 +242,7 @@ print "Database port = ".$db->database_port."\n";
print "User = ".$db->database_user."\n"; print "User = ".$db->database_user."\n";
print "\n"; print "\n";
if (! $confirmed) if (! $confirmed) {
{
print "Hit Enter to continue or CTRL+C to stop...\n"; print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN)); $input = trim(fgets(STDIN));
} }
@ -264,10 +260,8 @@ function processfamily($family, $date)
global $db, $sqls; global $db, $sqls;
$error=0; $error=0;
foreach ($sqls[$family] as $sql) foreach ($sqls[$family] as $sql) {
{ if (preg_match('/^@/', $sql)) {
if (preg_match('/^@/', $sql))
{
$newfamily=preg_replace('/@/', '', $sql); $newfamily=preg_replace('/@/', '', $sql);
processfamily($newfamily, $date); processfamily($newfamily, $date);
continue; continue;
@ -278,51 +272,51 @@ function processfamily($family, $date)
print "Run sql: ".$sql."\n"; print "Run sql: ".$sql."\n";
$resql=$db->query($sql); $resql=$db->query($sql);
if (! $resql) if (! $resql) {
{ if ($db->errno() != 'DB_ERROR_NOSUCHTABLE') {
if ($db->errno() != 'DB_ERROR_NOSUCHTABLE')
{
$error++; $error++;
} }
} }
if ($error) if ($error) {
{
print $db->lasterror(); print $db->lasterror();
$error++; $error++;
break; break;
} }
} }
if ($error) return -1; if ($error) {
else return 1; return -1;
} else {
return 1;
}
} }
$db->begin(); $db->begin();
$listofoptions=explode(',', $option); $listofoptions=explode(',', $option);
foreach ($listofoptions as $cursoroption) foreach ($listofoptions as $cursoroption) {
{
$oldfamily=''; $oldfamily='';
foreach ($sqls as $family => $familysql) foreach ($sqls as $family => $familysql) {
{ if ($cursoroption && $cursoroption != 'all' && $cursoroption != $family) {
if ($cursoroption && $cursoroption != 'all' && $cursoroption != $family) continue; continue;
}
if ($family != $oldfamily) print "Process action for family ".$family."\n"; if ($family != $oldfamily) {
print "Process action for family ".$family."\n";
}
$oldfamily = $family; $oldfamily = $family;
$result=processfamily($family, $date); $result=processfamily($family, $date);
if ($result < 0) if ($result < 0) {
{
$error++; $error++;
break; break;
} }
} }
} }
if ($error || $mode != 'confirm') if ($error || $mode != 'confirm') {
{
print "\nRollback any changes.\n"; print "\nRollback any changes.\n";
$db->rollback(); $db->rollback();
} else { } else {

View File

@ -41,14 +41,30 @@ $passwordbase=isset($argv[6])?$argv[6]:'';
// Include Dolibarr environment // Include Dolibarr environment
$res=0; $res=0;
if (! $res && file_exists($path."../../master.inc.php")) $res=@include $path."../../master.inc.php"; if (! $res && file_exists($path."../../master.inc.php")) {
if (! $res && file_exists($path."../../htdocs/master.inc.php")) $res=@include $path."../../htdocs/master.inc.php"; $res=@include $path."../../master.inc.php";
if (! $res && file_exists("../master.inc.php")) $res=@include "../master.inc.php"; }
if (! $res && file_exists("../../master.inc.php")) $res=@include "../../master.inc.php"; if (! $res && file_exists($path."../../htdocs/master.inc.php")) {
if (! $res && file_exists("../../../master.inc.php")) $res=@include "../../../master.inc.php"; $res=@include $path."../../htdocs/master.inc.php";
if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) $res=@include $path."../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only }
if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) $res=@include "../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only if (! $res && file_exists("../master.inc.php")) {
if (! $res) die("Failed to include master.inc.php file\n"); $res=@include "../master.inc.php";
}
if (! $res && file_exists("../../master.inc.php")) {
$res=@include "../../master.inc.php";
}
if (! $res && file_exists("../../../master.inc.php")) {
$res=@include "../../../master.inc.php";
}
if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) {
$res=@include $path."../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only
}
if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) {
$res=@include "../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only
}
if (! $res) {
die("Failed to include master.inc.php file\n");
}
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
@ -58,15 +74,13 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$login=''; $login='';
$server=''; $server='';
if (preg_match('/^(.*)@(.*):(.*)$/', $sourceserver, $reg)) if (preg_match('/^(.*)@(.*):(.*)$/', $sourceserver, $reg)) {
{
$login=$reg[1]; $login=$reg[1];
$server=$reg[2]; $server=$reg[2];
$sourcefile=$reg[3]; $sourcefile=$reg[3];
$targetfile=basename($sourcefile); $targetfile=basename($sourcefile);
} }
if (empty($sourceserver) || empty($server) || empty($login) || empty($sourcefile) || empty($password) || empty($database) || empty($loginbase) || empty($passwordbase)) if (empty($sourceserver) || empty($server) || empty($login) || empty($sourcefile) || empty($password) || empty($database) || empty($loginbase) || empty($passwordbase)) {
{
print "Usage: $script_file login@server:/src/file.(sql|gz|bz2) passssh databaseserver databasename loginbase passbase\n"; print "Usage: $script_file login@server:/src/file.(sql|gz|bz2) passssh databaseserver databasename loginbase passbase\n";
print "Return code: 0 if success, <>0 if error\n"; print "Return code: 0 if success, <>0 if error\n";
print "Warning, this script may take a long time.\n"; print "Warning, this script may take a long time.\n";
@ -88,14 +102,11 @@ if (! function_exists("ssh2_connect")) {
} }
$connection = ssh2_connect($server, 22); $connection = ssh2_connect($server, 22);
if ($connection) if ($connection) {
{ if (! @ssh2_auth_password($connection, $login, $password)) {
if (! @ssh2_auth_password($connection, $login, $password))
{
dol_syslog("Could not authenticate with username ".$login." . and password ".preg_replace('/./', '*', $password), LOG_ERR); dol_syslog("Could not authenticate with username ".$login." . and password ".preg_replace('/./', '*', $password), LOG_ERR);
exit(-5); exit(-5);
} } else {
else {
//$stream = ssh2_exec($connection, '/usr/bin/php -i'); //$stream = ssh2_exec($connection, '/usr/bin/php -i');
/* /*
print "Generate dump ".$filesys1.'.bz2'."\n"; print "Generate dump ".$filesys1.'.bz2'."\n";
@ -111,12 +122,10 @@ if ($connection)
ssh2_scp_recv($connection, $sourcefile, $targetdir.$targetfile); ssh2_scp_recv($connection, $sourcefile, $targetdir.$targetfile);
$fullcommand="cat ".$targetdir.$targetfile." | mysql -h".$databaseserver." -u".$loginbase." -p".$passwordbase." -D ".$database; $fullcommand="cat ".$targetdir.$targetfile." | mysql -h".$databaseserver." -u".$loginbase." -p".$passwordbase." -D ".$database;
if (preg_match('/\.bz2$/', $targetfile)) if (preg_match('/\.bz2$/', $targetfile)) {
{
$fullcommand="bzip2 -c -d ".$targetdir.$targetfile." | mysql -h".$databaseserver." -u".$loginbase." -p".$passwordbase." -D ".$database; $fullcommand="bzip2 -c -d ".$targetdir.$targetfile." | mysql -h".$databaseserver." -u".$loginbase." -p".$passwordbase." -D ".$database;
} }
if (preg_match('/\.gz$/', $targetfile)) if (preg_match('/\.gz$/', $targetfile)) {
{
$fullcommand="gzip -d ".$targetdir.$targetfile." | mysql -h".$databaseserver." -u".$loginbase." -p".$passwordbase." -D ".$database; $fullcommand="gzip -d ".$targetdir.$targetfile." | mysql -h".$databaseserver." -u".$loginbase." -p".$passwordbase." -D ".$database;
} }
print "Load dump with ".$fullcommand."\n"; print "Load dump with ".$fullcommand."\n";
@ -124,13 +133,14 @@ if ($connection)
$return_var=0; $return_var=0;
print strftime("%Y%m%d-%H%M%S").' '.$fullcommand."\n"; print strftime("%Y%m%d-%H%M%S").' '.$fullcommand."\n";
exec($fullcommand, $output, $return_var); exec($fullcommand, $output, $return_var);
foreach ($output as $line) print $line."\n"; foreach ($output as $line) {
print $line."\n";
}
//ssh2_sftp_unlink($sftp, $fileinstalllock); //ssh2_sftp_unlink($sftp, $fileinstalllock);
//print $output; //print $output;
} }
} } else {
else {
print 'Failed to connect to ssh2 to '.$server; print 'Failed to connect to ssh2 to '.$server;
exit(-6); exit(-6);
} }

View File

@ -36,14 +36,30 @@ $confirm=isset($argv[1])?$argv[1]:'';
// Include Dolibarr environment // Include Dolibarr environment
$res=0; $res=0;
if (! $res && file_exists($path."../../master.inc.php")) $res=@include $path."../../master.inc.php"; if (! $res && file_exists($path."../../master.inc.php")) {
if (! $res && file_exists($path."../../htdocs/master.inc.php")) $res=@include $path."../../htdocs/master.inc.php"; $res=@include $path."../../master.inc.php";
if (! $res && file_exists("../master.inc.php")) $res=@include "../master.inc.php"; }
if (! $res && file_exists("../../master.inc.php")) $res=@include "../../master.inc.php"; if (! $res && file_exists($path."../../htdocs/master.inc.php")) {
if (! $res && file_exists("../../../master.inc.php")) $res=@include "../../../master.inc.php"; $res=@include $path."../../htdocs/master.inc.php";
if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) $res=@include $path."../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only }
if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) $res=@include "../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only if (! $res && file_exists("../master.inc.php")) {
if (! $res) die("Failed to include master.inc.php file\n"); $res=@include "../master.inc.php";
}
if (! $res && file_exists("../../master.inc.php")) {
$res=@include "../../master.inc.php";
}
if (! $res && file_exists("../../../master.inc.php")) {
$res=@include "../../../master.inc.php";
}
if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) {
$res=@include $path."../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only
}
if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) {
$res=@include "../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only
}
if (! $res) {
die("Failed to include master.inc.php file\n");
}
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
@ -53,8 +69,7 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
print "***** ".$script_file." *****\n"; print "***** ".$script_file." *****\n";
print "Update dates to current year for database name = ".$db->database_name."\n"; print "Update dates to current year for database name = ".$db->database_name."\n";
if (empty($confirm)) if (empty($confirm)) {
{
print "Usage: $script_file confirm\n"; print "Usage: $script_file confirm\n";
print "Return code: 0 if success, <>0 if error\n"; print "Return code: 0 if success, <>0 if error\n";
exit(-1); exit(-1);
@ -78,48 +93,46 @@ $tables=array(
$year=2010; $year=2010;
$currentyear=$tmp['year']; $currentyear=$tmp['year'];
while ($year <= $currentyear) while ($year <= $currentyear) {
{
//$year=2021; //$year=2021;
$delta1=($currentyear - $year); $delta1=($currentyear - $year);
$delta2=($currentyear - $year - 1); $delta2=($currentyear - $year - 1);
//$delta=-1; //$delta=-1;
if ($delta1) if ($delta1) {
{ foreach ($tables as $tablekey => $tableval) {
foreach ($tables as $tablekey => $tableval)
{
print "Correct ".$tablekey." for year ".$year." and move them to current year ".$currentyear." "; print "Correct ".$tablekey." for year ".$year." and move them to current year ".$currentyear." ";
$sql="select rowid from ".MAIN_DB_PREFIX.$tablekey." where ".$tableval[0]." between '".$year."-01-01' and '".$year."-12-31' and ".$tableval[0]." < DATE_ADD(NOW(), INTERVAL -1 YEAR)"; $sql="select rowid from ".MAIN_DB_PREFIX.$tablekey." where ".$tableval[0]." between '".$year."-01-01' and '".$year."-12-31' and ".$tableval[0]." < DATE_ADD(NOW(), INTERVAL -1 YEAR)";
//$sql="select rowid from ".MAIN_DB_PREFIX.$tablekey." where ".$tableval[0]." between '".$year."-01-01' and '".$year."-12-31' and ".$tableval[0]." > NOW()"; //$sql="select rowid from ".MAIN_DB_PREFIX.$tablekey." where ".$tableval[0]." between '".$year."-01-01' and '".$year."-12-31' and ".$tableval[0]." > NOW()";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i=0; $i=0;
while ($i < $num) while ($i < $num) {
{
$obj=$db->fetch_object($resql); $obj=$db->fetch_object($resql);
if ($obj) if ($obj) {
{
print "."; print ".";
$sql2="UPDATE ".MAIN_DB_PREFIX.$tablekey." set "; $sql2="UPDATE ".MAIN_DB_PREFIX.$tablekey." set ";
$j=0; $j=0;
foreach ($tableval as $field) foreach ($tableval as $field) {
{ if ($j) {
if ($j) $sql2.=", "; $sql2.=", ";
}
$sql2.= $field." = ".$db->ifsql("DATE_ADD(".$field.", INTERVAL ".$delta1." YEAR) > NOW()", "DATE_ADD(".$field.", INTERVAL ".$delta2." YEAR)", "DATE_ADD(".$field.", INTERVAL ".$delta1." YEAR)"); $sql2.= $field." = ".$db->ifsql("DATE_ADD(".$field.", INTERVAL ".$delta1." YEAR) > NOW()", "DATE_ADD(".$field.", INTERVAL ".$delta2." YEAR)", "DATE_ADD(".$field.", INTERVAL ".$delta1." YEAR)");
$j++; $j++;
} }
$sql2.=" WHERE rowid = ".$obj->rowid; $sql2.=" WHERE rowid = ".$obj->rowid;
//print $sql2."\n"; //print $sql2."\n";
$resql2 = $db->query($sql2); $resql2 = $db->query($sql2);
if (! $resql2) dol_print_error($db); if (! $resql2) {
dol_print_error($db);
}
} }
$i++; $i++;
} }
} else {
dol_print_error($db);
} }
else dol_print_error($db);
print "\n"; print "\n";
} }
} }

View File

@ -7,7 +7,7 @@
<exclude-pattern type="relative">build/html</exclude-pattern> <exclude-pattern type="relative">build/html</exclude-pattern>
<exclude-pattern type="relative">build/aps</exclude-pattern> <exclude-pattern type="relative">build/aps</exclude-pattern>
<exclude-pattern type="relative">dev/tools/test/namespacemig</exclude-pattern> <exclude-pattern type="relative">dev/tools/test/namespacemig</exclude-pattern>
<exclude-pattern type="relative">dev/initdata/dbf/includes</exclude-pattern> <!-- <exclude-pattern type="relative">dev/initdata/dbf/includes</exclude-pattern> -->
<exclude-pattern type="relative">documents</exclude-pattern> <exclude-pattern type="relative">documents</exclude-pattern>
<exclude-pattern type="relative">htdocs/core/class/lessc.class.php</exclude-pattern> <exclude-pattern type="relative">htdocs/core/class/lessc.class.php</exclude-pattern>
<exclude-pattern type="relative">htdocs/custom</exclude-pattern> <exclude-pattern type="relative">htdocs/custom</exclude-pattern>
@ -104,9 +104,9 @@
</rule> </rule>
--> -->
<!-- We want to allow 'if () { ...small code... }' on same line for better code compacity and readability --> <!-- We want to allow 'if () { ...small code... }' on same line for better code compacity and readability -->
<rule ref="Generic.Formatting.DisallowMultipleStatements"> <!-- <rule ref="Generic.Formatting.DisallowMultipleStatements">
<severity>0</severity> <severity>0</severity>
</rule> </rule> -->
<!-- Check assignement have the = align on each line. Have 20 chars padding maximum and always show as errors --> <!-- Check assignement have the = align on each line. Have 20 chars padding maximum and always show as errors -->
@ -174,8 +174,8 @@
<rule ref="Generic.Strings.UnnecessaryStringConcat.Found"> <rule ref="Generic.Strings.UnnecessaryStringConcat.Found">
</rule> </rule>
<!-- Disallow usage of tab --> <!-- Disallow usage of space -->
<!-- <rule ref="Generic.WhiteSpace.DisallowTabIndent" /> --> <rule ref="Generic.WhiteSpace.DisallowSpaceIndent" />
<!-- Check indent are done with spaces and with correct number --> <!-- Check indent are done with spaces and with correct number -->
<!-- Disabled as this does not support tab --> <!-- Disabled as this does not support tab -->
@ -214,7 +214,7 @@
<rule ref="Squiz.WhiteSpace.ControlStructureSpacing.SpacingAfterOpen" /> <rule ref="Squiz.WhiteSpace.ControlStructureSpacing.SpacingAfterOpen" />
<rule ref="Squiz.WhiteSpace.ControlStructureSpacing.SpacingBeforeClose" /> <rule ref="Squiz.WhiteSpace.ControlStructureSpacing.SpacingBeforeClose" />
<!-- <rule ref="Squiz.ControlStructures.ControlSignature.SpaceAfterCloseParenthesis" /> --> <rule ref="Squiz.ControlStructures.ControlSignature.SpaceAfterCloseParenthesis" />
<!-- <rule ref="Squiz.ControlStructures.ControlSignature.SpaceAfterCloseBrace" /> --> <!-- <rule ref="Squiz.ControlStructures.ControlSignature.SpaceAfterCloseBrace" /> -->
<rule ref="Squiz.ControlStructures.ControlSignature.SpaceAfterKeyword" /> <rule ref="Squiz.ControlStructures.ControlSignature.SpaceAfterKeyword" />

View File

@ -48,8 +48,9 @@ if (! ($argv[1] && $argv[2])) {
echo "Usage: php pg2mysql_cli.php <inputfilename> <outputfilename> [engine]\n"; echo "Usage: php pg2mysql_cli.php <inputfilename> <outputfilename> [engine]\n";
exit(); exit();
} else { } else {
if (isset($argv[3])) if (isset($argv[3])) {
$config['engine'] = $argv[3]; $config['engine'] = $argv[3];
}
pg2mysql_large($argv[1], $argv[2]); pg2mysql_large($argv[1], $argv[2]);
echo <<<XHTML echo <<<XHTML
@ -74,14 +75,18 @@ function getfieldname($l)
// first check if its in nice quotes for us // first check if its in nice quotes for us
$regs = array(); $regs = array();
if (preg_match("/`(.*)`/", $l, $regs)) { if (preg_match("/`(.*)`/", $l, $regs)) {
if ($regs[1]) if ($regs[1]) {
return $regs[1]; return $regs[1];
else return null; } else {
} // if its not in quotes, then it should (we hope!) be the first "word" on the line, up to the first space. return null;
elseif (preg_match("/([^\ ]*)/", trim($l), $regs)) { }
if ($regs[1]) } elseif (preg_match("/([^\ ]*)/", trim($l), $regs)) {
// if its not in quotes, then it should (we hope!) be the first "word" on the line, up to the first space.
if ($regs[1]) {
return $regs[1]; return $regs[1];
else return null; } else {
return null;
}
} }
} }
@ -94,13 +99,15 @@ function getfieldname($l)
*/ */
function formatsize($s) function formatsize($s)
{ {
if ($s < pow(2, 14)) if ($s < pow(2, 14)) {
return "{$s}B"; return "{$s}B";
elseif ($s < pow(2, 20)) } elseif ($s < pow(2, 20)) {
return sprintf("%.1f", round($s / 1024, 1)) . "K"; return sprintf("%.1f", round($s / 1024, 1)) . "K";
elseif ($s < pow(2, 30)) } elseif ($s < pow(2, 30)) {
return sprintf("%.1f", round($s / 1024 / 1024, 1)) . "M"; return sprintf("%.1f", round($s / 1024 / 1024, 1)) . "M";
else return sprintf("%.1f", round($s / 1024 / 1024 / 1024, 1)) . "G"; } else {
return sprintf("%.1f", round($s / 1024 / 1024 / 1024, 1)) . "G";
}
} }
/** /**
@ -141,9 +148,11 @@ function pg2mysql_large($infilename, $outfilename)
$c = substr_count($instr, "'"); $c = substr_count($instr, "'");
// we have an odd number of ' marks // we have an odd number of ' marks
if ($c % 2 != 0) { if ($c % 2 != 0) {
if ($inquotes) if ($inquotes) {
$inquotes = false; $inquotes = false;
else $inquotes = true; } else {
$inquotes = true;
}
} }
if ($linenum % 10000 == 0) { if ($linenum % 10000 == 0) {
@ -323,9 +332,11 @@ function pg2mysql(&$input, &$arrayofprimaryalreadyintabledef, $header = true)
$line = str_replace(" bool DEFAULT false", " bool DEFAULT 0", $line); $line = str_replace(" bool DEFAULT false", " bool DEFAULT 0", $line);
if (preg_match("/ character varying\(([0-9]*)\)/", $line, $regs)) { if (preg_match("/ character varying\(([0-9]*)\)/", $line, $regs)) {
$num = $regs[1]; $num = $regs[1];
if ($num <= 255) if ($num <= 255) {
$line = preg_replace("/ character varying\([0-9]*\)/", " varchar($num)", $line); $line = preg_replace("/ character varying\([0-9]*\)/", " varchar($num)", $line);
else $line = preg_replace("/ character varying\([0-9]*\)/", " text", $line); } else {
$line = preg_replace("/ character varying\([0-9]*\)/", " text", $line);
}
} }
// character varying with no size, we will default to varchar(255) // character varying with no size, we will default to varchar(255)
if (preg_match("/ character varying/", $line)) { if (preg_match("/ character varying/", $line)) {
@ -345,9 +356,11 @@ function pg2mysql(&$input, &$arrayofprimaryalreadyintabledef, $header = true)
$line = preg_replace("/::.*$/", "\n", $line); $line = preg_replace("/::.*$/", "\n", $line);
if (preg_match("/character\(([0-9]*)\)/", $line, $regs)) { if (preg_match("/character\(([0-9]*)\)/", $line, $regs)) {
$num = $regs[1]; $num = $regs[1];
if ($num <= 255) if ($num <= 255) {
$line = preg_replace("/ character\([0-9]*\)/", " varchar($num)", $line); $line = preg_replace("/ character\([0-9]*\)/", " varchar($num)", $line);
else $line = preg_replace("/ character\([0-9]*\)/", " text", $line); } else {
$line = preg_replace("/ character\([0-9]*\)/", " text", $line);
}
} }
// timestamps // timestamps
$line = str_replace(" timestamp with time zone", " datetime", $line); $line = str_replace(" timestamp with time zone", " datetime", $line);
@ -457,9 +470,11 @@ function pg2mysql(&$input, &$arrayofprimaryalreadyintabledef, $header = true)
$c = substr_count($line, "'"); $c = substr_count($line, "'");
// we have an odd number of ' marks // we have an odd number of ' marks
if ($c % 2 != 0) { if ($c % 2 != 0) {
if ($inquotes) if ($inquotes) {
$inquotes = false; $inquotes = false;
else $inquotes = true; } else {
$inquotes = true;
}
// echo "inquotes=$inquotes\n"; // echo "inquotes=$inquotes\n";
} }
} while (substr($lines[$linenumber], - 3, - 1) != ");" || $inquotes); } while (substr($lines[$linenumber], - 3, - 1) != ");" || $inquotes);
@ -524,8 +539,9 @@ function pg2mysql(&$input, &$arrayofprimaryalreadyintabledef, $header = true)
} }
} }
if (substr($line, 0, 13) == 'DROP DATABASE') if (substr($line, 0, 13) == 'DROP DATABASE') {
$output .= $line; $output .= $line;
}
if (substr($line, 0, 15) == 'CREATE DATABASE') { if (substr($line, 0, 15) == 'CREATE DATABASE') {
$matches = array(); $matches = array();

View File

@ -4,6 +4,7 @@
use Dolibarr\Aaa as Aaa; use Dolibarr\Aaa as Aaa;
use function Dolibarr\faaa as faaa; // Need php 5.6+ use function Dolibarr\faaa as faaa; // Need php 5.6+
//use const Dolibarr\AAA; //use const Dolibarr\AAA;
//use Bbb as Bbb; //use Bbb as Bbb;

View File

@ -3,10 +3,11 @@
$a = microtime(true); $a = microtime(true);
$i = 0; $i = 0;
while ($i < 1000000) while ($i < 1000000) {
{
$key = '1234567890111213141516171819'.$i; $key = '1234567890111213141516171819'.$i;
if ($i == 1000) $key = 'MAIN_MODULE_AAAAAiiiiiiiiiiiiiiiiiiiiiiiiiiiii'; if ($i == 1000) {
$key = 'MAIN_MODULE_AAAAAiiiiiiiiiiiiiiiiiiiiiiiiiiiii';
}
//if (preg_match('/^MAIN_MODULE_/', $key)) { //if (preg_match('/^MAIN_MODULE_/', $key)) {
//if (substr($key, 0, 12) == 'MAIN_MODULE_') { //if (substr($key, 0, 12) == 'MAIN_MODULE_') {

View File

@ -89,8 +89,8 @@ $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 016', PDF_HEADER_STRING); $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 016', PDF_HEADER_STRING);
// set header and footer fonts // set header and footer fonts
$pdf->setHeaderFont(Array('helvetica', '', PDF_FONT_SIZE_MAIN)); $pdf->setHeaderFont(array('helvetica', '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array('helvetica', '', PDF_FONT_SIZE_DATA)); $pdf->setFooterFont(array('helvetica', '', PDF_FONT_SIZE_DATA));
// set default monospaced font // set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

View File

@ -64,8 +64,8 @@ $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
$pdf->SetHeaderData('', PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 038', PDF_HEADER_STRING); $pdf->SetHeaderData('', PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 038', PDF_HEADER_STRING);
// set header and footer fonts // set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); $pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font // set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

View File

@ -77,9 +77,10 @@ class autoTranslator
$files = $this->getTranslationFilesArray($this->_refLang); $files = $this->getTranslationFilesArray($this->_refLang);
$counter = 1; $counter = 1;
foreach ($files as $file) foreach ($files as $file) {
{ if ($this->_limittofile && $this->_limittofile != $file) {
if ($this->_limittofile && $this->_limittofile != $file) continue; continue;
}
$counter++; $counter++;
$fileContent = null; $fileContent = null;
$refPath = $this->_langDir.$this->_refLang.self::DIR_SEPARATOR.$file; $refPath = $this->_langDir.$this->_refLang.self::DIR_SEPARATOR.$file;
@ -88,54 +89,66 @@ class autoTranslator
// Define target dirs // Define target dirs
$targetlangs=array($this->_destlang); $targetlangs=array($this->_destlang);
if ($this->_destlang == 'all') if ($this->_destlang == 'all') {
{
$targetlangs=array(); $targetlangs=array();
// If we must process all languages // If we must process all languages
$arraytmp=dol_dir_list($this->_langDir, 'directories', 0); $arraytmp=dol_dir_list($this->_langDir, 'directories', 0);
foreach ($arraytmp as $dirtmp) foreach ($arraytmp as $dirtmp) {
{ if ($dirtmp['name'] === $this->_refLang) {
if ($dirtmp['name'] === $this->_refLang) continue; // We discard source language continue; // We discard source language
}
$tmppart=explode('_', $dirtmp['name']); $tmppart=explode('_', $dirtmp['name']);
if (preg_match('/^en/i', $dirtmp['name'])) continue; // We discard en_* languages if (preg_match('/^en/i', $dirtmp['name'])) {
if (preg_match('/^fr/i', $dirtmp['name'])) continue; // We discard fr_* languages continue; // We discard en_* languages
if (preg_match('/^es/i', $dirtmp['name'])) continue; // We discard es_* languages }
if (preg_match('/ca_ES/i', $dirtmp['name'])) continue; // We discard es_CA language if (preg_match('/^fr/i', $dirtmp['name'])) {
if (preg_match('/pt_BR/i', $dirtmp['name'])) continue; // We discard pt_BR language continue; // We discard fr_* languages
if (preg_match('/nl_BE/i', $dirtmp['name'])) continue; // We discard nl_BE language }
if (preg_match('/^\./i', $dirtmp['name'])) continue; // We discard files .* if (preg_match('/^es/i', $dirtmp['name'])) {
if (preg_match('/^CVS/i', $dirtmp['name'])) continue; // We discard CVS continue; // We discard es_* languages
}
if (preg_match('/ca_ES/i', $dirtmp['name'])) {
continue; // We discard es_CA language
}
if (preg_match('/pt_BR/i', $dirtmp['name'])) {
continue; // We discard pt_BR language
}
if (preg_match('/nl_BE/i', $dirtmp['name'])) {
continue; // We discard nl_BE language
}
if (preg_match('/^\./i', $dirtmp['name'])) {
continue; // We discard files .*
}
if (preg_match('/^CVS/i', $dirtmp['name'])) {
continue; // We discard CVS
}
$targetlangs[]=$dirtmp['name']; $targetlangs[]=$dirtmp['name'];
} }
//var_dump($targetlangs); //var_dump($targetlangs);
} }
// Process translation of source file for each target languages // Process translation of source file for each target languages
foreach ($targetlangs as $my_destlang) foreach ($targetlangs as $my_destlang) {
{
$this->_translatedFiles = array(); $this->_translatedFiles = array();
$destPath = $this->_langDir.$my_destlang.self::DIR_SEPARATOR.$file; $destPath = $this->_langDir.$my_destlang.self::DIR_SEPARATOR.$file;
// Check destination file presence // Check destination file presence
if (! file_exists($destPath)) if (! file_exists($destPath)) {
{
// No file present, we generate file // No file present, we generate file
echo "File not found: " . $destPath . ". We generate it.<br>\n"; echo "File not found: " . $destPath . ". We generate it.<br>\n";
$this->createTranslationFile($destPath, $my_destlang); $this->createTranslationFile($destPath, $my_destlang);
} } else {
else {
echo "Updating file: " . $destPath . "<br>\n"; echo "Updating file: " . $destPath . "<br>\n";
} }
// Translate lines // Translate lines
$fileContentDest = file($destPath, FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); $fileContentDest = file($destPath, FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$newlines=0; $newlines=0;
foreach ($fileContent as $line){ foreach ($fileContent as $line) {
$key = $this->getLineKey($line); $key = $this->getLineKey($line);
$value = $this->getLineValue($line); $value = $this->getLineValue($line);
if ($key && $value) if ($key && $value) {
{
$newlines+=$this->translateFileLine($fileContentDest, $file, $key, $value, $my_destlang); $newlines+=$this->translateFileLine($fileContentDest, $file, $key, $value, $my_destlang);
} }
} }
@ -159,8 +172,7 @@ class autoTranslator
{ {
$this->_time_end = date('Y-m-d H:i:s'); $this->_time_end = date('Y-m-d H:i:s');
if (isset($this->_translatedFiles[$file]) && count($this->_translatedFiles[$file])>0) if (isset($this->_translatedFiles[$file]) && count($this->_translatedFiles[$file])>0) {
{
$fp = fopen($destPath, 'a'); $fp = fopen($destPath, 'a');
fwrite($fp, "\n"); fwrite($fp, "\n");
fwrite($fp, "\n"); fwrite($fp, "\n");
@ -213,8 +225,7 @@ class autoTranslator
$destValue = $this->getLineValue($line); $destValue = $this->getLineValue($line);
// If translated return // If translated return
//print "destKey=".$destKey."\n"; //print "destKey=".$destKey."\n";
if ( trim($destKey) == trim($key) ) if (trim($destKey) == trim($key)) { // Found already existing translation (key already exits in dest file)
{ // Found already existing translation (key already exits in dest file)
return 0; return 0;
} }
} }
@ -227,13 +238,18 @@ class autoTranslator
$val=$value; $val=$value;
} else { } else {
// If not translated then translate // If not translated then translate
if ($this->_outputpagecode == 'UTF-8') $val=$this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2)); if ($this->_outputpagecode == 'UTF-8') {
else $val=utf8_decode($this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2))); $val=$this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2));
} else {
$val=utf8_decode($this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2)));
}
} }
$val=trim($val); $val=trim($val);
if (empty($val)) return 0; if (empty($val)) {
return 0;
}
$this->_translatedFiles[$file][] = $key . '=' . $val ; $this->_translatedFiles[$file][] = $key . '=' . $val ;
return 1; return 1;
@ -293,9 +309,13 @@ class autoTranslator
{ {
// We want to be sure that src_lang and dest_lang are using 2 chars only // We want to be sure that src_lang and dest_lang are using 2 chars only
$tmp=explode('_', $src_lang); $tmp=explode('_', $src_lang);
if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) $src_lang=$tmp[0]; if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) {
$src_lang=$tmp[0];
}
$tmp=explode('_', $dest_lang); $tmp=explode('_', $dest_lang);
if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) $dest_lang=$tmp[0]; if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) {
$dest_lang=$tmp[0];
}
//setting language pair //setting language pair
$lang_pair = $src_lang.'|'.$dest_lang; $lang_pair = $src_lang.'|'.$dest_lang;
@ -313,8 +333,7 @@ class autoTranslator
// Send request // Send request
//print "Url to translate: ".$url."\n"; //print "Url to translate: ".$url."\n";
if (! function_exists("curl_init")) if (! function_exists("curl_init")) {
{
print "Error, your PHP does not support curl functions.\n"; print "Error, your PHP does not support curl functions.\n";
die(); die();
} }
@ -331,8 +350,7 @@ class autoTranslator
$json = json_decode($body, true); $json = json_decode($body, true);
if ((! empty($json['responseStatus']) && $json['responseStatus'] != 200) if ((! empty($json['responseStatus']) && $json['responseStatus'] != 200)
|| count($json['data']['translations']) == 0) || count($json['data']['translations']) == 0) {
{
print "Error: ".$json['responseStatus']." ".$url."\n"; print "Error: ".$json['responseStatus']." ".$url."\n";
return false; return false;
} }

View File

@ -67,21 +67,17 @@ print 'Argument 1='.$argv[1]."\n";
print 'Argument 2='.$argv[2]."\n"; print 'Argument 2='.$argv[2]."\n";
print 'Argument 3='.$argv[3]."\n"; print 'Argument 3='.$argv[3]."\n";
$file=''; $file='';
if (isset($argv[4])) if (isset($argv[4])) {
{
$file=$argv[4]; $file=$argv[4];
print 'Argument 4='.$argv[4]."\n"; print 'Argument 4='.$argv[4]."\n";
} }
print 'Files will be generated/updated in directory '.$dir."\n"; print 'Files will be generated/updated in directory '.$dir."\n";
if ($argv[2] != 'all') if ($argv[2] != 'all') {
{ if (! is_dir($dir.'/'.$argv[2])) {
if (! is_dir($dir.'/'.$argv[2]))
{
print 'Create directory '.$dir.'/'.$argv[2]."\n"; print 'Create directory '.$dir.'/'.$argv[2]."\n";
$result=mkdir($dir.'/'.$argv[2]); $result=mkdir($dir.'/'.$argv[2]);
if (! $result) if (! $result) {
{
$db->close(); $db->close();
return -1; return -1;
} }

View File

@ -25,14 +25,12 @@ $path=dirname(__FILE__).'/';
$web=0; $web=0;
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') if (substr($sapi_type, 0, 3) == 'cgi') {
{
$web=1; $web=1;
} }
if ($web) if ($web) {
{
echo "<html>"; echo "<html>";
echo "<head>"; echo "<head>";
@ -87,9 +85,13 @@ if ($web)
} }
echo "If you call this with argument \"unused=true\" it searches for the translation strings that exist in en_US but are never used.\n"; echo "If you call this with argument \"unused=true\" it searches for the translation strings that exist in en_US but are never used.\n";
if ($web) print "<br>"; if ($web) {
print "<br>";
}
echo "IMPORTANT: that can take quite a lot of time (up to 10 minutes), you need to tune the max_execution_time on your php.ini accordingly.\n"; echo "IMPORTANT: that can take quite a lot of time (up to 10 minutes), you need to tune the max_execution_time on your php.ini accordingly.\n";
if ($web) print "<br>"; if ($web) {
print "<br>";
}
@ -105,8 +107,7 @@ $workdir = $htdocs."langs/en_US/";
$files = scandir($workdir); $files = scandir($workdir);
if (empty($files)) if (empty($files)) {
{
echo "Can't scan workdir = ".$workdir; echo "Can't scan workdir = ".$workdir;
exit; exit;
} }
@ -115,18 +116,17 @@ $dups=array();
$exludefiles = array('.','..','README'); $exludefiles = array('.','..','README');
$files = array_diff($files, $exludefiles); $files = array_diff($files, $exludefiles);
// To force a file: $files=array('myfile.lang'); // To force a file: $files=array('myfile.lang');
if (isset($argv[2])) if (isset($argv[2])) {
{
$files = array($argv[2]); $files = array($argv[2]);
} }
$langstrings_3d = array(); $langstrings_3d = array();
$langstrings_full = array(); $langstrings_full = array();
foreach ($files AS $file) { foreach ($files as $file) {
$path_file = pathinfo($file); $path_file = pathinfo($file);
// we're only interested in .lang files // we're only interested in .lang files
if ($path_file['extension']=='lang') { if ($path_file['extension']=='lang') {
$content = file($workdir.$file); $content = file($workdir.$file);
foreach ($content AS $line => $row) { foreach ($content as $line => $row) {
// don't want comment lines // don't want comment lines
if (substr($row, 0, 1) !== '#') { if (substr($row, 0, 1) !== '#') {
// don't want lines without the separator (why should those even be here, anyway...) // don't want lines without the separator (why should those even be here, anyway...)
@ -142,26 +142,26 @@ foreach ($files AS $file) {
} }
} }
foreach ($langstrings_3d AS $filename => $file) foreach ($langstrings_3d as $filename => $file) {
{ foreach ($file as $linenum => $value) {
foreach ($file AS $linenum => $value)
{
$keys = array_keys($langstrings_full, $value); $keys = array_keys($langstrings_full, $value);
if (count($keys)>1) if (count($keys)>1) {
{ foreach ($keys as $key) {
foreach ($keys AS $key) {
$dups[$value][$filename][$linenum] = trim($langstrings_3dtrans[$filename][$linenum]); $dups[$value][$filename][$linenum] = trim($langstrings_3dtrans[$filename][$linenum]);
} }
} }
} }
} }
if ($web) print "<h2>"; if ($web) {
print "<h2>";
}
print "Duplicate strings in lang files in $workdir - ".count($dups)." found\n"; print "Duplicate strings in lang files in $workdir - ".count($dups)." found\n";
if ($web) print "</h2>"; if ($web) {
print "</h2>";
}
if ($web) if ($web) {
{
echo '<table border_bottom="1">'."\n"; echo '<table border_bottom="1">'."\n";
echo "<thead><tr><th align=\"center\">#</th><th>String</th><th>File and lines</th></thead>\n"; echo "<thead><tr><th align=\"center\">#</th><th>String</th><th>File and lines</th></thead>\n";
echo "<tbody>\n"; echo "<tbody>\n";
@ -173,75 +173,126 @@ $sininstallandadmin='';
$sother=''; $sother='';
$count = 0; $count = 0;
foreach ($dups as $string => $pages) foreach ($dups as $string => $pages) {
{
$count++; $count++;
$s=''; $s='';
// Keyword $string // Keyword $string
if ($web) $s.="<tr>"; if ($web) {
if ($web) $s.="<td align=\"center\">"; $s.="<tr>";
if ($web) $s.=$count; }
if ($web) $s.="</td>"; if ($web) {
if ($web) $s.="<td>"; $s.="<td align=\"center\">";
}
if ($web) {
$s.=$count;
}
if ($web) {
$s.="</td>";
}
if ($web) {
$s.="<td>";
}
$s.=$string; $s.=$string;
if ($web) $s.="</td>"; if ($web) {
if ($web) $s.="<td>"; $s.="</td>";
if (! $web) $s.= ' : '; }
if ($web) {
$s.="<td>";
}
if (! $web) {
$s.= ' : ';
}
// Loop on each files keyword was found // Loop on each files keyword was found
$duplicateinsamefile=0; $duplicateinsamefile=0;
$inmain=0; $inmain=0;
$inadmin=0; $inadmin=0;
foreach ($pages AS $file => $lines) foreach ($pages as $file => $lines) {
{ if ($file == 'main.lang') {
if ($file == 'main.lang') { $inmain=1; $inadmin=0; } $inmain=1; $inadmin=0;
if ($file == 'admin.lang' && ! $inmain) { $inadmin=1; } }
if ($file == 'admin.lang' && ! $inmain) {
$inadmin=1;
}
$s.=$file." "; $s.=$file." ";
// Loop on each line keword was found into file. // Loop on each line keword was found into file.
$listoffilesforthisentry=array(); $listoffilesforthisentry=array();
foreach ($lines as $line => $translatedvalue) foreach ($lines as $line => $translatedvalue) {
{ if (! empty($listoffilesforthisentry[$file])) {
if (! empty($listoffilesforthisentry[$file])) $duplicateinsamefile=1; $duplicateinsamefile=1;
}
$listoffilesforthisentry[$file]=1; $listoffilesforthisentry[$file]=1;
$s.= "(".$line." - ".htmlentities($translatedvalue).") "; $s.= "(".$line." - ".htmlentities($translatedvalue).") ";
} }
if ($web) $s.="<br>"; if ($web) {
$s.="<br>";
}
}
if ($web) {
$s.="</td></tr>";
} }
if ($web) $s.="</td></tr>";
$s.="\n"; $s.="\n";
if ($duplicateinsamefile) $sduplicateinsamefile .= $s; if ($duplicateinsamefile) {
elseif ($inmain) $sinmainandother .= $s; $sduplicateinsamefile .= $s;
elseif ($inadmin) $sininstallandadmin .= $s; } elseif ($inmain) {
else $sother .= $s; $sinmainandother .= $s;
} elseif ($inadmin) {
$sininstallandadmin .= $s;
} else {
$sother .= $s;
}
} }
if (! $web) print "\n***** Entries duplicated in same file\n"; if (! $web) {
print "\n***** Entries duplicated in same file\n";
}
print $sduplicateinsamefile; print $sduplicateinsamefile;
if (! $web && empty($sduplicateinsamefile)) print "None\n"; if (! $web && empty($sduplicateinsamefile)) {
if (! $web) print "\n"; print "None\n";
}
if (! $web) {
print "\n";
}
if (! $web) print "***** Entries in main and another (keep only entry in main)\n"; if (! $web) {
print "***** Entries in main and another (keep only entry in main)\n";
}
print $sinmainandother; print $sinmainandother;
if (! $web && empty($sinmainandother)) print "None\n"; if (! $web && empty($sinmainandother)) {
if (! $web) print "\n"; print "None\n";
}
if (! $web) {
print "\n";
}
if (! $web) print "***** Entries in admin and another\n"; if (! $web) {
print "***** Entries in admin and another\n";
}
print $sininstallandadmin; print $sininstallandadmin;
if (! $web && empty($sininstallandadmin)) print "None\n"; if (! $web && empty($sininstallandadmin)) {
if (! $web) print "\n"; print "None\n";
}
if (! $web) {
print "\n";
}
if (! $web) print "***** Other\n"; if (! $web) {
print "***** Other\n";
}
print $sother; print $sother;
if (! $web && empty($sother)) print "None\n"; if (! $web && empty($sother)) {
if (! $web) print "\n"; print "None\n";
}
if (! $web) {
print "\n";
}
if ($web) if ($web) {
{
echo "</tbody>\n"; echo "</tbody>\n";
echo "</table>\n"; echo "</table>\n";
} }
@ -249,105 +300,254 @@ if ($web)
// STEP 2 - Search key not used // STEP 2 - Search key not used
if ((! empty($_REQUEST['unused']) && $_REQUEST['unused'] == 'true') || (isset($argv[1]) && $argv[1]=='unused=true')) if ((! empty($_REQUEST['unused']) && $_REQUEST['unused'] == 'true') || (isset($argv[1]) && $argv[1]=='unused=true')) {
{
print "***** Strings in en_US that are never used:\n"; print "***** Strings in en_US that are never used:\n";
$unused=array(); $unused=array();
foreach ($langstrings_dist AS $value => $line) foreach ($langstrings_dist as $value => $line) {
{
$qualifiedforclean=1; $qualifiedforclean=1;
// Check if we must keep this key to be into file for removal // Check if we must keep this key to be into file for removal
if (preg_match('/^Module\d+/', $value)) $qualifiedforclean=0; if (preg_match('/^Module\d+/', $value)) {
if (preg_match('/^Permission\d+/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^PermissionAdvanced\d+/', $value)) $qualifiedforclean=0; }
if (preg_match('/^ProfId\d+/', $value)) $qualifiedforclean=0; if (preg_match('/^Permission\d+/', $value)) {
if (preg_match('/^Delays_/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^BarcodeDesc/', $value)) $qualifiedforclean=0; }
if (preg_match('/^Extrafield/', $value)) $qualifiedforclean=0; if (preg_match('/^PermissionAdvanced\d+/', $value)) {
if (preg_match('/^LocalTax/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^Country/', $value)) $qualifiedforclean=0; }
if (preg_match('/^Civility/', $value)) $qualifiedforclean=0; if (preg_match('/^ProfId\d+/', $value)) {
if (preg_match('/^Currency/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^DemandReasonTypeSRC/', $value)) $qualifiedforclean=0; }
if (preg_match('/^PaperFormat/', $value)) $qualifiedforclean=0; if (preg_match('/^Delays_/', $value)) {
if (preg_match('/^Duration/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^AmountLT/', $value)) $qualifiedforclean=0; }
if (preg_match('/^TotalLT/', $value)) $qualifiedforclean=0; if (preg_match('/^BarcodeDesc/', $value)) {
if (preg_match('/^Month/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^MonthShort/', $value)) $qualifiedforclean=0; }
if (preg_match('/^Day\d/', $value)) $qualifiedforclean=0; if (preg_match('/^Extrafield/', $value)) {
if (preg_match('/^Short/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^ExportDataset_/', $value)) $qualifiedforclean=0; }
if (preg_match('/^ImportDataset_/', $value)) $qualifiedforclean=0; if (preg_match('/^LocalTax/', $value)) {
if (preg_match('/^ActionAC_/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^TypeLocaltax/', $value)) $qualifiedforclean=0; }
if (preg_match('/^StatusProspect/', $value)) $qualifiedforclean=0; if (preg_match('/^Country/', $value)) {
if (preg_match('/^PL_/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^TE_/', $value)) $qualifiedforclean=0; }
if (preg_match('/^JuridicalStatus/', $value)) $qualifiedforclean=0; if (preg_match('/^Civility/', $value)) {
if (preg_match('/^CalcMode/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^newLT/', $value)) $qualifiedforclean=0; }
if (preg_match('/^LT[0-9]/', $value)) $qualifiedforclean=0; if (preg_match('/^Currency/', $value)) {
if (preg_match('/^TypeContact_contrat_/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^ErrorPriceExpression/', $value)) $qualifiedforclean=0; }
if (preg_match('/^Language_/', $value)) $qualifiedforclean=0; if (preg_match('/^DemandReasonTypeSRC/', $value)) {
if (preg_match('/^DescADHERENT_/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^SubmitTranslation/', $value)) $qualifiedforclean=0; }
if (preg_match('/^ModuleCompanyCode/', $value)) $qualifiedforclean=0; if (preg_match('/^PaperFormat/', $value)) {
if (preg_match('/InDolibarr$/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
}
if (preg_match('/^Duration/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^AmountLT/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^TotalLT/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^Month/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^MonthShort/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^Day\d/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^Short/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^ExportDataset_/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^ImportDataset_/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^ActionAC_/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^TypeLocaltax/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^StatusProspect/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^PL_/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^TE_/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^JuridicalStatus/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^CalcMode/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^newLT/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^LT[0-9]/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^TypeContact_contrat_/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^ErrorPriceExpression/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^Language_/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^DescADHERENT_/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^SubmitTranslation/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^ModuleCompanyCode/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/InDolibarr$/', $value)) {
$qualifiedforclean=0;
}
// admin.lang // admin.lang
if (preg_match('/^DAV_ALLOW_PUBLIC_DIR/i', $value)) $qualifiedforclean=0; if (preg_match('/^DAV_ALLOW_PUBLIC_DIR/i', $value)) {
if (preg_match('/^DAV_ALLOW_ECM_DIR/i', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
}
if (preg_match('/^DAV_ALLOW_ECM_DIR/i', $value)) {
$qualifiedforclean=0;
}
// boxes.lang // boxes.lang
if (preg_match('/^BoxTitleLast/', $value)) $qualifiedforclean=0; if (preg_match('/^BoxTitleLast/', $value)) {
if (preg_match('/^BoxTitleLatest/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
}
if (preg_match('/^BoxTitleLatest/', $value)) {
$qualifiedforclean=0;
}
// install.lang // install.lang
if (preg_match('/^KeepDefaultValues/', $value)) $qualifiedforclean=0; if (preg_match('/^KeepDefaultValues/', $value)) {
$qualifiedforclean=0;
}
// mail.lang // mail.lang
if (preg_match('/MailingModuleDesc/i', $value)) $qualifiedforclean=0; if (preg_match('/MailingModuleDesc/i', $value)) {
$qualifiedforclean=0;
}
// main.lang // main.lang
if (preg_match('/^Duration/', $value)) $qualifiedforclean=0; if (preg_match('/^Duration/', $value)) {
if (preg_match('/^FormatDate/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^DateFormat/', $value)) $qualifiedforclean=0; }
if (preg_match('/^.b$/', $value)) $qualifiedforclean=0; if (preg_match('/^FormatDate/', $value)) {
if (preg_match('/^.*Bytes$/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^NoteSomeFeaturesAreDisabled/', $value)) $qualifiedforclean=0; }
if (preg_match('/^(DoTest|Under|Limits|Cards|CurrentValue|DateLimit|DateAndHour|NbOfLines|NbOfObjects|NbOfReferes|TotalTTCShort|VATs)/', $value)) $qualifiedforclean=0; if (preg_match('/^DateFormat/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^.b$/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^.*Bytes$/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^NoteSomeFeaturesAreDisabled/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^(DoTest|Under|Limits|Cards|CurrentValue|DateLimit|DateAndHour|NbOfLines|NbOfObjects|NbOfReferes|TotalTTCShort|VATs)/', $value)) {
$qualifiedforclean=0;
}
// modulebuilder // modulebuilder
if (preg_match('/^ModuleBuilderDesc/', $value)) $qualifiedforclean=0; if (preg_match('/^ModuleBuilderDesc/', $value)) {
$qualifiedforclean=0;
}
// orders // orders
if (preg_match('/^OrderSource/', $value)) $qualifiedforclean=0; if (preg_match('/^OrderSource/', $value)) {
if (preg_match('/^TypeContact_/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
}
if (preg_match('/^TypeContact_/', $value)) {
$qualifiedforclean=0;
}
// other.lang // other.lang
if (preg_match('/^Notify_/', $value)) $qualifiedforclean=0; if (preg_match('/^Notify_/', $value)) {
if (preg_match('/^PredefinedMail/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^DemoCompany/', $value)) $qualifiedforclean=0; }
if (preg_match('/^WeightUnit/', $value)) $qualifiedforclean=0; if (preg_match('/^PredefinedMail/', $value)) {
if (preg_match('/^LengthUnit/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^SurfaceUnit/', $value)) $qualifiedforclean=0; }
if (preg_match('/^VolumeUnit/', $value)) $qualifiedforclean=0; if (preg_match('/^DemoCompany/', $value)) {
if (preg_match('/^SizeUnit/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/^EMailText/', $value)) $qualifiedforclean=0; }
if (preg_match('/ById$/', $value)) $qualifiedforclean=0; if (preg_match('/^WeightUnit/', $value)) {
if (preg_match('/ByLogin$/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
}
if (preg_match('/^LengthUnit/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^SurfaceUnit/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^VolumeUnit/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^SizeUnit/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/^EMailText/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/ById$/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/ByLogin$/', $value)) {
$qualifiedforclean=0;
}
// printing // printing
if (preg_match('/PrintingDriverDesc$/', $value)) $qualifiedforclean=0; if (preg_match('/PrintingDriverDesc$/', $value)) {
if (preg_match('/PrintTestDesc$/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
}
if (preg_match('/PrintTestDesc$/', $value)) {
$qualifiedforclean=0;
}
// products // products
if (preg_match('/GlobalVariableUpdaterType$/', $value)) $qualifiedforclean=0; if (preg_match('/GlobalVariableUpdaterType$/', $value)) {
if (preg_match('/GlobalVariableUpdaterHelp$/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/OppStatus/', $value)) $qualifiedforclean=0; }
if (preg_match('/AvailabilityType/', $value)) $qualifiedforclean=0; if (preg_match('/GlobalVariableUpdaterHelp$/', $value)) {
if (preg_match('/CardProduct/', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
}
if (preg_match('/OppStatus/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/AvailabilityType/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/CardProduct/', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/sms/i', $value)) $qualifiedforclean=0; if (preg_match('/sms/i', $value)) {
if (preg_match('/TF_/i', $value)) $qualifiedforclean=0; $qualifiedforclean=0;
if (preg_match('/WithBankUsing/i', $value)) $qualifiedforclean=0; }
if (preg_match('/descWORKFLOW_/i', $value)) $qualifiedforclean=0; if (preg_match('/TF_/i', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/WithBankUsing/i', $value)) {
$qualifiedforclean=0;
}
if (preg_match('/descWORKFLOW_/i', $value)) {
$qualifiedforclean=0;
}
if (! $qualifiedforclean) if (! $qualifiedforclean) {
{
continue; continue;
} }
@ -359,28 +559,31 @@ if ((! empty($_REQUEST['unused']) && $_REQUEST['unused'] == 'true') || (isset($a
if (empty($output)) { if (empty($output)) {
$unused[$value] = $line; $unused[$value] = $line;
echo $line; // $trad contains the \n echo $line; // $trad contains the \n
} } else {
else {
unset($output); unset($output);
//print 'X'.$output.'Y'; //print 'X'.$output.'Y';
} }
} }
if (empty($unused)) print "No string not used found.\n"; if (empty($unused)) {
else { print "No string not used found.\n";
} else {
$filetosave='/tmp/'.($argv[2]?$argv[2]:"").'notused.lang'; $filetosave='/tmp/'.($argv[2]?$argv[2]:"").'notused.lang';
print "Strings in en_US that are never used are saved into file ".$filetosave.":\n"; print "Strings in en_US that are never used are saved into file ".$filetosave.":\n";
file_put_contents($filetosave, implode("", $unused)); file_put_contents($filetosave, implode("", $unused));
print "To remove from original file, run command :\n"; print "To remove from original file, run command :\n";
if (($argv[2]?$argv[2]:"")) print 'cd htdocs/langs/en_US; mv '.($argv[2]?$argv[2]:"")." ".($argv[2]?$argv[2]:"").".tmp; "; if (($argv[2]?$argv[2]:"")) {
print 'cd htdocs/langs/en_US; mv '.($argv[2]?$argv[2]:"")." ".($argv[2]?$argv[2]:"").".tmp; ";
}
print "diff ".($argv[2]?$argv[2]:"").".tmp ".$filetosave." | grep \< | cut -b 3- > ".($argv[2]?$argv[2]:""); print "diff ".($argv[2]?$argv[2]:"").".tmp ".$filetosave." | grep \< | cut -b 3- > ".($argv[2]?$argv[2]:"");
if (($argv[2]?$argv[2]:"")) print "; rm ".($argv[2]?$argv[2]:"").".tmp;\n"; if (($argv[2]?$argv[2]:"")) {
print "; rm ".($argv[2]?$argv[2]:"").".tmp;\n";
}
} }
} }
echo "\n"; echo "\n";
if ($web) if ($web) {
{
echo "</body>\n"; echo "</body>\n";
echo "</html>\n"; echo "</html>\n";
} }

View File

@ -63,8 +63,7 @@ $lSecondary = isset($argv[2])?$argv[2]:'';
$lEnglish = 'en_US'; $lEnglish = 'en_US';
$filesToProcess = isset($argv[3])?$argv[3]:''; $filesToProcess = isset($argv[3])?$argv[3]:'';
if (empty($lPrimary) || empty($lSecondary) || empty($filesToProcess)) if (empty($lPrimary) || empty($lSecondary) || empty($filesToProcess)) {
{
$rc = 1; $rc = 1;
$msg = '***** Script to clean language files *****'."\n"; $msg = '***** Script to clean language files *****'."\n";
$msg.= 'Usage: ./dev/translation/strip_language_file.php xx_XX xx_YY [file.lang|all]'."\n"; $msg.= 'Usage: ./dev/translation/strip_language_file.php xx_XX xx_YY [file.lang|all]'."\n";
@ -77,8 +76,7 @@ $aSecondary = array();
$aEnglish = array(); $aEnglish = array();
// Define array $filesToProcess // Define array $filesToProcess
if ($filesToProcess == 'all') if ($filesToProcess == 'all') {
{
$dir = new DirectoryIterator('htdocs/langs/'.$lPrimary); $dir = new DirectoryIterator('htdocs/langs/'.$lPrimary);
while ($dir->valid()) { while ($dir->valid()) {
if (!$dir->isDot() && $dir->isFile() && ! preg_match('/^\./', $dir->getFilename())) { if (!$dir->isDot() && $dir->isFile() && ! preg_match('/^\./', $dir->getFilename())) {
@ -87,15 +85,15 @@ if ($filesToProcess == 'all')
$dir->next(); $dir->next();
} }
$filesToProcess=$files; $filesToProcess=$files;
} else {
$filesToProcess=explode(',', $filesToProcess);
} }
else $filesToProcess=explode(',', $filesToProcess);
// Arguments should be OK here. // Arguments should be OK here.
// Loop on each file // Loop on each file
foreach ($filesToProcess as $fileToProcess) foreach ($filesToProcess as $fileToProcess) {
{
$lPrimaryFile = 'htdocs/langs/'.$lPrimary.'/'.$fileToProcess; $lPrimaryFile = 'htdocs/langs/'.$lPrimary.'/'.$fileToProcess;
$lSecondaryFile = 'htdocs/langs/'.$lSecondary.'/'.$fileToProcess; $lSecondaryFile = 'htdocs/langs/'.$lSecondary.'/'.$fileToProcess;
$lEnglishFile = 'htdocs/langs/'.$lEnglish.'/'.$fileToProcess; $lEnglishFile = 'htdocs/langs/'.$lEnglish.'/'.$fileToProcess;
@ -103,21 +101,21 @@ foreach ($filesToProcess as $fileToProcess)
print "---- Process language file ".$lSecondaryFile."\n"; print "---- Process language file ".$lSecondaryFile."\n";
if ( ! is_readable($lPrimaryFile) ) { if (! is_readable($lPrimaryFile)) {
$rc = 2; $rc = 2;
$msg = "Cannot read primary language file $lPrimaryFile."; $msg = "Cannot read primary language file $lPrimaryFile.";
print $msg . " (rc=$rc).\n"; print $msg . " (rc=$rc).\n";
exit($rc); exit($rc);
} }
if ( ! is_readable($lSecondaryFile) ) { if (! is_readable($lSecondaryFile)) {
$rc = 3; $rc = 3;
$msg = "Cannot read secondary language file $lSecondaryFile. We discard this file."; $msg = "Cannot read secondary language file $lSecondaryFile. We discard this file.";
print $msg . "\n"; print $msg . "\n";
continue; continue;
} }
if ( ! is_readable($lEnglishFile) ) { if (! is_readable($lEnglishFile)) {
$rc = 3; $rc = 3;
$msg = "Cannot read english language file $lEnglishFile. We discard this file."; $msg = "Cannot read english language file $lEnglishFile. We discard this file.";
print $msg . "\n"; print $msg . "\n";
@ -126,25 +124,23 @@ foreach ($filesToProcess as $fileToProcess)
// Start reading and parsing Secondary // Start reading and parsing Secondary
if ( $handle = fopen($lSecondaryFile, 'r') ) if ($handle = fopen($lSecondaryFile, 'r')) {
{
print "Read Secondary File $lSecondaryFile:\n"; print "Read Secondary File $lSecondaryFile:\n";
$cnt = 0; $cnt = 0;
while (($line = fgets($handle)) !== false) while (($line = fgets($handle)) !== false) {
{
$cnt++; $cnt++;
// strip comments // strip comments
if ( preg_match("/^\w*#/", $line) ) { if (preg_match("/^\w*#/", $line)) {
continue; continue;
} }
// strip empty lines // strip empty lines
if ( preg_match("/^\w*$/", $line) ) { if (preg_match("/^\w*$/", $line)) {
continue; continue;
} }
$a = mb_split('=', trim($line), 2); $a = mb_split('=', trim($line), 2);
if ( count($a) != 2 ) { if (count($a) != 2) {
print "ERROR in file $lSecondaryFile, line $cnt: " . trim($line) . "\n"; print "ERROR in file $lSecondaryFile, line $cnt: " . trim($line) . "\n";
continue; continue;
} }
@ -152,29 +148,27 @@ foreach ($filesToProcess as $fileToProcess)
list($key, $value) = $a; list($key, $value) = $a;
// key is redundant // key is redundant
if ( array_key_exists($key, $aSecondary) ) { if (array_key_exists($key, $aSecondary)) {
print "Key $key is redundant in file $lSecondaryFile (line: $cnt).\n"; print "Key $key is redundant in file $lSecondaryFile (line: $cnt).\n";
continue; continue;
} }
// String has no value // String has no value
if ( $value == '' ) { if ($value == '') {
print "Key $key has no value in file $lSecondaryFile (line: $cnt).\n"; print "Key $key has no value in file $lSecondaryFile (line: $cnt).\n";
continue; continue;
} }
$aSecondary[$key] = trim($value); $aSecondary[$key] = trim($value);
} }
if ( ! feof($handle) ) if (! feof($handle)) {
{
$rc = 5; $rc = 5;
$msg = "Unexpected fgets() fail"; $msg = "Unexpected fgets() fail";
print $msg . " (rc=$rc).\n"; print $msg . " (rc=$rc).\n";
exit($rc); exit($rc);
} }
fclose($handle); fclose($handle);
} } else {
else {
$rc = 6; $rc = 6;
$msg = "Cannot open file $lSecondaryFile"; $msg = "Cannot open file $lSecondaryFile";
print $msg . " (rc=$rc).\n"; print $msg . " (rc=$rc).\n";
@ -184,25 +178,23 @@ foreach ($filesToProcess as $fileToProcess)
// Start reading and parsing English // Start reading and parsing English
if ( $handle = fopen($lEnglishFile, 'r') ) if ($handle = fopen($lEnglishFile, 'r')) {
{
print "Read English File $lEnglishFile:\n"; print "Read English File $lEnglishFile:\n";
$cnt = 0; $cnt = 0;
while (($line = fgets($handle)) !== false) while (($line = fgets($handle)) !== false) {
{
$cnt++; $cnt++;
// strip comments // strip comments
if ( preg_match("/^\w*#/", $line) ) { if (preg_match("/^\w*#/", $line)) {
continue; continue;
} }
// strip empty lines // strip empty lines
if ( preg_match("/^\w*$/", $line) ) { if (preg_match("/^\w*$/", $line)) {
continue; continue;
} }
$a = mb_split('=', trim($line), 2); $a = mb_split('=', trim($line), 2);
if ( count($a) != 2 ) { if (count($a) != 2) {
print "ERROR in file $lEnglishFile, line $cnt: " . trim($line) . "\n"; print "ERROR in file $lEnglishFile, line $cnt: " . trim($line) . "\n";
continue; continue;
} }
@ -210,29 +202,27 @@ foreach ($filesToProcess as $fileToProcess)
list($key, $value) = $a; list($key, $value) = $a;
// key is redundant // key is redundant
if ( array_key_exists($key, $aEnglish) ) { if (array_key_exists($key, $aEnglish)) {
print "Key $key is redundant in file $lEnglishFile (line: $cnt).\n"; print "Key $key is redundant in file $lEnglishFile (line: $cnt).\n";
continue; continue;
} }
// String has no value // String has no value
if ( $value == '' ) { if ($value == '') {
print "Key $key has no value in file $lEnglishFile (line: $cnt).\n"; print "Key $key has no value in file $lEnglishFile (line: $cnt).\n";
continue; continue;
} }
$aEnglish[$key] = trim($value); $aEnglish[$key] = trim($value);
} }
if ( ! feof($handle) ) if (! feof($handle)) {
{
$rc = 5; $rc = 5;
$msg = "Unexpected fgets() fail"; $msg = "Unexpected fgets() fail";
print $msg . " (rc=$rc).\n"; print $msg . " (rc=$rc).\n";
exit($rc); exit($rc);
} }
fclose($handle); fclose($handle);
} } else {
else {
$rc = 6; $rc = 6;
$msg = "Cannot open file $lEnglishFile"; $msg = "Cannot open file $lEnglishFile";
print $msg . " (rc=$rc).\n"; print $msg . " (rc=$rc).\n";
@ -246,10 +236,8 @@ foreach ($filesToProcess as $fileToProcess)
$arrayofkeytoalwayskeep=array('DIRECTION','FONTFORPDF','FONTSIZEFORPDF','SeparatorDecimal','SeparatorThousand'); $arrayofkeytoalwayskeep=array('DIRECTION','FONTFORPDF','FONTSIZEFORPDF','SeparatorDecimal','SeparatorThousand');
if ( $handle = fopen($lPrimaryFile, 'r') ) if ($handle = fopen($lPrimaryFile, 'r')) {
{ if (! $oh = fopen($output, 'w')) {
if ( ! $oh = fopen($output, 'w') )
{
print "ERROR in writing to file ".$output."\n"; print "ERROR in writing to file ".$output."\n";
exit; exit;
} }
@ -259,21 +247,20 @@ foreach ($filesToProcess as $fileToProcess)
fwrite($oh, "# Dolibarr language file - Source file is en_US - ".(preg_replace('/\.lang$/', '', $fileToProcess))."\n"); fwrite($oh, "# Dolibarr language file - Source file is en_US - ".(preg_replace('/\.lang$/', '', $fileToProcess))."\n");
$cnt = 0; $cnt = 0;
while (($line = fgets($handle)) !== false) while (($line = fgets($handle)) !== false) {
{
$cnt++; $cnt++;
// strip comments // strip comments
if ( preg_match("/^\w*#/", $line) ) { if (preg_match("/^\w*#/", $line)) {
continue; continue;
} }
// strip empty lines // strip empty lines
if ( preg_match("/^\w*$/", $line) ) { if (preg_match("/^\w*$/", $line)) {
continue; continue;
} }
$a = mb_split('=', trim($line), 2); $a = mb_split('=', trim($line), 2);
if ( count($a) != 2 ) { if (count($a) != 2) {
print "ERROR in file $lPrimaryFile, line $cnt: " . trim($line) . "\n"; print "ERROR in file $lPrimaryFile, line $cnt: " . trim($line) . "\n";
continue; continue;
} }
@ -281,17 +268,16 @@ foreach ($filesToProcess as $fileToProcess)
list($key, $value) = $a; list($key, $value) = $a;
// key is redundant // key is redundant
if ( array_key_exists($key, $aPrimary) ) { if (array_key_exists($key, $aPrimary)) {
print "Key $key is redundant in file $lPrimaryFile (line: $cnt) - Already found into ".$fileFirstFound[$key]." (line: ".$lineFirstFound[$key].").\n"; print "Key $key is redundant in file $lPrimaryFile (line: $cnt) - Already found into ".$fileFirstFound[$key]." (line: ".$lineFirstFound[$key].").\n";
continue; continue;
} } else {
else {
$fileFirstFound[$key] = $fileToProcess; $fileFirstFound[$key] = $fileToProcess;
$lineFirstFound[$key] = $cnt; $lineFirstFound[$key] = $cnt;
} }
// String has no value // String has no value
if ( $value == '' ) { if ($value == '') {
print "Key $key has no value in file $lPrimaryFile (line: $cnt).\n"; print "Key $key has no value in file $lPrimaryFile (line: $cnt).\n";
continue; continue;
} }
@ -305,28 +291,23 @@ foreach ($filesToProcess as $fileToProcess)
//print "Found primary key = ".$key."\n"; //print "Found primary key = ".$key."\n";
// Key not in other file // Key not in other file
if (in_array($key, $arrayofkeytoalwayskeep) || preg_match('/^FormatDate/', $key) || preg_match('/^FormatHour/', $key)) if (in_array($key, $arrayofkeytoalwayskeep) || preg_match('/^FormatDate/', $key) || preg_match('/^FormatHour/', $key)) {
{
//print "Key $key is a key we always want to see into secondary file (line: $cnt).\n"; //print "Key $key is a key we always want to see into secondary file (line: $cnt).\n";
} } elseif (! array_key_exists($key, $aSecondary)) {
elseif ( ! array_key_exists($key, $aSecondary))
{
//print "Key $key does NOT exist in secondary language (line: $cnt).\n"; //print "Key $key does NOT exist in secondary language (line: $cnt).\n";
continue; continue;
} }
// String exists in both files and value into alternative language differs from main language but also from english files // String exists in both files and value into alternative language differs from main language but also from english files
if ( if ((! empty($aSecondary[$key]) && $aSecondary[$key] != $aPrimary[$key]
(! empty($aSecondary[$key]) && $aSecondary[$key] != $aPrimary[$key]
&& ! empty($aEnglish[$key]) && $aSecondary[$key] != $aEnglish[$key]) && ! empty($aEnglish[$key]) && $aSecondary[$key] != $aEnglish[$key])
|| in_array($key, $arrayofkeytoalwayskeep) || preg_match('/^FormatDate/', $key) || preg_match('/^FormatHour/', $key) || in_array($key, $arrayofkeytoalwayskeep) || preg_match('/^FormatDate/', $key) || preg_match('/^FormatHour/', $key)
) ) {
{
//print "Key $key differs (aSecondary=".$aSecondary[$key].", aPrimary=".$aPrimary[$key].", aEnglish=".$aEnglish[$key].") so we add it into new secondary language (line: $cnt).\n"; //print "Key $key differs (aSecondary=".$aSecondary[$key].", aPrimary=".$aPrimary[$key].", aEnglish=".$aEnglish[$key].") so we add it into new secondary language (line: $cnt).\n";
fwrite($oh, $key."=".(empty($aSecondary[$key])?$aPrimary[$key]:$aSecondary[$key])."\n"); fwrite($oh, $key."=".(empty($aSecondary[$key])?$aPrimary[$key]:$aSecondary[$key])."\n");
} }
} }
if ( ! feof($handle) ) { if (! feof($handle)) {
$rc = 7; $rc = 7;
$msg = "Unexpected fgets() fail"; $msg = "Unexpected fgets() fail";
print $msg . " (rc=$rc).\n"; print $msg . " (rc=$rc).\n";
@ -334,8 +315,7 @@ foreach ($filesToProcess as $fileToProcess)
} }
fclose($oh); fclose($oh);
fclose($handle); fclose($handle);
} } else {
else {
$rc = 8; $rc = 8;
$msg = "Cannot open file $lPrimaryFile"; $msg = "Cannot open file $lPrimaryFile";
print $msg . " (rc=$rc).\n"; print $msg . " (rc=$rc).\n";

View File

@ -37,7 +37,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array("admin", "members")); $langs->loadLangs(array("admin", "members"));
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
$choices = array('yesno', 'texte', 'chaine'); $choices = array('yesno', 'texte', 'chaine');
@ -126,17 +128,24 @@ if ($action == 'update' || $action == 'add') {
$constname = GETPOST('constname', 'alpha'); $constname = GETPOST('constname', 'alpha');
$constvalue = (GETPOST('constvalue_'.$constname) ? GETPOST('constvalue_'.$constname) : GETPOST('constvalue')); $constvalue = (GETPOST('constvalue_'.$constname) ? GETPOST('constvalue_'.$constname) : GETPOST('constvalue'));
if (($constname == 'ADHERENT_CARD_TYPE' || $constname == 'ADHERENT_ETIQUETTE_TYPE' || $constname == 'ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS') && $constvalue == -1) $constvalue = ''; if (($constname == 'ADHERENT_CARD_TYPE' || $constname == 'ADHERENT_ETIQUETTE_TYPE' || $constname == 'ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS') && $constvalue == -1) {
$constvalue = '';
}
if ($constname == 'ADHERENT_LOGIN_NOT_REQUIRED') { // Invert choice if ($constname == 'ADHERENT_LOGIN_NOT_REQUIRED') { // Invert choice
if ($constvalue) $constvalue = 0; if ($constvalue) {
else $constvalue = 1; $constvalue = 0;
} else {
$constvalue = 1;
}
} }
$consttype = GETPOST('consttype', 'alpha'); $consttype = GETPOST('consttype', 'alpha');
$constnote = GETPOST('constnote'); $constnote = GETPOST('constnote');
$res = dolibarr_set_const($db, $constname, $constvalue, $choices[$consttype], 0, $constnote, $conf->entity); $res = dolibarr_set_const($db, $constname, $constvalue, $choices[$consttype], 0, $constnote, $conf->entity);
if (!($res > 0)) $error++; if (!($res > 0)) {
$error++;
}
if (!$error) { if (!$error) {
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
@ -211,9 +220,15 @@ print "</td></tr>\n";
// Insert subscription into bank account // Insert subscription into bank account
print '<tr class="oddeven"><td>'.$langs->trans("MoreActionsOnSubscription").'</td>'; print '<tr class="oddeven"><td>'.$langs->trans("MoreActionsOnSubscription").'</td>';
$arraychoices = array('0'=>$langs->trans("None")); $arraychoices = array('0'=>$langs->trans("None"));
if (!empty($conf->banque->enabled)) $arraychoices['bankdirect'] = $langs->trans("MoreActionBankDirect"); if (!empty($conf->banque->enabled)) {
if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $arraychoices['invoiceonly'] = $langs->trans("MoreActionInvoiceOnly"); $arraychoices['bankdirect'] = $langs->trans("MoreActionBankDirect");
if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $arraychoices['bankviainvoice'] = $langs->trans("MoreActionBankViaInvoice"); }
if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) {
$arraychoices['invoiceonly'] = $langs->trans("MoreActionInvoiceOnly");
}
if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) {
$arraychoices['bankviainvoice'] = $langs->trans("MoreActionBankViaInvoice");
}
print '<td>'; print '<td>';
print $form->selectarray('ADHERENT_BANK_USE', $arraychoices, $conf->global->ADHERENT_BANK_USE, 0); print $form->selectarray('ADHERENT_BANK_USE', $arraychoices, $conf->global->ADHERENT_BANK_USE, 0);
if ($conf->global->ADHERENT_BANK_USE == 'bankdirect' || $conf->global->ADHERENT_BANK_USE == 'bankviainvoice') { if ($conf->global->ADHERENT_BANK_USE == 'bankdirect' || $conf->global->ADHERENT_BANK_USE == 'bankviainvoice') {
@ -349,7 +364,9 @@ foreach ($dirmodels as $reldir) {
$module = new $classname($db); $module = new $classname($db);
$modulequalified = 1; $modulequalified = 1;
if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
$modulequalified = 0;
}
if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
$modulequalified = 0; $modulequalified = 0;
} }
@ -404,8 +421,7 @@ foreach ($dirmodels as $reldir) {
// Preview // Preview
print '<td class="center">'; print '<td class="center">';
if ($module->type == 'pdf') if ($module->type == 'pdf') {
{
print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'">'.img_object($langs->trans("Preview"), 'contract').'</a>'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'">'.img_object($langs->trans("Preview"), 'contract').'</a>';
} else { } else {
print img_object($langs->trans("PreviewNotAvailable"), 'generic'); print img_object($langs->trans("PreviewNotAvailable"), 'generic');

View File

@ -36,7 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array("admin", "members")); $langs->loadLangs(array("admin", "members"));
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
$oldtypetonewone = array('texte'=>'text', 'chaine'=>'string'); // old type to new ones $oldtypetonewone = array('texte'=>'text', 'chaine'=>'string'); // old type to new ones
@ -92,7 +94,9 @@ if ($action == 'update' || $action == 'add') {
$res = dolibarr_set_const($db, $constname, $constvalue, $typetouse, 0, $constnote, $conf->entity); $res = dolibarr_set_const($db, $constname, $constvalue, $typetouse, 0, $constnote, $conf->entity);
if (!($res > 0)) $error++; if (!($res > 0)) {
$error++;
}
if (!$error) { if (!$error) {
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');

View File

@ -37,13 +37,17 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'adherent'; //Must be the $table_element of the class that manage extrafield $elementtype = 'adherent'; //Must be the $table_element of the class that manage extrafield
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*

View File

@ -40,13 +40,17 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'adherent_type'; //Must be the $table_element of the class that manage extrafield $elementtype = 'adherent_type'; //Must be the $table_element of the class that manage extrafield
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*

View File

@ -35,7 +35,9 @@ $langs->loadLangs(array("admin", "members"));
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*
@ -43,8 +45,11 @@ if (!$user->admin) accessforbidden();
*/ */
if ($action == 'setMEMBER_ENABLE_PUBLIC') { if ($action == 'setMEMBER_ENABLE_PUBLIC') {
if (GETPOST('value')) dolibarr_set_const($db, 'MEMBER_ENABLE_PUBLIC', 1, 'chaine', 0, '', $conf->entity); if (GETPOST('value')) {
else dolibarr_set_const($db, 'MEMBER_ENABLE_PUBLIC', 0, 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, 'MEMBER_ENABLE_PUBLIC', 1, 'chaine', 0, '', $conf->entity);
} else {
dolibarr_set_const($db, 'MEMBER_ENABLE_PUBLIC', 0, 'chaine', 0, '', $conf->entity);
}
} }
if ($action == 'update') { if ($action == 'update') {
@ -58,12 +63,15 @@ if ($action == 'update') {
$res = dolibarr_set_const($db, "MEMBER_NEWFORM_AMOUNT", $amount, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "MEMBER_NEWFORM_AMOUNT", $amount, 'chaine', 0, '', $conf->entity);
$res = dolibarr_set_const($db, "MEMBER_NEWFORM_EDITAMOUNT", $editamount, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "MEMBER_NEWFORM_EDITAMOUNT", $editamount, 'chaine', 0, '', $conf->entity);
$res = dolibarr_set_const($db, "MEMBER_NEWFORM_PAYONLINE", $payonline, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "MEMBER_NEWFORM_PAYONLINE", $payonline, 'chaine', 0, '', $conf->entity);
if ($forcetype < 0) $res = dolibarr_del_const($db, "MEMBER_NEWFORM_FORCETYPE", $conf->entity); if ($forcetype < 0) {
else { $res = dolibarr_del_const($db, "MEMBER_NEWFORM_FORCETYPE", $conf->entity);
} else {
$res = dolibarr_set_const($db, "MEMBER_NEWFORM_FORCETYPE", $forcetype, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "MEMBER_NEWFORM_FORCETYPE", $forcetype, 'chaine', 0, '', $conf->entity);
} }
if (!($res > 0)) $error++; if (!($res > 0)) {
$error++;
}
if (!$error) { if (!$error) {
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
@ -195,9 +203,15 @@ if (!empty($conf->global->MEMBER_ENABLE_PUBLIC)) {
$listofval = array(); $listofval = array();
$listofval['-1'] = $langs->trans('No'); $listofval['-1'] = $langs->trans('No');
$listofval['all'] = $langs->trans('Yes').' ('.$langs->trans("VisitorCanChooseItsPaymentMode").')'; $listofval['all'] = $langs->trans('Yes').' ('.$langs->trans("VisitorCanChooseItsPaymentMode").')';
if (!empty($conf->paybox->enabled)) $listofval['paybox'] = 'Paybox'; if (!empty($conf->paybox->enabled)) {
if (!empty($conf->paypal->enabled)) $listofval['paypal'] = 'PayPal'; $listofval['paybox'] = 'Paybox';
if (!empty($conf->stripe->enabled)) $listofval['stripe'] = 'Stripe'; }
if (!empty($conf->paypal->enabled)) {
$listofval['paypal'] = 'PayPal';
}
if (!empty($conf->stripe->enabled)) {
$listofval['stripe'] = 'Stripe';
}
print $form->selectarray("MEMBER_NEWFORM_PAYONLINE", $listofval, (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE) ? $conf->global->MEMBER_NEWFORM_PAYONLINE : ''), 0); print $form->selectarray("MEMBER_NEWFORM_PAYONLINE", $listofval, (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE) ? $conf->global->MEMBER_NEWFORM_PAYONLINE : ''), 0);
print "</td></tr>\n"; print "</td></tr>\n";

View File

@ -42,16 +42,24 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortfield) $sortfield = 'a.datep,a.id'; if (!$sortfield) {
if (!$sortorder) $sortorder = 'DESC'; $sortfield = 'a.datep,a.id';
}
if (!$sortorder) {
$sortorder = 'DESC';
}
if (GETPOST('actioncode', 'array')) { if (GETPOST('actioncode', 'array')) {
$actioncode = GETPOST('actioncode', 'array', 3); $actioncode = GETPOST('actioncode', 'array', 3);
if (!count($actioncode)) $actioncode = '0'; if (!count($actioncode)) {
$actioncode = '0';
}
} else { } else {
$actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)); $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
} }
@ -76,7 +84,9 @@ if ($result > 0) {
$parameters = array('id'=>$id, 'objcanvas'=>$objcanvas); $parameters = array('id'=>$id, 'objcanvas'=>$objcanvas);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) { if (empty($reshook)) {
// Cancel // Cancel
@ -115,7 +125,9 @@ if ($object->id > 0) {
$helpurl = "EN:Module_Foundations|FR:Module_Adh&eacute;rents|ES:M&oacute;dulo_Miembros"; $helpurl = "EN:Module_Foundations|FR:Module_Adh&eacute;rents|ES:M&oacute;dulo_Miembros";
llxHeader("", $title, $helpurl); llxHeader("", $title, $helpurl);
if (!empty($conf->notification->enabled)) $langs->load("mails"); if (!empty($conf->notification->enabled)) {
$langs->load("mails");
}
$head = member_prepare_head($object); $head = member_prepare_head($object);
print dol_get_fiche_head($head, 'agenda', $langs->trans("Member"), -1, 'user'); print dol_get_fiche_head($head, 'agenda', $langs->trans("Member"), -1, 'user');
@ -149,8 +161,12 @@ if ($object->id > 0) {
print '<br>'; print '<br>';
$param = '&id='.$id; $param = '&id='.$id;
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; $param .= '&contextpage='.$contextpage;
}
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.$limit;
}
print_barre_liste($langs->trans("ActionsOnMember"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', '', $newcardbutton, '', 0, 1, 1); print_barre_liste($langs->trans("ActionsOnMember"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', '', $newcardbutton, '', 0, 1, 1);

View File

@ -70,7 +70,9 @@ abstract class ActionsAdherentCardCommon
else else
{*/ {*/
$object = new Adherent($this->db); $object = new Adherent($this->db);
if (!empty($id)) $object->fetch($id); if (!empty($id)) {
$object->fetch($id);
}
$this->object = $object; $this->object = $object;
//} //}
} }
@ -89,7 +91,9 @@ abstract class ActionsAdherentCardCommon
global $conf, $langs, $user, $canvas; global $conf, $langs, $user, $canvas;
global $form, $formcompany, $objsoc; global $form, $formcompany, $objsoc;
if ($action == 'add' || $action == 'update') $this->assign_post(); if ($action == 'add' || $action == 'update') {
$this->assign_post();
}
foreach ($this->object as $key => $value) { foreach ($this->object as $key => $value) {
$this->tpl[$key] = $value; $this->tpl[$key] = $value;
@ -123,12 +127,24 @@ abstract class ActionsAdherentCardCommon
// Predefined with third party // Predefined with third party
if ((isset($objsoc->typent_code) && $objsoc->typent_code == 'TE_PRIVATE')) { if ((isset($objsoc->typent_code) && $objsoc->typent_code == 'TE_PRIVATE')) {
if (dol_strlen(trim($this->object->address)) == 0) $this->tpl['address'] = $objsoc->address; if (dol_strlen(trim($this->object->address)) == 0) {
if (dol_strlen(trim($this->object->zip)) == 0) $this->object->zip = $objsoc->zip; $this->tpl['address'] = $objsoc->address;
if (dol_strlen(trim($this->object->town)) == 0) $this->object->town = $objsoc->town; }
if (dol_strlen(trim($this->object->phone_perso)) == 0) $this->object->phone_perso = $objsoc->phone; if (dol_strlen(trim($this->object->zip)) == 0) {
if (dol_strlen(trim($this->object->phone_mobile)) == 0) $this->object->phone_mobile = $objsoc->phone_mobile; $this->object->zip = $objsoc->zip;
if (dol_strlen(trim($this->object->email)) == 0) $this->object->email = $objsoc->email; }
if (dol_strlen(trim($this->object->town)) == 0) {
$this->object->town = $objsoc->town;
}
if (dol_strlen(trim($this->object->phone_perso)) == 0) {
$this->object->phone_perso = $objsoc->phone;
}
if (dol_strlen(trim($this->object->phone_mobile)) == 0) {
$this->object->phone_mobile = $objsoc->phone_mobile;
}
if (dol_strlen(trim($this->object->email)) == 0) {
$this->object->email = $objsoc->email;
}
} }
// Zip // Zip
@ -137,17 +153,24 @@ abstract class ActionsAdherentCardCommon
// Town // Town
$this->tpl['select_town'] = $formcompany->select_ziptown($this->object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id')); $this->tpl['select_town'] = $formcompany->select_ziptown($this->object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id'));
if (dol_strlen(trim($this->object->country_id)) == 0) $this->object->country_id = $objsoc->country_id; if (dol_strlen(trim($this->object->country_id)) == 0) {
$this->object->country_id = $objsoc->country_id;
}
// Country // Country
$this->tpl['select_country'] = $form->select_country($this->object->country_id, 'country_id'); $this->tpl['select_country'] = $form->select_country($this->object->country_id, 'country_id');
$countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; $countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')';
if ($user->admin) $this->tpl['info_admin'] = info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); if ($user->admin) {
$this->tpl['info_admin'] = info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
}
// State // State
if ($this->object->country_id) $this->tpl['select_state'] = $formcompany->select_state($this->object->state_id, $this->object->country_code); if ($this->object->country_id) {
else $this->tpl['select_state'] = $countrynotdefined; $this->tpl['select_state'] = $formcompany->select_state($this->object->state_id, $this->object->country_code);
} else {
$this->tpl['select_state'] = $countrynotdefined;
}
// Physical or Moral // Physical or Moral
$selectarray = array('0'=>$langs->trans("Physical"), '1'=>$langs->trans("Moral")); $selectarray = array('0'=>$langs->trans("Physical"), '1'=>$langs->trans("Moral"));
@ -166,7 +189,9 @@ abstract class ActionsAdherentCardCommon
$dolibarr_user = new User($this->db); $dolibarr_user = new User($this->db);
$result = $dolibarr_user->fetch($this->object->user_id); $result = $dolibarr_user->fetch($this->object->user_id);
$this->tpl['dolibarr_user'] = $dolibarr_user->getLoginUrl(1); $this->tpl['dolibarr_user'] = $dolibarr_user->getLoginUrl(1);
} else $this->tpl['dolibarr_user'] = $langs->trans("NoDolibarrAccess"); } else {
$this->tpl['dolibarr_user'] = $langs->trans("NoDolibarrAccess");
}
} }
if ($action == 'view' || $action == 'delete') { if ($action == 'view' || $action == 'delete') {

View File

@ -60,9 +60,15 @@ class ActionsAdherentCardDefault extends ActionsAdherentCardCommon
$out = ''; $out = '';
if ($action == 'view') $out .= (!empty($conf->global->ADHERENT_ADDRESSES_MANAGEMENT) ? $langs->trans("Adherent") : $langs->trans("ContactAddress")); if ($action == 'view') {
if ($action == 'edit') $out .= (!empty($conf->global->ADHERENT_ADDRESSES_MANAGEMENT) ? $langs->trans("EditAdherent") : $langs->trans("EditAdherentAddress")); $out .= (!empty($conf->global->ADHERENT_ADDRESSES_MANAGEMENT) ? $langs->trans("Adherent") : $langs->trans("ContactAddress"));
if ($action == 'create') $out .= (!empty($conf->global->ADHERENT_ADDRESSES_MANAGEMENT) ? $langs->trans("NewAdherent") : $langs->trans("NewAdherentAddress")); }
if ($action == 'edit') {
$out .= (!empty($conf->global->ADHERENT_ADDRESSES_MANAGEMENT) ? $langs->trans("EditAdherent") : $langs->trans("EditAdherentAddress"));
}
if ($action == 'create') {
$out .= (!empty($conf->global->ADHERENT_ADDRESSES_MANAGEMENT) ? $langs->trans("NewAdherent") : $langs->trans("NewAdherentAddress"));
}
return $out; return $out;
} }

View File

@ -29,8 +29,12 @@ echo "<!-- BEGIN PHP TEMPLATE ADHERENTCARD_VIEW.TPL.PHP DEFAULT -->\n";
echo $this->control->tpl['showhead']; echo $this->control->tpl['showhead'];
dol_htmloutput_errors($this->control->tpl['error'], $this->control->tpl['errors']); dol_htmloutput_errors($this->control->tpl['error'], $this->control->tpl['errors']);
if (!empty($this->control->tpl['action_create_user'])) echo $this->control->tpl['action_create_user']; if (!empty($this->control->tpl['action_create_user'])) {
if (!empty($this->control->tpl['action_delete'])) echo $this->control->tpl['action_delete']; ?> echo $this->control->tpl['action_create_user'];
}
if (!empty($this->control->tpl['action_delete'])) {
echo $this->control->tpl['action_delete'];
} ?>
<table class="border allwidth"> <table class="border allwidth">

View File

@ -118,7 +118,9 @@ if ($id) {
$parameters = array('id'=>$id, 'rowid'=>$id, 'objcanvas'=>$objcanvas, 'confirm'=>$confirm); $parameters = array('id'=>$id, 'rowid'=>$id, 'objcanvas'=>$objcanvas, 'confirm'=>$confirm);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) { if (empty($reshook)) {
if ($cancel) { if ($cancel) {
@ -141,7 +143,9 @@ if (empty($reshook)) {
if (!$error) { if (!$error) {
if ($userid != $object->user_id) { // If link differs from currently in database if ($userid != $object->user_id) { // If link differs from currently in database
$result = $object->setUserId($userid); $result = $object->setUserId($userid);
if ($result < 0) dol_print_error($object->db, $object->error); if ($result < 0) {
dol_print_error($object->db, $object->error);
}
$action = ''; $action = '';
} }
} }
@ -169,7 +173,9 @@ if (empty($reshook)) {
if (!$error) { if (!$error) {
$result = $object->setThirdPartyId($socid); $result = $object->setThirdPartyId($socid);
if ($result < 0) dol_print_error($object->db, $object->error); if ($result < 0) {
dol_print_error($object->db, $object->error);
}
$action = ''; $action = '';
} }
} }
@ -221,8 +227,7 @@ if (empty($reshook)) {
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$birthdate = ''; $birthdate = '';
if (GETPOST("birthday", 'int') && GETPOST("birthmonth", 'int') && GETPOST("birthyear", 'int')) if (GETPOST("birthday", 'int') && GETPOST("birthmonth", 'int') && GETPOST("birthyear", 'int')) {
{
$birthdate = dol_mktime(12, 0, 0, GETPOST("birthmonth", 'int'), GETPOST("birthday", 'int'), GETPOST("birthyear", 'int')); $birthdate = dol_mktime(12, 0, 0, GETPOST("birthmonth", 'int'), GETPOST("birthday", 'int'), GETPOST("birthyear", 'int'));
} }
$lastname = GETPOST("lastname", 'alphanohtml'); $lastname = GETPOST("lastname", 'alphanohtml');
@ -294,8 +299,11 @@ if (empty($reshook)) {
//$object->note = trim(GETPOST("comment","alpha")); //$object->note = trim(GETPOST("comment","alpha"));
$object->morphy = GETPOST("morphy", 'alpha'); $object->morphy = GETPOST("morphy", 'alpha');
if (GETPOST('deletephoto', 'alpha')) $object->photo = ''; if (GETPOST('deletephoto', 'alpha')) {
elseif (!empty($_FILES['photo']['name'])) $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); $object->photo = '';
} elseif (!empty($_FILES['photo']['name'])) {
$object->photo = dol_sanitizeFileName($_FILES['photo']['name']);
}
// Get status and public property // Get status and public property
$object->statut = GETPOST("statut", 'alpha'); $object->statut = GETPOST("statut", 'alpha');
@ -303,18 +311,24 @@ if (empty($reshook)) {
// Fill array 'array_options' with data from add form // Fill array 'array_options' with data from add form
$ret = $extrafields->setOptionalsFromPost(null, $object); $ret = $extrafields->setOptionalsFromPost(null, $object);
if ($ret < 0) $error++; if ($ret < 0) {
$error++;
}
// Check if we need to also synchronize user information // Check if we need to also synchronize user information
$nosyncuser = 0; $nosyncuser = 0;
if ($object->user_id) { // If linked to a user if ($object->user_id) { // If linked to a user
if ($user->id != $object->user_id && empty($user->rights->user->user->creer)) $nosyncuser = 1; // Disable synchronizing if ($user->id != $object->user_id && empty($user->rights->user->user->creer)) {
$nosyncuser = 1; // Disable synchronizing
}
} }
// Check if we need to also synchronize password information // Check if we need to also synchronize password information
$nosyncuserpass = 0; $nosyncuserpass = 0;
if ($object->user_id) { // If linked to a user if ($object->user_id) { // If linked to a user
if ($user->id != $object->user_id && empty($user->rights->user->user->password)) $nosyncuserpass = 1; // Disable synchronizing if ($user->id != $object->user_id && empty($user->rights->user->user->password)) {
$nosyncuserpass = 1; // Disable synchronizing
}
} }
$result = $object->update($user, 0, $nosyncuser, $nosyncuserpass); $result = $object->update($user, 0, $nosyncuser, $nosyncuserpass);
@ -380,7 +394,9 @@ if (empty($reshook)) {
} }
if ($action == 'add' && $user->rights->adherent->creer) { if ($action == 'add' && $user->rights->adherent->creer) {
if ($canvas) $object->canvas = $canvas; if ($canvas) {
$object->canvas = $canvas;
}
$birthdate = ''; $birthdate = '';
if (GETPOSTISSET("birthday") && GETPOST("birthday") && GETPOSTISSET("birthmonth") && GETPOST("birthmonth") && GETPOSTISSET("birthyear") && GETPOST("birthyear")) { if (GETPOSTISSET("birthday") && GETPOST("birthday") && GETPOSTISSET("birthmonth") && GETPOST("birthmonth") && GETPOSTISSET("birthyear") && GETPOST("birthyear")) {
$birthdate = dol_mktime(12, 0, 0, GETPOST("birthmonth", 'int'), GETPOST("birthday", 'int'), GETPOST("birthyear", 'int')); $birthdate = dol_mktime(12, 0, 0, GETPOST("birthmonth", 'int'), GETPOST("birthday", 'int'), GETPOST("birthyear", 'int'));
@ -461,7 +477,9 @@ if (empty($reshook)) {
// Fill array 'array_options' with data from add form // Fill array 'array_options' with data from add form
$ret = $extrafields->setOptionalsFromPost(null, $object); $ret = $extrafields->setOptionalsFromPost(null, $object);
if ($ret < 0) $error++; if ($ret < 0) {
$error++;
}
// Check parameters // Check parameters
if (empty($morphy) || $morphy == "-1") { if (empty($morphy) || $morphy == "-1") {
@ -515,7 +533,9 @@ if (empty($reshook)) {
setEventMessages($langs->trans("ErrorBadEMail", $email), null, 'errors'); setEventMessages($langs->trans("ErrorBadEMail", $email), null, 'errors');
} }
$public = 0; $public = 0;
if (isset($public)) $public = 1; if (isset($public)) {
$public = 1;
}
if (!$error) { if (!$error) {
$db->begin(); $db->begin();
@ -590,7 +610,9 @@ if (empty($reshook)) {
$arraydefaultmessage = null; $arraydefaultmessage = null;
$labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_MEMBER_VALIDATION; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_MEMBER_VALIDATION;
if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); if (!empty($labeltouse)) {
$arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
}
if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
$subject = $arraydefaultmessage->topic; $subject = $arraydefaultmessage->topic;
@ -659,7 +681,9 @@ if (empty($reshook)) {
$arraydefaultmessage = null; $arraydefaultmessage = null;
$labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_CANCELATION; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_CANCELATION;
if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); if (!empty($labeltouse)) {
$arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
}
if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
$subject = $arraydefaultmessage->topic; $subject = $arraydefaultmessage->topic;
@ -757,7 +781,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
if (empty($object->error) && $id) { if (empty($object->error) && $id) {
$object = new Adherent($db); $object = new Adherent($db);
$result = $object->fetch($id); $result = $object->fetch($id);
if ($result <= 0) dol_print_error('', $object->error); if ($result <= 0) {
dol_print_error('', $object->error);
}
} }
$objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates
$objcanvas->display_canvas($action); // Show template $objcanvas->display_canvas($action); // Show template
@ -785,7 +811,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
if (!empty($socid)) { if (!empty($socid)) {
$object = new Societe($db); $object = new Societe($db);
if ($socid > 0) $object->fetch($socid); if ($socid > 0) {
$object->fetch($socid);
}
if (!($object->id > 0)) { if (!($object->id > 0)) {
$langs->load("errors"); $langs->load("errors");
@ -832,7 +860,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="add">'; print '<input type="hidden" name="action" value="add">';
print '<input type="hidden" name="socid" value="'.$socid.'">'; print '<input type="hidden" name="socid" value="'.$socid.'">';
if ($backtopage) print '<input type="hidden" name="backtopage" value="'.($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"]).'">'; if ($backtopage) {
print '<input type="hidden" name="backtopage" value="'.($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"]).'">';
}
print dol_get_fiche_head(''); print dol_get_fiche_head('');
@ -913,7 +943,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
$object->country_id = $object->country_id ? $object->country_id : $mysoc->country_id; $object->country_id = $object->country_id ? $object->country_id : $mysoc->country_id;
print '<tr><td width="25%">'.$langs->trans('Country').'</td><td>'; print '<tr><td width="25%">'.$langs->trans('Country').'</td><td>';
print $form->select_country(GETPOSTISSET('country_id') ? GETPOST('country_id', 'alpha') : $object->country_id, 'country_id'); print $form->select_country(GETPOSTISSET('country_id') ? GETPOST('country_id', 'alpha') : $object->country_id, 'country_id');
if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); if ($user->admin) {
print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
}
print '</td></tr>'; print '</td></tr>';
// State // State
@ -941,7 +973,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
if (!empty($conf->socialnetworks->enabled)) { if (!empty($conf->socialnetworks->enabled)) {
foreach ($socialnetworks as $key => $value) { foreach ($socialnetworks as $key => $value) {
if (!$value['active']) break; if (!$value['active']) {
break;
}
print '<tr><td>'.$langs->trans($value['label']).'</td><td><input type="text" name="member_'.$key.'" size="40" value="'.(GETPOSTISSET('member_'.$key) ? GETPOST('member_'.$key, 'alpha') : $object->socialnetworks[$key]).'"></td></tr>'; print '<tr><td>'.$langs->trans($value['label']).'</td><td><input type="text" name="member_'.$key.'" size="40" value="'.(GETPOSTISSET('member_'.$key) ? GETPOST('member_'.$key, 'alpha') : $object->socialnetworks[$key]).'"></td></tr>';
} }
} }
@ -1057,7 +1091,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
print '<input type="hidden" name="action" value="update" />'; print '<input type="hidden" name="action" value="update" />';
print '<input type="hidden" name="rowid" value="'.$id.'" />'; print '<input type="hidden" name="rowid" value="'.$id.'" />';
print '<input type="hidden" name="statut" value="'.$object->statut.'" />'; print '<input type="hidden" name="statut" value="'.$object->statut.'" />';
if ($backtopage) print '<input type="hidden" name="backtopage" value="'.($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"]).'">'; if ($backtopage) {
print '<input type="hidden" name="backtopage" value="'.($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"]).'">';
}
print dol_get_fiche_head($head, 'general', $langs->trans("Member"), 0, 'user'); print dol_get_fiche_head($head, 'general', $langs->trans("Member"), 0, 'user');
@ -1121,9 +1157,13 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
print '<td class="hideonsmartphone" valign="middle">'; print '<td class="hideonsmartphone" valign="middle">';
print $form->showphoto('memberphoto', $object)."\n"; print $form->showphoto('memberphoto', $object)."\n";
if ($caneditfieldmember) { if ($caneditfieldmember) {
if ($object->photo) print "<br>\n"; if ($object->photo) {
print "<br>\n";
}
print '<table class="nobordernopadding">'; print '<table class="nobordernopadding">';
if ($object->photo) print '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>'; if ($object->photo) {
print '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
}
print '<tr><td>'.$langs->trans("PhotoFile").'</td></tr>'; print '<tr><td>'.$langs->trans("PhotoFile").'</td></tr>';
print '<tr><td><input type="file" class="flat" name="photo" id="photoinput"></td></tr>'; print '<tr><td><input type="file" class="flat" name="photo" id="photoinput"></td></tr>';
print '</table>'; print '</table>';
@ -1150,7 +1190,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
//$object->country_id=$object->country_id?$object->country_id:$mysoc->country_id; // In edit mode we don't force to company country if not defined //$object->country_id=$object->country_id?$object->country_id:$mysoc->country_id; // In edit mode we don't force to company country if not defined
print '<tr><td>'.$langs->trans('Country').'</td><td>'; print '<tr><td>'.$langs->trans('Country').'</td><td>';
print $form->select_country(GETPOSTISSET("country_id") ? GETPOST("country_id", "alpha") : $object->country_id, 'country_id'); print $form->select_country(GETPOSTISSET("country_id") ? GETPOST("country_id", "alpha") : $object->country_id, 'country_id');
if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); if ($user->admin) {
print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
}
print '</td></tr>'; print '</td></tr>';
// State // State
@ -1174,7 +1216,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
if (!empty($conf->socialnetworks->enabled)) { if (!empty($conf->socialnetworks->enabled)) {
foreach ($socialnetworks as $key => $value) { foreach ($socialnetworks as $key => $value) {
if (!$value['active']) break; if (!$value['active']) {
break;
}
print '<tr><td>'.$langs->trans($value['label']).'</td><td><input type="text" name="'.$key.'" class="minwidth100" value="'.(GETPOSTISSET($key) ? GETPOST($key, 'alphanohtml') : $object->socialnetworks[$key]).'"></td></tr>'; print '<tr><td>'.$langs->trans($value['label']).'</td><td><input type="text" name="'.$key.'" class="minwidth100" value="'.(GETPOSTISSET($key) ? GETPOST($key, 'alphanohtml') : $object->socialnetworks[$key]).'"></td></tr>';
} }
} }
@ -1223,7 +1267,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
print '<tr><td>'.$langs->trans("LinkedToDolibarrUser").'</td><td colspan="2" class="valeur">'; print '<tr><td>'.$langs->trans("LinkedToDolibarrUser").'</td><td colspan="2" class="valeur">';
if ($object->user_id) { if ($object->user_id) {
$form->form_users($_SERVER['PHP_SELF'].'?rowid='.$object->id, $object->user_id, 'none'); $form->form_users($_SERVER['PHP_SELF'].'?rowid='.$object->id, $object->user_id, 'none');
} else print $langs->trans("NoDolibarrAccess"); } else {
print $langs->trans("NoDolibarrAccess");
}
print '</td></tr>'; print '</td></tr>';
// Other attributes. Fields from hook formObjectOptions and Extrafields. // Other attributes. Fields from hook formObjectOptions and Extrafields.
@ -1279,7 +1325,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
$login = dol_buildlogin($object->lastname, $object->firstname); $login = dol_buildlogin($object->lastname, $object->firstname);
} }
if (empty($login)) $login = strtolower(substr($object->firstname, 0, 4)).strtolower(substr($object->lastname, 0, 4)); if (empty($login)) {
$login = strtolower(substr($object->firstname, 0, 4)).strtolower(substr($object->lastname, 0, 4));
}
// Create a form array // Create a form array
$formquestion = array( $formquestion = array(
@ -1304,10 +1352,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
if ($object->morphy == 'mor') { if ($object->morphy == 'mor') {
$companyname = $object->company; $companyname = $object->company;
if (!empty($fullname)) $companyalias = $fullname; if (!empty($fullname)) {
$companyalias = $fullname;
}
} else { } else {
$companyname = $fullname; $companyname = $fullname;
if (!empty($object->company)) $companyalias = $object->company; if (!empty($object->company)) {
$companyalias = $object->company;
}
} }
// Create a form array // Create a form array
@ -1341,7 +1393,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
$arraydefaultmessage = null; $arraydefaultmessage = null;
$labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_MEMBER_VALIDATION; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_MEMBER_VALIDATION;
if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); if (!empty($labeltouse)) {
$arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
}
if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
$subject = $arraydefaultmessage->topic; $subject = $arraydefaultmessage->topic;
@ -1368,7 +1422,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
// Create form popup // Create form popup
$formquestion = array(); $formquestion = array();
if ($object->email) $formquestion[] = array('type' => 'checkbox', 'name' => 'send_mail', 'label' => $label, 'value' => ($conf->global->ADHERENT_DEFAULT_SENDINFOBYMAIL ?true:false)); if ($object->email) {
$formquestion[] = array('type' => 'checkbox', 'name' => 'send_mail', 'label' => $label, 'value' => ($conf->global->ADHERENT_DEFAULT_SENDINFOBYMAIL ?true:false));
}
if (!empty($conf->mailman->enabled) && !empty($conf->global->ADHERENT_USE_MAILMAN)) { if (!empty($conf->mailman->enabled) && !empty($conf->global->ADHERENT_USE_MAILMAN)) {
$formquestion[] = array('type'=>'other', 'label'=>$langs->transnoentitiesnoconv("SynchroMailManEnabled"), 'value'=>''); $formquestion[] = array('type'=>'other', 'label'=>$langs->transnoentitiesnoconv("SynchroMailManEnabled"), 'value'=>'');
} }
@ -1400,7 +1456,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
$arraydefaultmessage = null; $arraydefaultmessage = null;
$labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_CANCELATION; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_CANCELATION;
if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); if (!empty($labeltouse)) {
$arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
}
if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
$subject = $arraydefaultmessage->topic; $subject = $arraydefaultmessage->topic;
@ -1427,15 +1485,21 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
// Create an array // Create an array
$formquestion = array(); $formquestion = array();
if ($object->email) $formquestion[] = array('type' => 'checkbox', 'name' => 'send_mail', 'label' => $label, 'value' => (!empty($conf->global->ADHERENT_DEFAULT_SENDINFOBYMAIL) ? 'true' : 'false')); if ($object->email) {
if ($backtopage) $formquestion[] = array('type' => 'hidden', 'name' => 'backtopage', 'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"])); $formquestion[] = array('type' => 'checkbox', 'name' => 'send_mail', 'label' => $label, 'value' => (!empty($conf->global->ADHERENT_DEFAULT_SENDINFOBYMAIL) ? 'true' : 'false'));
}
if ($backtopage) {
$formquestion[] = array('type' => 'hidden', 'name' => 'backtopage', 'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"]));
}
print $form->formconfirm("card.php?rowid=".$id, $langs->trans("ResiliateMember"), $langs->trans("ConfirmResiliateMember"), "confirm_resign", $formquestion, 'no', 1, 240); print $form->formconfirm("card.php?rowid=".$id, $langs->trans("ResiliateMember"), $langs->trans("ConfirmResiliateMember"), "confirm_resign", $formquestion, 'no', 1, 240);
} }
// Confirm remove member // Confirm remove member
if ($action == 'delete') { if ($action == 'delete') {
$formquestion = array(); $formquestion = array();
if ($backtopage) $formquestion[] = array('type' => 'hidden', 'name' => 'backtopage', 'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"])); if ($backtopage) {
$formquestion[] = array('type' => 'hidden', 'name' => 'backtopage', 'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"]));
}
print $form->formconfirm("card.php?rowid=".$id, $langs->trans("DeleteMember"), $langs->trans("ConfirmDeleteMember"), "confirm_delete", $formquestion, 'no', 1); print $form->formconfirm("card.php?rowid=".$id, $langs->trans("DeleteMember"), $langs->trans("ConfirmDeleteMember"), "confirm_delete", $formquestion, 'no', 1);
} }
@ -1449,8 +1513,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
} }
$rowspan = 17; $rowspan = 17;
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $rowspan++; if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
if (!empty($conf->societe->enabled)) $rowspan++; $rowspan++;
}
if (!empty($conf->societe->enabled)) {
$rowspan++;
}
$linkback = '<a href="'.DOL_URL_ROOT.'/adherents/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/adherents/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
@ -1477,7 +1545,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
// Gender // Gender
print '<tr><td>'.$langs->trans("Gender").'</td>'; print '<tr><td>'.$langs->trans("Gender").'</td>';
print '<td>'; print '<td>';
if ($object->gender) print $langs->trans("Gender".$object->gender); if ($object->gender) {
print $langs->trans("Gender".$object->gender);
}
print '</td></tr>'; print '</td></tr>';
// Company // Company
@ -1519,10 +1589,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
print $langs->trans("SubscriptionNotNeeded"); print $langs->trans("SubscriptionNotNeeded");
} elseif (!$adht->subscription) { } elseif (!$adht->subscription) {
print $langs->trans("SubscriptionNotRecorded"); print $langs->trans("SubscriptionNotRecorded");
if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated if ($object->statut > 0) {
print " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated
}
} else { } else {
print $langs->trans("SubscriptionNotReceived"); print $langs->trans("SubscriptionNotReceived");
if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated if ($object->statut > 0) {
print " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated
}
} }
} }
print '</td></tr>'; print '</td></tr>';
@ -1691,8 +1765,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
// Create third party // Create third party
if (!empty($conf->societe->enabled) && !$object->socid) { if (!empty($conf->societe->enabled) && !$object->socid) {
if ($user->rights->societe->creer) { if ($user->rights->societe->creer) {
if ($object->statut != -1) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">'.$langs->trans("CreateDolibarrThirdParty").'</a></div>'; if ($object->statut != -1) {
else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("ValidateBefore")).'">'.$langs->trans("CreateDolibarrThirdParty").'</a></div>'; print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">'.$langs->trans("CreateDolibarrThirdParty").'</a></div>';
} else {
print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("ValidateBefore")).'">'.$langs->trans("CreateDolibarrThirdParty").'</a></div>';
}
} else { } else {
print '<div class="inline-block divButAction"><font class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("CreateDolibarrThirdParty")."</font></div>"; print '<div class="inline-block divButAction"><font class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("CreateDolibarrThirdParty")."</font></div>";
} }
@ -1701,8 +1778,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) {
// Create user // Create user
if (!$user->socid && !$object->user_id) { if (!$user->socid && !$object->user_id) {
if ($user->rights->user->user->creer) { if ($user->rights->user->user->creer) {
if ($object->statut != -1) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_user">'.$langs->trans("CreateDolibarrLogin").'</a></div>'; if ($object->statut != -1) {
else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("ValidateBefore")).'">'.$langs->trans("CreateDolibarrLogin").'</a></div>'; print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_user">'.$langs->trans("CreateDolibarrLogin").'</a></div>';
} else {
print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("ValidateBefore")).'">'.$langs->trans("CreateDolibarrLogin").'</a></div>';
}
} else { } else {
print '<div class="inline-block divButAction"><font class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("CreateDolibarrLogin")."</font></div>"; print '<div class="inline-block divButAction"><font class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("CreateDolibarrLogin")."</font></div>";
} }

View File

@ -80,8 +80,12 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) {
} }
$sql .= " WHERE d.fk_adherent_type = t.rowid AND d.statut = 1"; $sql .= " WHERE d.fk_adherent_type = t.rowid AND d.statut = 1";
$sql .= " AND d.entity IN (".getEntity('adherent').")"; $sql .= " AND d.entity IN (".getEntity('adherent').")";
if (is_numeric($foruserid)) $sql .= " AND d.rowid=".(int) $foruserid; if (is_numeric($foruserid)) {
if ($foruserlogin) $sql .= " AND d.login='".$db->escape($foruserlogin)."'"; $sql .= " AND d.rowid=".(int) $foruserid;
}
if ($foruserlogin) {
$sql .= " AND d.login='".$db->escape($foruserlogin)."'";
}
$sql .= " ORDER BY d.rowid ASC"; $sql .= " ORDER BY d.rowid ASC";
dol_syslog("Search members", LOG_DEBUG); dol_syslog("Search members", LOG_DEBUG);
@ -92,7 +96,9 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) {
while ($i < $num) { while ($i < $num) {
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
if ($objp->country == '-') $objp->country = ''; if ($objp->country == '-') {
$objp->country = '';
}
$adherentstatic->id = $objp->rowid; $adherentstatic->id = $objp->rowid;
$adherentstatic->ref = $objp->ref; $adherentstatic->ref = $objp->ref;
@ -147,7 +153,9 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) {
if (is_numeric($foruserid) || $foruserlogin) { if (is_numeric($foruserid) || $foruserlogin) {
$nb = $_Avery_Labels[$model]['NX'] * $_Avery_Labels[$model]['NY']; $nb = $_Avery_Labels[$model]['NX'] * $_Avery_Labels[$model]['NY'];
if ($nb <= 0) $nb = 1; // Protection to avoid empty page if ($nb <= 0) {
$nb = 1; // Protection to avoid empty page
}
for ($j = 0; $j < $nb; $j++) { for ($j = 0; $j < $nb; $j++) {
$arrayofmembers[] = array( $arrayofmembers[] = array(
@ -175,7 +183,9 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) {
// For labels // For labels
if ($mode == 'label') { if ($mode == 'label') {
if (empty($conf->global->ADHERENT_ETIQUETTE_TEXT)) $conf->global->ADHERENT_ETIQUETTE_TEXT = "__FULLNAME__\n__ADDRESS__\n__ZIP__ __TOWN__\n__COUNTRY__"; if (empty($conf->global->ADHERENT_ETIQUETTE_TEXT)) {
$conf->global->ADHERENT_ETIQUETTE_TEXT = "__FULLNAME__\n__ADDRESS__\n__ZIP__ __TOWN__\n__COUNTRY__";
}
$textleft = make_substitutions($conf->global->ADHERENT_ETIQUETTE_TEXT, $substitutionarray); $textleft = make_substitutions($conf->global->ADHERENT_ETIQUETTE_TEXT, $substitutionarray);
$textheader = ''; $textheader = '';
$textfooter = ''; $textfooter = '';
@ -203,7 +213,9 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) {
if (empty($model) || $model == '-1') { if (empty($model) || $model == '-1') {
$mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DescADHERENT_CARD_TYPE")); $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DescADHERENT_CARD_TYPE"));
} }
if (!$mesg) $result = members_card_pdf_create($db, $arrayofmembers, $model, $outputlangs); if (!$mesg) {
$result = members_card_pdf_create($db, $arrayofmembers, $model, $outputlangs);
}
} elseif ($mode == 'label') { } elseif ($mode == 'label') {
if (!count($arrayofmembers)) { if (!count($arrayofmembers)) {
$mesg = $langs->trans("ErrorRecordNotFound"); $mesg = $langs->trans("ErrorRecordNotFound");
@ -211,7 +223,9 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) {
if (empty($modellabel) || $modellabel == '-1') { if (empty($modellabel) || $modellabel == '-1') {
$mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DescADHERENT_ETIQUETTE_TYPE")); $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DescADHERENT_ETIQUETTE_TYPE"));
} }
if (!$mesg) $result = doc_label_pdf_create($db, $arrayofmembers, $modellabel, $outputlangs); if (!$mesg) {
$result = doc_label_pdf_create($db, $arrayofmembers, $modellabel, $outputlangs);
}
} }
if ($result <= 0) { if ($result <= 0) {

View File

@ -373,18 +373,24 @@ class Adherent extends CommonObject
// Detect if message is HTML // Detect if message is HTML
if ($msgishtml == -1) { if ($msgishtml == -1) {
$msgishtml = 0; $msgishtml = 0;
if (dol_textishtml($text, 0)) $msgishtml = 1; if (dol_textishtml($text, 0)) {
$msgishtml = 1;
}
} }
dol_syslog('send_an_email msgishtml='.$msgishtml); dol_syslog('send_an_email msgishtml='.$msgishtml);
$texttosend = $this->makeSubstitution($text); $texttosend = $this->makeSubstitution($text);
$subjecttosend = $this->makeSubstitution($subject); $subjecttosend = $this->makeSubstitution($subject);
if ($msgishtml) $texttosend = dol_htmlentitiesbr($texttosend); if ($msgishtml) {
$texttosend = dol_htmlentitiesbr($texttosend);
}
// Envoi mail confirmation // Envoi mail confirmation
$from = $conf->email_from; $from = $conf->email_from;
if (!empty($conf->global->ADHERENT_MAIL_FROM)) $from = $conf->global->ADHERENT_MAIL_FROM; if (!empty($conf->global->ADHERENT_MAIL_FROM)) {
$from = $conf->global->ADHERENT_MAIL_FROM;
}
$trackid = 'mem'.$this->id; $trackid = 'mem'.$this->id;
@ -413,10 +419,14 @@ class Adherent extends CommonObject
$birthday = dol_print_date($this->birth, 'day'); $birthday = dol_print_date($this->birth, 'day');
$msgishtml = 0; $msgishtml = 0;
if (dol_textishtml($text, 1)) $msgishtml = 1; if (dol_textishtml($text, 1)) {
$msgishtml = 1;
}
$infos = ''; $infos = '';
if ($this->civility_id) $infos .= $langs->transnoentities("UserTitle").": ".$this->getCivilityLabel()."\n"; if ($this->civility_id) {
$infos .= $langs->transnoentities("UserTitle").": ".$this->getCivilityLabel()."\n";
}
$infos .= $langs->transnoentities("id").": ".$this->id."\n"; $infos .= $langs->transnoentities("id").": ".$this->id."\n";
$infos .= $langs->transnoentities("ref").": ".$this->ref."\n"; $infos .= $langs->transnoentities("ref").": ".$this->ref."\n";
$infos .= $langs->transnoentities("Lastname").": ".$this->lastname."\n"; $infos .= $langs->transnoentities("Lastname").": ".$this->lastname."\n";
@ -514,7 +524,9 @@ class Adherent extends CommonObject
$this->error = $langs->trans("ErrorBadEMail", $this->email); $this->error = $langs->trans("ErrorBadEMail", $this->email);
return -1; return -1;
} }
if (!$this->datec) $this->datec = $now; if (!$this->datec) {
$this->datec = $now;
}
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
if (empty($this->login)) { if (empty($this->login)) {
$this->error = $langs->trans("ErrorWrongValueForParameterX", "Login"); $this->error = $langs->trans("ErrorWrongValueForParameterX", "Login");
@ -669,9 +681,15 @@ class Adherent extends CommonObject
$sql .= ", fk_adherent_type = ".$this->db->escape($this->typeid); $sql .= ", fk_adherent_type = ".$this->db->escape($this->typeid);
$sql .= ", morphy = '".$this->db->escape($this->morphy)."'"; $sql .= ", morphy = '".$this->db->escape($this->morphy)."'";
$sql .= ", birth = ".($this->birth ? "'".$this->db->idate($this->birth)."'" : "null"); $sql .= ", birth = ".($this->birth ? "'".$this->db->idate($this->birth)."'" : "null");
if ($this->socid) $sql .= ", fk_soc = '".$this->db->escape($this->socid)."'"; // Must be modified only when creating from a third-party if ($this->socid) {
if ($this->datefin) $sql .= ", datefin = '".$this->db->idate($this->datefin)."'"; // Must be modified only when deleting a subscription $sql .= ", fk_soc = '".$this->db->escape($this->socid)."'"; // Must be modified only when creating from a third-party
if ($this->datevalid) $sql .= ", datevalid = '".$this->db->idate($this->datevalid)."'"; // Must be modified only when validating a member }
if ($this->datefin) {
$sql .= ", datefin = '".$this->db->idate($this->datefin)."'"; // Must be modified only when deleting a subscription
}
if ($this->datevalid) {
$sql .= ", datevalid = '".$this->db->idate($this->datevalid)."'"; // Must be modified only when validating a member
}
$sql .= ", fk_user_mod = ".($user->id > 0 ? $user->id : 'null'); // Can be null because member can be create by a guest $sql .= ", fk_user_mod = ".($user->id > 0 ? $user->id : 'null'); // Can be null because member can be create by a guest
$sql .= " WHERE rowid = ".$this->id; $sql .= " WHERE rowid = ".$this->id;
@ -716,7 +734,9 @@ class Adherent extends CommonObject
// If password to set differs from the one found into database // If password to set differs from the one found into database
$result = $this->setPassword($user, $this->pass, $isencrypted, $notrigger, $nosyncuserpass); $result = $this->setPassword($user, $this->pass, $isencrypted, $notrigger, $nosyncuserpass);
if (!$nbrowsaffected) $nbrowsaffected++; if (!$nbrowsaffected) {
$nbrowsaffected++;
}
} }
} }
@ -759,7 +779,9 @@ class Adherent extends CommonObject
//var_dump($this->login);exit; //var_dump($this->login);exit;
// If option ADHERENT_LOGIN_NOT_REQUIRED is on, there is no login of member, so we do not overwrite user login to keep existing one. // If option ADHERENT_LOGIN_NOT_REQUIRED is on, there is no login of member, so we do not overwrite user login to keep existing one.
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $luser->login = $this->login; if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
$luser->login = $this->login;
}
$luser->ref = $this->ref; $luser->ref = $this->ref;
$luser->civility_id = $this->civility_id; $luser->civility_id = $this->civility_id;
@ -925,14 +947,18 @@ class Adherent extends CommonObject
$errorflag = 0; $errorflag = 0;
// Check parameters // Check parameters
if (empty($rowid)) $rowid = $this->id; if (empty($rowid)) {
$rowid = $this->id;
}
$this->db->begin(); $this->db->begin();
if (!$error && !$notrigger) { if (!$error && !$notrigger) {
// Call trigger // Call trigger
$result = $this->call_trigger('MEMBER_DELETE', $user); $result = $this->call_trigger('MEMBER_DELETE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
@ -1474,7 +1500,9 @@ class Adherent extends CommonObject
$error = 0; $error = 0;
// Clean parameters // Clean parameters
if (!$amount) $amount = 0; if (!$amount) {
$amount = 0;
}
$this->db->begin(); $this->db->begin();
@ -1605,10 +1633,14 @@ class Adherent extends CommonObject
if ($this->morphy == 'mor') { if ($this->morphy == 'mor') {
$companyname = $this->company; $companyname = $this->company;
if (!empty($fullname)) $companyalias = $fullname; if (!empty($fullname)) {
$companyalias = $fullname;
}
} else { } else {
$companyname = $fullname; $companyname = $fullname;
if (!empty($this->company)) $companyalias = $this->company; if (!empty($this->company)) {
$companyalias = $this->company;
}
} }
$result = $customer->create_from_member($this, $companyname, $companyalias); $result = $customer->create_from_member($this, $companyname, $companyalias);
@ -1671,7 +1703,9 @@ class Adherent extends CommonObject
if (!$error) { if (!$error) {
// Add line to draft invoice // Add line to draft invoice
$idprodsubscription = 0; $idprodsubscription = 0;
if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) $idprodsubscription = $conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS; if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
$idprodsubscription = $conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS;
}
$vattouse = 0; $vattouse = 0;
if (isset($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) && $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS == 'defaultforfoundationcountry') { if (isset($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) && $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS == 'defaultforfoundationcountry') {
@ -1758,8 +1792,12 @@ class Adherent extends CommonObject
$outputlangs = $langs; $outputlangs = $langs;
$newlang = ''; $newlang = '';
$lang_id = GETPOST('lang_id'); $lang_id = GETPOST('lang_id');
if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($lang_id)) $newlang = $lang_id; if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($lang_id)) {
if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $customer->default_lang; $newlang = $lang_id;
}
if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
$newlang = $customer->default_lang;
}
if (!empty($newlang)) { if (!empty($newlang)) {
$outputlangs = new Translate("", $conf); $outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang); $outputlangs->setDefaultLang($newlang);
@ -1901,7 +1939,9 @@ class Adherent extends CommonObject
$result = $mailmanspip->add_to_mailman($this); $result = $mailmanspip->add_to_mailman($this);
if ($result < 0) { if ($result < 0) {
if (!empty($mailmanspip->error)) $this->errors[] = $mailmanspip->error; if (!empty($mailmanspip->error)) {
$this->errors[] = $mailmanspip->error;
}
$err += 1; $err += 1;
} }
foreach ($mailmanspip->mladded_ko as $tmplist => $tmpemail) { foreach ($mailmanspip->mladded_ko as $tmplist => $tmpemail) {
@ -1950,7 +1990,9 @@ class Adherent extends CommonObject
if (!empty($conf->global->ADHERENT_USE_MAILMAN)) { if (!empty($conf->global->ADHERENT_USE_MAILMAN)) {
$result = $mailmanspip->del_to_mailman($this); $result = $mailmanspip->del_to_mailman($this);
if ($result < 0) { if ($result < 0) {
if (!empty($mailmanspip->error)) $this->errors[] = $mailmanspip->error; if (!empty($mailmanspip->error)) {
$this->errors[] = $mailmanspip->error;
}
$err += 1; $err += 1;
} }
@ -1991,7 +2033,9 @@ class Adherent extends CommonObject
$langs->load("dict"); $langs->load("dict");
$code = (empty($this->civility_id) ? '' : $this->civility_id); $code = (empty($this->civility_id) ? '' : $this->civility_id);
if (empty($code)) return ''; if (empty($code)) {
return '';
}
return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code); return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code);
} }
@ -2012,7 +2056,9 @@ class Adherent extends CommonObject
{ {
global $conf, $langs; global $conf, $langs;
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) $withpictoimg = 0; if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) {
$withpictoimg = 0;
}
$result = ''; $result = '';
$label = ''; $label = '';
@ -2028,9 +2074,15 @@ class Adherent extends CommonObject
$label .= '<div class="centpercent">'; $label .= '<div class="centpercent">';
$label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Member").'</u>'; $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Member").'</u>';
$label .= ' '.$this->getLibStatut(4); $label .= ' '.$this->getLibStatut(4);
if (!empty($this->ref)) $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref; if (!empty($this->ref)) {
if (!empty($this->firstname) || !empty($this->lastname)) $label .= '<br><b>'.$langs->trans('Name').':</b> '.$this->getFullName($langs); $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
if (!empty($this->company)) $label .= '<br><b>'.$langs->trans('Company').':</b> '.$this->company; }
if (!empty($this->firstname) || !empty($this->lastname)) {
$label .= '<br><b>'.$langs->trans('Name').':</b> '.$this->getFullName($langs);
}
if (!empty($this->company)) {
$label .= '<br><b>'.$langs->trans('Company').':</b> '.$this->company;
}
$label .= '</div>'; $label .= '</div>';
$url = DOL_URL_ROOT.'/adherents/card.php?rowid='.$this->id; $url = DOL_URL_ROOT.'/adherents/card.php?rowid='.$this->id;
@ -2041,8 +2093,12 @@ class Adherent extends CommonObject
if ($option != 'nolink') { if ($option != 'nolink') {
// Add param to save lastsearch_values or not // Add param to save lastsearch_values or not
$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; $add_save_lastsearch_values = 1;
}
if ($add_save_lastsearch_values) {
$url .= '&save_lastsearch_values=1';
}
} }
$linkstart .= '<a href="'.$url.'"'; $linkstart .= '<a href="'.$url.'"';
@ -2061,16 +2117,20 @@ class Adherent extends CommonObject
$linkend = '</a>'; $linkend = '</a>';
$result .= $linkstart; $result .= $linkstart;
if ($withpictoimg) $result .= '<div class="inline-block nopadding valignmiddle">'; if ($withpictoimg) {
$result .= '<div class="inline-block nopadding valignmiddle">';
}
if ($withpictoimg) { if ($withpictoimg) {
$paddafterimage = ''; $paddafterimage = '';
if (abs($withpictoimg) == 1) $paddafterimage = 'style="margin-right: 3px;"'; if (abs($withpictoimg) == 1) {
$paddafterimage = 'style="margin-right: 3px;"';
}
// Only picto // Only picto
if ($withpictoimg > 0) if ($withpictoimg > 0) {
$picto = '<span class="nopadding'.($morecss ? ' userimg'.$morecss : '').'">'. $picto = '<span class="nopadding'.($morecss ? ' userimg'.$morecss : '').'">'.
img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>'; img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</span>';
} else {
// Picto must be a photo // Picto must be a photo
else {
$picto = '<span class="nopadding'.($morecss ? ' userimg'.$morecss : '').'"'.($paddafterimage ? ' '.$paddafterimage : '').'>'; $picto = '<span class="nopadding'.($morecss ? ' userimg'.$morecss : '').'"'.($paddafterimage ? ' '.$paddafterimage : '').'>';
$picto .= Form::showphoto('memberphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1); $picto .= Form::showphoto('memberphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1);
$picto .= '</span>'; $picto .= '</span>';
@ -2078,8 +2138,10 @@ class Adherent extends CommonObject
$result .= $picto; $result .= $picto;
} }
if ($withpictoimg > -2 && $withpictoimg != 2) { if ($withpictoimg > -2 && $withpictoimg != 2) {
if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result .= '<span class="nopadding valignmiddle'.((!isset($this->statut) || $this->statut) ? '' : ' strikefordisabled'). if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
$result .= '<span class="nopadding valignmiddle'.((!isset($this->statut) || $this->statut) ? '' : ' strikefordisabled').
($morecss ? ' usertext'.$morecss : '').'">'; ($morecss ? ' usertext'.$morecss : '').'">';
}
if ($mode == 'login') { if ($mode == 'login') {
$result .= dol_trunc($this->login, $maxlen); $result .= dol_trunc($this->login, $maxlen);
} elseif ($mode == 'ref') { } elseif ($mode == 'ref') {
@ -2087,9 +2149,13 @@ class Adherent extends CommonObject
} else { } else {
$result .= $this->getFullName($langs, '', ($mode == 'firstname' ? 2 : ($mode == 'lastname' ? 4 : -1)), $maxlen); $result .= $this->getFullName($langs, '', ($mode == 'firstname' ? 2 : ($mode == 'lastname' ? 4 : -1)), $maxlen);
} }
if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result .= '</span>'; if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
$result .= '</span>';
}
}
if ($withpictoimg) {
$result .= '</div>';
} }
if ($withpictoimg) $result .= '</div>';
$result .= $linkend; $result .= $linkend;
if ($addlinktonotes) { if ($addlinktonotes) {
@ -2214,7 +2280,9 @@ class Adherent extends CommonObject
// phpcs:enable // phpcs:enable
global $conf, $langs; global $conf, $langs;
if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe if ($user->socid) {
return -1; // protection pour eviter appel par utilisateur externe
}
$now = dol_now(); $now = dol_now();
@ -2398,9 +2466,15 @@ class Adherent extends CommonObject
// phpcs:enable // phpcs:enable
global $conf; global $conf;
$dn = ''; $dn = '';
if ($mode == 0) $dn = $conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS].",".$conf->global->LDAP_MEMBER_DN; if ($mode == 0) {
if ($mode == 1) $dn = $conf->global->LDAP_MEMBER_DN; $dn = $conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS].",".$conf->global->LDAP_MEMBER_DN;
if ($mode == 2) $dn = $conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS]; }
if ($mode == 1) {
$dn = $conf->global->LDAP_MEMBER_DN;
}
if ($mode == 2) {
$dn = $conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS];
}
return $dn; return $dn;
} }
@ -2448,31 +2522,65 @@ class Adherent extends CommonObject
// Check if it is the LDAP key and if its value has been changed // Check if it is the LDAP key and if its value has been changed
if (!empty($conf->global->LDAP_KEY_MEMBERS) && $conf->global->LDAP_KEY_MEMBERS == $conf->global->$constname) { if (!empty($conf->global->LDAP_KEY_MEMBERS) && $conf->global->LDAP_KEY_MEMBERS == $conf->global->$constname) {
if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) $keymodified = true; // For check if LDAP key has been modified if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) {
$keymodified = true; // For check if LDAP key has been modified
} }
} }
} }
if ($this->firstname && !empty($conf->global->LDAP_MEMBER_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_MEMBER_FIELD_FIRSTNAME] = $this->firstname; }
if ($this->poste && !empty($conf->global->LDAP_MEMBER_FIELD_TITLE)) $info[$conf->global->LDAP_MEMBER_FIELD_TITLE] = $this->poste; if ($this->firstname && !empty($conf->global->LDAP_MEMBER_FIELD_FIRSTNAME)) {
if ($this->company && !empty($conf->global->LDAP_MEMBER_FIELD_COMPANY)) $info[$conf->global->LDAP_MEMBER_FIELD_COMPANY] = $this->company; $info[$conf->global->LDAP_MEMBER_FIELD_FIRSTNAME] = $this->firstname;
if ($this->address && !empty($conf->global->LDAP_MEMBER_FIELD_ADDRESS)) $info[$conf->global->LDAP_MEMBER_FIELD_ADDRESS] = $this->address; }
if ($this->zip && !empty($conf->global->LDAP_MEMBER_FIELD_ZIP)) $info[$conf->global->LDAP_MEMBER_FIELD_ZIP] = $this->zip; if ($this->poste && !empty($conf->global->LDAP_MEMBER_FIELD_TITLE)) {
if ($this->town && !empty($conf->global->LDAP_MEMBER_FIELD_TOWN)) $info[$conf->global->LDAP_MEMBER_FIELD_TOWN] = $this->town; $info[$conf->global->LDAP_MEMBER_FIELD_TITLE] = $this->poste;
if ($this->country_code && !empty($conf->global->LDAP_MEMBER_FIELD_COUNTRY)) $info[$conf->global->LDAP_MEMBER_FIELD_COUNTRY] = $this->country_code; }
if ($this->company && !empty($conf->global->LDAP_MEMBER_FIELD_COMPANY)) {
$info[$conf->global->LDAP_MEMBER_FIELD_COMPANY] = $this->company;
}
if ($this->address && !empty($conf->global->LDAP_MEMBER_FIELD_ADDRESS)) {
$info[$conf->global->LDAP_MEMBER_FIELD_ADDRESS] = $this->address;
}
if ($this->zip && !empty($conf->global->LDAP_MEMBER_FIELD_ZIP)) {
$info[$conf->global->LDAP_MEMBER_FIELD_ZIP] = $this->zip;
}
if ($this->town && !empty($conf->global->LDAP_MEMBER_FIELD_TOWN)) {
$info[$conf->global->LDAP_MEMBER_FIELD_TOWN] = $this->town;
}
if ($this->country_code && !empty($conf->global->LDAP_MEMBER_FIELD_COUNTRY)) {
$info[$conf->global->LDAP_MEMBER_FIELD_COUNTRY] = $this->country_code;
}
foreach ($socialnetworks as $key => $value) { foreach ($socialnetworks as $key => $value) {
if ($this->socialnetworks[$value['label']] && !empty($conf->global->{'LDAP_MEMBER_FIELD_'.strtoupper($value['label'])})) { if ($this->socialnetworks[$value['label']] && !empty($conf->global->{'LDAP_MEMBER_FIELD_'.strtoupper($value['label'])})) {
$info[$conf->global->{'LDAP_MEMBER_FIELD_'.strtoupper($value['label'])}] = $this->socialnetworks[$value['label']]; $info[$conf->global->{'LDAP_MEMBER_FIELD_'.strtoupper($value['label'])}] = $this->socialnetworks[$value['label']];
} }
} }
if ($this->phone && !empty($conf->global->LDAP_MEMBER_FIELD_PHONE)) $info[$conf->global->LDAP_MEMBER_FIELD_PHONE] = $this->phone; if ($this->phone && !empty($conf->global->LDAP_MEMBER_FIELD_PHONE)) {
if ($this->phone_perso && !empty($conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO)) $info[$conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO] = $this->phone_perso; $info[$conf->global->LDAP_MEMBER_FIELD_PHONE] = $this->phone;
if ($this->phone_mobile && !empty($conf->global->LDAP_MEMBER_FIELD_MOBILE)) $info[$conf->global->LDAP_MEMBER_FIELD_MOBILE] = $this->phone_mobile; }
if ($this->fax && !empty($conf->global->LDAP_MEMBER_FIELD_FAX)) $info[$conf->global->LDAP_MEMBER_FIELD_FAX] = $this->fax; if ($this->phone_perso && !empty($conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO)) {
if ($this->note_private && !empty($conf->global->LDAP_MEMBER_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_MEMBER_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2); $info[$conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO] = $this->phone_perso;
if ($this->note_public && !empty($conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC)) $info[$conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC] = dol_string_nohtmltag($this->note_public, 2); }
if ($this->birth && !empty($conf->global->LDAP_MEMBER_FIELD_BIRTHDATE)) $info[$conf->global->LDAP_MEMBER_FIELD_BIRTHDATE] = dol_print_date($this->birth, 'dayhourldap'); if ($this->phone_mobile && !empty($conf->global->LDAP_MEMBER_FIELD_MOBILE)) {
if (isset($this->statut) && !empty($conf->global->LDAP_FIELD_MEMBER_STATUS)) $info[$conf->global->LDAP_FIELD_MEMBER_STATUS] = $this->statut; $info[$conf->global->LDAP_MEMBER_FIELD_MOBILE] = $this->phone_mobile;
if ($this->datefin && !empty($conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION)) $info[$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION] = dol_print_date($this->datefin, 'dayhourldap'); }
if ($this->fax && !empty($conf->global->LDAP_MEMBER_FIELD_FAX)) {
$info[$conf->global->LDAP_MEMBER_FIELD_FAX] = $this->fax;
}
if ($this->note_private && !empty($conf->global->LDAP_MEMBER_FIELD_DESCRIPTION)) {
$info[$conf->global->LDAP_MEMBER_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2);
}
if ($this->note_public && !empty($conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC)) {
$info[$conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC] = dol_string_nohtmltag($this->note_public, 2);
}
if ($this->birth && !empty($conf->global->LDAP_MEMBER_FIELD_BIRTHDATE)) {
$info[$conf->global->LDAP_MEMBER_FIELD_BIRTHDATE] = dol_print_date($this->birth, 'dayhourldap');
}
if (isset($this->statut) && !empty($conf->global->LDAP_FIELD_MEMBER_STATUS)) {
$info[$conf->global->LDAP_FIELD_MEMBER_STATUS] = $this->statut;
}
if ($this->datefin && !empty($conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION)) {
$info[$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION] = dol_print_date($this->datefin, 'dayhourldap');
}
// When password is modified // When password is modified
if (!empty($this->pass)) { if (!empty($this->pass)) {
@ -2482,8 +2590,9 @@ class Adherent extends CommonObject
if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) { if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) {
$info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // Create OpenLDAP MD5 password (TODO add type of encryption) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // Create OpenLDAP MD5 password (TODO add type of encryption)
} }
} // Set LDAP password if possible } elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') {
elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') { // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password // Set LDAP password if possible
// If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) { if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
// Just for the default MD5 ! // Just for the default MD5 !
if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) { if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) {
@ -2493,18 +2602,30 @@ class Adherent extends CommonObject
$info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = '{md5}'.base64_encode(hex2bin($this->pass_indatabase_crypted)); $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = '{md5}'.base64_encode(hex2bin($this->pass_indatabase_crypted));
} }
} }
} // Use $this->pass_indatabase value if exists } elseif (!empty($this->pass_indatabase)) {
elseif (!empty($this->pass_indatabase)) { // Use $this->pass_indatabase value if exists
if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD)) {
if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 4); // md5 for OpenLdap TODO add type of encryption $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte
}
if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) {
$info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 4); // md5 for OpenLdap TODO add type of encryption
}
} }
} }
// Subscriptions // Subscriptions
if ($this->first_subscription_date && !empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE)) $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE] = dol_print_date($this->first_subscription_date, 'dayhourldap'); if ($this->first_subscription_date && !empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE)) {
if (isset($this->first_subscription_amount) && !empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT)) $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT] = $this->first_subscription_amount; $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE] = dol_print_date($this->first_subscription_date, 'dayhourldap');
if ($this->last_subscription_date && !empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE)) $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE] = dol_print_date($this->last_subscription_date, 'dayhourldap'); }
if (isset($this->last_subscription_amount) && !empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT)) $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT] = $this->last_subscription_amount; if (isset($this->first_subscription_amount) && !empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT)) {
$info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT] = $this->first_subscription_amount;
}
if ($this->last_subscription_date && !empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE)) {
$info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE] = dol_print_date($this->last_subscription_date, 'dayhourldap');
}
if (isset($this->last_subscription_amount) && !empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT)) {
$info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT] = $this->last_subscription_amount;
}
return $info; return $info;
} }
@ -2626,8 +2747,12 @@ class Adherent extends CommonObject
global $conf; global $conf;
//Only valid members //Only valid members
if ($this->statut <= 0) return false; if ($this->statut <= 0) {
if (!$this->datefin) return false; return false;
}
if (!$this->datefin) {
return false;
}
$now = dol_now(); $now = dol_now();
@ -2720,7 +2845,9 @@ class Adherent extends CommonObject
$arraydefaultmessage = null; $arraydefaultmessage = null;
$labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_REMIND_EXPIRATION; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_REMIND_EXPIRATION;
if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'member', $user, $outputlangs, 0, 1, $labeltouse); if (!empty($labeltouse)) {
$arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
}
if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $adherent); $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $adherent);
@ -2763,7 +2890,9 @@ class Adherent extends CommonObject
if ($message) { if ($message) {
$actionmsg = $langs->transnoentities('MailFrom').': '.dol_escape_htmltag($from); $actionmsg = $langs->transnoentities('MailFrom').': '.dol_escape_htmltag($from);
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTo').': '.dol_escape_htmltag($sendto)); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTo').': '.dol_escape_htmltag($sendto));
if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".dol_escape_htmltag($sendtocc)); if ($sendtocc) {
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".dol_escape_htmltag($sendtocc));
}
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subject); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subject);
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":"); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
$actionmsg = dol_concatdesc($actionmsg, $message); $actionmsg = dol_concatdesc($actionmsg, $message);
@ -2843,7 +2972,9 @@ class Adherent extends CommonObject
$listofids .= $idmember; $listofids .= $idmember;
$i++; $i++;
} }
if ($listofids) $listofids .= ']'; if ($listofids) {
$listofids .= ']';
}
$this->output .= $listofids; $this->output .= $listofids;
} }
if ($nbko) { if ($nbko) {
@ -2864,7 +2995,9 @@ class Adherent extends CommonObject
$listofids .= $idmember; $listofids .= $idmember;
$i++; $i++;
} }
if ($listofids) $listofids .= ']'; if ($listofids) {
$listofids .= ']';
}
$this->output .= $listofids; $this->output .= $listofids;
} }
} }

View File

@ -313,7 +313,9 @@ class AdherentType extends CommonObject
if (!$notrigger) { if (!$notrigger) {
// Call trigger // Call trigger
$result = $this->call_trigger('MEMBER_TYPE_CREATE', $user); $result = $this->call_trigger('MEMBER_TYPE_CREATE', $user);
if ($result < 0) { $error++; } if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
@ -386,7 +388,9 @@ class AdherentType extends CommonObject
if (!$error && !$notrigger) { if (!$error && !$notrigger) {
// Call trigger // Call trigger
$result = $this->call_trigger('MEMBER_TYPE_MODIFY', $user); $result = $this->call_trigger('MEMBER_TYPE_MODIFY', $user);
if ($result < 0) { $error++; } if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
@ -423,7 +427,9 @@ class AdherentType extends CommonObject
if ($resql) { if ($resql) {
// Call trigger // Call trigger
$result = $this->call_trigger('MEMBER_TYPE_DELETE', $user); $result = $this->call_trigger('MEMBER_TYPE_DELETE', $user);
if ($result < 0) { $error++; $this->db->rollback(); return -2; } if ($result < 0) {
$error++; $this->db->rollback(); return -2;
}
// End call triggers // End call triggers
$this->db->commit(); $this->db->commit();
@ -499,7 +505,9 @@ class AdherentType extends CommonObject
$sql = "SELECT rowid, libelle as label"; $sql = "SELECT rowid, libelle as label";
$sql .= " FROM ".MAIN_DB_PREFIX."adherent_type"; $sql .= " FROM ".MAIN_DB_PREFIX."adherent_type";
$sql .= " WHERE entity IN (".getEntity('member_type').")"; $sql .= " WHERE entity IN (".getEntity('member_type').")";
if ($status >= 0) $sql .= " AND statut = ".((int) $status); if ($status >= 0) {
$sql .= " AND statut = ".((int) $status);
}
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) { if ($resql) {
@ -539,7 +547,9 @@ class AdherentType extends CommonObject
$sql .= " FROM ".MAIN_DB_PREFIX."adherent as a"; $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a";
$sql .= " WHERE a.entity IN (".getEntity('member').")"; $sql .= " WHERE a.entity IN (".getEntity('member').")";
$sql .= " AND a.fk_adherent_type = ".$this->id; $sql .= " AND a.fk_adherent_type = ".$this->id;
if (!empty($excludefilter)) $sql .= ' AND ('.$excludefilter.')'; if (!empty($excludefilter)) {
$sql .= ' AND ('.$excludefilter.')';
}
dol_syslog(get_class($this)."::listUsersForGroup", LOG_DEBUG); dol_syslog(get_class($this)."::listUsersForGroup", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
@ -554,7 +564,9 @@ class AdherentType extends CommonObject
$memberstatic->fetch($obj->rowid); $memberstatic->fetch($obj->rowid);
} }
$ret[$obj->rowid] = $memberstatic; $ret[$obj->rowid] = $memberstatic;
} else $ret[$obj->rowid] = $obj->rowid; } else {
$ret[$obj->rowid] = $obj->rowid;
}
} }
} }
@ -578,7 +590,13 @@ class AdherentType extends CommonObject
public function getmorphylib($morphy = '') public function getmorphylib($morphy = '')
{ {
global $langs; global $langs;
if ($morphy == 'phy') { return $langs->trans("Physical"); } elseif ($morphy == 'mor') { return $langs->trans("Moral"); } else return $langs->trans("MorAndPhy"); if ($morphy == 'phy') {
return $langs->trans("Physical");
} elseif ($morphy == 'mor') {
return $langs->trans("Moral");
} else {
return $langs->trans("MorAndPhy");
}
//return $morphy; //return $morphy;
} }
@ -609,8 +627,12 @@ class AdherentType extends CommonObject
$linkend = '</a>'; $linkend = '</a>';
$result .= $linkstart; $result .= $linkstart;
if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); if ($withpicto) {
if ($withpicto != 2) $result .= ($maxlen ?dol_trunc($this->label, $maxlen) : $this->label); $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
}
if ($withpicto != 2) {
$result .= ($maxlen ?dol_trunc($this->label, $maxlen) : $this->label);
}
$result .= $linkend; $result .= $linkend;
return $result; return $result;
@ -642,7 +664,9 @@ class AdherentType extends CommonObject
$langs->load('companies'); $langs->load('companies');
$statusType = 'status4'; $statusType = 'status4';
if ($status == 0) $statusType = 'status5'; if ($status == 0) {
$statusType = 'status5';
}
if (empty($this->labelStatus) || empty($this->labelStatusShort)) { if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
$this->labelStatus[0] = $langs->trans("ActivityCeased"); $this->labelStatus[0] = $langs->trans("ActivityCeased");
@ -670,9 +694,15 @@ class AdherentType extends CommonObject
// phpcs:enable // phpcs:enable
global $conf; global $conf;
$dn = ''; $dn = '';
if ($mode == 0) $dn = $conf->global->LDAP_KEY_MEMBERS_TYPES."=".$info[$conf->global->LDAP_KEY_MEMBERS_TYPES].",".$conf->global->LDAP_MEMBER_TYPE_DN; if ($mode == 0) {
if ($mode == 1) $dn = $conf->global->LDAP_MEMBER_TYPE_DN; $dn = $conf->global->LDAP_KEY_MEMBERS_TYPES."=".$info[$conf->global->LDAP_KEY_MEMBERS_TYPES].",".$conf->global->LDAP_MEMBER_TYPE_DN;
if ($mode == 2) $dn = $conf->global->LDAP_KEY_MEMBERS_TYPES."=".$info[$conf->global->LDAP_KEY_MEMBERS_TYPES]; }
if ($mode == 1) {
$dn = $conf->global->LDAP_MEMBER_TYPE_DN;
}
if ($mode == 2) {
$dn = $conf->global->LDAP_KEY_MEMBERS_TYPES."=".$info[$conf->global->LDAP_KEY_MEMBERS_TYPES];
}
return $dn; return $dn;
} }
@ -695,11 +725,15 @@ class AdherentType extends CommonObject
$info["objectclass"] = explode(',', $conf->global->LDAP_MEMBER_TYPE_OBJECT_CLASS); $info["objectclass"] = explode(',', $conf->global->LDAP_MEMBER_TYPE_OBJECT_CLASS);
// Champs // Champs
if ($this->label && !empty($conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME)) $info[$conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME] = $this->label; if ($this->label && !empty($conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME)) {
if ($this->note && !empty($conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note, 0, 'UTF-8', 1); $info[$conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME] = $this->label;
}
if ($this->note && !empty($conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION)) {
$info[$conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note, 0, 'UTF-8', 1);
}
if (!empty($conf->global->LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS)) { if (!empty($conf->global->LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS)) {
$valueofldapfield = array(); $valueofldapfield = array();
foreach ($this->members as $key=>$val) { // This is array of users for group into dolibarr database. foreach ($this->members as $key => $val) { // This is array of users for group into dolibarr database.
$member = new Adherent($this->db); $member = new Adherent($this->db);
$member->fetch($val->id, '', '', '', false, false); $member->fetch($val->id, '', '', '', false, false);
$info2 = $member->_load_ldap_info(); $info2 = $member->_load_ldap_info();

View File

@ -36,7 +36,7 @@ class Members extends DolibarrApi
/** /**
* @var array $FIELDS Mandatory fields, checked when create and update object * @var array $FIELDS Mandatory fields, checked when create and update object
*/ */
static $FIELDS = array( public static $FIELDS = array(
'morphy', 'morphy',
'typeid' 'typeid'
); );
@ -325,7 +325,9 @@ class Members extends DolibarrApi
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'id') continue; if ($field == 'id') {
continue;
}
// Process the status separately because it must be updated using // Process the status separately because it must be updated using
// the validate() and resiliate() methods of the class Adherent. // the validate() and resiliate() methods of the class Adherent.
if ($field == 'statut') { if ($field == 'statut') {
@ -399,8 +401,9 @@ class Members extends DolibarrApi
{ {
$member = array(); $member = array();
foreach (Members::$FIELDS as $field) { foreach (Members::$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");
}
$member[$field] = $data[$field]; $member[$field] = $data[$field];
} }
return $member; return $member;

View File

@ -30,7 +30,7 @@ class MembersTypes extends DolibarrApi
/** /**
* @var array $FIELDS Mandatory fields, checked when create and update object * @var array $FIELDS Mandatory fields, checked when create and update object
*/ */
static $FIELDS = array( public static $FIELDS = array(
'label', 'label',
); );
@ -190,7 +190,9 @@ class MembersTypes extends DolibarrApi
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'id') continue; if ($field == 'id') {
continue;
}
// Process the status separately because it must be updated using // Process the status separately because it must be updated using
// the validate() and resiliate() methods of the class AdherentType. // the validate() and resiliate() methods of the class AdherentType.
$membertype->$field = $value; $membertype->$field = $value;
@ -250,8 +252,9 @@ class MembersTypes extends DolibarrApi
{ {
$membertype = array(); $membertype = array();
foreach (MembersTypes::$FIELDS as $field) { foreach (MembersTypes::$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");
}
$membertype[$field] = $data[$field]; $membertype[$field] = $data[$field];
} }
return $membertype; return $membertype;

View File

@ -30,7 +30,7 @@ class Subscriptions extends DolibarrApi
/** /**
* @var array $FIELDS Mandatory fields, checked when create and update object * @var array $FIELDS Mandatory fields, checked when create and update object
*/ */
static $FIELDS = array( public static $FIELDS = array(
'fk_adherent', 'fk_adherent',
'dateh', 'dateh',
'datef', 'datef',

View File

@ -50,12 +50,18 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "ASC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "name"; $sortorder = "ASC";
}
if (!$sortfield) {
$sortfield = "name";
}
$form = new Form($db); $form = new Form($db);
@ -96,8 +102,9 @@ if ($id > 0) {
$totalsize += $file['size']; $totalsize += $file['size'];
} }
if (!empty($conf->notification->enabled)) if (!empty($conf->notification->enabled)) {
$langs->load("mails"); $langs->load("mails");
}
$head = member_prepare_head($object); $head = member_prepare_head($object);

View File

@ -27,7 +27,9 @@ require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
// Security check // Security check
if (!$user->rights->adherent->export) accessforbidden(); if (!$user->rights->adherent->export) {
accessforbidden();
}
/* /*
@ -38,8 +40,12 @@ llxHeader();
$now = dol_now(); $now = dol_now();
if (empty($sortorder)) { $sortorder = "ASC"; } if (empty($sortorder)) {
if (empty($sortfield)) { $sortfield = "d.login"; } $sortorder = "ASC";
}
if (empty($sortfield)) {
$sortfield = "d.login";
}
if (!isset($statut)) { if (!isset($statut)) {
$statut = 1; $statut = 1;
} }

View File

@ -257,7 +257,7 @@ print "</tr>\n";
krsort($Total); krsort($Total);
$i = 0; $i = 0;
foreach ($Total as $key=>$value) { foreach ($Total as $key => $value) {
if ($i >= 8) { if ($i >= 8) {
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print "<td>...</td>"; print "<td>...</td>";

View File

@ -142,7 +142,9 @@ if (!empty($conf->global->LDAP_MEMBER_ACTIVE) && $conf->global->LDAP_MEMBER_ACTI
print "</div>\n"; print "</div>\n";
if (!empty($conf->global->LDAP_MEMBER_ACTIVE) && $conf->global->LDAP_MEMBER_ACTIVE != 'ldap2dolibarr') print "<br>\n"; if (!empty($conf->global->LDAP_MEMBER_ACTIVE) && $conf->global->LDAP_MEMBER_ACTIVE != 'ldap2dolibarr') {
print "<br>\n";
}

View File

@ -69,24 +69,36 @@ $catid = GETPOST("catid", 'int');
$optioncss = GETPOST('optioncss', 'alpha'); $optioncss = GETPOST('optioncss', 'alpha');
$filter = GETPOST("filter", 'alpha'); $filter = GETPOST("filter", 'alpha');
if ($filter) $search_filter = $filter; // For backward compatibility if ($filter) {
$search_filter = $filter; // For backward compatibility
}
$statut = GETPOST("statut", 'alpha'); $statut = GETPOST("statut", 'alpha');
if ($statut != '') $search_status = $statut; // For backward compatibility if ($statut != '') {
$search_status = $statut; // For backward compatibility
}
$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'));
if ($search_status < -1) $search_status = ''; if ($search_status < -1) {
$search_status = '';
}
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) { $sortorder = ($filter == 'outofdate' ? "DESC" : "ASC"); } if (!$sortorder) {
if (!$sortfield) { $sortfield = ($filter == 'outofdate' ? "d.datefin" : "d.lastname"); } $sortorder = ($filter == 'outofdate' ? "DESC" : "ASC");
}
if (!$sortfield) {
$sortfield = ($filter == 'outofdate' ? "d.datefin" : "d.lastname");
}
$object = new Adherent($db); $object = new Adherent($db);
@ -117,7 +129,9 @@ $fieldstosearchall = array(
'd.note_public'=>'NotePublic', 'd.note_public'=>'NotePublic',
'd.note_private'=>'NotePrivate', 'd.note_private'=>'NotePrivate',
); );
if ($db->type == 'pgsql') unset($fieldstosearchall['d.rowid']); if ($db->type == 'pgsql') {
unset($fieldstosearchall['d.rowid']);
}
$arrayfields = array( $arrayfields = array(
'd.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 'd.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1),
'd.civility'=>array('label'=>$langs->trans("Civility"), 'checked'=>0), 'd.civility'=>array('label'=>$langs->trans("Civility"), 'checked'=>0),
@ -153,12 +167,18 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') {
$massaction = '';
}
$parameters = array('socid'=>$socid); $parameters = array('socid'=>$socid);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) { if (empty($reshook)) {
// Selection of new fields // Selection of new fields
@ -212,7 +232,9 @@ if (empty($reshook)) {
if ($result < 0 && !count($tmpmember->errors)) { if ($result < 0 && !count($tmpmember->errors)) {
setEventMessages($tmpmember->error, $tmpmember->errors, 'errors'); setEventMessages($tmpmember->error, $tmpmember->errors, 'errors');
} else { } else {
if ($result > 0) $nbclose++; if ($result > 0) {
$nbclose++;
}
} }
} }
@ -256,8 +278,11 @@ $sql .= " s.nom,";
$sql .= " t.libelle as type, t.subscription,"; $sql .= " t.libelle as type, t.subscription,";
$sql .= " state.code_departement as state_code, state.nom as state_name,"; $sql .= " state.code_departement as state_code, state.nom as state_name,";
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) if (!empty($extrafields->attributes[$object->table_element]['label'])) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : '');
}
}
// Add fields from hooks // Add fields from hooks
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
@ -276,16 +301,34 @@ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid =
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on (s.rowid = d.fk_soc)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on (s.rowid = d.fk_soc)";
$sql .= ", ".MAIN_DB_PREFIX."adherent_type as t"; $sql .= ", ".MAIN_DB_PREFIX."adherent_type as t";
$sql .= " WHERE d.fk_adherent_type = t.rowid "; $sql .= " WHERE d.fk_adherent_type = t.rowid ";
if ($catid > 0) $sql .= " AND cm.fk_categorie = ".$db->escape($catid); if ($catid > 0) {
if ($catid == -2) $sql .= " AND cm.fk_categorie IS NULL"; $sql .= " AND cm.fk_categorie = ".$db->escape($catid);
if ($search_categ > 0) $sql .= " AND cm.fk_categorie = ".$db->escape($search_categ); }
if ($search_categ == -2) $sql .= " AND cm.fk_categorie IS NULL"; if ($catid == -2) {
$sql .= " AND cm.fk_categorie IS NULL";
}
if ($search_categ > 0) {
$sql .= " AND cm.fk_categorie = ".$db->escape($search_categ);
}
if ($search_categ == -2) {
$sql .= " AND cm.fk_categorie IS NULL";
}
$sql .= " AND d.entity IN (".getEntity('adherent').")"; $sql .= " AND d.entity IN (".getEntity('adherent').")";
if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); if ($sall) {
if ($search_type > 0) $sql .= " AND t.rowid=".$db->escape($search_type); $sql .= natural_search(array_keys($fieldstosearchall), $sall);
if ($search_filter == 'withoutsubscription') $sql .= " AND (datefin IS NULL OR t.subscription = 0)"; }
if ($search_filter == 'uptodate') $sql .= " AND (datefin >= '".$db->idate($now)."' OR t.subscription = 0)"; if ($search_type > 0) {
if ($search_filter == 'outofdate') $sql .= " AND (datefin < '".$db->idate($now)."' AND t.subscription = 1)"; $sql .= " AND t.rowid=".$db->escape($search_type);
}
if ($search_filter == 'withoutsubscription') {
$sql .= " AND (datefin IS NULL OR t.subscription = 0)";
}
if ($search_filter == 'uptodate') {
$sql .= " AND (datefin >= '".$db->idate($now)."' OR t.subscription = 0)";
}
if ($search_filter == 'outofdate') {
$sql .= " AND (datefin < '".$db->idate($now)."' AND t.subscription = 1)";
}
if ($search_status != '') { if ($search_status != '') {
// Peut valoir un nombre ou liste de nombre separes par virgules // Peut valoir un nombre ou liste de nombre separes par virgules
$sql .= " AND d.statut in (".$db->sanitize($db->escape($search_status)).")"; $sql .= " AND d.statut in (".$db->sanitize($db->escape($search_status)).")";
@ -293,21 +336,51 @@ if ($search_status != '') {
if ($search_ref) { if ($search_ref) {
$sql .= natural_search("d.ref", $search_ref); $sql .= natural_search("d.ref", $search_ref);
} }
if ($search_civility) $sql .= natural_search("d.civility", $search_civility); if ($search_civility) {
if ($search_firstname) $sql .= natural_search("d.firstname", $search_firstname); $sql .= natural_search("d.civility", $search_civility);
if ($search_lastname) $sql .= natural_search(array("d.firstname", "d.lastname", "d.societe"), $search_lastname); }
if ($search_gender != '' && $search_gender != '-1') $sql .= natural_search("d.gender", $search_gender); if ($search_firstname) {
if ($search_login) $sql .= natural_search("d.login", $search_login); $sql .= natural_search("d.firstname", $search_firstname);
if ($search_company) $sql .= natural_search("s.nom", $search_company); }
if ($search_email) $sql .= natural_search("d.email", $search_email); if ($search_lastname) {
if ($search_address) $sql .= natural_search("d.address", $search_address); $sql .= natural_search(array("d.firstname", "d.lastname", "d.societe"), $search_lastname);
if ($search_town) $sql .= natural_search("d.town", $search_town); }
if ($search_zip) $sql .= natural_search("d.zip", $search_zip); if ($search_gender != '' && $search_gender != '-1') {
if ($search_state) $sql .= natural_search("state.nom", $search_state); $sql .= natural_search("d.gender", $search_gender);
if ($search_phone) $sql .= natural_search("d.phone", $search_phone); }
if ($search_phone_perso) $sql .= natural_search("d.phone_perso", $search_phone_perso); if ($search_login) {
if ($search_phone_mobile) $sql .= natural_search("d.phone_mobile", $search_phone_mobile); $sql .= natural_search("d.login", $search_login);
if ($search_country) $sql .= " AND d.country IN (".$search_country.')'; }
if ($search_company) {
$sql .= natural_search("s.nom", $search_company);
}
if ($search_email) {
$sql .= natural_search("d.email", $search_email);
}
if ($search_address) {
$sql .= natural_search("d.address", $search_address);
}
if ($search_town) {
$sql .= natural_search("d.town", $search_town);
}
if ($search_zip) {
$sql .= natural_search("d.zip", $search_zip);
}
if ($search_state) {
$sql .= natural_search("state.nom", $search_state);
}
if ($search_phone) {
$sql .= natural_search("d.phone", $search_phone);
}
if ($search_phone_perso) {
$sql .= natural_search("d.phone_perso", $search_phone_perso);
}
if ($search_phone_mobile) {
$sql .= natural_search("d.phone_mobile", $search_phone_mobile);
}
if ($search_country) {
$sql .= " AND d.country IN (".$search_country.')';
}
// Add where from extra fields // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
@ -323,8 +396,11 @@ $sql .= $db->order($sortfield, $sortorder);
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) $nbtotalofrecords = $db->num_rows($resql); if ($resql) {
else dol_print_error($db); $nbtotalofrecords = $db->num_rows($resql);
} else {
dol_print_error($db);
}
if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
$page = 0; $page = 0;
$offset = 0; $offset = 0;
@ -355,13 +431,27 @@ llxHeader('', $langs->trans("Member"), 'EN:Module_Foundations|FR:Module_Adh&eacu
$titre = $langs->trans("MembersList"); $titre = $langs->trans("MembersList");
if (GETPOSTISSET("search_status")) { if (GETPOSTISSET("search_status")) {
if ($search_status == '-1,1') { $titre = $langs->trans("MembersListQualified"); } if ($search_status == '-1,1') {
if ($search_status == '-1') { $titre = $langs->trans("MembersListToValid"); } $titre = $langs->trans("MembersListQualified");
if ($search_status == '1' && $filter == '') { $titre = $langs->trans("MembersValidated"); } }
if ($search_status == '1' && $filter == 'withoutsubscription') { $titre = $langs->trans("MembersWithSubscriptionToReceive"); } if ($search_status == '-1') {
if ($search_status == '1' && $filter == 'uptodate') { $titre = $langs->trans("MembersListUpToDate"); } $titre = $langs->trans("MembersListToValid");
if ($search_status == '1' && $filter == 'outofdate') { $titre = $langs->trans("MembersListNotUpToDate"); } }
if ($search_status == '0') { $titre = $langs->trans("MembersListResiliated"); } if ($search_status == '1' && $filter == '') {
$titre = $langs->trans("MembersValidated");
}
if ($search_status == '1' && $filter == 'withoutsubscription') {
$titre = $langs->trans("MembersWithSubscriptionToReceive");
}
if ($search_status == '1' && $filter == 'uptodate') {
$titre = $langs->trans("MembersListUpToDate");
}
if ($search_status == '1' && $filter == 'outofdate') {
$titre = $langs->trans("MembersListNotUpToDate");
}
if ($search_status == '0') {
$titre = $langs->trans("MembersListResiliated");
}
} elseif ($action == 'search') { } elseif ($action == 'search') {
$titre = $langs->trans("MembersListQualified"); $titre = $langs->trans("MembersListQualified");
} }
@ -373,30 +463,78 @@ if ($search_type > 0) {
} }
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($sall != "") $param .= "&sall=".urlencode($sall); }
if ($search_ref) $param .= "&search_ref=".urlencode($search_ref); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($search_civility) $param .= "&search_civility=".urlencode($search_civility); $param .= '&limit='.urlencode($limit);
if ($search_firstname) $param .= "&search_firstname=".urlencode($search_firstname); }
if ($search_lastname) $param .= "&search_lastname=".urlencode($search_lastname); if ($sall != "") {
if ($search_gender) $param .= "&search_gender=".urlencode($search_gender); $param .= "&sall=".urlencode($sall);
if ($search_login) $param .= "&search_login=".urlencode($search_login); }
if ($search_email) $param .= "&search_email=".urlencode($search_email); if ($search_ref) {
if ($search_categ) $param .= "&search_categ=".urlencode($search_categ); $param .= "&search_ref=".urlencode($search_ref);
if ($search_company) $param .= "&search_company=".urlencode($search_company); }
if ($search_address != '') $param .= "&search_address=".urlencode($search_address); if ($search_civility) {
if ($search_town != '') $param .= "&search_town=".urlencode($search_town); $param .= "&search_civility=".urlencode($search_civility);
if ($search_zip != '') $param .= "&search_zip=".urlencode($search_zip); }
if ($search_state != '') $param .= "&search_state=".urlencode($search_state); if ($search_firstname) {
if ($search_country != '') $param .= "&search_country=".urlencode($search_country); $param .= "&search_firstname=".urlencode($search_firstname);
if ($search_phone != '') $param .= "&search_phone=".urlencode($search_phone); }
if ($search_phone_perso != '') $param .= "&search_phone_perso=".urlencode($search_phone_perso); if ($search_lastname) {
if ($search_phone_mobile != '') $param .= "&search_phone_mobile=".urlencode($search_phone_mobile); $param .= "&search_lastname=".urlencode($search_lastname);
if ($search_filter && $search_filter != '-1') $param .= "&search_filter=".urlencode($search_filter); }
if ($search_status != "" && $search_status != '-1') $param .= "&search_status=".urlencode($search_status); if ($search_gender) {
if ($search_type > 0) $param .= "&search_type=".urlencode($search_type); $param .= "&search_gender=".urlencode($search_gender);
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); }
if ($search_login) {
$param .= "&search_login=".urlencode($search_login);
}
if ($search_email) {
$param .= "&search_email=".urlencode($search_email);
}
if ($search_categ) {
$param .= "&search_categ=".urlencode($search_categ);
}
if ($search_company) {
$param .= "&search_company=".urlencode($search_company);
}
if ($search_address != '') {
$param .= "&search_address=".urlencode($search_address);
}
if ($search_town != '') {
$param .= "&search_town=".urlencode($search_town);
}
if ($search_zip != '') {
$param .= "&search_zip=".urlencode($search_zip);
}
if ($search_state != '') {
$param .= "&search_state=".urlencode($search_state);
}
if ($search_country != '') {
$param .= "&search_country=".urlencode($search_country);
}
if ($search_phone != '') {
$param .= "&search_phone=".urlencode($search_phone);
}
if ($search_phone_perso != '') {
$param .= "&search_phone_perso=".urlencode($search_phone_perso);
}
if ($search_phone_mobile != '') {
$param .= "&search_phone_mobile=".urlencode($search_phone_mobile);
}
if ($search_filter && $search_filter != '-1') {
$param .= "&search_filter=".urlencode($search_filter);
}
if ($search_status != "" && $search_status != '-1') {
$param .= "&search_status=".urlencode($search_status);
}
if ($search_type > 0) {
$param .= "&search_type=".urlencode($search_type);
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
}
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@ -405,10 +543,18 @@ $arrayofmassactions = array(
//'presend'=>$langs->trans("SendByMail"), //'presend'=>$langs->trans("SendByMail"),
//'builddoc'=>$langs->trans("PDFMerge"), //'builddoc'=>$langs->trans("PDFMerge"),
); );
if ($user->rights->adherent->creer) $arrayofmassactions['close'] = $langs->trans("Resiliate"); if ($user->rights->adherent->creer) {
if ($user->rights->adherent->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); $arrayofmassactions['close'] = $langs->trans("Resiliate");
if ($user->rights->societe->creer) $arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag"); }
if (in_array($massaction, array('presend', 'predelete','preaffecttag'))) $arrayofmassactions = array(); if ($user->rights->adherent->supprimer) {
$arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
}
if ($user->rights->societe->creer) {
$arrayofmassactions['preaffecttag'] = '<span class="fa fa-tag paddingrightonly"></span>'.$langs->trans("AffectTag");
}
if (in_array($massaction, array('presend', 'predelete','preaffecttag'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
$newcardbutton = ''; $newcardbutton = '';
@ -417,7 +563,9 @@ if ($user->rights->adherent->creer) {
} }
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -434,7 +582,9 @@ $trackid = 'mem'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($sall) { if ($sall) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); foreach ($fieldstosearchall as $key => $val) {
$fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
} }
@ -448,8 +598,11 @@ if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) {
} }
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; if (empty($reshook)) {
else $moreforfilter = $hookmanager->resPrint; $moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if (!empty($moreforfilter)) { if (!empty($moreforfilter)) {
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
@ -458,7 +611,9 @@ if (!empty($moreforfilter)) {
$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); if ($massactionbutton) {
$selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
}
print '<div class="div-table-responsive">'; print '<div class="div-table-responsive">';
print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
@ -609,26 +764,66 @@ print '</td>';
print "</tr>\n"; print "</tr>\n";
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) print_liste_field_titre("ID", $_SERVER["PHP_SELF"], '', '', $param, 'align="center"', $sortfield, $sortorder); if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) {
if (!empty($arrayfields['d.ref']['checked'])) print_liste_field_titre($arrayfields['d.ref']['label'], $_SERVER["PHP_SELF"], 'd.ref', '', $param, '', $sortfield, $sortorder); print_liste_field_titre("ID", $_SERVER["PHP_SELF"], '', '', $param, 'align="center"', $sortfield, $sortorder);
if (!empty($arrayfields['d.civility']['checked'])) print_liste_field_titre($arrayfields['d.civility']['label'], $_SERVER["PHP_SELF"], 'd.civility', '', $param, '', $sortfield, $sortorder); }
if (!empty($arrayfields['d.firstname']['checked'])) print_liste_field_titre($arrayfields['d.firstname']['label'], $_SERVER["PHP_SELF"], 'd.firstname', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['d.ref']['checked'])) {
if (!empty($arrayfields['d.lastname']['checked'])) print_liste_field_titre($arrayfields['d.lastname']['label'], $_SERVER["PHP_SELF"], 'd.lastname', '', $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['d.ref']['label'], $_SERVER["PHP_SELF"], 'd.ref', '', $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['d.gender']['checked'])) print_liste_field_titre($arrayfields['d.gender']['label'], $_SERVER['PHP_SELF'], 'd.gender', $param, "", "", $sortfield, $sortorder); }
if (!empty($arrayfields['d.company']['checked'])) print_liste_field_titre($arrayfields['d.company']['label'], $_SERVER["PHP_SELF"], 'd.societe', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['d.civility']['checked'])) {
if (!empty($arrayfields['d.login']['checked'])) print_liste_field_titre($arrayfields['d.login']['label'], $_SERVER["PHP_SELF"], 'd.login', '', $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['d.civility']['label'], $_SERVER["PHP_SELF"], 'd.civility', '', $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['d.morphy']['checked'])) print_liste_field_titre($arrayfields['d.morphy']['label'], $_SERVER["PHP_SELF"], 'd.morphy', '', $param, '', $sortfield, $sortorder); }
if (!empty($arrayfields['t.libelle']['checked'])) print_liste_field_titre($arrayfields['t.libelle']['label'], $_SERVER["PHP_SELF"], 't.libelle', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['d.firstname']['checked'])) {
if (!empty($arrayfields['d.address']['checked'])) print_liste_field_titre($arrayfields['d.address']['label'], $_SERVER["PHP_SELF"], 'd.address', '', $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['d.firstname']['label'], $_SERVER["PHP_SELF"], 'd.firstname', '', $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['d.zip']['checked'])) print_liste_field_titre($arrayfields['d.zip']['label'], $_SERVER["PHP_SELF"], 'd.zip', '', $param, '', $sortfield, $sortorder); }
if (!empty($arrayfields['d.town']['checked'])) print_liste_field_titre($arrayfields['d.town']['label'], $_SERVER["PHP_SELF"], 'd.town', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['d.lastname']['checked'])) {
if (!empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['d.lastname']['label'], $_SERVER["PHP_SELF"], 'd.lastname', '', $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, 'align="center"', $sortfield, $sortorder); }
if (!empty($arrayfields['d.phone']['checked'])) print_liste_field_titre($arrayfields['d.phone']['label'], $_SERVER["PHP_SELF"], 'd.phone', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['d.gender']['checked'])) {
if (!empty($arrayfields['d.phone_perso']['checked'])) print_liste_field_titre($arrayfields['d.phone_perso']['label'], $_SERVER["PHP_SELF"], 'd.phone_perso', '', $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['d.gender']['label'], $_SERVER['PHP_SELF'], 'd.gender', $param, "", "", $sortfield, $sortorder);
if (!empty($arrayfields['d.phone_mobile']['checked'])) print_liste_field_titre($arrayfields['d.phone_mobile']['label'], $_SERVER["PHP_SELF"], 'd.phone_mobile', '', $param, '', $sortfield, $sortorder); }
if (!empty($arrayfields['d.email']['checked'])) print_liste_field_titre($arrayfields['d.email']['label'], $_SERVER["PHP_SELF"], 'd.email', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['d.company']['checked'])) {
if (!empty($arrayfields['d.datefin']['checked'])) print_liste_field_titre($arrayfields['d.datefin']['label'], $_SERVER["PHP_SELF"], 'd.datefin', '', $param, 'align="center"', $sortfield, $sortorder); print_liste_field_titre($arrayfields['d.company']['label'], $_SERVER["PHP_SELF"], 'd.societe', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.login']['checked'])) {
print_liste_field_titre($arrayfields['d.login']['label'], $_SERVER["PHP_SELF"], 'd.login', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.morphy']['checked'])) {
print_liste_field_titre($arrayfields['d.morphy']['label'], $_SERVER["PHP_SELF"], 'd.morphy', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['t.libelle']['checked'])) {
print_liste_field_titre($arrayfields['t.libelle']['label'], $_SERVER["PHP_SELF"], 't.libelle', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.address']['checked'])) {
print_liste_field_titre($arrayfields['d.address']['label'], $_SERVER["PHP_SELF"], 'd.address', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.zip']['checked'])) {
print_liste_field_titre($arrayfields['d.zip']['label'], $_SERVER["PHP_SELF"], 'd.zip', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.town']['checked'])) {
print_liste_field_titre($arrayfields['d.town']['label'], $_SERVER["PHP_SELF"], 'd.town', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['state.nom']['checked'])) {
print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['country.code_iso']['checked'])) {
print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, 'align="center"', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.phone']['checked'])) {
print_liste_field_titre($arrayfields['d.phone']['label'], $_SERVER["PHP_SELF"], 'd.phone', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.phone_perso']['checked'])) {
print_liste_field_titre($arrayfields['d.phone_perso']['label'], $_SERVER["PHP_SELF"], 'd.phone_perso', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.phone_mobile']['checked'])) {
print_liste_field_titre($arrayfields['d.phone_mobile']['label'], $_SERVER["PHP_SELF"], 'd.phone_mobile', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.email']['checked'])) {
print_liste_field_titre($arrayfields['d.email']['label'], $_SERVER["PHP_SELF"], 'd.email', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.datefin']['checked'])) {
print_liste_field_titre($arrayfields['d.datefin']['label'], $_SERVER["PHP_SELF"], 'd.datefin', '', $param, 'align="center"', $sortfield, $sortorder);
}
// Extra fields // Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
@ -636,10 +831,18 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if (!empty($arrayfields['d.datec']['checked'])) print_liste_field_titre($arrayfields['d.datec']['label'], $_SERVER["PHP_SELF"], "d.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); if (!empty($arrayfields['d.datec']['checked'])) {
if (!empty($arrayfields['d.birth']['checked'])) print_liste_field_titre($arrayfields['d.birth']['label'], $_SERVER["PHP_SELF"], "d.birth", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); print_liste_field_titre($arrayfields['d.datec']['label'], $_SERVER["PHP_SELF"], "d.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
if (!empty($arrayfields['d.tms']['checked'])) print_liste_field_titre($arrayfields['d.tms']['label'], $_SERVER["PHP_SELF"], "d.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); }
if (!empty($arrayfields['d.statut']['checked'])) print_liste_field_titre($arrayfields['d.statut']['label'], $_SERVER["PHP_SELF"], "d.statut", "", $param, 'class="right"', $sortfield, $sortorder); if (!empty($arrayfields['d.birth']['checked'])) {
print_liste_field_titre($arrayfields['d.birth']['label'], $_SERVER["PHP_SELF"], "d.birth", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.tms']['checked'])) {
print_liste_field_titre($arrayfields['d.tms']['label'], $_SERVER["PHP_SELF"], "d.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.statut']['checked'])) {
print_liste_field_titre($arrayfields['d.statut']['label'], $_SERVER["PHP_SELF"], "d.statut", "", $param, 'class="right"', $sortfield, $sortorder);
}
print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ');
print "</tr>\n"; print "</tr>\n";
@ -676,7 +879,9 @@ while ($i < min($num, $limit)) {
if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) {
print '<td class="center">'.$obj->rowid.'</td>'; print '<td class="center">'.$obj->rowid.'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Ref // Ref
@ -684,35 +889,47 @@ while ($i < min($num, $limit)) {
print "<td>"; print "<td>";
print $memberstatic->getNomUrl(-1, 0, 'card', 'ref', '', -1, 0, 1); print $memberstatic->getNomUrl(-1, 0, 'card', 'ref', '', -1, 0, 1);
print "</td>\n"; print "</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Civility // Civility
if (!empty($arrayfields['d.civility']['checked'])) { if (!empty($arrayfields['d.civility']['checked'])) {
print "<td>"; print "<td>";
print $obj->civility; print $obj->civility;
print "</td>\n"; print "</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Firstname // Firstname
if (!empty($arrayfields['d.firstname']['checked'])) { if (!empty($arrayfields['d.firstname']['checked'])) {
print "<td>"; print "<td>";
print $obj->firstname; print $obj->firstname;
print "</td>\n"; print "</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Lastname // Lastname
if (!empty($arrayfields['d.lastname']['checked'])) { if (!empty($arrayfields['d.lastname']['checked'])) {
print "<td>"; print "<td>";
print $obj->lastname; print $obj->lastname;
print "</td>\n"; print "</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Gender // Gender
if (!empty($arrayfields['d.gender']['checked'])) { if (!empty($arrayfields['d.gender']['checked'])) {
print '<td>'; print '<td>';
if ($obj->gender) print $langs->trans("Gender".$obj->gender); if ($obj->gender) {
print $langs->trans("Gender".$obj->gender);
}
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Company // Company
if (!empty($arrayfields['d.company']['checked'])) { if (!empty($arrayfields['d.company']['checked'])) {
@ -723,7 +940,9 @@ while ($i < min($num, $limit)) {
// Login // Login
if (!empty($arrayfields['d.login']['checked'])) { if (!empty($arrayfields['d.login']['checked'])) {
print "<td>".$obj->login."</td>\n"; print "<td>".$obj->login."</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Nature (Moral/Physical) // Nature (Moral/Physical)
if (!empty($arrayfields['d.morphy']['checked'])) { if (!empty($arrayfields['d.morphy']['checked'])) {
@ -737,7 +956,9 @@ while ($i < min($num, $limit)) {
} }
print $s; print $s;
print "</td>\n"; print "</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Type label // Type label
if (!empty($arrayfields['t.libelle']['checked'])) { if (!empty($arrayfields['t.libelle']['checked'])) {
@ -746,33 +967,43 @@ while ($i < min($num, $limit)) {
print '<td class="nowrap">'; print '<td class="nowrap">';
print $membertypestatic->getNomUrl(1, 32); print $membertypestatic->getNomUrl(1, 32);
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Address // Address
if (!empty($arrayfields['d.address']['checked'])) { if (!empty($arrayfields['d.address']['checked'])) {
print '<td class="nocellnopadd">'; print '<td class="nocellnopadd">';
print $obj->address; print $obj->address;
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Zip // Zip
if (!empty($arrayfields['d.zip']['checked'])) { if (!empty($arrayfields['d.zip']['checked'])) {
print '<td class="nocellnopadd">'; print '<td class="nocellnopadd">';
print $obj->zip; print $obj->zip;
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Town // Town
if (!empty($arrayfields['d.town']['checked'])) { if (!empty($arrayfields['d.town']['checked'])) {
print '<td class="nocellnopadd">'; print '<td class="nocellnopadd">';
print $obj->town; print $obj->town;
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// State // State
if (!empty($arrayfields['state.nom']['checked'])) { if (!empty($arrayfields['state.nom']['checked'])) {
print "<td>".$obj->state_name."</td>\n"; print "<td>".$obj->state_name."</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Country // Country
if (!empty($arrayfields['country.code_iso']['checked'])) { if (!empty($arrayfields['country.code_iso']['checked'])) {
@ -780,28 +1011,36 @@ while ($i < min($num, $limit)) {
$tmparray = getCountry($obj->country, 'all'); $tmparray = getCountry($obj->country, 'all');
print $tmparray['label']; print $tmparray['label'];
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Phone pro // Phone pro
if (!empty($arrayfields['d.phone']['checked'])) { if (!empty($arrayfields['d.phone']['checked'])) {
print '<td class="nocellnopadd">'; print '<td class="nocellnopadd">';
print $obj->phone; print $obj->phone;
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Phone perso // Phone perso
if (!empty($arrayfields['d.phone_perso']['checked'])) { if (!empty($arrayfields['d.phone_perso']['checked'])) {
print '<td class="nocellnopadd">'; print '<td class="nocellnopadd">';
print $obj->phone_perso; print $obj->phone_perso;
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Phone mobile // Phone mobile
if (!empty($arrayfields['d.phone_mobile']['checked'])) { if (!empty($arrayfields['d.phone_mobile']['checked'])) {
print '<td class="nocellnopadd">'; print '<td class="nocellnopadd">';
print $obj->phone_mobile; print $obj->phone_mobile;
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// EMail // EMail
if (!empty($arrayfields['d.email']['checked'])) { if (!empty($arrayfields['d.email']['checked'])) {
@ -822,7 +1061,9 @@ while ($i < min($num, $limit)) {
print '<td class="nowrap left">'; print '<td class="nowrap left">';
if ($obj->subscription == 'yes') { if ($obj->subscription == 'yes') {
print $langs->trans("SubscriptionNotReceived"); print $langs->trans("SubscriptionNotReceived");
if ($obj->statut > 0) print " ".img_warning(); if ($obj->statut > 0) {
print " ".img_warning();
}
} else { } else {
print '&nbsp;'; print '&nbsp;';
} }
@ -840,38 +1081,50 @@ while ($i < min($num, $limit)) {
print '<td class="nowrap center">'; print '<td class="nowrap center">';
print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Birth // Birth
if (!empty($arrayfields['d.birth']['checked'])) { if (!empty($arrayfields['d.birth']['checked'])) {
print '<td class="nowrap center">'; print '<td class="nowrap center">';
print dol_print_date($db->jdate($obj->birth), 'day', 'tzuser'); print dol_print_date($db->jdate($obj->birth), 'day', 'tzuser');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Date modification // Date modification
if (!empty($arrayfields['d.tms']['checked'])) { if (!empty($arrayfields['d.tms']['checked'])) {
print '<td class="nowrap center">'; print '<td class="nowrap center">';
print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Status // Status
if (!empty($arrayfields['d.statut']['checked'])) { if (!empty($arrayfields['d.statut']['checked'])) {
print '<td class="nowrap right">'; print '<td class="nowrap right">';
print $memberstatic->LibStatut($obj->statut, $obj->subscription, $datefin, 5); print $memberstatic->LibStatut($obj->statut, $obj->subscription, $datefin, 5);
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Action column // Action column
print '<td class="center">'; print '<td class="center">';
if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
$selected = 0; $selected = 0;
if (in_array($obj->rowid, $arrayofselected)) $selected = 1; if (in_array($obj->rowid, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print "</tr>\n"; print "</tr>\n";
$i++; $i++;
@ -884,7 +1137,11 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
// If no record found // If no record found
if ($num == 0) { if ($num == 0) {
$colspan = 1; $colspan = 1;
foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } foreach ($arrayfields as $key => $val) {
if (!empty($val['checked'])) {
$colspan++;
}
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
} }

View File

@ -82,8 +82,12 @@ if ($resql) {
while ($i < $num) { while ($i < $num) {
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if ($obj->code == 'phy') $foundphy++; if ($obj->code == 'phy') {
if ($obj->code == 'mor') $foundmor++; $foundphy++;
}
if ($obj->code == 'mor') {
$foundmor++;
}
$data[$obj->code] = array('label'=>$obj->code, 'nb'=>$obj->nb, 'nbsubscriptions'=>$obj->nbsubscriptions, 'lastdate'=>$db->jdate($obj->lastdate), 'lastsubscriptiondate'=>$db->jdate($obj->lastsubscriptiondate)); $data[$obj->code] = array('label'=>$obj->code, 'nb'=>$obj->nb, 'nbsubscriptions'=>$obj->nbsubscriptions, 'lastdate'=>$db->jdate($obj->lastdate), 'lastsubscriptiondate'=>$db->jdate($obj->lastsubscriptiondate));
@ -113,8 +117,12 @@ if ($resql) {
while ($i < $num) { while ($i < $num) {
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if ($obj->code == 'phy') $foundphy++; if ($obj->code == 'phy') {
if ($obj->code == 'mor') $foundmor++; $foundphy++;
}
if ($obj->code == 'mor') {
$foundmor++;
}
$data[$obj->code]['nbactive'] = $obj->nb; $data[$obj->code]['nbactive'] = $obj->nb;
@ -152,8 +160,12 @@ print '<td class="right">'.$langs->trans("NbOfSubscriptions").'</td>';
print '<td class="center">'.$langs->trans("LatestSubscriptionDate").'</td>'; print '<td class="center">'.$langs->trans("LatestSubscriptionDate").'</td>';
print '</tr>'; print '</tr>';
if (!$foundphy) $data[] = array('label'=>'phy', 'nb'=>'0', 'nbactive'=>'0', 'lastdate'=>'', 'lastsubscriptiondate'=>''); if (!$foundphy) {
if (!$foundmor) $data[] = array('label'=>'mor', 'nb'=>'0', 'nbactive'=>'0', 'lastdate'=>'', 'lastsubscriptiondate'=>''); $data[] = array('label'=>'phy', 'nb'=>'0', 'nbactive'=>'0', 'lastdate'=>'', 'lastsubscriptiondate'=>'');
}
if (!$foundmor) {
$data[] = array('label'=>'mor', 'nb'=>'0', 'nbactive'=>'0', 'lastdate'=>'', 'lastsubscriptiondate'=>'');
}
foreach ($data as $val) { foreach ($data as $val) {
$nb = $val['nb']; $nb = $val['nb'];

View File

@ -56,13 +56,23 @@ $langs->loadLangs(array("companies", "members", "banks"));
$memberstatic = new Adherent($db); $memberstatic = new Adherent($db);
$arrayjs = array('https://www.google.com/jsapi'); $arrayjs = array('https://www.google.com/jsapi');
if (!empty($conf->dol_use_jmobile)) $arrayjs = array(); if (!empty($conf->dol_use_jmobile)) {
$arrayjs = array();
}
$title = $langs->trans("Statistics"); $title = $langs->trans("Statistics");
if ($mode == 'memberbycountry') $title = $langs->trans("MembersStatisticsByCountries"); if ($mode == 'memberbycountry') {
if ($mode == 'memberbystate') $title = $langs->trans("MembersStatisticsByState"); $title = $langs->trans("MembersStatisticsByCountries");
if ($mode == 'memberbytown') $title = $langs->trans("MembersStatisticsByTown"); }
if ($mode == 'memberbyregion') $title = $langs->trans("MembersStatisticsByRegion"); if ($mode == 'memberbystate') {
$title = $langs->trans("MembersStatisticsByState");
}
if ($mode == 'memberbytown') {
$title = $langs->trans("MembersStatisticsByTown");
}
if ($mode == 'memberbyregion') {
$title = $langs->trans("MembersStatisticsByRegion");
}
llxHeader('', $title, '', '', 0, 0, $arrayjs); llxHeader('', $title, '', '', 0, 0, $arrayjs);
@ -207,11 +217,15 @@ if ($mode && !count($data)) {
print $langs->trans("NoValidatedMemberYet").'<br>'; print $langs->trans("NoValidatedMemberYet").'<br>';
print '<br>'; print '<br>';
} else { } else {
if ($mode == 'memberbycountry') print '<span class="opacitymedium">'.$langs->trans("MembersByCountryDesc").'</span><br>'; if ($mode == 'memberbycountry') {
elseif ($mode == 'memberbystate') print '<span class="opacitymedium">'.$langs->trans("MembersByStateDesc").'</span><br>'; print '<span class="opacitymedium">'.$langs->trans("MembersByCountryDesc").'</span><br>';
elseif ($mode == 'memberbytown') print '<span class="opacitymedium">'.$langs->trans("MembersByTownDesc").'</span><br>'; } elseif ($mode == 'memberbystate') {
elseif ($mode == 'memberbyregion') print '<span class="opacitymedium">'.$langs->trans("MembersByRegion").'</span><br>'; //+ print '<span class="opacitymedium">'.$langs->trans("MembersByStateDesc").'</span><br>';
else { } elseif ($mode == 'memberbytown') {
print '<span class="opacitymedium">'.$langs->trans("MembersByTownDesc").'</span><br>';
} elseif ($mode == 'memberbyregion') {
print '<span class="opacitymedium">'.$langs->trans("MembersByRegion").'</span><br>'; //+
} else {
print '<span class="opacitymedium">'.$langs->trans("MembersStatisticsDesc").'</span><br>'; print '<span class="opacitymedium">'.$langs->trans("MembersStatisticsDesc").'</span><br>';
print '<br>'; print '<br>';
print '<a href="'.$_SERVER["PHP_SELF"].'?mode=memberbycountry">'.$langs->trans("MembersStatisticsByCountries").'</a><br>'; print '<a href="'.$_SERVER["PHP_SELF"].'?mode=memberbycountry">'.$langs->trans("MembersStatisticsByCountries").'</a><br>';
@ -229,7 +243,9 @@ if ($mode && !count($data)) {
// Show graphics // Show graphics
if (count($arrayjs) && $mode == 'memberbycountry') { if (count($arrayjs) && $mode == 'memberbycountry') {
$color_file = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; $color_file = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php';
if (is_readable($color_file)) include_once $color_file; if (is_readable($color_file)) {
include_once $color_file;
}
// Assume we've already included the proper headers so just call our script inline // Assume we've already included the proper headers so just call our script inline
// More doc: https://developers.google.com/chart/interactive/docs/gallery/geomap?hl=fr-FR // More doc: https://developers.google.com/chart/interactive/docs/gallery/geomap?hl=fr-FR
@ -248,11 +264,15 @@ if (count($arrayjs) && $mode == 'memberbycountry') {
foreach ($data as $val) { foreach ($data as $val) {
$valcountry = strtoupper($val['code']); // Should be ISO-3166 code (faster) $valcountry = strtoupper($val['code']); // Should be ISO-3166 code (faster)
//$valcountry=ucfirst($val['label_en']); //$valcountry=ucfirst($val['label_en']);
if ($valcountry == 'Great Britain') { $valcountry = 'United Kingdom'; } // fix case of uk (when we use labels) if ($valcountry == 'Great Britain') {
$valcountry = 'United Kingdom';
} // fix case of uk (when we use labels)
print "\tdata.setValue(".$i.", 0, \"".$valcountry."\");\n"; print "\tdata.setValue(".$i.", 0, \"".$valcountry."\");\n";
print "\tdata.setValue(".$i.", 1, ".$val['nb'].");\n"; print "\tdata.setValue(".$i.", 1, ".$val['nb'].");\n";
// Google's Geomap only supports up to 400 entries // Google's Geomap only supports up to 400 entries
if ($i >= 400) { break; } if ($i >= 400) {
break;
}
$i++; $i++;
} }
@ -279,7 +299,9 @@ if ($mode) {
print '<table class="liste centpercent">'; print '<table class="liste centpercent">';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
print '<td>'.$label.'</td>'; print '<td>'.$label.'</td>';
if ($label2) print '<td class="center">'.$label2.'</td>'; if ($label2) {
print '<td class="center">'.$label2.'</td>';
}
print '<td class="right">'.$langs->trans("NbOfMembers").' <span class="opacitymedium">('.$langs->trans("AllTime").')</span></td>'; print '<td class="right">'.$langs->trans("NbOfMembers").' <span class="opacitymedium">('.$langs->trans("AllTime").')</span></td>';
print '<td class="center">'.$langs->trans("LastMemberDate").'</td>'; print '<td class="center">'.$langs->trans("LastMemberDate").'</td>';
print '<td class="center">'.$langs->trans("LatestSubscriptionDate").'</td>'; print '<td class="center">'.$langs->trans("LatestSubscriptionDate").'</td>';
@ -289,7 +311,9 @@ if ($mode) {
$year = $val['year']; $year = $val['year'];
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$val['label'].'</td>'; print '<td>'.$val['label'].'</td>';
if ($label2) print '<td class="center">'.$val['label2'].'</td>'; if ($label2) {
print '<td class="center">'.$val['label2'].'</td>';
}
print '<td class="right">'.$val['nb'].'</td>'; print '<td class="right">'.$val['nb'].'</td>';
print '<td class="center">'.dol_print_date($val['lastdate'], 'dayhour').'</td>'; print '<td class="center">'.dol_print_date($val['lastdate'], 'dayhour').'</td>';
print '<td class="center">'.dol_print_date($val['lastsubscriptiondate'], 'dayhour').'</td>'; print '<td class="center">'.dol_print_date($val['lastsubscriptiondate'], 'dayhour').'</td>';

View File

@ -32,8 +32,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php';
$WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); $WIDTH = DolGraph::getDefaultGraphSizeForStats('width');
$HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height');
$userid = GETPOST('userid', 'int'); if ($userid < 0) $userid = 0; $userid = GETPOST('userid', 'int'); if ($userid < 0) {
$socid = GETPOST('socid', 'int'); if ($socid < 0) $socid = 0; $userid = 0;
}
$socid = GETPOST('socid', 'int'); if ($socid < 0) {
$socid = 0;
}
// Security check // Security check
if ($user->socid > 0) { if ($user->socid > 0) {
@ -209,7 +213,9 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
// Show graphs // Show graphs
print '<table class="border centpercent"><tr class="pair nohover"><td class="center">'; print '<table class="border centpercent"><tr class="pair nohover"><td class="center">';
if ($mesg) { print $mesg; } else { if ($mesg) {
print $mesg;
} else {
print $px1->show(); print $px1->show();
print "<br>\n"; print "<br>\n";
print $px2->show(); print $px2->show();

View File

@ -50,14 +50,20 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
// Default sort order (if not yet defined by previous GETPOST) // Default sort order (if not yet defined by previous GETPOST)
if (!$sortfield) $sortfield = "c.rowid"; if (!$sortfield) {
if (!$sortorder) $sortorder = "DESC"; $sortfield = "c.rowid";
}
if (!$sortorder) {
$sortorder = "DESC";
}
// Security check // Security check
@ -150,7 +156,9 @@ if (empty($reshook) && $action == 'setuserid' && ($user->rights->user->self->cre
if (!$error) { if (!$error) {
if ($_POST["userid"] != $object->user_id) { // If link differs from currently in database if ($_POST["userid"] != $object->user_id) { // If link differs from currently in database
$result = $object->setUserId($_POST["userid"]); $result = $object->setUserId($_POST["userid"]);
if ($result < 0) dol_print_error('', $object->error); if ($result < 0) {
dol_print_error('', $object->error);
}
$_POST['action'] = ''; $_POST['action'] = '';
$action = ''; $action = '';
} }
@ -178,7 +186,9 @@ if (empty($reshook) && $action == 'setsocid') {
if (!$error) { if (!$error) {
$result = $object->setThirdPartyId(GETPOST('socid', 'int')); $result = $object->setThirdPartyId(GETPOST('socid', 'int'));
if ($result < 0) dol_print_error('', $object->error); if ($result < 0) {
dol_print_error('', $object->error);
}
$_POST['action'] = ''; $_POST['action'] = '';
$action = ''; $action = '';
} }
@ -423,25 +433,37 @@ llxHeader("", $title, $helpurl);
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
}
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.urlencode($limit);
}
$param .= '&id='.$rowid; $param .= '&id='.$rowid;
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
}
// Add $param from extra fields // Add $param from extra fields
//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; //include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
if ($rowid > 0) { if ($rowid > 0) {
$res = $object->fetch($rowid); $res = $object->fetch($rowid);
if ($res < 0) { dol_print_error($db, $object->error); exit; } if ($res < 0) {
dol_print_error($db, $object->error); exit;
}
$adht->fetch($object->typeid); $adht->fetch($object->typeid);
$head = member_prepare_head($object); $head = member_prepare_head($object);
$rowspan = 10; $rowspan = 10;
if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $rowspan++; if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
if (!empty($conf->societe->enabled)) $rowspan++; $rowspan++;
}
if (!empty($conf->societe->enabled)) {
$rowspan++;
}
print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">'; print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
@ -514,10 +536,14 @@ if ($rowid > 0) {
} else { } else {
if (!$adht->subscription) { if (!$adht->subscription) {
print $langs->trans("SubscriptionNotRecorded"); print $langs->trans("SubscriptionNotRecorded");
if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled if ($object->statut > 0) {
print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled
}
} else { } else {
print $langs->trans("SubscriptionNotReceived"); print $langs->trans("SubscriptionNotReceived");
if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled if ($object->statut > 0) {
print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled
}
} }
} }
print '</td></tr>'; print '</td></tr>';
@ -554,7 +580,9 @@ if ($rowid > 0) {
print '<table class="nobordernopadding" width="100%"><tr><td>'; print '<table class="nobordernopadding" width="100%"><tr><td>';
print $langs->trans("LinkedToDolibarrThirdParty"); print $langs->trans("LinkedToDolibarrThirdParty");
print '</td>'; print '</td>';
if ($action != 'editthirdparty' && $user->rights->adherent->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editthirdparty&amp;rowid='.$object->id.'">'.img_edit($langs->trans('SetLinkToThirdParty'), 1).'</a></td>'; if ($action != 'editthirdparty' && $user->rights->adherent->creer) {
print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editthirdparty&amp;rowid='.$object->id.'">'.img_edit($langs->trans('SetLinkToThirdParty'), 1).'</a></td>';
}
print '</tr></table>'; print '</tr></table>';
print '</td><td colspan="2" class="valeur">'; print '</td><td colspan="2" class="valeur">';
if ($action == 'editthirdparty') { if ($action == 'editthirdparty') {
@ -600,7 +628,9 @@ if ($rowid > 0) {
} else { } else {
if ($object->user_id) { if ($object->user_id) {
$form->form_users($_SERVER['PHP_SELF'].'?rowid='.$object->id, $object->user_id, 'none'); $form->form_users($_SERVER['PHP_SELF'].'?rowid='.$object->id, $object->user_id, 'none');
} else print $langs->trans("NoDolibarrAccess"); } else {
print $langs->trans("NoDolibarrAccess");
}
} }
print '</td></tr>'; print '</td></tr>';
@ -623,8 +653,11 @@ if ($rowid > 0) {
if ($action != 'addsubscription' && $action != 'create_thirdparty') { if ($action != 'addsubscription' && $action != 'create_thirdparty') {
print '<div class="tabsAction">'; print '<div class="tabsAction">';
if ($object->statut > 0) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?rowid='.$rowid.'&action=addsubscription">'.$langs->trans("AddSubscription")."</a></div>"; if ($object->statut > 0) {
else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("ValidateBefore")).'">'.$langs->trans("AddSubscription").'</a></div>'; print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?rowid='.$rowid.'&action=addsubscription">'.$langs->trans("AddSubscription")."</a></div>";
} else {
print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("ValidateBefore")).'">'.$langs->trans("AddSubscription").'</a></div>';
}
print '</div>'; print '</div>';
} }
@ -727,7 +760,9 @@ if ($rowid > 0) {
if (empty($num)) { if (empty($num)) {
$colspan = 6; $colspan = 6;
if (!empty($conf->banque->enabled)) $colspan++; if (!empty($conf->banque->enabled)) {
$colspan++;
}
print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>'; print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
} }
@ -764,13 +799,23 @@ if ($rowid > 0) {
$invoiceonly = 0; // 1 means option by default is invoice only $invoiceonly = 0; // 1 means option by default is invoice only
$bankviainvoice = 0; // 1 means option by default is write to bank via invoice $bankviainvoice = 0; // 1 means option by default is write to bank via invoice
if (GETPOST('paymentsave')) { if (GETPOST('paymentsave')) {
if (GETPOST('paymentsave') == 'bankdirect') $bankdirect = 1; if (GETPOST('paymentsave') == 'bankdirect') {
if (GETPOST('paymentsave') == 'invoiceonly') $invoiceonly = 1; $bankdirect = 1;
if (GETPOST('paymentsave') == 'bankviainvoice') $bankviainvoice = 1; }
if (GETPOST('paymentsave') == 'invoiceonly') {
$invoiceonly = 1;
}
if (GETPOST('paymentsave') == 'bankviainvoice') {
$bankviainvoice = 1;
}
} else { } else {
if (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankviainvoice' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $bankviainvoice = 1; if (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankviainvoice' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) {
elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && !empty($conf->banque->enabled)) $bankdirect = 1; $bankviainvoice = 1;
elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'invoiceonly' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $invoiceonly = 1; } elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && !empty($conf->banque->enabled)) {
$bankdirect = 1;
} elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'invoiceonly' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) {
$invoiceonly = 1;
}
} }
print "\n\n<!-- Form add subscription -->\n"; print "\n\n<!-- Form add subscription -->\n";
@ -804,7 +849,9 @@ if ($rowid > 0) {
} }
}); });
'; ';
if (GETPOST('paymentsave')) print '$("#'.GETPOST('paymentsave').'").prop("checked",true);'; if (GETPOST('paymentsave')) {
print '$("#'.GETPOST('paymentsave').'").prop("checked",true);';
}
print '});'; print '});';
print '</script>'."\n"; print '</script>'."\n";
} }
@ -817,10 +864,14 @@ if ($rowid > 0) {
if ($object->morphy == 'mor') { if ($object->morphy == 'mor') {
$companyname = $object->company; $companyname = $object->company;
if (!empty($fullname)) $companyalias = $fullname; if (!empty($fullname)) {
$companyalias = $fullname;
}
} else { } else {
$companyname = $fullname; $companyname = $fullname;
if (!empty($object->company)) $companyalias = $object->company; if (!empty($object->company)) {
$companyalias = $object->company;
}
} }
// Create a form array // Create a form array
@ -901,7 +952,9 @@ if ($rowid > 0) {
// Label // Label
print '<tr><td>'.$langs->trans("Label").'</td>'; print '<tr><td>'.$langs->trans("Label").'</td>';
print '<td><input name="label" type="text" size="32" value="'; print '<td><input name="label" type="text" size="32" value="';
if (empty($conf->global->MEMBER_NO_DEFAULT_LABEL)) print $langs->trans("Subscription").' '.dol_print_date(($datefrom ? $datefrom : time()), "%Y"); if (empty($conf->global->MEMBER_NO_DEFAULT_LABEL)) {
print $langs->trans("Subscription").' '.dol_print_date(($datefrom ? $datefrom : time()), "%Y");
}
print '"></td></tr>'; print '"></td></tr>';
// Complementary action // Complementary action
@ -929,16 +982,21 @@ if ($rowid > 0) {
print '<input type="radio" class="moreaction" id="invoiceonly" name="paymentsave" value="invoiceonly"'.(!empty($invoiceonly) ? ' checked' : ''); print '<input type="radio" class="moreaction" id="invoiceonly" name="paymentsave" value="invoiceonly"'.(!empty($invoiceonly) ? ' checked' : '');
//if (empty($object->fk_soc)) print ' disabled'; //if (empty($object->fk_soc)) print ' disabled';
print '> '.$langs->trans("MoreActionInvoiceOnly"); print '> '.$langs->trans("MoreActionInvoiceOnly");
if ($object->fk_soc) print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')'; if ($object->fk_soc) {
else { print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')';
} else {
print ' ('; print ' (';
if (empty($object->fk_soc)) print img_warning($langs->trans("NoThirdPartyAssociatedToMember")); if (empty($object->fk_soc)) {
print img_warning($langs->trans("NoThirdPartyAssociatedToMember"));
}
print $langs->trans("NoThirdPartyAssociatedToMember"); print $langs->trans("NoThirdPartyAssociatedToMember");
print ' - <a href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">'; print ' - <a href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">';
print $langs->trans("CreateDolibarrThirdParty"); print $langs->trans("CreateDolibarrThirdParty");
print '</a>)'; print '</a>)';
} }
if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. <span class="opacitymedium">'.$langs->trans("NoVatOnSubscription", 0).'</span>'; if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') {
print '. <span class="opacitymedium">'.$langs->trans("NoVatOnSubscription", 0).'</span>';
}
if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) { if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
$prodtmp = new Product($db); $prodtmp = new Product($db);
$result = $prodtmp->fetch($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS); $result = $prodtmp->fetch($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS);
@ -958,13 +1016,17 @@ if ($rowid > 0) {
print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')'; print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')';
} else { } else {
print ' ('; print ' (';
if (empty($object->fk_soc)) print img_warning($langs->trans("NoThirdPartyAssociatedToMember")); if (empty($object->fk_soc)) {
print img_warning($langs->trans("NoThirdPartyAssociatedToMember"));
}
print $langs->trans("NoThirdPartyAssociatedToMember"); print $langs->trans("NoThirdPartyAssociatedToMember");
print ' - <a href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">'; print ' - <a href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&amp;action=create_thirdparty">';
print $langs->trans("CreateDolibarrThirdParty"); print $langs->trans("CreateDolibarrThirdParty");
print '</a>)'; print '</a>)';
} }
if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. <span class="opacitymedium">'.$langs->trans("NoVatOnSubscription", 0).'</span>'; if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') {
print '. <span class="opacitymedium">'.$langs->trans("NoVatOnSubscription", 0).'</span>';
}
if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) { if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
$prodtmp = new Product($db); $prodtmp = new Product($db);
$result = $prodtmp->fetch($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS); $result = $prodtmp->fetch($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS);

View File

@ -48,8 +48,9 @@ $note = GETPOST('note', 'alpha');
$typeid = (int) GETPOST('typeid', 'int'); $typeid = (int) GETPOST('typeid', 'int');
$amount = price2num(GETPOST('amount', 'alpha'), 'MT'); $amount = price2num(GETPOST('amount', 'alpha'), 'MT');
if (!$user->rights->adherent->cotisation->lire) if (!$user->rights->adherent->cotisation->lire) {
accessforbidden(); accessforbidden();
}
$permissionnote = $user->rights->adherent->cotisation->creer; // Used by the include of actions_setnotes.inc.php $permissionnote = $user->rights->adherent->cotisation->creer; // Used by the include of actions_setnotes.inc.php
$permissiondellink = $user->rights->adherent->cotisation->creer; // Used by the include of actions_dellink.inc.php $permissiondellink = $user->rights->adherent->cotisation->creer; // Used by the include of actions_dellink.inc.php
@ -65,7 +66,9 @@ $result = restrictedArea($user, 'subscription', 0); // TODO Check on object id
* Actions * Actions
*/ */
if ($cancel) $action = ''; if ($cancel) {
$action = '';
}
//include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once //include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
@ -122,7 +125,9 @@ if ($user->rights->adherent->cotisation->creer && $action == 'update' && !$cance
$errmsg = $object->error; $errmsg = $object->error;
} else { } else {
foreach ($object->errors as $error) { foreach ($object->errors as $error) {
if ($errmsg) $errmsg .= '<br>'; if ($errmsg) {
$errmsg .= '<br>';
}
$errmsg .= $error; $errmsg .= $error;
} }
} }
@ -269,7 +274,9 @@ if ($rowid && $action != 'edit') {
//$formquestion=array(); //$formquestion=array();
//$formquestion['text']='<b>'.$langs->trans("ThisWillAlsoDeleteBankRecord").'</b>'; //$formquestion['text']='<b>'.$langs->trans("ThisWillAlsoDeleteBankRecord").'</b>';
$text = $langs->trans("ConfirmDeleteSubscription"); $text = $langs->trans("ConfirmDeleteSubscription");
if (!empty($conf->banque->enabled) && !empty($conf->global->ADHERENT_BANK_USE)) $text .= '<br>'.img_warning().' '.$langs->trans("ThisWillAlsoDeleteBankRecord"); if (!empty($conf->banque->enabled) && !empty($conf->global->ADHERENT_BANK_USE)) {
$text .= '<br>'.img_warning().' '.$langs->trans("ThisWillAlsoDeleteBankRecord");
}
print $form->formconfirm($_SERVER["PHP_SELF"]."?rowid=".$object->id, $langs->trans("DeleteSubscription"), $text, "confirm_delete", $formquestion, 0, 1); print $form->formconfirm($_SERVER["PHP_SELF"]."?rowid=".$object->id, $langs->trans("DeleteSubscription"), $text, "confirm_delete", $formquestion, 0, 1);
} }

View File

@ -31,8 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array("companies", "members", "bills", "users")); $langs->loadLangs(array("companies", "members", "bills", "users"));
if (!$user->rights->adherent->lire) if (!$user->rights->adherent->lire) {
accessforbidden(); accessforbidden();
}
$rowid = GETPOST("rowid", 'int'); $rowid = GETPOST("rowid", 'int');

View File

@ -55,12 +55,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) { $sortorder = "DESC"; } if (!$sortorder) {
if (!$sortfield) { $sortfield = "c.dateadh"; } $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "c.dateadh";
}
$object = new Subscription($db); $object = new Subscription($db);
@ -102,12 +108,18 @@ $result = restrictedArea($user, 'adherent', '', '', 'cotisation');
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') {
$massaction = '';
}
$parameters = array('socid'=>$socid); $parameters = array('socid'=>$socid);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) { if (empty($reshook)) {
// Selection of new fields // Selection of new fields
@ -157,16 +169,33 @@ if (isset($date_select) && $date_select != '') {
$sql .= " AND c.dateadh < '".((int) $date_select + 1)."-01-01 00:00:00'"; $sql .= " AND c.dateadh < '".((int) $date_select + 1)."-01-01 00:00:00'";
} }
if ($search_ref) { if ($search_ref) {
if (is_numeric($search_ref)) $sql .= " AND (c.rowid = ".$db->escape($search_ref).")"; if (is_numeric($search_ref)) {
else $sql .= " AND 1 = 2"; // Always wrong $sql .= " AND (c.rowid = ".$db->escape($search_ref).")";
} else {
$sql .= " AND 1 = 2"; // Always wrong
}
}
if ($search_type) {
$sql .= natural_search(array('c.fk_type'), $search_type);
}
if ($search_lastname) {
$sql .= natural_search(array('d.lastname', 'd.societe'), $search_lastname);
}
if ($search_firstname) {
$sql .= natural_search(array('d.firstname'), $search_firstname);
}
if ($search_login) {
$sql .= natural_search('d.login', $search_login);
}
if ($search_note) {
$sql .= natural_search('c.note', $search_note);
}
if ($search_account > 0) {
$sql .= " AND b.fk_account = ".urldecode($search_account);
}
if ($search_amount) {
$sql .= natural_search('c.subscription', $search_amount, 1);
} }
if ($search_type) $sql .= natural_search(array('c.fk_type'), $search_type);
if ($search_lastname) $sql .= natural_search(array('d.lastname', 'd.societe'), $search_lastname);
if ($search_firstname) $sql .= natural_search(array('d.firstname'), $search_firstname);
if ($search_login) $sql .= natural_search('d.login', $search_login);
if ($search_note) $sql .= natural_search('c.note', $search_note);
if ($search_account > 0) $sql .= " AND b.fk_account = ".urldecode($search_account);
if ($search_amount) $sql .= natural_search('c.subscription', $search_amount, 1);
// Add where from extra fields // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
@ -182,8 +211,11 @@ $sql .= $db->order($sortfield, $sortorder);
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) $nbtotalofrecords = $db->num_rows($resql); if ($resql) {
else dol_print_error($db); $nbtotalofrecords = $db->num_rows($resql);
} else {
dol_print_error($db);
}
if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
$page = 0; $page = 0;
$offset = 0; $offset = 0;
@ -215,19 +247,41 @@ llxHeader('', $langs->trans("ListOfSubscriptions"), $help_url);
$i = 0; $i = 0;
$title = $langs->trans("ListOfSubscriptions"); $title = $langs->trans("ListOfSubscriptions");
if (!empty($date_select)) $title .= ' ('.$langs->trans("Year").' '.$date_select.')'; if (!empty($date_select)) {
$title .= ' ('.$langs->trans("Year").' '.$date_select.')';
}
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($statut != '') $param .= "&statut=".urlencode($statut); }
if ($search_type) $param .= "&search_type=".urlencode($search_type); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($date_select) $param .= "&date_select=".urlencode($date_select); $param .= '&limit='.urlencode($limit);
if ($search_lastname) $param .= "&search_lastname=".urlencode($search_lastname); }
if ($search_login) $param .= "&search_login=".urlencode($search_login); if ($statut != '') {
if ($search_account) $param .= "&search_account=".urlencode($search_account); $param .= "&statut=".urlencode($statut);
if ($search_amount) $param .= "&search_amount=".urlencode($search_amount); }
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); if ($search_type) {
$param .= "&search_type=".urlencode($search_type);
}
if ($date_select) {
$param .= "&date_select=".urlencode($date_select);
}
if ($search_lastname) {
$param .= "&search_lastname=".urlencode($search_lastname);
}
if ($search_login) {
$param .= "&search_login=".urlencode($search_login);
}
if ($search_account) {
$param .= "&search_account=".urlencode($search_account);
}
if ($search_amount) {
$param .= "&search_amount=".urlencode($search_amount);
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
}
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@ -237,7 +291,9 @@ $arrayofmassactions = array(
//'builddoc'=>$langs->trans("PDFMerge"), //'builddoc'=>$langs->trans("PDFMerge"),
); );
//if ($user->rights->adherent->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); //if ($user->rights->adherent->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); if (in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
$newcardbutton = ''; $newcardbutton = '';
@ -246,7 +302,9 @@ if ($user->rights->adherent->cotisation->creer) {
} }
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -263,7 +321,9 @@ $trackid = 'sub'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($sall) { if ($sall) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); foreach ($fieldstosearchall as $key => $val) {
$fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
} }
@ -271,7 +331,9 @@ $moreforfilter = '';
$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); if ($massactionbutton) {
$selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
}
print '<div class="div-table-responsive">'; print '<div class="div-table-responsive">';
print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
@ -366,16 +428,36 @@ print "</tr>\n";
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
if (!empty($arrayfields['d.ref']['checked'])) print_liste_field_titre($arrayfields['d.ref']['label'], $_SERVER["PHP_SELF"], "c.rowid", $param, "", "", $sortfield, $sortorder); if (!empty($arrayfields['d.ref']['checked'])) {
if (!empty($arrayfields['d.fk_type']['checked'])) print_liste_field_titre($arrayfields['d.fk_type']['label'], $_SERVER["PHP_SELF"], "c.fk_type", $param, "", "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['d.ref']['label'], $_SERVER["PHP_SELF"], "c.rowid", $param, "", "", $sortfield, $sortorder);
if (!empty($arrayfields['d.lastname']['checked'])) print_liste_field_titre($arrayfields['d.lastname']['label'], $_SERVER["PHP_SELF"], "d.lastname", $param, "", "", $sortfield, $sortorder); }
if (!empty($arrayfields['d.firstname']['checked'])) print_liste_field_titre($arrayfields['d.firstname']['label'], $_SERVER["PHP_SELF"], "d.firstname", $param, "", "", $sortfield, $sortorder); if (!empty($arrayfields['d.fk_type']['checked'])) {
if (!empty($arrayfields['d.login']['checked'])) print_liste_field_titre($arrayfields['d.login']['label'], $_SERVER["PHP_SELF"], "d.login", $param, "", "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['d.fk_type']['label'], $_SERVER["PHP_SELF"], "c.fk_type", $param, "", "", $sortfield, $sortorder);
if (!empty($arrayfields['t.libelle']['checked'])) print_liste_field_titre($arrayfields['t.libelle']['label'], $_SERVER["PHP_SELF"], "c.note", $param, "", '', $sortfield, $sortorder); }
if (!empty($arrayfields['d.bank']['checked'])) print_liste_field_titre($arrayfields['d.bank']['label'], $_SERVER["PHP_SELF"], "b.fk_account", $param, "", "", $sortfield, $sortorder); if (!empty($arrayfields['d.lastname']['checked'])) {
if (!empty($arrayfields['c.dateadh']['checked'])) print_liste_field_titre($arrayfields['c.dateadh']['label'], $_SERVER["PHP_SELF"], "c.dateadh", $param, "", '', $sortfield, $sortorder, 'center nowraponall '); print_liste_field_titre($arrayfields['d.lastname']['label'], $_SERVER["PHP_SELF"], "d.lastname", $param, "", "", $sortfield, $sortorder);
if (!empty($arrayfields['c.datef']['checked'])) print_liste_field_titre($arrayfields['c.datef']['label'], $_SERVER["PHP_SELF"], "c.datef", $param, "", '', $sortfield, $sortorder, 'center nowraponall '); }
if (!empty($arrayfields['d.amount']['checked'])) print_liste_field_titre($arrayfields['d.amount']['label'], $_SERVER["PHP_SELF"], "c.subscription", $param, "", '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['d.firstname']['checked'])) {
print_liste_field_titre($arrayfields['d.firstname']['label'], $_SERVER["PHP_SELF"], "d.firstname", $param, "", "", $sortfield, $sortorder);
}
if (!empty($arrayfields['d.login']['checked'])) {
print_liste_field_titre($arrayfields['d.login']['label'], $_SERVER["PHP_SELF"], "d.login", $param, "", "", $sortfield, $sortorder);
}
if (!empty($arrayfields['t.libelle']['checked'])) {
print_liste_field_titre($arrayfields['t.libelle']['label'], $_SERVER["PHP_SELF"], "c.note", $param, "", '', $sortfield, $sortorder);
}
if (!empty($arrayfields['d.bank']['checked'])) {
print_liste_field_titre($arrayfields['d.bank']['label'], $_SERVER["PHP_SELF"], "b.fk_account", $param, "", "", $sortfield, $sortorder);
}
if (!empty($arrayfields['c.dateadh']['checked'])) {
print_liste_field_titre($arrayfields['c.dateadh']['label'], $_SERVER["PHP_SELF"], "c.dateadh", $param, "", '', $sortfield, $sortorder, 'center nowraponall ');
}
if (!empty($arrayfields['c.datef']['checked'])) {
print_liste_field_titre($arrayfields['c.datef']['label'], $_SERVER["PHP_SELF"], "c.datef", $param, "", '', $sortfield, $sortorder, 'center nowraponall ');
}
if (!empty($arrayfields['d.amount']['checked'])) {
print_liste_field_titre($arrayfields['d.amount']['label'], $_SERVER["PHP_SELF"], "c.subscription", $param, "", '', $sortfield, $sortorder, 'right ');
}
// Extra fields // Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
@ -384,8 +466,12 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if (!empty($arrayfields['c.datec']['checked'])) print_liste_field_titre($arrayfields['c.datec']['label'], $_SERVER["PHP_SELF"], "c.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); if (!empty($arrayfields['c.datec']['checked'])) {
if (!empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); print_liste_field_titre($arrayfields['c.datec']['label'], $_SERVER["PHP_SELF"], "c.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
}
if (!empty($arrayfields['c.tms']['checked'])) {
print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
}
print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ');
print "</tr>\n"; print "</tr>\n";
@ -419,8 +505,10 @@ while ($i < min($num, $limit)) {
// Ref // Ref
if (!empty($arrayfields['d.ref']['checked'])) { if (!empty($arrayfields['d.ref']['checked'])) {
print '<td class="nowraponall">'.$subscription->getNomUrl(1).'</td>'; print '<td>'.$subscription->getNomUrl(1).'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Type // Type
if (!empty($arrayfields['d.fk_type']['checked'])) { if (!empty($arrayfields['d.fk_type']['checked'])) {
@ -429,24 +517,32 @@ while ($i < min($num, $limit)) {
print $adht->getNomUrl(1); print $adht->getNomUrl(1);
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Lastname // Lastname
if (!empty($arrayfields['d.lastname']['checked'])) { if (!empty($arrayfields['d.lastname']['checked'])) {
print '<td>'.$adherent->getNomUrl(-1, 0, 'card', 'lastname').'</td>'; print '<td>'.$adherent->getNomUrl(-1, 0, 'card', 'lastname').'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Firstname // Firstname
if (!empty($arrayfields['d.firstname']['checked'])) { if (!empty($arrayfields['d.firstname']['checked'])) {
print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($adherent->firstname).'">'.$adherent->firstname.'</td>'; print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($adherent->firstname).'">'.$adherent->firstname.'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Login // Login
if (!empty($arrayfields['d.login']['checked'])) { if (!empty($arrayfields['d.login']['checked'])) {
print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($adherent->login).'">'.$adherent->login.'</td>'; print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($adherent->login).'">'.$adherent->login.'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Label // Label
@ -454,7 +550,9 @@ while ($i < min($num, $limit)) {
print '<td>'; print '<td>';
print dol_trunc($obj->note, 128); print dol_trunc($obj->note, 128);
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Banque // Banque
@ -467,24 +565,34 @@ while ($i < min($num, $limit)) {
print $accountstatic->getNomUrl(1); print $accountstatic->getNomUrl(1);
} }
print "</td>\n"; print "</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Date start // Date start
if (!empty($arrayfields['c.dateadh']['checked'])) { if (!empty($arrayfields['c.dateadh']['checked'])) {
print '<td class="center">'.dol_print_date($db->jdate($obj->dateadh), 'day')."</td>\n"; print '<td class="center">'.dol_print_date($db->jdate($obj->dateadh), 'day')."</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Date end // Date end
if (!empty($arrayfields['c.datef']['checked'])) { if (!empty($arrayfields['c.datef']['checked'])) {
print '<td class="center">'.dol_print_date($db->jdate($obj->datef), 'day')."</td>\n"; print '<td class="center">'.dol_print_date($db->jdate($obj->datef), 'day')."</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Price // Price
if (!empty($arrayfields['d.amount']['checked'])) { if (!empty($arrayfields['d.amount']['checked'])) {
print '<td class="right">'.price($obj->subscription).'</td>'; print '<td class="right">'.price($obj->subscription).'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'd.amount'; $totalarray['nbfield']++;
}
if (!$i) {
$totalarray['pos'][$totalarray['nbfield']] = 'd.amount';
}
$totalarray['val']['d.amount'] += $obj->subscription; $totalarray['val']['d.amount'] += $obj->subscription;
} }
// Extra fields // Extra fields
@ -498,24 +606,32 @@ while ($i < min($num, $limit)) {
print '<td class="nowrap center">'; print '<td class="nowrap center">';
print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Date modification // Date modification
if (!empty($arrayfields['c.tms']['checked'])) { if (!empty($arrayfields['c.tms']['checked'])) {
print '<td class="nowrap center">'; print '<td class="nowrap center">';
print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Action column // Action column
print '<td class="center">'; print '<td class="center">';
if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
$selected = 0; $selected = 0;
if (in_array($obj->rowid, $arrayofselected)) $selected = 1; if (in_array($obj->rowid, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print "</tr>\n"; print "</tr>\n";
$i++; $i++;
@ -528,7 +644,11 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
// If no record found // If no record found
if ($num == 0) { if ($num == 0) {
$colspan = 1; $colspan = 1;
foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } foreach ($arrayfields as $key => $val) {
if (!empty($val['checked'])) {
$colspan++;
}
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
} }

View File

@ -52,12 +52,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) { $sortorder = "DESC"; } if (!$sortorder) {
if (!$sortfield) { $sortfield = "d.lastname"; } $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "d.lastname";
}
$label = GETPOST("label", "alpha"); $label = GETPOST("label", "alpha");
$morphy = GETPOST("morphy", "alpha"); $morphy = GETPOST("morphy", "alpha");
@ -118,7 +124,9 @@ if ($action == 'add' && $user->rights->adherent->configurer) {
// Fill array 'array_options' with data from add form // Fill array 'array_options' with data from add form
$ret = $extrafields->setOptionalsFromPost(null, $object); $ret = $extrafields->setOptionalsFromPost(null, $object);
if ($ret < 0) $error++; if ($ret < 0) {
$error++;
}
if (empty($object->label)) { if (empty($object->label)) {
$error++; $error++;
@ -167,7 +175,9 @@ if ($action == 'update' && $user->rights->adherent->configurer) {
// Fill array 'array_options' with data from add form // Fill array 'array_options' with data from add form
$ret = $extrafields->setOptionalsFromPost(null, $object); $ret = $extrafields->setOptionalsFromPost(null, $object);
if ($ret < 0) $error++; if ($ret < 0) {
$error++;
}
$ret = $object->update($user); $ret = $object->update($user);
@ -222,8 +232,12 @@ if (!$rowid && $action != 'create' && $action != 'edit') {
$i = 0; $i = 0;
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; $param .= '&contextpage='.$contextpage;
}
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.$limit;
}
$newcardbutton = ''; $newcardbutton = '';
if ($user->rights->adherent->configurer) { if ($user->rights->adherent->configurer) {
@ -231,7 +245,9 @@ if (!$rowid && $action != 'create' && $action != 'edit') {
} }
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -273,14 +289,20 @@ if (!$rowid && $action != 'create' && $action != 'edit') {
print '</td>'; print '</td>';
print '<td>'.dol_escape_htmltag($objp->label).'</td>'; print '<td>'.dol_escape_htmltag($objp->label).'</td>';
print '<td class="center">'; print '<td class="center">';
if ($objp->morphy == 'phy') { print $langs->trans("Physical"); } elseif ($objp->morphy == 'mor') { print $langs->trans("Moral"); } else print $langs->trans("MorAndPhy"); if ($objp->morphy == 'phy') {
print $langs->trans("Physical");
} elseif ($objp->morphy == 'mor') {
print $langs->trans("Moral");
} else {
print $langs->trans("MorAndPhy");
}
print '</td>'; print '</td>';
print '<td class="center">'.yn($objp->subscription).'</td>'; print '<td class="center">'.yn($objp->subscription).'</td>';
print '<td class="center">'.yn($objp->vote).'</td>'; print '<td class="center">'.yn($objp->vote).'</td>';
print '<td class="center">'.$membertype->getLibStatut(5).'</td>'; print '<td class="center">'.$membertype->getLibStatut(5).'</td>';
if ($user->rights->adherent->configurer) if ($user->rights->adherent->configurer) {
print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edit&rowid='.$objp->rowid.'">'.img_edit().'</a></td>'; print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edit&rowid='.$objp->rowid.'">'.img_edit().'</a></td>';
else { } else {
print '<td class="right">&nbsp;</td>'; print '<td class="right">&nbsp;</td>';
} }
print "</tr>"; print "</tr>";
@ -510,8 +532,11 @@ if ($rowid > 0) {
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) $nbtotalofrecords = $db->num_rows($result); if ($resql) {
else dol_print_error($db); $nbtotalofrecords = $db->num_rows($result);
} else {
dol_print_error($db);
}
if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
$page = 0; $page = 0;
$offset = 0; $offset = 0;
@ -551,12 +576,24 @@ if ($rowid > 0) {
} }
$param = "&rowid=".$object->id; $param = "&rowid=".$object->id;
if (!empty($status)) $param .= "&status=".$status; if (!empty($status)) {
if (!empty($search_lastname)) $param .= "&search_lastname=".$search_lastname; $param .= "&status=".$status;
if (!empty($search_firstname)) $param .= "&search_firstname=".$search_firstname; }
if (!empty($search_login)) $param .= "&search_login=".$search_login; if (!empty($search_lastname)) {
if (!empty($search_email)) $param .= "&search_email=".$search_email; $param .= "&search_lastname=".$search_lastname;
if (!empty($filter)) $param .= "&filter=".$filter; }
if (!empty($search_firstname)) {
$param .= "&search_firstname=".$search_firstname;
}
if (!empty($search_login)) {
$param .= "&search_login=".$search_login;
}
if (!empty($search_email)) {
$param .= "&search_email=".$search_email;
}
if (!empty($filter)) {
$param .= "&filter=".$filter;
}
if ($sall) { if ($sall) {
print $langs->trans("Filter")." (".$langs->trans("Lastname").", ".$langs->trans("Firstname").", ".$langs->trans("EMail").", ".$langs->trans("Address")." ".$langs->trans("or")." ".$langs->trans("Town")."): ".$sall; print $langs->trans("Filter")." (".$langs->trans("Lastname").", ".$langs->trans("Firstname").", ".$langs->trans("EMail").", ".$langs->trans("Address")." ".$langs->trans("or")." ".$langs->trans("Town")."): ".$sall;
@ -663,7 +700,9 @@ if ($rowid > 0) {
print '<td class="nowrap left">'; print '<td class="nowrap left">';
if ($objp->subscription == 'yes') { if ($objp->subscription == 'yes') {
print $langs->trans("SubscriptionNotReceived"); print $langs->trans("SubscriptionNotReceived");
if ($objp->status > 0) print " ".img_warning(); if ($objp->status > 0) {
print " ".img_warning();
}
} else { } else {
print '&nbsp;'; print '&nbsp;';
} }

View File

@ -51,7 +51,9 @@ $hookmanager->initHooks(array('membertypeldapcard', 'globalcard'));
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) { if (empty($reshook)) {
if ($action == 'dolibarr2ldap') { if ($action == 'dolibarr2ldap') {
@ -128,7 +130,9 @@ if ($conf->global->LDAP_MEMBER_TYPE_ACTIVE == 1) {
print "</div>\n"; print "</div>\n";
if ($conf->global->LDAP_MEMBER_TYPE_ACTIVE == 1) print "<br>\n"; if ($conf->global->LDAP_MEMBER_TYPE_ACTIVE == 1) {
print "<br>\n";
}

View File

@ -42,7 +42,9 @@ $ref = GETPOST('ref', 'alphanohtml');
// Security check // Security check
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
// Security check // Security check
$result = restrictedArea($user, 'adherent', $id, 'adherent_type'); $result = restrictedArea($user, 'adherent', $id, 'adherent_type');
@ -184,7 +186,9 @@ print "\n<div class=\"tabsAction\">\n";
if ($action == '') { if ($action == '') {
if ($user->rights->produit->creer || $user->rights->service->creer) { if ($user->rights->produit->creer || $user->rights->service->creer) {
print '<a class="butAction" href="'.DOL_URL_ROOT.'/adherents/type_translation.php?action=add&rowid='.$object->id.'">'.$langs->trans("Add").'</a>'; print '<a class="butAction" href="'.DOL_URL_ROOT.'/adherents/type_translation.php?action=add&rowid='.$object->id.'">'.$langs->trans("Add").'</a>';
if ($cnt_trans > 0) print '<a class="butAction" href="'.DOL_URL_ROOT.'/adherents/type_translation.php?action=edit&rowid='.$object->id.'">'.$langs->trans("Update").'</a>'; if ($cnt_trans > 0) {
print '<a class="butAction" href="'.DOL_URL_ROOT.'/adherents/type_translation.php?action=edit&rowid='.$object->id.'">'.$langs->trans("Update").'</a>';
}
} }
} }
@ -242,7 +246,9 @@ if ($action == 'edit') {
print '</div>'; print '</div>';
} }
} }
if (!$cnt_trans && $action != 'add') print '<div class="opacitymedium">'.$langs->trans('NoTranslation').'</div>'; if (!$cnt_trans && $action != 'add') {
print '<div class="opacitymedium">'.$langs->trans('NoTranslation').'</div>';
}
} }

View File

@ -32,40 +32,35 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
// Load translation files required by the page // Load translation files required by the page
$langs->load("admin"); $langs->load("admin");
if (!$user->admin) if (!$user->admin) {
accessforbidden(); accessforbidden();
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
//Activate ProfId //Activate ProfId
if ($action == 'setproductionmode') if ($action == 'setproductionmode') {
{
$status = GETPOST('status', 'alpha'); $status = GETPOST('status', 'alpha');
if (dolibarr_set_const($db, 'API_PRODUCTION_MODE', $status, 'chaine', 0, '', 0) > 0) if (dolibarr_set_const($db, 'API_PRODUCTION_MODE', $status, 'chaine', 0, '', 0) > 0) {
{
$error = 0; $error = 0;
if ($status == 1) if ($status == 1) {
{
$result = dol_mkdir($conf->api->dir_temp); $result = dol_mkdir($conf->api->dir_temp);
if ($result < 0) if ($result < 0) {
{
setEventMessages($langs->trans("ErrorFailedToCreateDir", $conf->api->dir_temp), null, 'errors'); setEventMessages($langs->trans("ErrorFailedToCreateDir", $conf->api->dir_temp), null, 'errors');
$error++; $error++;
} }
} else { } else {
// Delete the cache file otherwise it does not update // Delete the cache file otherwise it does not update
$result = dol_delete_file($conf->api->dir_temp.'/routes.php'); $result = dol_delete_file($conf->api->dir_temp.'/routes.php');
if ($result < 0) if ($result < 0) {
{
setEventMessages($langs->trans("ErrorFailedToDeleteFile", $conf->api->dir_temp.'/routes.php'), null, 'errors'); setEventMessages($langs->trans("ErrorFailedToDeleteFile", $conf->api->dir_temp.'/routes.php'), null, 'errors');
$error++; $error++;
} }
} }
if (!$error) if (!$error) {
{
header("Location: ".$_SERVER["PHP_SELF"]); header("Location: ".$_SERVER["PHP_SELF"]);
exit; exit;
} }
@ -74,8 +69,7 @@ if ($action == 'setproductionmode')
} }
} }
if ($action == 'save') if ($action == 'save') {
{
dolibarr_set_const($db, 'API_RESTRICT_ON_IP', GETPOST('API_RESTRICT_ON_IP', 'alpha')); dolibarr_set_const($db, 'API_RESTRICT_ON_IP', GETPOST('API_RESTRICT_ON_IP', 'alpha'));
} }
@ -110,8 +104,7 @@ print "</tr>";
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$langs->trans("ApiProductionMode").'</td>'; print '<td>'.$langs->trans("ApiProductionMode").'</td>';
$production_mode = (empty($conf->global->API_PRODUCTION_MODE) ?false:true); $production_mode = (empty($conf->global->API_PRODUCTION_MODE) ?false:true);
if ($production_mode) if ($production_mode) {
{
print '<td><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setproductionmode&token='.newToken().'&value='.($i + 1).'&status=0">'; print '<td><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setproductionmode&token='.newToken().'&value='.($i + 1).'&status=0">';
print img_picto($langs->trans("Activated"), 'switch_on'); print img_picto($langs->trans("Activated"), 'switch_on');
print '</a></td>'; print '</a></td>';
@ -155,8 +148,7 @@ print '<br>';
// Explorer // Explorer
print '<u>'.$langs->trans("ApiExporerIs").':</u><br>'; print '<u>'.$langs->trans("ApiExporerIs").':</u><br>';
if (dol_is_dir(DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/explorer')) if (dol_is_dir(DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/explorer')) {
{
$url = DOL_MAIN_URL_ROOT.'/api/index.php/explorer'; $url = DOL_MAIN_URL_ROOT.'/api/index.php/explorer';
print img_picto('', 'globe').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n"; print img_picto('', 'globe').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
} else { } else {

View File

@ -30,7 +30,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array("admin", "other", "blockedlog")); $langs->loadLangs(array("admin", "other", "blockedlog"));
if (!$user->admin || empty($conf->blockedlog->enabled)) accessforbidden(); if (!$user->admin || empty($conf->blockedlog->enabled)) {
accessforbidden();
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$backtopage = GETPOST('backtopage', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha');
@ -43,14 +45,14 @@ $withtab = GETPOST('withtab', 'int');
*/ */
$reg = array(); $reg = array();
if (preg_match('/set_(.*)/', $action, $reg)) if (preg_match('/set_(.*)/', $action, $reg)) {
{
$code = $reg[1]; $code = $reg[1];
$values = GETPOST($code); $values = GETPOST($code);
if (is_array($values)) $values = implode(',', $values); if (is_array($values)) {
$values = implode(',', $values);
}
if (dolibarr_set_const($db, $code, $values, 'chaine', 0, '', $conf->entity) > 0) if (dolibarr_set_const($db, $code, $values, 'chaine', 0, '', $conf->entity) > 0) {
{
header("Location: ".$_SERVER["PHP_SELF"].($withtab ? '?withtab='.$withtab : '')); header("Location: ".$_SERVER["PHP_SELF"].($withtab ? '?withtab='.$withtab : ''));
exit; exit;
} else { } else {
@ -58,11 +60,9 @@ if (preg_match('/set_(.*)/', $action, $reg))
} }
} }
if (preg_match('/del_(.*)/', $action, $reg)) if (preg_match('/del_(.*)/', $action, $reg)) {
{
$code = $reg[1]; $code = $reg[1];
if (dolibarr_del_const($db, $code, 0) > 0) if (dolibarr_del_const($db, $code, 0) > 0) {
{
Header("Location: ".$_SERVER["PHP_SELF"].($withtab ? '?withtab='.$withtab : '')); Header("Location: ".$_SERVER["PHP_SELF"].($withtab ? '?withtab='.$withtab : ''));
exit; exit;
} else { } else {
@ -142,10 +142,8 @@ $sql .= " WHERE active > 0";
$countryArray = array(); $countryArray = array();
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{ while ($obj = $db->fetch_object($resql)) {
while ($obj = $db->fetch_object($resql))
{
$countryArray[$obj->code_iso] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso) != "Country".$obj->code_iso ? $langs->transnoentitiesnoconv("Country".$obj->code_iso) : ($obj->label != '-' ? $obj->label : '')); $countryArray[$obj->code_iso] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso) != "Country".$obj->code_iso ? $langs->transnoentitiesnoconv("Country".$obj->code_iso) : ($obj->label != '-' ? $obj->label : ''));
} }
} }
@ -163,8 +161,7 @@ print '<tr class="oddeven">';
print '<td class="titlefield">'; print '<td class="titlefield">';
print $langs->trans("ListOfTrackedEvents").'</td><td>'; print $langs->trans("ListOfTrackedEvents").'</td><td>';
$arrayoftrackedevents = $block_static->trackedevents; $arrayoftrackedevents = $block_static->trackedevents;
foreach ($arrayoftrackedevents as $key => $val) foreach ($arrayoftrackedevents as $key => $val) {
{
print $key.' - '.$langs->trans($val).'<br>'; print $key.' - '.$langs->trans($val).'<br>';
} }
@ -174,8 +171,7 @@ print '</tr>';
print '</table>'; print '</table>';
if ($withtab) if ($withtab) {
{
print dol_get_fiche_end(); print dol_get_fiche_end();
} }

View File

@ -33,7 +33,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array("admin", "other", "blockedlog", "bills")); $langs->loadLangs(array("admin", "other", "blockedlog", "bills"));
if ((!$user->admin && !$user->rights->blockedlog->read) || empty($conf->blockedlog->enabled)) accessforbidden(); if ((!$user->admin && !$user->rights->blockedlog->read) || empty($conf->blockedlog->enabled)) {
accessforbidden();
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'blockedloglist'; // To manage different context of search $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'blockedloglist'; // To manage different context of search
@ -41,32 +43,46 @@ $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
$search_showonlyerrors = GETPOST('search_showonlyerrors', 'int'); $search_showonlyerrors = GETPOST('search_showonlyerrors', 'int');
if ($search_showonlyerrors < 0) $search_showonlyerrors = 0; if ($search_showonlyerrors < 0) {
$search_showonlyerrors = 0;
}
$search_id = GETPOST('search_id', 'alpha'); $search_id = GETPOST('search_id', 'alpha');
$search_fk_user = GETPOST('search_fk_user', 'intcomma'); $search_fk_user = GETPOST('search_fk_user', 'intcomma');
$search_start = -1; $search_start = -1;
if (GETPOST('search_startyear') != '') $search_start = dol_mktime(0, 0, 0, GETPOST('search_startmonth'), GETPOST('search_startday'), GETPOST('search_startyear')); if (GETPOST('search_startyear') != '') {
$search_start = dol_mktime(0, 0, 0, GETPOST('search_startmonth'), GETPOST('search_startday'), GETPOST('search_startyear'));
}
$search_end = -1; $search_end = -1;
if (GETPOST('search_endyear') != '') $search_end = dol_mktime(23, 59, 59, GETPOST('search_endmonth'), GETPOST('search_endday'), GETPOST('search_endyear')); if (GETPOST('search_endyear') != '') {
$search_end = dol_mktime(23, 59, 59, GETPOST('search_endmonth'), GETPOST('search_endday'), GETPOST('search_endyear'));
}
$search_code = GETPOST('search_code', 'alpha'); $search_code = GETPOST('search_code', 'alpha');
$search_ref = GETPOST('search_ref', 'alpha'); $search_ref = GETPOST('search_ref', 'alpha');
$search_amount = GETPOST('search_amount', 'alpha'); $search_amount = GETPOST('search_amount', 'alpha');
if (($search_start == -1 || empty($search_start)) && !GETPOSTISSET('search_startmonth')) $search_start = dol_time_plus_duree(dol_now(), '-1', 'w'); if (($search_start == -1 || empty($search_start)) && !GETPOSTISSET('search_startmonth')) {
$search_start = dol_time_plus_duree(dol_now(), '-1', 'w');
}
// Load variable for pagination // Load variable for pagination
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (empty($sortfield)) $sortfield = 'rowid'; if (empty($sortfield)) {
if (empty($sortorder)) $sortorder = 'DESC'; $sortfield = 'rowid';
}
if (empty($sortorder)) {
$sortorder = 'DESC';
}
$block_static = new BlockedLog($db); $block_static = new BlockedLog($db);
$block_static->loadTrackedEvents(); $block_static->loadTrackedEvents();
@ -76,8 +92,7 @@ $result = restrictedArea($user, 'blockedlog', 0, '');
$max_execution_time_for_importexport = (empty($conf->global->EXPORT_MAX_EXECUTION_TIME) ? 300 : $conf->global->EXPORT_MAX_EXECUTION_TIME); // 5mn if not defined $max_execution_time_for_importexport = (empty($conf->global->EXPORT_MAX_EXECUTION_TIME) ? 300 : $conf->global->EXPORT_MAX_EXECUTION_TIME); // 5mn if not defined
$max_time = @ini_get("max_execution_time"); $max_time = @ini_get("max_execution_time");
if ($max_time && $max_time < $max_execution_time_for_importexport) if ($max_time && $max_time < $max_execution_time_for_importexport) {
{
dol_syslog("max_execution_time=".$max_time." is lower than max_execution_time_for_importexport=".$max_execution_time_for_importexport.". We try to increase it dynamically."); dol_syslog("max_execution_time=".$max_time." is lower than max_execution_time_for_importexport=".$max_execution_time_for_importexport.". We try to increase it dynamically.");
@ini_set("max_execution_time", $max_execution_time_for_importexport); // This work only if safe mode is off. also web servers has timeout of 300 @ini_set("max_execution_time", $max_execution_time_for_importexport); // This work only if safe mode is off. also web servers has timeout of 300
} }
@ -88,8 +103,7 @@ if ($max_time && $max_time < $max_execution_time_for_importexport)
*/ */
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$search_id = ''; $search_id = '';
$search_fk_user = ''; $search_fk_user = '';
$search_start = -1; $search_start = -1;
@ -120,14 +134,12 @@ if ($action === 'downloadblockchain') {
$previoushash = ''; $previoushash = '';
$firstid = ''; $firstid = '';
if (!$error) if (!$error) {
{
// Get ID of first line // Get ID of first line
$sql = "SELECT rowid,date_creation,tms,user_fullname,action,amounts,element,fk_object,date_object,ref_object,signature,fk_user,object_data"; $sql = "SELECT rowid,date_creation,tms,user_fullname,action,amounts,element,fk_object,date_object,ref_object,signature,fk_user,object_data";
$sql .= " FROM ".MAIN_DB_PREFIX."blockedlog"; $sql .= " FROM ".MAIN_DB_PREFIX."blockedlog";
$sql .= " WHERE entity = ".$conf->entity; $sql .= " WHERE entity = ".$conf->entity;
if (GETPOST('monthtoexport', 'int') > 0 || GETPOST('yeartoexport', 'int') > 0) if (GETPOST('monthtoexport', 'int') > 0 || GETPOST('yeartoexport', 'int') > 0) {
{
$dates = dol_get_first_day(GETPOST('yeartoexport', 'int'), GETPOST('monthtoexport', 'int') ?GETPOST('monthtoexport', 'int') : 1); $dates = dol_get_first_day(GETPOST('yeartoexport', 'int'), GETPOST('monthtoexport', 'int') ?GETPOST('monthtoexport', 'int') : 1);
$datee = dol_get_last_day(GETPOST('yeartoexport', 'int'), GETPOST('monthtoexport', 'int') ?GETPOST('monthtoexport', 'int') : 12); $datee = dol_get_last_day(GETPOST('yeartoexport', 'int'), GETPOST('monthtoexport', 'int') ?GETPOST('monthtoexport', 'int') : 12);
$sql .= " AND date_creation BETWEEN '".$db->idate($dates)."' AND '".$db->idate($datee)."'"; $sql .= " AND date_creation BETWEEN '".$db->idate($dates)."' AND '".$db->idate($datee)."'";
@ -136,12 +148,10 @@ if ($action === 'downloadblockchain') {
$sql .= $db->plimit(1); $sql .= $db->plimit(1);
$res = $db->query($sql); $res = $db->query($sql);
if ($res) if ($res) {
{
// Make the first fetch to get first line // Make the first fetch to get first line
$obj = $db->fetch_object($res); $obj = $db->fetch_object($res);
if ($obj) if ($obj) {
{
$previoushash = $block_static->getPreviousHash(0, $obj->rowid); $previoushash = $block_static->getPreviousHash(0, $obj->rowid);
$firstid = $obj->rowid; $firstid = $obj->rowid;
} else { // If not data found for filter, we do not need previoushash neither firstid } else { // If not data found for filter, we do not need previoushash neither firstid
@ -154,14 +164,12 @@ if ($action === 'downloadblockchain') {
} }
} }
if (!$error) if (!$error) {
{
// Now restart request with all data = no limit(1) in sql request // Now restart request with all data = no limit(1) in sql request
$sql = "SELECT rowid,date_creation,tms,user_fullname,action,amounts,element,fk_object,date_object,ref_object,signature,fk_user,object_data"; $sql = "SELECT rowid,date_creation,tms,user_fullname,action,amounts,element,fk_object,date_object,ref_object,signature,fk_user,object_data";
$sql .= " FROM ".MAIN_DB_PREFIX."blockedlog"; $sql .= " FROM ".MAIN_DB_PREFIX."blockedlog";
$sql .= " WHERE entity = ".$conf->entity; $sql .= " WHERE entity = ".$conf->entity;
if (GETPOST('monthtoexport', 'int') > 0 || GETPOST('yeartoexport', 'int') > 0) if (GETPOST('monthtoexport', 'int') > 0 || GETPOST('yeartoexport', 'int') > 0) {
{
$dates = dol_get_first_day(GETPOST('yeartoexport', 'int'), GETPOST('monthtoexport', 'int') ?GETPOST('monthtoexport', 'int') : 1); $dates = dol_get_first_day(GETPOST('yeartoexport', 'int'), GETPOST('monthtoexport', 'int') ?GETPOST('monthtoexport', 'int') : 1);
$datee = dol_get_last_day(GETPOST('yeartoexport', 'int'), GETPOST('monthtoexport', 'int') ?GETPOST('monthtoexport', 'int') : 12); $datee = dol_get_last_day(GETPOST('yeartoexport', 'int'), GETPOST('monthtoexport', 'int') ?GETPOST('monthtoexport', 'int') : 12);
$sql .= " AND date_creation BETWEEN '".$db->idate($dates)."' AND '".$db->idate($datee)."'"; $sql .= " AND date_creation BETWEEN '".$db->idate($dates)."' AND '".$db->idate($datee)."'";
@ -169,8 +177,7 @@ if ($action === 'downloadblockchain') {
$sql .= " ORDER BY rowid ASC"; // Required so later we can use the parameter $previoushash of checkSignature() $sql .= " ORDER BY rowid ASC"; // Required so later we can use the parameter $previoushash of checkSignature()
$res = $db->query($sql); $res = $db->query($sql);
if ($res) if ($res) {
{
header('Content-Type: application/octet-stream'); header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"unalterable-log-archive-".$dolibarr_main_db_name."-".(GETPOST('yeartoexport', 'int') > 0 ? GETPOST('yeartoexport', 'int').(GETPOST('monthtoexport', 'int') > 0 ?sprintf("%02d", GETPOST('monthtoexport', 'int')) : '').'-' : '').$previoushash.".csv\""); header("Content-disposition: attachment; filename=\"unalterable-log-archive-".$dolibarr_main_db_name."-".(GETPOST('yeartoexport', 'int') > 0 ? GETPOST('yeartoexport', 'int').(GETPOST('monthtoexport', 'int') > 0 ?sprintf("%02d", GETPOST('monthtoexport', 'int')) : '').'-' : '').$previoushash.".csv\"");
@ -193,8 +200,7 @@ if ($action === 'downloadblockchain') {
$loweridinerror = 0; $loweridinerror = 0;
$i = 0; $i = 0;
while ($obj = $db->fetch_object($res)) while ($obj = $db->fetch_object($res)) {
{
// We set here all data used into signature calculation (see checkSignature method) and more // We set here all data used into signature calculation (see checkSignature method) and more
// IMPORTANT: We must have here, the same rule for transformation of data than into the fetch method (db->jdate for date, ...) // IMPORTANT: We must have here, the same rule for transformation of data than into the fetch method (db->jdate for date, ...)
$block_static->id = $obj->rowid; $block_static->id = $obj->rowid;
@ -213,19 +219,20 @@ if ($action === 'downloadblockchain') {
$checksignature = $block_static->checkSignature($previoushash); // If $previoushash is not defined, checkSignature will search it $checksignature = $block_static->checkSignature($previoushash); // If $previoushash is not defined, checkSignature will search it
if ($checksignature) if ($checksignature) {
{
$statusofrecord = 'Valid'; $statusofrecord = 'Valid';
if ($loweridinerror > 0) $statusofrecordnote = 'ValidButFoundAPreviousKO'; if ($loweridinerror > 0) {
else $statusofrecordnote = ''; $statusofrecordnote = 'ValidButFoundAPreviousKO';
} else {
$statusofrecordnote = '';
}
} else { } else {
$statusofrecord = 'KO'; $statusofrecord = 'KO';
$statusofrecordnote = 'LineCorruptedOrNotMatchingPreviousOne'; $statusofrecordnote = 'LineCorruptedOrNotMatchingPreviousOne';
$loweridinerror = $obj->rowid; $loweridinerror = $obj->rowid;
} }
if ($i == 0) if ($i == 0) {
{
$statusofrecordnote = $langs->trans("PreviousFingerprint").': '.$previoushash.($statusofrecordnote ? ' - '.$statusofrecordnote : ''); $statusofrecordnote = $langs->trans("PreviousFingerprint").': '.$previoushash.($statusofrecordnote ? ' - '.$statusofrecordnote : '');
} }
print $obj->rowid; print $obj->rowid;
@ -263,8 +270,7 @@ if ($action === 'downloadblockchain') {
$form = new Form($db); $form = new Form($db);
if (GETPOST('withtab', 'alpha')) if (GETPOST('withtab', 'alpha')) {
{
$title = $langs->trans("ModuleSetup").' '.$langs->trans('BlockedLog'); $title = $langs->trans("ModuleSetup").' '.$langs->trans('BlockedLog');
} else { } else {
$title = $langs->trans("BrowseBlockedLog"); $title = $langs->trans("BrowseBlockedLog");
@ -275,10 +281,8 @@ llxHeader('', $langs->trans("BrowseBlockedLog"));
$MAXLINES = 10000; $MAXLINES = 10000;
$blocks = $block_static->getLog('all', $search_id, $MAXLINES, $sortfield, $sortorder, $search_fk_user, $search_start, $search_end, $search_ref, $search_amount, $search_code); $blocks = $block_static->getLog('all', $search_id, $MAXLINES, $sortfield, $sortorder, $search_fk_user, $search_start, $search_end, $search_ref, $search_amount, $search_code);
if (!is_array($blocks)) if (!is_array($blocks)) {
{ if ($blocks == -2) {
if ($blocks == -2)
{
setEventMessages($langs->trans("TooManyRecordToScanRestrictFilters", $MAXLINES), null, 'errors'); setEventMessages($langs->trans("TooManyRecordToScanRestrictFilters", $MAXLINES), null, 'errors');
} else { } else {
dol_print_error($block_static->db, $block_static->error, $block_static->errors); dol_print_error($block_static->db, $block_static->error, $block_static->errors);
@ -287,15 +291,13 @@ if (!is_array($blocks))
} }
$linkback = ''; $linkback = '';
if (GETPOST('withtab', 'alpha')) if (GETPOST('withtab', 'alpha')) {
{
$linkback = '<a href="'.($backtopage ? $backtopage : DOL_URL_ROOT.'/admin/modules.php').'">'.$langs->trans("BackToModuleList").'</a>'; $linkback = '<a href="'.($backtopage ? $backtopage : DOL_URL_ROOT.'/admin/modules.php').'">'.$langs->trans("BackToModuleList").'</a>';
} }
print load_fiche_titre($title, $linkback); print load_fiche_titre($title, $linkback);
if (GETPOST('withtab', 'alpha')) if (GETPOST('withtab', 'alpha')) {
{
$head = blockedlogadmin_prepare_head(); $head = blockedlogadmin_prepare_head();
print dol_get_fiche_head($head, 'fingerprints', '', -1); print dol_get_fiche_head($head, 'fingerprints', '', -1);
} }
@ -305,19 +307,45 @@ print '<span class="opacitymedium hideonsmartphone">'.$langs->trans("Fingerprint
print '<br>'; print '<br>';
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($search_id != '') $param .= '&search_id='.urlencode($search_id); }
if ($search_fk_user > 0) $param .= '&search_fk_user='.urlencode($search_fk_user); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($search_startyear > 0) $param .= '&search_startyear='.urlencode(GETPOST('search_startyear', 'int')); $param .= '&limit='.urlencode($limit);
if ($search_startmonth > 0) $param .= '&search_startmonth='.urlencode(GETPOST('search_startmonth', 'int')); }
if ($search_startday > 0) $param .= '&search_startday='.urlencode(GETPOST('search_startday', 'int')); if ($search_id != '') {
if ($search_endyear > 0) $param .= '&search_endyear='.urlencode(GETPOST('search_endyear', 'int')); $param .= '&search_id='.urlencode($search_id);
if ($search_endmonth > 0) $param .= '&search_endmonth='.urlencode(GETPOST('search_endmonth', 'int')); }
if ($search_endday > 0) $param .= '&search_endday='.urlencode(GETPOST('search_endday', 'int')); if ($search_fk_user > 0) {
if ($search_showonlyerrors > 0) $param .= '&search_showonlyerrors='.urlencode($search_showonlyerrors); $param .= '&search_fk_user='.urlencode($search_fk_user);
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); }
if (GETPOST('withtab', 'alpha')) $param .= '&withtab='.urlencode(GETPOST('withtab', 'alpha')); if ($search_startyear > 0) {
$param .= '&search_startyear='.urlencode(GETPOST('search_startyear', 'int'));
}
if ($search_startmonth > 0) {
$param .= '&search_startmonth='.urlencode(GETPOST('search_startmonth', 'int'));
}
if ($search_startday > 0) {
$param .= '&search_startday='.urlencode(GETPOST('search_startday', 'int'));
}
if ($search_endyear > 0) {
$param .= '&search_endyear='.urlencode(GETPOST('search_endyear', 'int'));
}
if ($search_endmonth > 0) {
$param .= '&search_endmonth='.urlencode(GETPOST('search_endmonth', 'int'));
}
if ($search_endday > 0) {
$param .= '&search_endday='.urlencode(GETPOST('search_endday', 'int'));
}
if ($search_showonlyerrors > 0) {
$param .= '&search_showonlyerrors='.urlencode($search_showonlyerrors);
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
}
if (GETPOST('withtab', 'alpha')) {
$param .= '&withtab='.urlencode(GETPOST('withtab', 'alpha'));
}
// Add $param from extra fields // Add $param from extra fields
//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; //include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@ -332,8 +360,7 @@ $smonth = GETPOST('monthtoexport', 'int');
$retstring = ''; $retstring = '';
$retstring .= '<select class="flat valignmiddle maxwidth75imp marginrightonly" id="monthtoexport" name="monthtoexport">'; $retstring .= '<select class="flat valignmiddle maxwidth75imp marginrightonly" id="monthtoexport" name="monthtoexport">';
$retstring .= '<option value="0" selected>&nbsp;</option>'; $retstring .= '<option value="0" selected>&nbsp;</option>';
for ($month = 1; $month <= 12; $month++) for ($month = 1; $month <= 12; $month++) {
{
$retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>'; $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
$retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b"); $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
$retstring .= "</option>"; $retstring .= "</option>";
@ -343,7 +370,9 @@ print $retstring;
print '<input type="text" name="yeartoexport" class="valignmiddle maxwidth50imp" value="'.GETPOST('yeartoexport', 'int').'">'; print '<input type="text" name="yeartoexport" class="valignmiddle maxwidth50imp" value="'.GETPOST('yeartoexport', 'int').'">';
print '<input type="hidden" name="withtab" value="'.GETPOST('withtab', 'alpha').'">'; print '<input type="hidden" name="withtab" value="'.GETPOST('withtab', 'alpha').'">';
print '<input type="submit" name="downloadcsv" class="button" value="'.$langs->trans('DownloadLogCSV').'">'; print '<input type="submit" name="downloadcsv" class="button" value="'.$langs->trans('DownloadLogCSV').'">';
if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY)) print ' | <a href="?action=downloadblockchain'.(GETPOST('withtab', 'alpha') ? '&withtab='.GETPOST('withtab', 'alpha') : '').'">'.$langs->trans('DownloadBlockChain').'</a>'; if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY)) {
print ' | <a href="?action=downloadblockchain'.(GETPOST('withtab', 'alpha') ? '&withtab='.GETPOST('withtab', 'alpha') : '').'">'.$langs->trans('DownloadBlockChain').'</a>';
}
print ' </div><br>'; print ' </div><br>';
print '</form>'; print '</form>';
@ -352,7 +381,9 @@ print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'"
print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -446,10 +477,8 @@ if (!empty($conf->global->BLOCKEDLOG_SCAN_ALL_FOR_LOWERIDINERROR)) {
$loweridinerror = 0; $loweridinerror = 0;
$checkresult = array(); $checkresult = array();
$checkdetail = array(); $checkdetail = array();
if (is_array($blocks)) if (is_array($blocks)) {
{ foreach ($blocks as &$block) {
foreach ($blocks as &$block)
{
$tmpcheckresult = $block->checkSignature('', 1); // Note: this make a sql request at each call, we can't avoid this as the sorting order is various $tmpcheckresult = $block->checkSignature('', 1); // Note: this make a sql request at each call, we can't avoid this as the sorting order is various
$checksignature = $tmpcheckresult['checkresult']; $checksignature = $tmpcheckresult['checkresult'];
@ -457,26 +486,25 @@ if (!empty($conf->global->BLOCKEDLOG_SCAN_ALL_FOR_LOWERIDINERROR)) {
$checkresult[$block->id] = $checksignature; // false if error $checkresult[$block->id] = $checksignature; // false if error
$checkdetail[$block->id] = $tmpcheckresult; $checkdetail[$block->id] = $tmpcheckresult;
if (!$checksignature) if (!$checksignature) {
{ if (empty($loweridinerror)) {
if (empty($loweridinerror)) $loweridinerror = $block->id; $loweridinerror = $block->id;
else $loweridinerror = min($loweridinerror, $block->id); } else {
$loweridinerror = min($loweridinerror, $block->id);
}
} }
} }
} }
} }
if (is_array($blocks)) if (is_array($blocks)) {
{
$nbshown = 0; $nbshown = 0;
$MAXFORSHOWLINK = 100; $MAXFORSHOWLINK = 100;
$object_link = ''; $object_link = '';
foreach ($blocks as &$block) foreach ($blocks as &$block) {
{
//if (empty($search_showonlyerrors) || ! $checkresult[$block->id] || ($loweridinerror && $block->id >= $loweridinerror)) //if (empty($search_showonlyerrors) || ! $checkresult[$block->id] || ($loweridinerror && $block->id >= $loweridinerror))
if (empty($search_showonlyerrors) || !$checkresult[$block->id]) if (empty($search_showonlyerrors) || !$checkresult[$block->id]) {
{
$nbshown++; $nbshown++;
if ($nbshown < $MAXFORSHOWLINK) { // For performance and memory purpose, we get/show the link of objects only for the 100 first output if ($nbshown < $MAXFORSHOWLINK) { // For performance and memory purpose, we get/show the link of objects only for the 100 first output
@ -527,12 +555,10 @@ if (is_array($blocks))
// Status // Status
print '<td class="center">'; print '<td class="center">';
if (!$checkresult[$block->id] || ($loweridinerror && $block->id >= $loweridinerror)) // If error if (!$checkresult[$block->id] || ($loweridinerror && $block->id >= $loweridinerror)) { // If error
{
if ($checkresult[$block->id]) { if ($checkresult[$block->id]) {
print '<span class="badge badge-status4 badge-status" title="'.$langs->trans('OkCheckFingerprintValidityButChainIsKo').'">OK</span>'; print '<span class="badge badge-status4 badge-status" title="'.$langs->trans('OkCheckFingerprintValidityButChainIsKo').'">OK</span>';
} } else {
else {
print '<span class="badge badge-status8 badge-status" title="'.$langs->trans('KoCheckFingerprintValidity').'">KO</span>'; print '<span class="badge badge-status8 badge-status" title="'.$langs->trans('KoCheckFingerprintValidity').'">KO</span>';
} }
} else { } else {
@ -542,9 +568,10 @@ if (is_array($blocks))
// Note // Note
print '<td class="center">'; print '<td class="center">';
if (!$checkresult[$block->id] || ($loweridinerror && $block->id >= $loweridinerror)) // If error if (!$checkresult[$block->id] || ($loweridinerror && $block->id >= $loweridinerror)) { // If error
{ if ($checkresult[$block->id]) {
if ($checkresult[$block->id]) print $form->textwithpicto('', $langs->trans('OkCheckFingerprintValidityButChainIsKo')); print $form->textwithpicto('', $langs->trans('OkCheckFingerprintValidityButChainIsKo'));
}
} }
if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY) && !empty($conf->global->BLOCKEDLOG_AUTHORITY_URL)) { if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY) && !empty($conf->global->BLOCKEDLOG_AUTHORITY_URL)) {
@ -598,8 +625,7 @@ jQuery(document).ready(function () {
</script>'."\n"; </script>'."\n";
if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY) && !empty($conf->global->BLOCKEDLOG_AUTHORITY_URL)) if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY) && !empty($conf->global->BLOCKEDLOG_AUTHORITY_URL)) {
{
?> ?>
<script type="text/javascript"> <script type="text/javascript">
@ -621,8 +647,7 @@ if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY) && !empty($conf->glob
<?php <?php
} }
if (GETPOST('withtab', 'alpha')) if (GETPOST('withtab', 'alpha')) {
{
print dol_get_fiche_end(); print dol_get_fiche_end();
} }

View File

@ -26,9 +26,15 @@
// This script is called with a POST method. // This script is called with a POST method.
// Directory to scan (full path) is inside POST['dir']. // Directory to scan (full path) is inside POST['dir'].
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); define('NOTOKENRENEWAL', 1); // Disables token renewal
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); }
if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
$res = require '../../master.inc.php'; $res = require '../../master.inc.php';

View File

@ -26,9 +26,15 @@
// This script is called with a POST method. // This script is called with a POST method.
// Directory to scan (full path) is inside POST['dir']. // Directory to scan (full path) is inside POST['dir'].
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); define('NOTOKENRENEWAL', 1); // Disables token renewal
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); }
if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
$res = require '../../main.inc.php'; $res = require '../../main.inc.php';

View File

@ -26,9 +26,15 @@
// This script is called with a POST method. // This script is called with a POST method.
// Directory to scan (full path) is inside POST['dir']. // Directory to scan (full path) is inside POST['dir'].
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); define('NOTOKENRENEWAL', 1); // Disables token renewal
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); }
if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
require '../../main.inc.php'; require '../../main.inc.php';
@ -37,7 +43,9 @@ require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php';
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
$block = new BlockedLog($db); $block = new BlockedLog($db);
if ((!$user->admin && !$user->rights->blockedlog->read) || empty($conf->blockedlog->enabled)) accessforbidden(); if ((!$user->admin && !$user->rights->blockedlog->read) || empty($conf->blockedlog->enabled)) {
accessforbidden();
}
$langs->loadLangs(array("admin")); $langs->loadLangs(array("admin"));
@ -49,8 +57,7 @@ $langs->loadLangs(array("admin"));
print '<div id="pop-info"><table width="100%" height="80%" class="border"><thead><th width="50%" class="left">'.$langs->trans('Field').'</th><th class="left">'.$langs->trans('Value').'</th></thead>'; print '<div id="pop-info"><table width="100%" height="80%" class="border"><thead><th width="50%" class="left">'.$langs->trans('Field').'</th><th class="left">'.$langs->trans('Value').'</th></thead>';
print '<tbody>'; print '<tbody>';
if ($block->fetch($id) > 0) if ($block->fetch($id) > 0) {
{
$objtoshow = $block->object_data; $objtoshow = $block->object_data;
print formatObject($objtoshow, ''); print formatObject($objtoshow, '');
} else { } else {
@ -77,18 +84,14 @@ function formatObject($objtoshow, $prefix)
$newobjtoshow = $objtoshow; $newobjtoshow = $objtoshow;
if (is_object($newobjtoshow) || is_array($newobjtoshow)) if (is_object($newobjtoshow) || is_array($newobjtoshow)) {
{
//var_dump($newobjtoshow); //var_dump($newobjtoshow);
foreach ($newobjtoshow as $key => $val) foreach ($newobjtoshow as $key => $val) {
{ if (!is_object($val) && !is_array($val)) {
if (!is_object($val) && !is_array($val))
{
// TODO $val can be '__PHP_Incomplete_Class', the is_object return false // TODO $val can be '__PHP_Incomplete_Class', the is_object return false
$s .= '<tr><td>'.($prefix ? $prefix.' > ' : '').$key.'</td>'; $s .= '<tr><td>'.($prefix ? $prefix.' > ' : '').$key.'</td>';
$s .= '<td>'; $s .= '<td>';
if (in_array($key, array('date', 'datef', 'dateh', 'datec', 'datem', 'datep'))) if (in_array($key, array('date', 'datef', 'dateh', 'datec', 'datem', 'datep'))) {
{
/*var_dump(is_object($val)); /*var_dump(is_object($val));
var_dump(is_array($val)); var_dump(is_array($val));
var_dump(is_array($val)); var_dump(is_array($val));
@ -99,11 +102,9 @@ function formatObject($objtoshow, $prefix)
$s .= $val; $s .= $val;
} }
$s .= '</td></tr>'; $s .= '</td></tr>';
} elseif (is_array($val)) } elseif (is_array($val)) {
{
$s .= formatObject($val, ($prefix ? $prefix.' > ' : '').$key); $s .= formatObject($val, ($prefix ? $prefix.' > ' : '').$key);
} elseif (is_object($val)) } elseif (is_object($val)) {
{
$s .= formatObject($val, ($prefix ? $prefix.' > ' : '').$key); $s .= formatObject($val, ($prefix ? $prefix.' > ' : '').$key);
} }
} }

View File

@ -26,14 +26,22 @@
// This script is called with a POST method. // This script is called with a POST method.
// Directory to scan (full path) is inside POST['dir']. // Directory to scan (full path) is inside POST['dir'].
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); define('NOTOKENRENEWAL', 1); // Disables token renewal
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); }
if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
require '../../main.inc.php'; require '../../main.inc.php';
if (empty($conf->global->BLOCKEDLOG_AUTHORITY_URL)) exit('BLOCKEDLOG_AUTHORITY_URL not set'); if (empty($conf->global->BLOCKEDLOG_AUTHORITY_URL)) {
exit('BLOCKEDLOG_AUTHORITY_URL not set');
}
require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php'; require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php';
require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/authority.class.php'; require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/authority.class.php';

View File

@ -122,7 +122,9 @@ class BlockedLogAuthority
public function checkBlock($block) public function checkBlock($block)
{ {
if (strlen($block) != 64) return false; if (strlen($block) != 64) {
return false;
}
$blocks = str_split($this->blockchain, 64); $blocks = str_split($this->blockchain, 64);
@ -148,8 +150,7 @@ class BlockedLogAuthority
dol_syslog(get_class($this)."::fetch id=".$id, LOG_DEBUG); dol_syslog(get_class($this)."::fetch id=".$id, LOG_DEBUG);
if (empty($id) && empty($signature)) if (empty($id) && empty($signature)) {
{
$this->error = 'BadParameter'; $this->error = 'BadParameter';
return -1; return -1;
} }
@ -159,14 +160,15 @@ class BlockedLogAuthority
$sql = "SELECT b.rowid, b.signature, b.blockchain, b.tms"; $sql = "SELECT b.rowid, b.signature, b.blockchain, b.tms";
$sql .= " FROM ".MAIN_DB_PREFIX."blockedlog_authority as b"; $sql .= " FROM ".MAIN_DB_PREFIX."blockedlog_authority as b";
if ($id) $sql .= " WHERE b.rowid = ".$id; if ($id) {
elseif ($signature)$sql .= " WHERE b.signature = '".$this->db->escape($signature)."'"; $sql .= " WHERE b.rowid = ".$id;
} elseif ($signature) {
$sql .= " WHERE b.signature = '".$this->db->escape($signature)."'";
}
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{ if ($this->db->num_rows($resql)) {
if ($this->db->num_rows($resql))
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid; $this->id = $obj->rowid;
@ -216,12 +218,10 @@ class BlockedLogAuthority
$sql .= ")"; $sql .= ")";
$res = $this->db->query($sql); $res = $this->db->query($sql);
if ($res) if ($res) {
{
$id = $this->db->last_insert_id(MAIN_DB_PREFIX."blockedlog_authority"); $id = $this->db->last_insert_id(MAIN_DB_PREFIX."blockedlog_authority");
if ($id > 0) if ($id > 0) {
{
$this->id = $id; $this->id = $id;
$this->db->commit(); $this->db->commit();
@ -262,8 +262,7 @@ class BlockedLogAuthority
$sql .= " WHERE rowid=".$this->id; $sql .= " WHERE rowid=".$this->id;
$res = $this->db->query($sql); $res = $this->db->query($sql);
if ($res) if ($res) {
{
$this->db->commit(); $this->db->commit();
return 1; return 1;

View File

@ -319,11 +319,9 @@ class BlockedLog
} else { } else {
$this->error++; $this->error++;
} }
} elseif ($this->action == 'MODULE_SET') } elseif ($this->action == 'MODULE_SET') {
{
return '<i class="opacitymedium">System to track events into unalterable logs were enabled</i>'; return '<i class="opacitymedium">System to track events into unalterable logs were enabled</i>';
} elseif ($this->action == 'MODULE_RESET') } elseif ($this->action == 'MODULE_RESET') {
{
if ($this->signature == '0000000000') { if ($this->signature == '0000000000') {
return '<i class="opacitymedium">System to track events into unalterable logs were disabled after some recording were done. We saved a special Fingerprint to track the chain as broken.</i>'; return '<i class="opacitymedium">System to track events into unalterable logs were disabled after some recording were done. We saved a special Fingerprint to track the chain as broken.</i>';
} else { } else {
@ -342,7 +340,9 @@ class BlockedLog
{ {
global $langs, $cachedUser; global $langs, $cachedUser;
if (empty($cachedUser))$cachedUser = array(); if (empty($cachedUser)) {
$cachedUser = array();
}
if (empty($cachedUser[$this->fk_user])) { if (empty($cachedUser[$this->fk_user])) {
$u = new User($this->db); $u = new User($this->db);
@ -371,7 +371,9 @@ class BlockedLog
{ {
global $langs, $user, $mysoc; global $langs, $user, $mysoc;
if (is_object($fuser)) $user = $fuser; if (is_object($fuser)) {
$user = $fuser;
}
// Generic fields // Generic fields
@ -380,20 +382,15 @@ class BlockedLog
// amount // amount
$this->amounts = $amounts; $this->amounts = $amounts;
// date // date
if ($object->element == 'payment' || $object->element == 'payment_supplier') if ($object->element == 'payment' || $object->element == 'payment_supplier') {
{
$this->date_object = $object->datepaye; $this->date_object = $object->datepaye;
} elseif ($object->element == 'payment_salary') } elseif ($object->element == 'payment_salary') {
{
$this->date_object = $object->datev; $this->date_object = $object->datev;
} elseif ($object->element == 'payment_donation' || $object->element == 'payment_various') } elseif ($object->element == 'payment_donation' || $object->element == 'payment_various') {
{
$this->date_object = $object->datepaid ? $object->datepaid : $object->datep; $this->date_object = $object->datepaid ? $object->datepaid : $object->datep;
} elseif ($object->element == 'subscription') } elseif ($object->element == 'subscription') {
{
$this->date_object = $object->dateh; $this->date_object = $object->dateh;
} elseif ($object->element == 'cashcontrol') } elseif ($object->element == 'cashcontrol') {
{
$this->date_object = $object->date_creation; $this->date_object = $object->date_creation;
} else { } else {
$this->date_object = $object->date; $this->date_object = $object->date;
@ -424,70 +421,79 @@ class BlockedLog
'name', 'lastname', 'firstname', 'region', 'region_id', 'region_code', 'state', 'state_id', 'state_code', 'country', 'country_id', 'country_code', 'name', 'lastname', 'firstname', 'region', 'region_id', 'region_code', 'state', 'state_id', 'state_code', 'country', 'country_id', 'country_code',
'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2', 'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2',
'barcode_type', 'barcode_type_code', 'barcode_type_label', 'barcode_type_coder', 'mode_reglement_id', 'cond_reglement_id', 'mode_reglement', 'cond_reglement', 'shipping_method_id', 'barcode_type', 'barcode_type_code', 'barcode_type_label', 'barcode_type_coder', 'mode_reglement_id', 'cond_reglement_id', 'mode_reglement', 'cond_reglement', 'shipping_method_id',
'fk_incoterms', 'label_incoterms', 'location_incoterms', 'lines') 'fk_incoterms', 'label_incoterms', 'location_incoterms', 'lines'));
);
} }
// Add thirdparty info // Add thirdparty info
if (empty($object->thirdparty) && method_exists($object, 'fetch_thirdparty')) $object->fetch_thirdparty(); if (empty($object->thirdparty) && method_exists($object, 'fetch_thirdparty')) {
if (!empty($object->thirdparty)) $object->fetch_thirdparty();
{ }
if (!empty($object->thirdparty)) {
$this->object_data->thirdparty = new stdClass(); $this->object_data->thirdparty = new stdClass();
foreach ($object->thirdparty as $key=>$value) foreach ($object->thirdparty as $key => $value) {
{ if (in_array($key, $arrayoffieldstoexclude)) {
if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties continue; // Discard some properties
}
if (!in_array($key, array( if (!in_array($key, array(
'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode', 'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode',
'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur' 'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur'
))) continue; // Discard if not into a dedicated list ))) {
if (!is_object($value) && !is_null($value) && $value !== '') $this->object_data->thirdparty->{$key} = $value; continue; // Discard if not into a dedicated list
}
if (!is_object($value) && !is_null($value) && $value !== '') {
$this->object_data->thirdparty->{$key} = $value;
}
} }
} }
// Add company info // Add company info
if (!empty($mysoc)) if (!empty($mysoc)) {
{
$this->object_data->mycompany = new stdClass(); $this->object_data->mycompany = new stdClass();
foreach ($mysoc as $key=>$value) foreach ($mysoc as $key => $value) {
{ if (in_array($key, $arrayoffieldstoexclude)) {
if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties continue; // Discard some properties
}
if (!in_array($key, array( if (!in_array($key, array(
'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode', 'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode',
'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur' 'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur'
))) continue; // Discard if not into a dedicated list ))) {
if (!is_object($value) && !is_null($value) && $value !== '') $this->object_data->mycompany->{$key} = $value; continue; // Discard if not into a dedicated list
}
if (!is_object($value) && !is_null($value) && $value !== '') {
$this->object_data->mycompany->{$key} = $value;
}
} }
} }
// Add user info // Add user info
if (!empty($user)) if (!empty($user)) {
{
$this->fk_user = $user->id; $this->fk_user = $user->id;
$this->user_fullname = $user->getFullName($langs); $this->user_fullname = $user->getFullName($langs);
} }
// Field specific to object // Field specific to object
if ($this->element == 'facture') if ($this->element == 'facture') {
{ foreach ($object as $key => $value) {
foreach ($object as $key=>$value) if (in_array($key, $arrayoffieldstoexclude)) {
{ continue; // Discard some properties
if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties }
if (!in_array($key, array( if (!in_array($key, array(
'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'datev', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public', 'lines' 'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'datev', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public', 'lines'
))) continue; // Discard if not into a dedicated list ))) {
if ($key == 'lines') continue; // Discard if not into a dedicated list
{ }
if ($key == 'lines') {
$lineid = 0; $lineid = 0;
foreach ($value as $tmpline) // $tmpline is object FactureLine foreach ($value as $tmpline) { // $tmpline is object FactureLine
{
$lineid++; $lineid++;
foreach ($tmpline as $keyline => $valueline) foreach ($tmpline as $keyline => $valueline) {
{
if (!in_array($keyline, array( if (!in_array($keyline, array(
'ref', 'multicurrency_code', 'multicurrency_total_ht', 'multicurrency_total_tva', 'multicurrency_total_ttc', 'qty', 'product_type', 'vat_src_code', 'tva_tx', 'info_bits', 'localtax1_tx', 'localtax2_tx', 'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2' 'ref', 'multicurrency_code', 'multicurrency_total_ht', 'multicurrency_total_tva', 'multicurrency_total_ttc', 'qty', 'product_type', 'vat_src_code', 'tva_tx', 'info_bits', 'localtax1_tx', 'localtax2_tx', 'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2'
))) continue; // Discard if not into a dedicated list ))) {
continue; // Discard if not into a dedicated list
}
if (empty($this->object_data->invoiceline[$lineid]) || !is_object($this->object_data->invoiceline[$lineid])) { // To avoid warning if (empty($this->object_data->invoiceline[$lineid]) || !is_object($this->object_data->invoiceline[$lineid])) { // To avoid warning
$this->object_data->invoiceline[$lineid] = new stdClass(); $this->object_data->invoiceline[$lineid] = new stdClass();
@ -498,24 +504,33 @@ class BlockedLog
} }
} }
} }
} elseif (!is_object($value) && !is_null($value) && $value !== '') $this->object_data->{$key} = $value; } elseif (!is_object($value) && !is_null($value) && $value !== '') {
$this->object_data->{$key} = $value;
}
} }
if (!empty($object->newref)) $this->object_data->ref = $object->newref; if (!empty($object->newref)) {
} elseif ($this->element == 'invoice_supplier') $this->object_data->ref = $object->newref;
{ }
foreach ($object as $key => $value) } elseif ($this->element == 'invoice_supplier') {
{ foreach ($object as $key => $value) {
if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties if (in_array($key, $arrayoffieldstoexclude)) {
continue; // Discard some properties
}
if (!in_array($key, array( if (!in_array($key, array(
'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public' 'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public'
))) continue; // Discard if not into a dedicated list ))) {
if (!is_object($value) && !is_null($value) && $value !== '') $this->object_data->{$key} = $value; continue; // Discard if not into a dedicated list
}
if (!is_object($value) && !is_null($value) && $value !== '') {
$this->object_data->{$key} = $value;
}
} }
if (!empty($object->newref)) $this->object_data->ref = $object->newref; if (!empty($object->newref)) {
} elseif ($this->element == 'payment' || $this->element == 'payment_supplier' || $this->element == 'payment_donation' || $this->element == 'payment_various') $this->object_data->ref = $object->newref;
{ }
} elseif ($this->element == 'payment' || $this->element == 'payment_supplier' || $this->element == 'payment_donation' || $this->element == 'payment_various') {
$datepayment = $object->datepaye ? $object->datepaye : ($object->datepaid ? $object->datepaid : $object->datep); $datepayment = $object->datepaye ? $object->datepaye : ($object->datepaid ? $object->datepaid : $object->datep);
$paymenttypeid = $object->paiementid ? $object->paiementid : ($object->paymenttype ? $object->paymenttype : $object->type_payment); $paymenttypeid = $object->paiementid ? $object->paiementid : ($object->paymenttype ? $object->paymenttype : $object->type_payment);
@ -523,53 +538,51 @@ class BlockedLog
$this->object_data->date = $datepayment; $this->object_data->date = $datepayment;
$this->object_data->type_code = dol_getIdFromCode($this->db, $paymenttypeid, 'c_paiement', 'id', 'code'); $this->object_data->type_code = dol_getIdFromCode($this->db, $paymenttypeid, 'c_paiement', 'id', 'code');
if (!empty($object->num_payment)) $this->object_data->payment_num = $object->num_payment; if (!empty($object->num_payment)) {
if (!empty($object->note_private)) $this->object_data->note_private = $object->note_private; $this->object_data->payment_num = $object->num_payment;
}
if (!empty($object->note_private)) {
$this->object_data->note_private = $object->note_private;
}
//$this->object_data->fk_account = $object->fk_account; //$this->object_data->fk_account = $object->fk_account;
//var_dump($this->object_data);exit; //var_dump($this->object_data);exit;
$totalamount = 0; $totalamount = 0;
if (!is_array($object->amounts) && $object->amount) if (!is_array($object->amounts) && $object->amount) {
{
$object->amounts = array($object->id => $object->amount); $object->amounts = array($object->id => $object->amount);
} }
$paymentpartnumber = 0; $paymentpartnumber = 0;
foreach ($object->amounts as $objid => $amount) foreach ($object->amounts as $objid => $amount) {
{ if (empty($amount)) {
if (empty($amount)) continue; continue;
}
$totalamount += $amount; $totalamount += $amount;
$tmpobject = null; $tmpobject = null;
if ($this->element == 'payment_supplier') if ($this->element == 'payment_supplier') {
{
include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
$tmpobject = new FactureFournisseur($this->db); $tmpobject = new FactureFournisseur($this->db);
} elseif ($this->element == 'payment') } elseif ($this->element == 'payment') {
{
include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
$tmpobject = new Facture($this->db); $tmpobject = new Facture($this->db);
} elseif ($this->element == 'payment_donation') } elseif ($this->element == 'payment_donation') {
{
include_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; include_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
$tmpobject = new Don($this->db); $tmpobject = new Don($this->db);
} elseif ($this->element == 'payment_various') } elseif ($this->element == 'payment_various') {
{
include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php'; include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php';
$tmpobject = new PaymentVarious($this->db); $tmpobject = new PaymentVarious($this->db);
} }
if (!is_object($tmpobject)) if (!is_object($tmpobject)) {
{
continue; continue;
} }
$result = $tmpobject->fetch($objid); $result = $tmpobject->fetch($objid);
if ($result <= 0) if ($result <= 0) {
{
$this->error = $tmpobject->error; $this->error = $tmpobject->error;
$this->errors = $tmpobject->errors; $this->errors = $tmpobject->errors;
dol_syslog("Failed to fetch object with id ".$objid, LOG_ERR); dol_syslog("Failed to fetch object with id ".$objid, LOG_ERR);
@ -579,50 +592,61 @@ class BlockedLog
$paymentpart = new stdClass(); $paymentpart = new stdClass();
$paymentpart->amount = $amount; $paymentpart->amount = $amount;
if (!in_array($this->element, array('payment_donation', 'payment_various'))) if (!in_array($this->element, array('payment_donation', 'payment_various'))) {
{
$result = $tmpobject->fetch_thirdparty(); $result = $tmpobject->fetch_thirdparty();
if ($result == 0) if ($result == 0) {
{
$this->error = 'Failed to fetch thirdparty for object with id '.$tmpobject->id; $this->error = 'Failed to fetch thirdparty for object with id '.$tmpobject->id;
$this->errors[] = $this->error; $this->errors[] = $this->error;
dol_syslog("Failed to fetch thirdparty for object with id ".$tmpobject->id, LOG_ERR); dol_syslog("Failed to fetch thirdparty for object with id ".$tmpobject->id, LOG_ERR);
return -1; return -1;
} elseif ($result < 0) } elseif ($result < 0) {
{
$this->error = $tmpobject->error; $this->error = $tmpobject->error;
$this->errors = $tmpobject->errors; $this->errors = $tmpobject->errors;
return -1; return -1;
} }
$paymentpart->thirdparty = new stdClass(); $paymentpart->thirdparty = new stdClass();
foreach ($tmpobject->thirdparty as $key=>$value) foreach ($tmpobject->thirdparty as $key => $value) {
{ if (in_array($key, $arrayoffieldstoexclude)) {
if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties continue; // Discard some properties
}
if (!in_array($key, array( if (!in_array($key, array(
'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode', 'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode',
'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur' 'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur'
))) continue; // Discard if not into a dedicated list ))) {
if (!is_object($value) && !is_null($value) && $value !== '') $paymentpart->thirdparty->{$key} = $value; continue; // Discard if not into a dedicated list
}
if (!is_object($value) && !is_null($value) && $value !== '') {
$paymentpart->thirdparty->{$key} = $value;
}
} }
} }
// Init object to avoid warnings // Init object to avoid warnings
if ($this->element == 'payment_donation') $paymentpart->donation = new stdClass(); if ($this->element == 'payment_donation') {
else $paymentpart->invoice = new stdClass(); $paymentpart->donation = new stdClass();
} else {
$paymentpart->invoice = new stdClass();
}
if ($this->element != 'payment_various') if ($this->element != 'payment_various') {
{ foreach ($tmpobject as $key => $value) {
foreach ($tmpobject as $key=>$value) if (in_array($key, $arrayoffieldstoexclude)) {
{ continue; // Discard some properties
if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties }
if (!in_array($key, array( if (!in_array($key, array(
'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public' 'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public'
))) continue; // Discard if not into a dedicated list ))) {
continue; // Discard if not into a dedicated list
}
if (!is_object($value) && !is_null($value) && $value !== '') { if (!is_object($value) && !is_null($value) && $value !== '') {
if ($this->element == 'payment_donation') $paymentpart->donation->{$key} = $value; if ($this->element == 'payment_donation') {
elseif ($this->element == 'payment_various') $paymentpart->various->{$key} = $value; $paymentpart->donation->{$key} = $value;
else $paymentpart->invoice->{$key} = $value; } elseif ($this->element == 'payment_various') {
$paymentpart->various->{$key} = $value;
} else {
$paymentpart->invoice->{$key} = $value;
}
} }
} }
@ -633,33 +657,47 @@ class BlockedLog
$this->object_data->amount = $totalamount; $this->object_data->amount = $totalamount;
if (!empty($object->newref)) $this->object_data->ref = $object->newref; if (!empty($object->newref)) {
} elseif ($this->element == 'payment_salary') $this->object_data->ref = $object->newref;
{ }
} elseif ($this->element == 'payment_salary') {
$this->object_data->amounts = array($object->amount); $this->object_data->amounts = array($object->amount);
if (!empty($object->newref)) $this->object_data->ref = $object->newref; if (!empty($object->newref)) {
} elseif ($this->element == 'subscription') $this->object_data->ref = $object->newref;
{ }
foreach ($object as $key=>$value) } elseif ($this->element == 'subscription') {
{ foreach ($object as $key => $value) {
if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties if (in_array($key, $arrayoffieldstoexclude)) {
continue; // Discard some properties
}
if (!in_array($key, array( if (!in_array($key, array(
'id', 'datec', 'dateh', 'datef', 'fk_adherent', 'amount', 'import_key', 'statut', 'note' 'id', 'datec', 'dateh', 'datef', 'fk_adherent', 'amount', 'import_key', 'statut', 'note'
))) continue; // Discard if not into a dedicated list ))) {
if (!is_object($value) && !is_null($value) && $value !== '') $this->object_data->{$key} = $value; continue; // Discard if not into a dedicated list
}
if (!is_object($value) && !is_null($value) && $value !== '') {
$this->object_data->{$key} = $value;
}
} }
if (!empty($object->newref)) $this->object_data->ref = $object->newref; if (!empty($object->newref)) {
$this->object_data->ref = $object->newref;
}
} else // Generic case } else // Generic case
{ {
foreach ($object as $key=>$value) foreach ($object as $key => $value) {
{ if (in_array($key, $arrayoffieldstoexclude)) {
if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties continue; // Discard some properties
if (!is_object($value) && !is_null($value) && $value !== '') $this->object_data->{$key} = $value; }
if (!is_object($value) && !is_null($value) && $value !== '') {
$this->object_data->{$key} = $value;
}
} }
if (!empty($object->newref)) $this->object_data->ref = $object->newref; if (!empty($object->newref)) {
$this->object_data->ref = $object->newref;
}
} }
return 1; return 1;
@ -675,8 +713,7 @@ class BlockedLog
{ {
global $langs; global $langs;
if (empty($id)) if (empty($id)) {
{
$this->error = 'BadParameter'; $this->error = 'BadParameter';
return -1; return -1;
} }
@ -684,11 +721,12 @@ class BlockedLog
$sql = "SELECT b.rowid, b.date_creation, b.signature, b.signature_line, b.amounts, b.action, b.element, b.fk_object, b.entity,"; $sql = "SELECT b.rowid, b.date_creation, b.signature, b.signature_line, b.amounts, b.action, b.element, b.fk_object, b.entity,";
$sql .= " b.certified, b.tms, b.fk_user, b.user_fullname, b.date_object, b.ref_object, b.object_data, b.object_version"; $sql .= " b.certified, b.tms, b.fk_user, b.user_fullname, b.date_object, b.ref_object, b.object_data, b.object_version";
$sql .= " FROM ".MAIN_DB_PREFIX."blockedlog as b"; $sql .= " FROM ".MAIN_DB_PREFIX."blockedlog as b";
if ($id) $sql .= " WHERE b.rowid = ".((int) $id); if ($id) {
$sql .= " WHERE b.rowid = ".((int) $id);
}
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj) { if ($obj) {
$this->id = $obj->rowid; $this->id = $obj->rowid;
@ -759,7 +797,9 @@ class BlockedLog
{ {
$res = $this->db->query("UPDATE ".MAIN_DB_PREFIX."blockedlog SET certified=1 WHERE rowid=".$this->id); $res = $this->db->query("UPDATE ".MAIN_DB_PREFIX."blockedlog SET certified=1 WHERE rowid=".$this->id);
if ($res === false) return false; if ($res === false) {
return false;
}
return true; return true;
} }
@ -785,8 +825,7 @@ class BlockedLog
dol_syslog(get_class($this).'::create action='.$this->action.' fk_user='.$this->fk_user.' user_fullname='.$this->user_fullname, LOG_DEBUG); dol_syslog(get_class($this).'::create action='.$this->action.' fk_user='.$this->fk_user.' user_fullname='.$this->user_fullname, LOG_DEBUG);
// Check parameters/properties // Check parameters/properties
if (!isset($this->amounts)) // amount can be 0 for some events (like when module is disabled) if (!isset($this->amounts)) { // amount can be 0 for some events (like when module is disabled)
{
$this->error = $langs->trans("BlockLogNeedAmountsValue"); $this->error = $langs->trans("BlockLogNeedAmountsValue");
dol_syslog($this->error, LOG_WARNING); dol_syslog($this->error, LOG_WARNING);
return -1; return -1;
@ -803,7 +842,9 @@ class BlockedLog
dol_syslog($this->error, LOG_WARNING); dol_syslog($this->error, LOG_WARNING);
return -3; return -3;
} }
if (empty($this->fk_user)) $this->user_fullname = '(Anonymous)'; if (empty($this->fk_user)) {
$this->user_fullname = '(Anonymous)';
}
$this->date_creation = dol_now(); $this->date_creation = dol_now();
@ -817,7 +858,9 @@ class BlockedLog
$this->signature_line = dol_hash($keyforsignature, '5'); // Not really usefull $this->signature_line = dol_hash($keyforsignature, '5'); // Not really usefull
$this->signature = dol_hash($previoushash.$keyforsignature, '5'); $this->signature = dol_hash($previoushash.$keyforsignature, '5');
if ($forcesignature) $this->signature = $forcesignature; if ($forcesignature) {
$this->signature = $forcesignature;
}
//var_dump($keyforsignature);var_dump($previoushash);var_dump($this->signature_line);var_dump($this->signature); //var_dump($keyforsignature);var_dump($previoushash);var_dump($this->signature_line);var_dump($this->signature);
$sql = "INSERT INTO ".MAIN_DB_PREFIX."blockedlog ("; $sql = "INSERT INTO ".MAIN_DB_PREFIX."blockedlog (";
@ -855,12 +898,10 @@ class BlockedLog
$sql .= ")"; $sql .= ")";
$res = $this->db->query($sql); $res = $this->db->query($sql);
if ($res) if ($res) {
{
$id = $this->db->last_insert_id(MAIN_DB_PREFIX."blockedlog"); $id = $this->db->last_insert_id(MAIN_DB_PREFIX."blockedlog");
if ($id > 0) if ($id > 0) {
{
$this->id = $id; $this->id = $id;
$this->db->commit(); $this->db->commit();
@ -888,8 +929,7 @@ class BlockedLog
*/ */
public function checkSignature($previoushash = '', $returnarray = 0) public function checkSignature($previoushash = '', $returnarray = 0)
{ {
if (empty($previoushash)) if (empty($previoushash)) {
{
$previoushash = $this->getPreviousHash(0, $this->id); $previoushash = $this->getPreviousHash(0, $this->id);
} }
// Recalculate hash // Recalculate hash
@ -951,15 +991,16 @@ class BlockedLog
$sql = "SELECT rowid, signature FROM ".MAIN_DB_PREFIX."blockedlog"; $sql = "SELECT rowid, signature FROM ".MAIN_DB_PREFIX."blockedlog";
$sql .= " WHERE entity=".$conf->entity; $sql .= " WHERE entity=".$conf->entity;
if ($beforeid) $sql .= " AND rowid < ".(int) $beforeid; if ($beforeid) {
$sql .= " AND rowid < ".(int) $beforeid;
}
$sql .= " ORDER BY rowid DESC LIMIT 1"; $sql .= " ORDER BY rowid DESC LIMIT 1";
$sql .= ($withlock ? " FOR UPDATE " : ""); $sql .= ($withlock ? " FOR UPDATE " : "");
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) { if ($resql) {
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj) if ($obj) {
{
$previoussignature = $obj->signature; $previoussignature = $obj->signature;
} }
} else { } else {
@ -967,8 +1008,7 @@ class BlockedLog
exit; exit;
} }
if (empty($previoussignature)) if (empty($previoussignature)) {
{
// First signature line (line 0) // First signature line (line 0)
$previoussignature = $this->getSignature(); $previoussignature = $this->getSignature();
} }
@ -1014,13 +1054,27 @@ class BlockedLog
WHERE entity=".$conf->entity." AND element='".$this->db->escape($element)."'"; WHERE entity=".$conf->entity." AND element='".$this->db->escape($element)."'";
} }
if ($fk_object) $sql .= natural_search("rowid", $fk_object, 1); if ($fk_object) {
if ($search_fk_user > 0) $sql .= natural_search("fk_user", $search_fk_user, 2); $sql .= natural_search("rowid", $fk_object, 1);
if ($search_start > 0) $sql .= " AND date_creation >= '".$this->db->idate($search_start)."'"; }
if ($search_end > 0) $sql .= " AND date_creation <= '".$this->db->idate($search_end)."'"; if ($search_fk_user > 0) {
if ($search_ref != '') $sql .= natural_search("ref_object", $search_ref); $sql .= natural_search("fk_user", $search_fk_user, 2);
if ($search_amount != '') $sql .= natural_search("amounts", $search_amount, 1); }
if ($search_code != '' && $search_code != '-1') $sql .= natural_search("action", $search_code, 3); if ($search_start > 0) {
$sql .= " AND date_creation >= '".$this->db->idate($search_start)."'";
}
if ($search_end > 0) {
$sql .= " AND date_creation <= '".$this->db->idate($search_end)."'";
}
if ($search_ref != '') {
$sql .= natural_search("ref_object", $search_ref);
}
if ($search_amount != '') {
$sql .= natural_search("amounts", $search_amount, 1);
}
if ($search_code != '' && $search_code != '-1') {
$sql .= natural_search("action", $search_code, 3);
}
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
$sql .= $this->db->plimit($limit + 1); // We want more, because we will stop into loop later with error if we reach max $sql .= $this->db->plimit($limit + 1); // We want more, because we will stop into loop later with error if we reach max
@ -1030,11 +1084,9 @@ class BlockedLog
$results = array(); $results = array();
$i = 0; $i = 0;
while ($obj = $this->db->fetch_object($res)) while ($obj = $this->db->fetch_object($res)) {
{
$i++; $i++;
if ($i > $limit) if ($i > $limit) {
{
// Too many record, we will consume too much memory // Too many record, we will consume too much memory
return -2; return -2;
} }
@ -1096,15 +1148,20 @@ class BlockedLog
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog"; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog";
$sql .= " WHERE entity = ".$conf->entity; $sql .= " WHERE entity = ".$conf->entity;
if ($ignoresystem) $sql .= " AND action not in ('MODULE_SET','MODULE_RESET')"; if ($ignoresystem) {
$sql .= " AND action not in ('MODULE_SET','MODULE_RESET')";
}
$sql .= $this->db->plimit(1); $sql .= $this->db->plimit(1);
$res = $this->db->query($sql); $res = $this->db->query($sql);
if ($res !== false) if ($res !== false) {
{
$obj = $this->db->fetch_object($res); $obj = $this->db->fetch_object($res);
if ($obj) $result = true; if ($obj) {
} else dol_print_error($this->db); $result = true;
}
} else {
dol_print_error($this->db);
}
dol_syslog("Module Blockedlog alreadyUsed with ignoresystem=".$ignoresystem." is ".$result); dol_syslog("Module Blockedlog alreadyUsed with ignoresystem=".$ignoresystem." is ".$result);

View File

@ -44,8 +44,7 @@ function blockedlogadmin_prepare_head()
require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php'; require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php';
$b = new BlockedLog($db); $b = new BlockedLog($db);
if ($b->alreadyUsed()) if ($b->alreadyUsed()) {
{
$head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">...</span>' : ''); $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">...</span>' : '');
} }
$head[$h][2] = 'fingerprints'; $head[$h][2] = 'fingerprints';

View File

@ -52,8 +52,7 @@ $object = new Bookmark($db);
* Actions * Actions
*/ */
if ($action == 'add' || $action == 'addproduct' || $action == 'update') if ($action == 'add' || $action == 'addproduct' || $action == 'update') {
{
if ($action == 'update') { if ($action == 'update') {
$invertedaction = 'edit'; $invertedaction = 'edit';
} else { } else {
@ -62,14 +61,17 @@ if ($action == 'add' || $action == 'addproduct' || $action == 'update')
$error = 0; $error = 0;
if (GETPOST('cancel', 'alpha')) if (GETPOST('cancel', 'alpha')) {
{ if (empty($backtopage)) {
if (empty($backtopage)) $backtopage = ($urlsource ? $urlsource : ((!empty($url) && !preg_match('/^http/i', $url)) ? $url : DOL_URL_ROOT.'/bookmarks/list.php')); $backtopage = ($urlsource ? $urlsource : ((!empty($url) && !preg_match('/^http/i', $url)) ? $url : DOL_URL_ROOT.'/bookmarks/list.php'));
}
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} }
if ($action == 'update') $object->fetch(GETPOST("id", 'int')); if ($action == 'update') {
$object->fetch(GETPOST("id", 'int'));
}
// Check if null because user not admin can't set an user and send empty value here. // Check if null because user not admin can't set an user and send empty value here.
if (!empty($userid)) { if (!empty($userid)) {
$object->fk_user = $userid; $object->fk_user = $userid;
@ -89,21 +91,23 @@ if ($action == 'add' || $action == 'addproduct' || $action == 'update')
setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("UrlOrLink")), null, 'errors'); setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("UrlOrLink")), null, 'errors');
} }
if (!$error) if (!$error) {
{
$object->favicon = 'none'; $object->favicon = 'none';
if ($action == 'update') $res = $object->update(); if ($action == 'update') {
else $res = $object->create(); $res = $object->update();
} else {
$res = $object->create();
}
if ($res > 0) if ($res > 0) {
{ if (empty($backtopage)) {
if (empty($backtopage)) $backtopage = ($urlsource ? $urlsource : ((!empty($url) && !preg_match('/^http/i', $url)) ? $url : DOL_URL_ROOT.'/bookmarks/list.php')); $backtopage = ($urlsource ? $urlsource : ((!empty($url) && !preg_match('/^http/i', $url)) ? $url : DOL_URL_ROOT.'/bookmarks/list.php'));
}
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} else { } else {
if ($object->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') if ($object->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
{
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->transnoentities("WarningBookmarkAlreadyExists"), null, 'warnings'); setEventMessages($langs->transnoentities("WarningBookmarkAlreadyExists"), null, 'warnings');
} else { } else {
@ -137,8 +141,7 @@ $h++;
$hselected = 'card'; $hselected = 'card';
if ($action == 'create') if ($action == 'create') {
{
/* /*
* Fact bookmark creation mode * Fact bookmark creation mode
*/ */
@ -189,8 +192,7 @@ if ($action == 'create')
} }
if ($id > 0 && !preg_match('/^add/i', $action)) if ($id > 0 && !preg_match('/^add/i', $action)) {
{
/* /*
* Fact bookmark mode or visually edition * Fact bookmark mode or visually edition
*/ */
@ -205,8 +207,7 @@ if ($id > 0 && !preg_match('/^add/i', $action))
) )
); );
if ($action == 'edit') if ($action == 'edit') {
{
print '<form name="edit" method="POST" action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data">'; print '<form name="edit" method="POST" action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="action" value="update">';
@ -239,8 +240,11 @@ if ($id > 0 && !preg_match('/^add/i', $action))
} }
print '</td><td>'; print '</td><td>';
if ($action == 'edit') print '<input class="flat minwidth300" name="title" value="'.(GETPOSTISSET("title") ? GETPOST("title", '', 2) : $object->title).'">'; if ($action == 'edit') {
else print $object->title; print '<input class="flat minwidth300" name="title" value="'.(GETPOSTISSET("title") ? GETPOST("title", '', 2) : $object->title).'">';
} else {
print $object->title;
}
print '</td></tr>'; print '</td></tr>';
print '<tr><td>'; print '<tr><td>';
@ -252,28 +256,32 @@ if ($id > 0 && !preg_match('/^add/i', $action))
print '</span>'; print '</span>';
} }
print '</td><td>'; print '</td><td>';
if ($action == 'edit') print '<input class="flat minwidth500 quatrevingtpercent" name="url" value="'.(GETPOSTISSET("url") ? GETPOST("url") : $object->url).'">'; if ($action == 'edit') {
else print '<a href="'.(preg_match('/^http/i', $object->url) ? $object->url : DOL_URL_ROOT.$object->url).'"'.($object->target ? ' target="_blank"' : '').'>'.$object->url.'</a>'; print '<input class="flat minwidth500 quatrevingtpercent" name="url" value="'.(GETPOSTISSET("url") ? GETPOST("url") : $object->url).'">';
} else {
print '<a href="'.(preg_match('/^http/i', $object->url) ? $object->url : DOL_URL_ROOT.$object->url).'"'.($object->target ? ' target="_blank"' : '').'>'.$object->url.'</a>';
}
print '</td></tr>'; print '</td></tr>';
print '<tr><td>'.$langs->trans("BehaviourOnClick").'</td><td>'; print '<tr><td>'.$langs->trans("BehaviourOnClick").'</td><td>';
if ($action == 'edit') if ($action == 'edit') {
{
$liste = array(1=>$langs->trans("OpenANewWindow"), 0=>$langs->trans("ReplaceWindow")); $liste = array(1=>$langs->trans("OpenANewWindow"), 0=>$langs->trans("ReplaceWindow"));
print $form->selectarray('target', $liste, GETPOSTISSET("target") ? GETPOST("target") : $object->target); print $form->selectarray('target', $liste, GETPOSTISSET("target") ? GETPOST("target") : $object->target);
} else { } else {
if ($object->target == 0) print $langs->trans("ReplaceWindow"); if ($object->target == 0) {
if ($object->target == 1) print $langs->trans("OpenANewWindow"); print $langs->trans("ReplaceWindow");
}
if ($object->target == 1) {
print $langs->trans("OpenANewWindow");
}
} }
print '</td></tr>'; print '</td></tr>';
print '<tr><td>'.$langs->trans("Owner").'</td><td>'; print '<tr><td>'.$langs->trans("Owner").'</td><td>';
if ($action == 'edit' && $user->admin) if ($action == 'edit' && $user->admin) {
{
print img_picto('', 'user').' '.$form->select_dolusers(GETPOSTISSET('userid') ? GETPOST('userid', 'int') : ($object->fk_user ? $object->fk_user : ''), 'userid', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); print img_picto('', 'user').' '.$form->select_dolusers(GETPOSTISSET('userid') ? GETPOST('userid', 'int') : ($object->fk_user ? $object->fk_user : ''), 'userid', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300');
} else { } else {
if ($object->fk_user > 0) if ($object->fk_user > 0) {
{
$fuser = new User($db); $fuser = new User($db);
$fuser->fetch($object->fk_user); $fuser->fetch($object->fk_user);
print $fuser->getNomUrl(1); print $fuser->getNomUrl(1);
@ -285,8 +293,11 @@ if ($id > 0 && !preg_match('/^add/i', $action))
// Position // Position
print '<tr><td>'.$langs->trans("Position").'</td><td>'; print '<tr><td>'.$langs->trans("Position").'</td><td>';
if ($action == 'edit') print '<input class="flat" name="position" size="5" value="'.(GETPOSTISSET("position") ? GETPOST("position", 'int') : $object->position).'">'; if ($action == 'edit') {
else print $object->position; print '<input class="flat" name="position" size="5" value="'.(GETPOSTISSET("position") ? GETPOST("position", 'int') : $object->position).'">';
} else {
print $object->position;
}
print '</td></tr>'; print '</td></tr>';
// Date creation // Date creation
@ -298,8 +309,7 @@ if ($id > 0 && !preg_match('/^add/i', $action))
print dol_get_fiche_end(); print dol_get_fiche_end();
if ($action == 'edit') if ($action == 'edit') {
{
print '<div align="center"><input class="button button-save" type="submit" name="save" value="'.$langs->trans("Save").'"> &nbsp; &nbsp; <input class="button button-cancel" type="submit" name="cancel" value="'.$langs->trans("Cancel").'"></div>'; print '<div align="center"><input class="button button-save" type="submit" name="save" value="'.$langs->trans("Save").'"> &nbsp; &nbsp; <input class="button button-cancel" type="submit" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
print '</form>'; print '</form>';
} }
@ -310,14 +320,12 @@ if ($id > 0 && !preg_match('/^add/i', $action))
print "<div class=\"tabsAction\">\n"; print "<div class=\"tabsAction\">\n";
// Edit // Edit
if ($user->rights->bookmark->creer && $action != 'edit') if ($user->rights->bookmark->creer && $action != 'edit') {
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit&amp;token='.newToken().'">'.$langs->trans("Edit").'</a>'."\n"; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit&amp;token='.newToken().'">'.$langs->trans("Edit").'</a>'."\n";
} }
// Remove // Remove
if ($user->rights->bookmark->supprimer && $action != 'edit') if ($user->rights->bookmark->supprimer && $action != 'edit') {
{
print '<a class="butActionDelete" href="list.php?bid='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans("Delete").'</a>'."\n"; print '<a class="butActionDelete" href="list.php?bid='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans("Delete").'</a>'."\n";
} }

View File

@ -45,12 +45,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
$page = 0;
} // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortfield) $sortfield = 'position'; if (!$sortfield) {
if (!$sortorder) $sortorder = 'ASC'; $sortfield = 'position';
}
if (!$sortorder) {
$sortorder = 'ASC';
}
$id = GETPOST("id", 'int'); $id = GETPOST("id", 'int');
@ -65,11 +71,9 @@ $permissiontodelete = $user->rights->bookmark->delete;
* Actions * Actions
*/ */
if ($action == 'delete') if ($action == 'delete') {
{
$res = $object->remove($id); $res = $object->remove($id);
if ($res > 0) if ($res > 0) {
{
header("Location: ".$_SERVER["PHP_SELF"]); header("Location: ".$_SERVER["PHP_SELF"]);
exit; exit;
} else { } else {
@ -93,32 +97,30 @@ $sql .= " u.login, u.lastname, u.firstname";
$sql .= " FROM ".MAIN_DB_PREFIX."bookmark as b LEFT JOIN ".MAIN_DB_PREFIX."user as u ON b.fk_user=u.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."bookmark as b LEFT JOIN ".MAIN_DB_PREFIX."user as u ON b.fk_user=u.rowid";
$sql .= " WHERE 1=1"; $sql .= " WHERE 1=1";
$sql .= " AND b.entity IN (".getEntity('bookmark').")"; $sql .= " AND b.entity IN (".getEntity('bookmark').")";
if (!$user->admin) $sql .= " AND (b.fk_user = ".$user->id." OR b.fk_user is NULL OR b.fk_user = 0)"; if (!$user->admin) {
$sql .= " AND (b.fk_user = ".$user->id." OR b.fk_user is NULL OR b.fk_user = 0)";
}
$sql .= $db->order($sortfield.", position", $sortorder); $sql .= $db->order($sortfield.", position", $sortorder);
// Count total nb of records // Count total nb of records
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$resql = $db->query($sql); $resql = $db->query($sql);
$nbtotalofrecords = $db->num_rows($resql); $nbtotalofrecords = $db->num_rows($resql);
if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
} }
// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) {
{
$num = $nbtotalofrecords; $num = $nbtotalofrecords;
} else { } else {
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
@ -127,9 +129,15 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords)
} }
$param = ""; $param = "";
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($optioncss != '') $param = '&optioncss='.urlencode($optioncss); }
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.urlencode($limit);
}
if ($optioncss != '') {
$param = '&optioncss='.urlencode($optioncss);
}
$moreforfilter = ''; $moreforfilter = '';
@ -140,12 +148,18 @@ $arrayofmassactions = array(
//'builddoc'=>$langs->trans("PDFMerge"), //'builddoc'=>$langs->trans("PDFMerge"),
//'presend'=>$langs->trans("SendByMail"), //'presend'=>$langs->trans("SendByMail"),
); );
if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if ($permissiontodelete) {
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
}
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -176,8 +190,7 @@ print "</tr>\n";
$cacheOfUsers = array(); $cacheOfUsers = array();
$i = 0; $i = 0;
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$object->id = $obj->rowid; $object->id = $obj->rowid;
@ -197,28 +210,39 @@ while ($i < min($num, $limit))
// Title // Title
print "<td>"; print "<td>";
$linkintern = 1; $linkintern = 1;
if ($linkintern) print '<a href="'.$obj->url.'">'; if ($linkintern) {
print '<a href="'.$obj->url.'">';
}
print $title; print $title;
if ($linkintern) print "</a>"; if ($linkintern) {
print "</a>";
}
print "</td>\n"; print "</td>\n";
// Url // Url
print '<td class="tdoverflowmax200">'; print '<td class="tdoverflowmax200">';
if (!$linkintern) print '<a href="'.$obj->url.'"'.($obj->target ? ' target="newlink" rel="noopener"' : '').'>'; if (!$linkintern) {
print '<a href="'.$obj->url.'"'.($obj->target ? ' target="newlink" rel="noopener"' : '').'>';
}
print $link; print $link;
if (!$linkintern) print '</a>'; if (!$linkintern) {
print '</a>';
}
print "</td>\n"; print "</td>\n";
// Target // Target
print '<td class="center">'; print '<td class="center">';
if ($obj->target == 0) print $langs->trans("BookmarkTargetReplaceWindowShort"); if ($obj->target == 0) {
if ($obj->target == 1) print $langs->trans("BookmarkTargetNewWindowShort"); print $langs->trans("BookmarkTargetReplaceWindowShort");
}
if ($obj->target == 1) {
print $langs->trans("BookmarkTargetNewWindowShort");
}
print "</td>\n"; print "</td>\n";
// Author // Author
print '<td class="center">'; print '<td class="center">';
if ($obj->fk_user) if ($obj->fk_user) {
{
if (empty($cacheOfUsers[$obj->fk_user])) { if (empty($cacheOfUsers[$obj->fk_user])) {
$tmpuser = new User($db); $tmpuser = new User($db);
$tmpuser->fetch($obj->fk_user); $tmpuser->fetch($obj->fk_user);
@ -239,12 +263,10 @@ while ($i < min($num, $limit))
// Actions // Actions
print '<td class="nowrap right">'; print '<td class="nowrap right">';
if ($user->rights->bookmark->creer) if ($user->rights->bookmark->creer) {
{
print '<a class="editfielda" href="'.DOL_URL_ROOT.'/bookmarks/card.php?action=edit&token='.newToken().'&id='.$obj->rowid.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'">'.img_edit()."</a>"; print '<a class="editfielda" href="'.DOL_URL_ROOT.'/bookmarks/card.php?action=edit&token='.newToken().'&id='.$obj->rowid.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'">'.img_edit()."</a>";
} }
if ($user->rights->bookmark->supprimer) if ($user->rights->bookmark->supprimer) {
{
print '<a class="marginleftonly" href="'.$_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&id='.$obj->rowid.'">'.img_delete().'</a>'; print '<a class="marginleftonly" href="'.$_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&id='.$obj->rowid.'">'.img_delete().'</a>';
} else { } else {
print "&nbsp;"; print "&nbsp;";

View File

@ -1182,7 +1182,7 @@ if ($resql) {
print_liste_field_titre($arrayfields['p.total_tva']['label'], $_SERVER["PHP_SELF"], 'p.total_tva', '', $param, 'class="right"', $sortfield, $sortorder); print_liste_field_titre($arrayfields['p.total_tva']['label'], $_SERVER["PHP_SELF"], 'p.total_tva', '', $param, 'class="right"', $sortfield, $sortorder);
} }
if (!empty($arrayfields['p.total_ttc']['checked'])) { if (!empty($arrayfields['p.total_ttc']['checked'])) {
print_liste_field_titre($arrayfields['p.total_ttc']['label'], $_SERVER["PHP_SELF"], 'p.total', '', $param, 'class="right"', $sortfield, $sortorder); print_liste_field_titre($arrayfields['p.total_ttc']['label'], $_SERVER["PHP_SELF"], 'p.total_ttc', '', $param, 'class="right"', $sortfield, $sortorder);
} }
if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) { if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) {
print_liste_field_titre($arrayfields['p.total_ht_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); print_liste_field_titre($arrayfields['p.total_ht_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder);

View File

@ -1273,8 +1273,7 @@ class FormMail extends Form
//print $sql; //print $sql;
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
return -1; return -1;
} }

View File

@ -1141,12 +1141,12 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
if ($date < $nextnewyeardate && $yearoffsettype == '+') { if ($date < $nextnewyeardate && $yearoffsettype == '+') {
$yearoffset = 1; $yearoffset = 1;
} }
} // If after or equal of current new year date } elseif ($date >= $newyeardate && $yearoffsettype == '-') {
elseif ($date >= $newyeardate && $yearoffsettype == '-') { // If after or equal of current new year date
$yearoffset = -1; $yearoffset = -1;
} }
} // For backward compatibility } elseif (date("m", $date) < $maskraz && empty($resetEveryMonth)) {
elseif (date("m", $date) < $maskraz && empty($resetEveryMonth)) { // For backward compatibility
$yearoffset = -1; $yearoffset = -1;
} // If current month lower that month of return to zero, year is previous year } // If current month lower that month of return to zero, year is previous year
@ -2121,8 +2121,7 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '')
$classpath = 'mrp/class'; $classpath = 'mrp/class';
$module = 'mrp'; $module = 'mrp';
$myobject = 'mo'; $myobject = 'mo';
} } elseif ($objecttype == 'productlot') {
elseif ($objecttype == 'productlot') {
$classpath = 'product/stock/class'; $classpath = 'product/stock/class';
$module = 'stock'; $module = 'stock';
$myobject = 'productlot'; $myobject = 'productlot';

View File

@ -32,22 +32,21 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/cron.lib.php';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('admin', 'cron')); $langs->loadLangs(array('admin', 'cron'));
if (!$user->admin) if (!$user->admin) {
accessforbidden(); accessforbidden();
}
$actionsave = GETPOST("save", 'alphanohtml'); $actionsave = GETPOST("save", 'alphanohtml');
// Save parameters // Save parameters
if (!empty($actionsave)) if (!empty($actionsave)) {
{
$i = 0; $i = 0;
$db->begin(); $db->begin();
$i += dolibarr_set_const($db, 'CRON_KEY', GETPOST("CRON_KEY"), 'chaine', 0, '', 0); $i += dolibarr_set_const($db, 'CRON_KEY', GETPOST("CRON_KEY"), 'chaine', 0, '', 0);
if ($i >= 1) if ($i >= 1) {
{
$db->commit(); $db->commit();
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
} else { } else {
@ -90,13 +89,15 @@ print "</tr>";
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td class="fieldrequired">'.$langs->trans("KeyForCronAccess").'</td>'; print '<td class="fieldrequired">'.$langs->trans("KeyForCronAccess").'</td>';
$disabled = ''; $disabled = '';
if (!empty($conf->global->CRON_DISABLE_KEY_CHANGE)) $disabled = ' disabled="disabled"'; if (!empty($conf->global->CRON_DISABLE_KEY_CHANGE)) {
$disabled = ' disabled="disabled"';
}
print '<td>'; print '<td>';
if (empty($conf->global->CRON_DISABLE_KEY_CHANGE)) if (empty($conf->global->CRON_DISABLE_KEY_CHANGE)) {
{
print '<input type="text" class="flat minwidth300"'.$disabled.' id="CRON_KEY" name="CRON_KEY" value="'.(GETPOST('CRON_KEY') ?GETPOST('CRON_KEY') : (!empty($conf->global->CRON_KEY) ? $conf->global->CRON_KEY : '')).'">'; print '<input type="text" class="flat minwidth300"'.$disabled.' id="CRON_KEY" name="CRON_KEY" value="'.(GETPOST('CRON_KEY') ?GETPOST('CRON_KEY') : (!empty($conf->global->CRON_KEY) ? $conf->global->CRON_KEY : '')).'">';
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
print '&nbsp;'.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"'); print '&nbsp;'.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"');
}
} else { } else {
print (!empty($conf->global->CRON_KEY) ? $conf->global->CRON_KEY : ''); print (!empty($conf->global->CRON_KEY) ? $conf->global->CRON_KEY : '');
print '<input type="hidden" id="CRON_KEY" name="CRON_KEY" value="'.(GETPOST('CRON_KEY') ?GETPOST('CRON_KEY') : (!empty($conf->global->CRON_KEY) ? $conf->global->CRON_KEY : '')).'">'; print '<input type="hidden" id="CRON_KEY" name="CRON_KEY" value="'.(GETPOST('CRON_KEY') ?GETPOST('CRON_KEY') : (!empty($conf->global->CRON_KEY) ? $conf->global->CRON_KEY : '')).'">';
@ -119,7 +120,9 @@ print '</form>';
print '<br><br><br>'; print '<br><br><br>';
//print $langs->trans("UseMenuModuleToolsToAddCronJobs", dol_buildpath('/cron/list.php?leftmenu=admintools', 1)).'<br>'; //print $langs->trans("UseMenuModuleToolsToAddCronJobs", dol_buildpath('/cron/list.php?leftmenu=admintools', 1)).'<br>';
if (!empty($conf->global->CRON_WARNING_DELAY_HOURS)) print info_admin($langs->trans("WarningCronDelayed", $conf->global->CRON_WARNING_DELAY_HOURS)).'<br>'; if (!empty($conf->global->CRON_WARNING_DELAY_HOURS)) {
print info_admin($langs->trans("WarningCronDelayed", $conf->global->CRON_WARNING_DELAY_HOURS)).'<br>';
}
print '<br>'; print '<br>';
@ -128,8 +131,7 @@ dol_print_cron_urls();
print '<br>'; print '<br>';
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
{
print "\n".'<script type="text/javascript">'; print "\n".'<script type="text/javascript">';
print '$(document).ready(function () { print '$(document).ready(function () {
$("#generate_token").click(function() { $("#generate_token").click(function() {

View File

@ -36,7 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/cron.lib.php';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array('admin', 'cron', 'members')); $langs->loadLangs(array('admin', 'cron', 'members'));
if (!$user->rights->cron->create) accessforbidden(); if (!$user->rights->cron->create) {
accessforbidden();
}
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
@ -53,23 +55,18 @@ $securitykey = GETPOST('securitykey', 'alpha');
*/ */
$object = new Cronjob($db); $object = new Cronjob($db);
if (!empty($id)) if (!empty($id)) {
{
$result = $object->fetch($id); $result = $object->fetch($id);
if ($result < 0) if ($result < 0) {
{
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
} }
} }
if (!empty($cancel)) if (!empty($cancel)) {
{ if (!empty($id) && empty($backtopage)) {
if (!empty($id) && empty($backtopage))
{
$action = ''; $action = '';
} else { } else {
if ($backtopage) if ($backtopage) {
{
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} else { } else {
@ -80,12 +77,10 @@ if (!empty($cancel))
} }
// Delete jobs // Delete jobs
if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->cron->delete) if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->cron->delete) {
{
$result = $object->delete($user); $result = $object->delete($user);
if ($result < 0) if ($result < 0) {
{
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
$action = 'edit'; $action = 'edit';
} else { } else {
@ -95,10 +90,8 @@ if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->cron->del
} }
// Execute jobs // Execute jobs
if ($action == 'confirm_execute' && $confirm == "yes" && $user->rights->cron->execute) if ($action == 'confirm_execute' && $confirm == "yes" && $user->rights->cron->execute) {
{ if (!empty($conf->global->CRON_KEY) && $conf->global->CRON_KEY != $securitykey) {
if (!empty($conf->global->CRON_KEY) && $conf->global->CRON_KEY != $securitykey)
{
setEventMessages('Security key '.$securitykey.' is wrong', null, 'errors'); setEventMessages('Security key '.$securitykey.' is wrong', null, 'errors');
$action = ''; $action = '';
} else { } else {
@ -106,16 +99,17 @@ if ($action == 'confirm_execute' && $confirm == "yes" && $user->rights->cron->ex
$result = $object->run_jobs($user->login); $result = $object->run_jobs($user->login);
if ($result < 0) if ($result < 0) {
{
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
$action = ''; $action = '';
} else { } else {
$res = $object->reprogram_jobs($user->login, $now); $res = $object->reprogram_jobs($user->login, $now);
if ($res > 0) if ($res > 0) {
{ if ($object->lastresult > 0) {
if ($object->lastresult > 0) setEventMessages($langs->trans("JobFinished"), null, 'warnings'); setEventMessages($langs->trans("JobFinished"), null, 'warnings');
else setEventMessages($langs->trans("JobFinished"), null, 'mesgs'); } else {
setEventMessages($langs->trans("JobFinished"), null, 'mesgs');
}
$action = ''; $action = '';
} else { } else {
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
@ -126,8 +120,7 @@ if ($action == 'confirm_execute' && $confirm == "yes" && $user->rights->cron->ex
} }
if ($action == 'add') if ($action == 'add') {
{
$object->jobtype = GETPOST('jobtype'); $object->jobtype = GETPOST('jobtype');
$object->label = GETPOST('label'); $object->label = GETPOST('label');
$object->command = GETPOST('command'); $object->command = GETPOST('command');
@ -160,8 +153,7 @@ if ($action == 'add')
} }
// Save parameters // Save parameters
if ($action == 'update') if ($action == 'update') {
{
$object->id = $id; $object->id = $id;
$object->jobtype = GETPOST('jobtype'); $object->jobtype = GETPOST('jobtype');
$object->label = GETPOST('label'); $object->label = GETPOST('label');
@ -194,8 +186,7 @@ if ($action == 'update')
} }
} }
if ($action == 'activate') if ($action == 'activate') {
{
$object->status = 1; $object->status = 1;
// Add cron task // Add cron task
@ -211,8 +202,7 @@ if ($action == 'activate')
} }
} }
if ($action == 'inactive') if ($action == 'inactive') {
{
$object->status = 0; $object->status = 0;
$object->processing = 0; $object->processing = 0;
@ -240,16 +230,13 @@ $formCron = new FormCron($db);
llxHeader('', $langs->trans("CronTask")); llxHeader('', $langs->trans("CronTask"));
if ($action == 'edit' || empty($action) || $action == 'delete' || $action == 'execute') if ($action == 'edit' || empty($action) || $action == 'delete' || $action == 'execute') {
{
$head = cron_prepare_head($object); $head = cron_prepare_head($object);
} elseif ($action == 'create') } elseif ($action == 'create') {
{
print load_fiche_titre($langs->trans("CronTask"), '', 'title_setup'); print load_fiche_titre($langs->trans("CronTask"), '', 'title_setup');
} }
if ($conf->use_javascript_ajax) if ($conf->use_javascript_ajax) {
{
print "\n".'<script type="text/javascript" language="javascript">'; print "\n".'<script type="text/javascript" language="javascript">';
print 'jQuery(document).ready(function () { print 'jQuery(document).ready(function () {
function initfields() function initfields()
@ -271,8 +258,7 @@ if ($conf->use_javascript_ajax)
print '</script>'."\n"; print '</script>'."\n";
} }
if ($action == 'delete') if ($action == 'delete') {
{
print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("CronDelete"), $langs->trans("CronConfirmDelete"), "confirm_delete", '', '', 1); print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("CronDelete"), $langs->trans("CronConfirmDelete"), "confirm_delete", '', '', 1);
$action = ''; $action = '';
@ -290,13 +276,11 @@ if ($action == 'execute') {
* Create Template * Create Template
*/ */
if (empty($object->status) && $action != 'create') if (empty($object->status) && $action != 'create') {
{
setEventMessages($langs->trans("CronTaskInactive"), null, 'warnings'); setEventMessages($langs->trans("CronTaskInactive"), null, 'warnings');
} }
if (($action == "create") || ($action == "edit")) if (($action == "create") || ($action == "edit")) {
{
print '<form name="cronform" action="'.$_SERVER["PHP_SELF"].'" method="post">'; print '<form name="cronform" action="'.$_SERVER["PHP_SELF"].'" method="post">';
print '<input type="hidden" name="token" value="'.newToken().'">'."\n"; print '<input type="hidden" name="token" value="'.newToken().'">'."\n";
print '<input type="hidden" name="backtopage" value="'.GETPOST('backtopage').'">'."\n"; print '<input type="hidden" name="backtopage" value="'.GETPOST('backtopage').'">'."\n";
@ -307,8 +291,11 @@ if (($action == "create") || ($action == "edit"))
print '<input type="hidden" name="action" value="add">'."\n"; print '<input type="hidden" name="action" value="add">'."\n";
} }
if ($action == "edit") print dol_get_fiche_head($head, 'card', $langs->trans("CronTask"), 0, 'cron'); if ($action == "edit") {
else print dol_get_fiche_head(''); print dol_get_fiche_head($head, 'card', $langs->trans("CronTask"), 0, 'cron');
} else {
print dol_get_fiche_head('');
}
print '<table class="border centpercent">'; print '<table class="border centpercent">';
@ -395,10 +382,8 @@ if (($action == "create") || ($action == "edit"))
print $langs->trans('CronEvery')."</td>"; print $langs->trans('CronEvery')."</td>";
print "<td>"; print "<td>";
print '<select name="nbfrequency">'; print '<select name="nbfrequency">';
for ($i = 1; $i <= 60; $i++) for ($i = 1; $i <= 60; $i++) {
{ if ($object->frequency == $i) {
if ($object->frequency == $i)
{
print "<option value='".$i."' selected>".$i."</option>"; print "<option value='".$i."' selected>".$i."</option>";
} else { } else {
print "<option value='".$i."'>".$i."</option>"; print "<option value='".$i."'>".$i."</option>";
@ -406,8 +391,7 @@ if (($action == "create") || ($action == "edit"))
} }
print "</select>"; print "</select>";
$input = " <input type=\"radio\" name=\"unitfrequency\" value=\"60\" id=\"frequency_minute\" "; $input = " <input type=\"radio\" name=\"unitfrequency\" value=\"60\" id=\"frequency_minute\" ";
if ($object->unitfrequency == "60") if ($object->unitfrequency == "60") {
{
$input .= ' checked />'; $input .= ' checked />';
} else { } else {
$input .= ' />'; $input .= ' />';
@ -448,8 +432,7 @@ if (($action == "create") || ($action == "edit"))
print "<tr><td>"; print "<tr><td>";
print $langs->trans('CronDtStart')."</td><td>"; print $langs->trans('CronDtStart')."</td><td>";
if (!empty($object->datestart)) if (!empty($object->datestart)) {
{
print $form->selectDate($object->datestart, 'datestart', 1, 1, '', "cronform"); print $form->selectDate($object->datestart, 'datestart', 1, 1, '', "cronform");
} else { } else {
print $form->selectDate('', 'datestart', 1, 1, '', "cronform"); print $form->selectDate('', 'datestart', 1, 1, '', "cronform");
@ -499,8 +482,7 @@ if (($action == "create") || ($action == "edit"))
print $langs->trans('CronDtNextLaunch'); print $langs->trans('CronDtNextLaunch');
print ' ('.$langs->trans('CronFrom').')'; print ' ('.$langs->trans('CronFrom').')';
print "</td><td>"; print "</td><td>";
if (!empty($object->datenextrun)) if (!empty($object->datenextrun)) {
{
print $form->selectDate($object->datenextrun, 'datenextrun', 1, 1, '', "cronform"); print $form->selectDate($object->datenextrun, 'datenextrun', 1, 1, '', "cronform");
} else { } else {
print $form->selectDate(-1, 'datenextrun', 1, 1, '', "cronform"); print $form->selectDate(-1, 'datenextrun', 1, 1, '', "cronform");
@ -588,12 +570,10 @@ if (($action == "create") || ($action == "edit"))
} }
print "</td></tr>"; print "</td></tr>";
if (!empty($conf->multicompany->enabled)) if (!empty($conf->multicompany->enabled)) {
{
print '<tr><td>'; print '<tr><td>';
print $langs->trans('Entity')."</td><td>"; print $langs->trans('Entity')."</td><td>";
if (!$object->entity) if (!$object->entity) {
{
print $langs->trans("AllEntities"); print $langs->trans("AllEntities");
} else { } else {
$mc->getInfo($object->entity); $mc->getInfo($object->entity);
@ -615,20 +595,32 @@ if (($action == "create") || ($action == "edit"))
print '<tr><td class="titlefield">'; print '<tr><td class="titlefield">';
print $langs->trans('CronEvery')."</td>"; print $langs->trans('CronEvery')."</td>";
print "<td>"; print "<td>";
if ($object->unitfrequency == "60") print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Minutes'); if ($object->unitfrequency == "60") {
if ($object->unitfrequency == "3600") print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Hours'); print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Minutes');
if ($object->unitfrequency == "86400") print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Days'); }
if ($object->unitfrequency == "604800") print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Weeks'); if ($object->unitfrequency == "3600") {
print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Hours');
}
if ($object->unitfrequency == "86400") {
print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Days');
}
if ($object->unitfrequency == "604800") {
print $langs->trans('CronEach')." ".($object->frequency)." ".$langs->trans('Weeks');
}
print "</td></tr>"; print "</td></tr>";
print '<tr><td>'; print '<tr><td>';
print $langs->trans('CronDtStart')."</td><td>"; print $langs->trans('CronDtStart')."</td><td>";
if (!empty($object->datestart)) {print $form->textwithpicto(dol_print_date($object->datestart, 'dayhoursec'), $langs->trans("CurrentTimeZone")); } if (!empty($object->datestart)) {
print $form->textwithpicto(dol_print_date($object->datestart, 'dayhoursec'), $langs->trans("CurrentTimeZone"));
}
print "</td></tr>"; print "</td></tr>";
print "<tr><td>"; print "<tr><td>";
print $langs->trans('CronDtEnd')."</td><td>"; print $langs->trans('CronDtEnd')."</td><td>";
if (!empty($object->dateend)) {print $form->textwithpicto(dol_print_date($object->dateend, 'dayhoursec'), $langs->trans("CurrentTimeZone")); } if (!empty($object->dateend)) {
print $form->textwithpicto(dol_print_date($object->dateend, 'dayhoursec'), $langs->trans("CurrentTimeZone"));
}
print "</td></tr>"; print "</td></tr>";
print "<tr><td>"; print "<tr><td>";
@ -652,12 +644,19 @@ if (($action == "create") || ($action == "edit"))
print $langs->trans('CronDtNextLaunch'); print $langs->trans('CronDtNextLaunch');
print ' ('.$langs->trans('CronFrom').')'; print ' ('.$langs->trans('CronFrom').')';
print "</td><td>"; print "</td><td>";
if (!$object->status) print $langs->trans("Disabled"); if (!$object->status) {
elseif (!empty($object->datenextrun)) { print img_picto('', 'object_calendarday').' '.$form->textwithpicto(dol_print_date($object->datenextrun, 'dayhoursec'), $langs->trans("CurrentTimeZone")); } else { print $langs->trans('CronNone'); } print $langs->trans("Disabled");
if ($object->status == Cronjob::STATUS_ENABLED) } elseif (!empty($object->datenextrun)) {
{ print img_picto('', 'object_calendarday').' '.$form->textwithpicto(dol_print_date($object->datenextrun, 'dayhoursec'), $langs->trans("CurrentTimeZone"));
if ($object->maxrun && $object->nbrun >= $object->maxrun) print img_warning($langs->trans("MaxRunReached")); } else {
elseif ($object->datenextrun && $object->datenextrun < $now) print img_warning($langs->trans("Late")); print $langs->trans('CronNone');
}
if ($object->status == Cronjob::STATUS_ENABLED) {
if ($object->maxrun && $object->nbrun >= $object->maxrun) {
print img_warning($langs->trans("MaxRunReached"));
} elseif ($object->datenextrun && $object->datenextrun < $now) {
print img_warning($langs->trans("Late"));
}
} }
print "</td></tr>"; print "</td></tr>";
@ -672,19 +671,31 @@ if (($action == "create") || ($action == "edit"))
print '<tr><td class="titlefield">'; print '<tr><td class="titlefield">';
print $langs->trans('CronDtLastLaunch')."</td><td>"; print $langs->trans('CronDtLastLaunch')."</td><td>";
if (!empty($object->datelastrun)) {print $form->textwithpicto(dol_print_date($object->datelastrun, 'dayhoursec'), $langs->trans("CurrentTimeZone")); } else {print $langs->trans('CronNone'); } if (!empty($object->datelastrun)) {
print $form->textwithpicto(dol_print_date($object->datelastrun, 'dayhoursec'), $langs->trans("CurrentTimeZone"));
} else {
print $langs->trans('CronNone');
}
print "</td></tr>"; print "</td></tr>";
print '<tr><td>'; print '<tr><td>';
print $langs->trans('CronDtLastResult')."</td><td>"; print $langs->trans('CronDtLastResult')."</td><td>";
if (!empty($object->datelastresult)) {print $form->textwithpicto(dol_print_date($object->datelastresult, 'dayhoursec'), $langs->trans("CurrentTimeZone")); } else {print $langs->trans('CronNone'); } if (!empty($object->datelastresult)) {
print $form->textwithpicto(dol_print_date($object->datelastresult, 'dayhoursec'), $langs->trans("CurrentTimeZone"));
} else {
print $langs->trans('CronNone');
}
print "</td></tr>"; print "</td></tr>";
print '<tr><td>'; print '<tr><td>';
print $langs->trans('CronLastResult')."</td><td>"; print $langs->trans('CronLastResult')."</td><td>";
if ($object->lastresult) print '<span class="error">'; if ($object->lastresult) {
print '<span class="error">';
}
print $object->lastresult; print $object->lastresult;
if ($object->lastresult) print '</span>'; if ($object->lastresult) {
print '</span>';
}
print "</td></tr>"; print "</td></tr>";
print '<tr><td>'; print '<tr><td>';
@ -705,11 +716,9 @@ if (($action == "create") || ($action == "edit"))
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&id='.$object->id.'">'.$langs->trans("Edit").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&id='.$object->id.'">'.$langs->trans("Edit").'</a>';
} }
if ((empty($user->rights->cron->execute))) if ((empty($user->rights->cron->execute))) {
{
print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("CronExecute").'</a>'; print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("CronExecute").'</a>';
} elseif (empty($object->status)) } elseif (empty($object->status)) {
{
print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("JobDisabled")).'">'.$langs->trans("CronExecute").'</a>'; print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("JobDisabled")).'">'.$langs->trans("CronExecute").'</a>';
} else { } else {
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=execute&id='.$object->id.(empty($conf->global->CRON_KEY) ? '' : '&securitykey='.$conf->global->CRON_KEY).'">'.$langs->trans("CronExecute").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=execute&id='.$object->id.(empty($conf->global->CRON_KEY) ? '' : '&securitykey='.$conf->global->CRON_KEY).'">'.$langs->trans("CronExecute").'</a>';

View File

@ -199,30 +199,66 @@ class Cronjob extends CommonObject
// Clean parameters // Clean parameters
if (isset($this->label)) $this->label = trim($this->label); if (isset($this->label)) {
if (isset($this->jobtype)) $this->jobtype = trim($this->jobtype); $this->label = trim($this->label);
if (isset($this->command)) $this->command = trim($this->command); }
if (isset($this->classesname)) $this->classesname = trim($this->classesname); if (isset($this->jobtype)) {
if (isset($this->objectname)) $this->objectname = trim($this->objectname); $this->jobtype = trim($this->jobtype);
if (isset($this->methodename)) $this->methodename = trim($this->methodename); }
if (isset($this->params)) $this->params = trim($this->params); if (isset($this->command)) {
if (isset($this->md5params)) $this->md5params = trim($this->md5params); $this->command = trim($this->command);
if (isset($this->module_name)) $this->module_name = trim($this->module_name); }
if (isset($this->priority)) $this->priority = trim($this->priority); if (isset($this->classesname)) {
if (isset($this->lastoutput)) $this->lastoutput = trim($this->lastoutput); $this->classesname = trim($this->classesname);
if (isset($this->lastresult)) $this->lastresult = trim($this->lastresult); }
if (isset($this->unitfrequency)) $this->unitfrequency = trim($this->unitfrequency); if (isset($this->objectname)) {
if (isset($this->frequency)) $this->frequency = trim($this->frequency); $this->objectname = trim($this->objectname);
if (isset($this->status)) $this->status = trim($this->status); }
if (isset($this->note_private)) $this->note_private = trim($this->note_private); if (isset($this->methodename)) {
$this->methodename = trim($this->methodename);
}
if (isset($this->params)) {
$this->params = trim($this->params);
}
if (isset($this->md5params)) {
$this->md5params = trim($this->md5params);
}
if (isset($this->module_name)) {
$this->module_name = trim($this->module_name);
}
if (isset($this->priority)) {
$this->priority = trim($this->priority);
}
if (isset($this->lastoutput)) {
$this->lastoutput = trim($this->lastoutput);
}
if (isset($this->lastresult)) {
$this->lastresult = trim($this->lastresult);
}
if (isset($this->unitfrequency)) {
$this->unitfrequency = trim($this->unitfrequency);
}
if (isset($this->frequency)) {
$this->frequency = trim($this->frequency);
}
if (isset($this->status)) {
$this->status = trim($this->status);
}
if (isset($this->note_private)) {
$this->note_private = trim($this->note_private);
}
if (isset($this->nbrun)) { if (isset($this->nbrun)) {
$this->nbrun = (int) $this->nbrun; $this->nbrun = (int) $this->nbrun;
} }
if (isset($this->maxrun)) { if (isset($this->maxrun)) {
$this->maxrun = (int) $this->maxrun; $this->maxrun = (int) $this->maxrun;
} }
if (isset($this->libname)) $this->libname = trim($this->libname); if (isset($this->libname)) {
if (isset($this->test)) $this->test = trim($this->test); $this->libname = trim($this->libname);
}
if (isset($this->test)) {
$this->test = trim($this->test);
}
// Check parameters // Check parameters
// Put here code to add a control on parameters values // Put here code to add a control on parameters values
@ -335,16 +371,13 @@ class Cronjob extends CommonObject
$this->errors[] = "Error ".$this->db->lasterror(); $this->errors[] = "Error ".$this->db->lasterror();
} }
if (!$error) if (!$error) {
{
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."cronjob"); $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."cronjob");
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -411,10 +444,8 @@ class Cronjob extends CommonObject
dol_syslog(get_class($this)."::fetch", LOG_DEBUG); dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{ if ($this->db->num_rows($resql)) {
if ($this->db->num_rows($resql))
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid; $this->id = $obj->rowid;
@ -514,15 +545,22 @@ class Cronjob extends CommonObject
$sql .= " t.test"; $sql .= " t.test";
$sql .= " FROM ".MAIN_DB_PREFIX."cronjob as t"; $sql .= " FROM ".MAIN_DB_PREFIX."cronjob as t";
$sql .= " WHERE 1 = 1"; $sql .= " WHERE 1 = 1";
if ($processing >= 0) $sql .= " AND t.processing = ".(empty($processing) ? '0' : '1'); if ($processing >= 0) {
if ($status >= 0 && $status < 2) $sql .= " AND t.status = ".(empty($status) ? '0' : '1'); $sql .= " AND t.processing = ".(empty($processing) ? '0' : '1');
elseif ($status == 2) $sql .= " AND t.status = 2"; }
if ($status >= 0 && $status < 2) {
$sql .= " AND t.status = ".(empty($status) ? '0' : '1');
} elseif ($status == 2) {
$sql .= " AND t.status = 2";
}
//Manage filter //Manage filter
if (is_array($filter) && count($filter) > 0) { if (is_array($filter) && count($filter) > 0) {
foreach ($filter as $key => $value) foreach ($filter as $key => $value) {
{ if ($key == 't.rowid') {
if ($key == 't.rowid') $sql .= ' AND '.$key.' = '.$this->db->escape($value); $sql .= ' AND '.$key.' = '.$this->db->escape($value);
else $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\''; } else {
$sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\'';
}
} }
} }
@ -539,15 +577,12 @@ class Cronjob extends CommonObject
dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
if ($num) if ($num) {
{ while ($i < $num) {
while ($i < $num)
{
$line = new Cronjobline(); $line = new Cronjobline();
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
@ -615,28 +650,70 @@ class Cronjob extends CommonObject
$error = 0; $error = 0;
// Clean parameters // Clean parameters
if (isset($this->label)) $this->label = trim($this->label); if (isset($this->label)) {
if (isset($this->jobtype)) $this->jobtype = trim($this->jobtype); $this->label = trim($this->label);
if (isset($this->command)) $this->command = trim($this->command); }
if (isset($this->classesname)) $this->classesname = trim($this->classesname); if (isset($this->jobtype)) {
if (isset($this->objectname)) $this->objectname = trim($this->objectname); $this->jobtype = trim($this->jobtype);
if (isset($this->methodename)) $this->methodename = trim($this->methodename); }
if (isset($this->params)) $this->params = trim($this->params); if (isset($this->command)) {
if (isset($this->md5params)) $this->md5params = trim($this->md5params); $this->command = trim($this->command);
if (isset($this->module_name)) $this->module_name = trim($this->module_name); }
if (isset($this->priority)) $this->priority = trim($this->priority); if (isset($this->classesname)) {
if (isset($this->lastoutput)) $this->lastoutput = trim($this->lastoutput); $this->classesname = trim($this->classesname);
if (isset($this->lastresult)) $this->lastresult = trim($this->lastresult); }
if (isset($this->unitfrequency)) $this->unitfrequency = trim($this->unitfrequency); if (isset($this->objectname)) {
if (isset($this->frequency)) $this->frequency = trim($this->frequency); $this->objectname = trim($this->objectname);
if (isset($this->status)) $this->status = trim($this->status); }
if (isset($this->note_private)) $this->note_private = trim($this->note_private); if (isset($this->methodename)) {
if (isset($this->nbrun)) $this->nbrun = trim($this->nbrun); $this->methodename = trim($this->methodename);
if (isset($this->libname)) $this->libname = trim($this->libname); }
if (isset($this->test)) $this->test = trim($this->test); if (isset($this->params)) {
$this->params = trim($this->params);
}
if (isset($this->md5params)) {
$this->md5params = trim($this->md5params);
}
if (isset($this->module_name)) {
$this->module_name = trim($this->module_name);
}
if (isset($this->priority)) {
$this->priority = trim($this->priority);
}
if (isset($this->lastoutput)) {
$this->lastoutput = trim($this->lastoutput);
}
if (isset($this->lastresult)) {
$this->lastresult = trim($this->lastresult);
}
if (isset($this->unitfrequency)) {
$this->unitfrequency = trim($this->unitfrequency);
}
if (isset($this->frequency)) {
$this->frequency = trim($this->frequency);
}
if (isset($this->status)) {
$this->status = trim($this->status);
}
if (isset($this->note_private)) {
$this->note_private = trim($this->note_private);
}
if (isset($this->nbrun)) {
$this->nbrun = trim($this->nbrun);
}
if (isset($this->libname)) {
$this->libname = trim($this->libname);
}
if (isset($this->test)) {
$this->test = trim($this->test);
}
if (empty($this->maxrun)) $this->maxrun = 0; if (empty($this->maxrun)) {
if (empty($this->processing)) $this->processing = 0; $this->maxrun = 0;
}
if (empty($this->processing)) {
$this->processing = 0;
}
// Check parameters // Check parameters
// Put here code to add a control on parameters values // Put here code to add a control on parameters values
@ -715,13 +792,13 @@ class Cronjob extends CommonObject
dol_syslog(get_class($this)."::update", LOG_DEBUG); dol_syslog(get_class($this)."::update", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } if (!$resql) {
$error++; $this->errors[] = "Error ".$this->db->lasterror();
}
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -758,10 +835,8 @@ class Cronjob extends CommonObject
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@ -803,8 +878,7 @@ class Cronjob extends CommonObject
$result = $object->create($user); $result = $object->create($user);
// Other options // Other options
if ($result < 0) if ($result < 0) {
{
$this->error = $object->error; $this->error = $object->error;
$error++; $error++;
} }
@ -817,8 +891,7 @@ class Cronjob extends CommonObject
unset($object->context['createfromclone']); unset($object->context['createfromclone']);
// End // End
if (!$error) if (!$error) {
{
$this->db->commit(); $this->db->commit();
return $object->id; return $object->id;
} else { } else {
@ -887,7 +960,9 @@ class Cronjob extends CommonObject
global $dolibarr_main_authentication, $dolibarr_main_demo; global $dolibarr_main_authentication, $dolibarr_main_demo;
global $menumanager; global $menumanager;
if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips if (!empty($conf->dol_no_mouse_hover)) {
$notooltip = 1; // Force disable tooltips
}
$result = ''; $result = '';
@ -900,33 +975,40 @@ class Cronjob extends CommonObject
$url = DOL_URL_ROOT.'/cron/card.php?id='.$this->id; $url = DOL_URL_ROOT.'/cron/card.php?id='.$this->id;
if ($option != 'nolink') if ($option != 'nolink') {
{
// Add param to save lastsearch_values or not // Add param to save lastsearch_values or not
$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; $add_save_lastsearch_values = 1;
}
if ($add_save_lastsearch_values) {
$url .= '&save_lastsearch_values=1';
}
} }
$linkclose = ''; $linkclose = '';
if (empty($notooltip)) if (empty($notooltip)) {
{ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label = $langs->trans("ShowCronJob"); $label = $langs->trans("ShowCronJob");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } else {
$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
}
$linkstart = '<a href="'.$url.'"'; $linkstart = '<a href="'.$url.'"';
$linkstart .= $linkclose.'>'; $linkstart .= $linkclose.'>';
$linkend = '</a>'; $linkend = '</a>';
$result .= $linkstart; $result .= $linkstart;
if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); if ($withpicto) {
if ($withpicto != 2) $result .= $this->ref; $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
}
if ($withpicto != 2) {
$result .= $this->ref;
}
$result .= $linkend; $result .= $linkend;
//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
@ -949,10 +1031,8 @@ class Cronjob extends CommonObject
dol_syslog(get_class($this)."::fetch", LOG_DEBUG); dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{ if ($this->db->num_rows($resql)) {
if ($this->db->num_rows($resql))
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid; $this->id = $obj->rowid;
$this->date_creation = $this->db->jdate($obj->datec); $this->date_creation = $this->db->jdate($obj->datec);
@ -992,8 +1072,7 @@ class Cronjob extends CommonObject
$langs->load('cron'); $langs->load('cron');
if (empty($userlogin)) if (empty($userlogin)) {
{
$this->error = "User login is mandatory"; $this->error = "User login is mandatory";
dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
return -1; return -1;
@ -1001,8 +1080,7 @@ class Cronjob extends CommonObject
// Force the environment of running to the environment declared for job, so jobs launched from command line will run into correct environment // Force the environment of running to the environment declared for job, so jobs launched from command line will run into correct environment
// When job is ran from GUI, the environment should already be same, except if job has entity 0 (visible into all environments) // When job is ran from GUI, the environment should already be same, except if job has entity 0 (visible into all environments)
if ($conf->entity != $this->entity && $this->entity > 0) if ($conf->entity != $this->entity && $this->entity > 0) {
{
dol_syslog("We try to run a job in entity ".$this->entity." when we are in entity ".$conf->entity, LOG_WARNING); dol_syslog("We try to run a job in entity ".$this->entity." when we are in entity ".$conf->entity, LOG_WARNING);
} }
$savcurrententity = $conf->entity; $savcurrententity = $conf->entity;
@ -1012,15 +1090,13 @@ class Cronjob extends CommonObject
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
$user = new User($this->db); $user = new User($this->db);
$result = $user->fetch('', $userlogin); $result = $user->fetch('', $userlogin);
if ($result < 0) if ($result < 0) {
{
$this->error = "User Error:".$user->error; $this->error = "User Error:".$user->error;
dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
$conf->entity = $savcurrententity; $conf->entity = $savcurrententity;
return -1; return -1;
} else { } else {
if (empty($user->id)) if (empty($user->id)) {
{
$this->error = " User user login:".$userlogin." do not exists"; $this->error = " User user login:".$userlogin." do not exists";
dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
$conf->entity = $savcurrententity; $conf->entity = $savcurrententity;
@ -1032,16 +1108,14 @@ class Cronjob extends CommonObject
// Increase limit of time. Works only if we are not in safe mode // Increase limit of time. Works only if we are not in safe mode
$ExecTimeLimit = 600; $ExecTimeLimit = 600;
if (!empty($ExecTimeLimit)) if (!empty($ExecTimeLimit)) {
{
$err = error_reporting(); $err = error_reporting();
error_reporting(0); // Disable all errors error_reporting(0); // Disable all errors
//error_reporting(E_ALL); //error_reporting(E_ALL);
@set_time_limit($ExecTimeLimit); // Need more than 240 on Windows 7/64 @set_time_limit($ExecTimeLimit); // Need more than 240 on Windows 7/64
error_reporting($err); error_reporting($err);
} }
if (!empty($MemoryLimit)) if (!empty($MemoryLimit)) {
{
@ini_set('memory_limit', $MemoryLimit); @ini_set('memory_limit', $MemoryLimit);
} }
@ -1060,16 +1134,16 @@ class Cronjob extends CommonObject
} }
// Run a method // Run a method
if ($this->jobtype == 'method') if ($this->jobtype == 'method') {
{
// load classes // load classes
if (!$error) if (!$error) {
{
$ret = dol_include_once($this->classesname); $ret = dol_include_once($this->classesname);
if ($ret === false || (!class_exists($this->objectname))) if ($ret === false || (!class_exists($this->objectname))) {
{ if ($ret === false) {
if ($ret === false) $this->error = $langs->trans('CronCannotLoadClass', $this->classesname, $this->objectname); $this->error = $langs->trans('CronCannotLoadClass', $this->classesname, $this->objectname);
else $this->error = $langs->trans('CronCannotLoadObject', $this->classesname, $this->objectname); } else {
$this->error = $langs->trans('CronCannotLoadObject', $this->classesname, $this->objectname);
}
dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
$this->lastoutput = $this->error; $this->lastoutput = $this->error;
$this->lastresult = -1; $this->lastresult = -1;
@ -1079,10 +1153,8 @@ class Cronjob extends CommonObject
} }
// test if method exists // test if method exists
if (!$error) if (!$error) {
{ if (!method_exists($this->objectname, $this->methodename)) {
if (!method_exists($this->objectname, $this->methodename))
{
$this->error = $langs->trans('CronMethodDoesNotExists', $this->objectname, $this->methodename); $this->error = $langs->trans('CronMethodDoesNotExists', $this->objectname, $this->methodename);
dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
$this->lastoutput = $this->error; $this->lastoutput = $this->error;
@ -1090,8 +1162,7 @@ class Cronjob extends CommonObject
$retval = $this->lastresult; $retval = $this->lastresult;
$error++; $error++;
} }
if (in_array(strtolower(trim($this->methodename)), array('executecli'))) if (in_array(strtolower(trim($this->methodename)), array('executecli'))) {
{
$this->error = $langs->trans('CronMethodNotAllowed', $this->methodename, $this->objectname); $this->error = $langs->trans('CronMethodNotAllowed', $this->methodename, $this->objectname);
dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
$this->lastoutput = $this->error; $this->lastoutput = $this->error;
@ -1102,13 +1173,11 @@ class Cronjob extends CommonObject
} }
// Load langs // Load langs
if (!$error) if (!$error) {
{
$result = $langs->load($this->module_name); $result = $langs->load($this->module_name);
$result = $langs->load($this->module_name.'@'.$this->module_name, 0, 0, '', 0, 1); $result = $langs->load($this->module_name.'@'.$this->module_name, 0, 0, '', 0, 1);
if ($result < 0) // If technical error if ($result < 0) { // If technical error
{
dol_syslog(get_class($this)."::run_jobs Cannot load module lang file - ".$langs->error, LOG_ERR); dol_syslog(get_class($this)."::run_jobs Cannot load module lang file - ".$langs->error, LOG_ERR);
$this->error = $langs->error; $this->error = $langs->error;
$this->lastoutput = $this->error; $this->lastoutput = $this->error;
@ -1118,34 +1187,39 @@ class Cronjob extends CommonObject
} }
} }
if (!$error) if (!$error) {
{
dol_syslog(get_class($this)."::run_jobs START ".$this->objectname."->".$this->methodename."(".$this->params.");", LOG_DEBUG); dol_syslog(get_class($this)."::run_jobs START ".$this->objectname."->".$this->methodename."(".$this->params.");", LOG_DEBUG);
// Create Object for the called module // Create Object for the called module
$object = new $this->objectname($this->db); $object = new $this->objectname($this->db);
if ($this->entity > 0) $object->entity = $this->entity; // We work on a dedicated entity if ($this->entity > 0) {
$object->entity = $this->entity; // We work on a dedicated entity
}
$params_arr = array(); $params_arr = array();
if (!empty($this->params) || $this->params === '0') { if (!empty($this->params) || $this->params === '0') {
$params_arr = array_map('trim', explode(",", $this->params)); $params_arr = array_map('trim', explode(",", $this->params));
} }
if (!is_array($params_arr)) if (!is_array($params_arr)) {
{
$result = call_user_func(array($object, $this->methodename), $this->params); $result = call_user_func(array($object, $this->methodename), $this->params);
} else { } else {
$result = call_user_func_array(array($object, $this->methodename), $params_arr); $result = call_user_func_array(array($object, $this->methodename), $params_arr);
} }
if ($result === false || (!is_bool($result) && $result != 0)) if ($result === false || (!is_bool($result) && $result != 0)) {
{
$langs->load("errors"); $langs->load("errors");
$errmsg = ''; $errmsg = '';
if (!is_array($object->errors) || !in_array($object->error, $object->errors)) $errmsg .= $object->error; if (!is_array($object->errors) || !in_array($object->error, $object->errors)) {
if (is_array($object->errors) && count($object->errors)) $errmsg .= (($errmsg ? ', ' : '').join(', ', $object->errors)); $errmsg .= $object->error;
if (empty($errmsg)) $errmsg = $langs->trans('ErrorUnknown'); }
if (is_array($object->errors) && count($object->errors)) {
$errmsg .= (($errmsg ? ', ' : '').join(', ', $object->errors));
}
if (empty($errmsg)) {
$errmsg = $langs->trans('ErrorUnknown');
}
dol_syslog(get_class($this)."::run_jobs END result=".$result." error=".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::run_jobs END result=".$result." error=".$errmsg, LOG_ERR);
@ -1167,8 +1241,7 @@ class Cronjob extends CommonObject
//load lib //load lib
$libpath = '/'.strtolower($this->module_name).'/lib/'.$this->libname; $libpath = '/'.strtolower($this->module_name).'/lib/'.$this->libname;
$ret = dol_include_once($libpath); $ret = dol_include_once($libpath);
if ($ret === false) if ($ret === false) {
{
$this->error = $langs->trans('CronCannotLoadLib').': '.$libpath; $this->error = $langs->trans('CronCannotLoadLib').': '.$libpath;
dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
$conf->entity = $savcurrententity; $conf->entity = $savcurrententity;
@ -1178,8 +1251,7 @@ class Cronjob extends CommonObject
// Load langs // Load langs
$result = $langs->load($this->module_name); $result = $langs->load($this->module_name);
$result = $langs->load($this->module_name.'@'.$this->module_name); // If this->module_name was an existing language file, this will make nothing $result = $langs->load($this->module_name.'@'.$this->module_name); // If this->module_name was an existing language file, this will make nothing
if ($result < 0) // If technical error if ($result < 0) { // If technical error
{
dol_syslog(get_class($this)."::run_jobs Cannot load module langs".$langs->error, LOG_ERR); dol_syslog(get_class($this)."::run_jobs Cannot load module langs".$langs->error, LOG_ERR);
$conf->entity = $savcurrententity; $conf->entity = $savcurrententity;
return -1; return -1;
@ -1187,15 +1259,13 @@ class Cronjob extends CommonObject
dol_syslog(get_class($this)."::run_jobs ".$this->libname."::".$this->methodename."(".$this->params.");", LOG_DEBUG); dol_syslog(get_class($this)."::run_jobs ".$this->libname."::".$this->methodename."(".$this->params.");", LOG_DEBUG);
$params_arr = explode(", ", $this->params); $params_arr = explode(", ", $this->params);
if (!is_array($params_arr)) if (!is_array($params_arr)) {
{
$result = call_user_func($this->methodename, $this->params); $result = call_user_func($this->methodename, $this->params);
} else { } else {
$result = call_user_func_array($this->methodename, $params_arr); $result = call_user_func_array($this->methodename, $params_arr);
} }
if ($result === false || (!is_bool($result) && $result != 0)) if ($result === false || (!is_bool($result) && $result != 0)) {
{
$langs->load("errors"); $langs->load("errors");
dol_syslog(get_class($this)."::run_jobs result=".$result, LOG_ERR); dol_syslog(get_class($this)."::run_jobs result=".$result, LOG_ERR);
$this->error = $langs->trans('ErrorUnknown'); $this->error = $langs->trans('ErrorUnknown');
@ -1211,8 +1281,7 @@ class Cronjob extends CommonObject
} }
// Run a command line // Run a command line
if ($this->jobtype == 'command') if ($this->jobtype == 'command') {
{
global $dolibarr_cron_allow_cli; global $dolibarr_cron_allow_cli;
if (empty($dolibarr_cron_allow_cli)) { if (empty($dolibarr_cron_allow_cli)) {
@ -1222,10 +1291,11 @@ class Cronjob extends CommonObject
$this->lastresult = $langs->trans("ErrorParameterMustBeEnabledToAllwoThisFeature", 'dolibarr_cron_allow_cli'); $this->lastresult = $langs->trans("ErrorParameterMustBeEnabledToAllwoThisFeature", 'dolibarr_cron_allow_cli');
} else { } else {
$outputdir = $conf->cron->dir_temp; $outputdir = $conf->cron->dir_temp;
if (empty($outputdir)) $outputdir = $conf->cronjob->dir_temp; if (empty($outputdir)) {
$outputdir = $conf->cronjob->dir_temp;
}
if (!empty($outputdir)) if (!empty($outputdir)) {
{
dol_mkdir($outputdir); dol_mkdir($outputdir);
$outputfile = $outputdir.'/cronjob.'.$userlogin.'.out'; // File used with popen method $outputfile = $outputdir.'/cronjob.'.$userlogin.'.out'; // File used with popen method
@ -1247,8 +1317,7 @@ class Cronjob extends CommonObject
$this->datelastresult = dol_now(); $this->datelastresult = dol_now();
$this->processing = 0; $this->processing = 0;
$result = $this->update($user); // This include begin/commit $result = $this->update($user); // This include begin/commit
if ($result < 0) if ($result < 0) {
{
dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR); dol_syslog(get_class($this)."::run_jobs ".$this->error, LOG_ERR);
$conf->entity = $savcurrententity; $conf->entity = $savcurrententity;
return -1; return -1;
@ -1275,14 +1344,12 @@ class Cronjob extends CommonObject
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
$user = new User($this->db); $user = new User($this->db);
$result = $user->fetch('', $userlogin); $result = $user->fetch('', $userlogin);
if ($result < 0) if ($result < 0) {
{
$this->error = "User Error : ".$user->error; $this->error = "User Error : ".$user->error;
dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR); dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR);
return -1; return -1;
} else { } else {
if (empty($user->id)) if (empty($user->id)) {
{
$this->error = " User user login:".$userlogin." do not exists"; $this->error = " User user login:".$userlogin." do not exists";
dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR); dol_syslog(get_class($this)."::reprogram_jobs ".$this->error, LOG_ERR);
return -1; return -1;
@ -1291,17 +1358,17 @@ class Cronjob extends CommonObject
dol_syslog(get_class($this)."::reprogram_jobs datenextrun=".$this->datenextrun." ".dol_print_date($this->datenextrun, 'dayhourrfc')." frequency=".$this->frequency." unitfrequency=".$this->unitfrequency, LOG_DEBUG); dol_syslog(get_class($this)."::reprogram_jobs datenextrun=".$this->datenextrun." ".dol_print_date($this->datenextrun, 'dayhourrfc')." frequency=".$this->frequency." unitfrequency=".$this->unitfrequency, LOG_DEBUG);
if (empty($this->datenextrun)) if (empty($this->datenextrun)) {
{ if (empty($this->datestart)) {
if (empty($this->datestart)) $this->datenextrun = $now + ($this->frequency * $this->unitfrequency); $this->datenextrun = $now + ($this->frequency * $this->unitfrequency);
else $this->datenextrun = $this->datestart + ($this->frequency * $this->unitfrequency); } else {
$this->datenextrun = $this->datestart + ($this->frequency * $this->unitfrequency);
}
} }
if ($this->datenextrun < $now && $this->frequency > 0 && $this->unitfrequency > 0) if ($this->datenextrun < $now && $this->frequency > 0 && $this->unitfrequency > 0) {
{
// Loop until date is after future // Loop until date is after future
while ($this->datenextrun < $now) while ($this->datenextrun < $now) {
{
$this->datenextrun += ($this->frequency * $this->unitfrequency); $this->datenextrun += ($this->frequency * $this->unitfrequency);
// TODO For exact frequency (every month, every year, ...), use instead a dol_time_plus_duree($time, $duration_value, $duration_unit) // TODO For exact frequency (every month, every year, ...), use instead a dol_time_plus_duree($time, $duration_value, $duration_unit)
@ -1313,11 +1380,9 @@ class Cronjob extends CommonObject
// Archive job // Archive job
if ($this->autodelete == 2) if ($this->autodelete == 2) {
{
if (($this->maxrun > 0 && ($this->nbrun >= $this->maxrun)) if (($this->maxrun > 0 && ($this->nbrun >= $this->maxrun))
|| ($this->dateend && ($this->datenextrun > $this->dateend))) || ($this->dateend && ($this->datenextrun > $this->dateend))) {
{
$this->status = self::STATUS_ARCHIVED; $this->status = self::STATUS_ARCHIVED;
dol_syslog(get_class($this)."::reprogram_jobs Job will be set to archived", LOG_ERR); dol_syslog(get_class($this)."::reprogram_jobs Job will be set to archived", LOG_ERR);
} }
@ -1377,9 +1442,15 @@ class Cronjob extends CommonObject
} }
$statusType = 'status4'; $statusType = 'status4';
if ($status == 1 && $processing) $statusType = 'status1'; if ($status == 1 && $processing) {
if ($status == 0) $statusType = 'status5'; $statusType = 'status1';
if ($this->lastresult) $statusType = 'status8'; }
if ($status == 0) {
$statusType = 'status5';
}
if ($this->lastresult) {
$statusType = 'status8';
}
return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
} }

View File

@ -30,7 +30,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
$langs->loadLangs(array('admin', 'cron')); $langs->loadLangs(array('admin', 'cron'));
// Security check // Security check
if (!$user->rights->cron->read) accessforbidden(); if (!$user->rights->cron->read) {
accessforbidden();
}
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');

View File

@ -34,7 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array("admin", "cron", "bills", "members")); $langs->loadLangs(array("admin", "cron", "bills", "members"));
if (!$user->rights->cron->read) accessforbidden(); if (!$user->rights->cron->read) {
accessforbidden();
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
@ -48,12 +50,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortfield) $sortfield = 't.status,t.priority'; if (!$sortfield) {
if (!$sortorder) $sortorder = 'DESC,ASC'; $sortfield = 't.status,t.priority';
}
if (!$sortorder) {
$sortorder = 'DESC,ASC';
}
$mode = GETPOST('mode', 'aZ09'); $mode = GETPOST('mode', 'aZ09');
//Search criteria //Search criteria
@ -82,21 +90,25 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$search_label = ''; $search_label = '';
$search_status = -1; $search_status = -1;
$search_lastresult = ''; $search_lastresult = '';
@ -104,20 +116,17 @@ if (empty($reshook))
$search_array_options = array(); $search_array_options = array();
} }
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
{
$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
} }
$filter = array(); $filter = array();
if (!empty($search_label)) if (!empty($search_label)) {
{
$filter['t.label'] = $search_label; $filter['t.label'] = $search_label;
} }
// Delete jobs // Delete jobs
if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->cron->delete) if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->cron->delete) {
{
//Delete cron task //Delete cron task
$object = new Cronjob($db); $object = new Cronjob($db);
$object->id = $id; $object->id = $id;
@ -129,10 +138,8 @@ if (empty($reshook))
} }
// Execute jobs // Execute jobs
if ($action == 'confirm_execute' && $confirm == "yes" && $user->rights->cron->execute) if ($action == 'confirm_execute' && $confirm == "yes" && $user->rights->cron->execute) {
{ if (!empty($conf->global->CRON_KEY) && $conf->global->CRON_KEY != $securitykey) {
if (!empty($conf->global->CRON_KEY) && $conf->global->CRON_KEY != $securitykey)
{
setEventMessages('Security key '.$securitykey.' is wrong', null, 'errors'); setEventMessages('Security key '.$securitykey.' is wrong', null, 'errors');
$action = ''; $action = '';
} else { } else {
@ -148,12 +155,13 @@ if (empty($reshook))
// Programm next run // Programm next run
$res = $object->reprogram_jobs($user->login, $now); $res = $object->reprogram_jobs($user->login, $now);
if ($res > 0) if ($res > 0) {
{ if ($resrunjob >= 0) { // We show the result of reprogram only if no error message already reported
if ($resrunjob >= 0) // We show the result of reprogram only if no error message already reported if ($object->lastresult >= 0) {
{ setEventMessages($langs->trans("JobFinished"), null, 'mesgs');
if ($object->lastresult >= 0) setEventMessages($langs->trans("JobFinished"), null, 'mesgs'); } else {
else setEventMessages($langs->trans("JobFinished"), null, 'errors'); setEventMessages($langs->trans("JobFinished"), null, 'errors');
}
} }
$action = ''; $action = '';
} else { } else {
@ -162,10 +170,18 @@ if (empty($reshook))
} }
$param = '&search_status='.urlencode($search_status); $param = '&search_status='.urlencode($search_status);
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($search_label) $param .= '&search_label='.urlencode($search_label); }
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.urlencode($limit);
}
if ($search_label) {
$param .= '&search_label='.urlencode($search_label);
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
}
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@ -182,19 +198,21 @@ if (empty($reshook))
$permissiontodelete = $user->rights->cron->delete; $permissiontodelete = $user->rights->cron->delete;
$uploaddir = $conf->cron->dir_output; $uploaddir = $conf->cron->dir_output;
include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
if ($permissiontoadd) if ($permissiontoadd) {
{
$tmpcron = new Cronjob($db); $tmpcron = new Cronjob($db);
foreach ($toselect as $id) foreach ($toselect as $id) {
{
$result = $tmpcron->fetch($id); $result = $tmpcron->fetch($id);
if ($result) if ($result) {
{
$result = 0; $result = 0;
if ($massaction == 'disable') $result = $tmpcron->setStatut(Cronjob::STATUS_DISABLED); if ($massaction == 'disable') {
elseif ($massaction == 'enable') $result = $tmpcron->setStatut(Cronjob::STATUS_ENABLED); $result = $tmpcron->setStatut(Cronjob::STATUS_DISABLED);
} elseif ($massaction == 'enable') {
$result = $tmpcron->setStatut(Cronjob::STATUS_ENABLED);
}
//else dol_print_error($db, 'Bad value for massaction'); //else dol_print_error($db, 'Bad value for massaction');
if ($result < 0) setEventMessages($tmpcron->error, $tmpcron->errors, 'errors'); if ($result < 0) {
setEventMessages($tmpcron->error, $tmpcron->errors, 'errors');
}
} else { } else {
$error++; $error++;
} }
@ -248,8 +266,12 @@ $sql .= " t.libname,";
$sql .= " t.test"; $sql .= " t.test";
$sql .= " FROM ".MAIN_DB_PREFIX."cronjob as t"; $sql .= " FROM ".MAIN_DB_PREFIX."cronjob as t";
$sql .= " WHERE entity IN (0,".$conf->entity.")"; $sql .= " WHERE entity IN (0,".$conf->entity.")";
if ($search_status >= 0 && $search_status < 2 && $search_status != '') $sql .= " AND t.status = ".(empty($search_status) ? '0' : '1'); if ($search_status >= 0 && $search_status < 2 && $search_status != '') {
if ($search_lastresult != '') $sql .= natural_search("t.lastresult", $search_lastresult, 1); $sql .= " AND t.status = ".(empty($search_status) ? '0' : '1');
}
if ($search_lastresult != '') {
$sql .= natural_search("t.lastresult", $search_lastresult, 1);
}
//Manage filter //Manage filter
if (is_array($filter) && count($filter) > 0) { if (is_array($filter) && count($filter) > 0) {
foreach ($filter as $key => $value) { foreach ($filter as $key => $value) {
@ -274,12 +296,10 @@ $sql .= $db->order($sortfield, $sortorder);
// Count total nb of records // Count total nb of records
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result); $nbtotalofrecords = $db->num_rows($result);
if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
@ -288,32 +308,48 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$result = $db->query($sql); $result = $db->query($sql);
if (!$result) dol_print_error($db); if (!$result) {
dol_print_error($db);
}
$num = $db->num_rows($result); $num = $db->num_rows($result);
$arrayofselected = is_array($toselect) ? $toselect : array(); $arrayofselected = is_array($toselect) ? $toselect : array();
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($search_status) $param .= '&search_status='.urlencode($search_status); }
if ($search_label) $param .= '&search_label='.urlencode($search_label); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($search_module_name) $param .= '&search_module_name='.urlencode($search_module_name); $param .= '&limit='.urlencode($limit);
if ($search_lastresult) $param .= '&search_lastresult='.urlencode($search_lastresult); }
if ($mode) $param .= '&mode='.urlencode($mode); if ($search_status) {
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); $param .= '&search_status='.urlencode($search_status);
}
if ($search_label) {
$param .= '&search_label='.urlencode($search_label);
}
if ($search_module_name) {
$param .= '&search_module_name='.urlencode($search_module_name);
}
if ($search_lastresult) {
$param .= '&search_lastresult='.urlencode($search_lastresult);
}
if ($mode) {
$param .= '&mode='.urlencode($mode);
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
}
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
$stringcurrentdate = $langs->trans("CurrentHour").': '.dol_print_date(dol_now(), 'dayhour'); $stringcurrentdate = $langs->trans("CurrentHour").': '.dol_print_date(dol_now(), 'dayhour');
if ($action == 'delete') if ($action == 'delete') {
{
print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$id.$param, $langs->trans("CronDelete"), $langs->trans("CronConfirmDelete"), "confirm_delete", '', '', 1); print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$id.$param, $langs->trans("CronDelete"), $langs->trans("CronConfirmDelete"), "confirm_delete", '', '', 1);
} }
if ($action == 'execute') if ($action == 'execute') {
{
print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$id.'&securitykey='.$securitykey.$param, $langs->trans("CronExecute"), $langs->trans("CronConfirmExecute"), "confirm_execute", '', '', 1); print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$id.'&securitykey='.$securitykey.$param, $langs->trans("CronExecute"), $langs->trans("CronConfirmExecute"), "confirm_execute", '', '', 1);
} }
@ -324,8 +360,12 @@ $arrayofmassactions = array(
'enable'=>$langs->trans("CronStatusActiveBtn"), 'enable'=>$langs->trans("CronStatusActiveBtn"),
'disable'=>$langs->trans("CronStatusInactiveBtn"), 'disable'=>$langs->trans("CronStatusInactiveBtn"),
); );
if ($user->rights->mymodule->delete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if ($user->rights->mymodule->delete) {
if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
}
if (in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
if ($mode == 'modulesetup') { if ($mode == 'modulesetup') {
@ -337,7 +377,9 @@ if ($mode == 'modulesetup') {
} }
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'" name="search_form">'."\n"; print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'" name="search_form">'."\n";
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -362,7 +404,9 @@ print_barre_liste($pagetitle, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $
$text = $langs->trans("HoursOnThisPageAreOnServerTZ").' '.$stringcurrentdate.'<br>'; $text = $langs->trans("HoursOnThisPageAreOnServerTZ").' '.$stringcurrentdate.'<br>';
if (!empty($conf->global->CRON_WARNING_DELAY_HOURS)) $text .= $langs->trans("WarningCronDelayed", $conf->global->CRON_WARNING_DELAY_HOURS); if (!empty($conf->global->CRON_WARNING_DELAY_HOURS)) {
$text .= $langs->trans("WarningCronDelayed", $conf->global->CRON_WARNING_DELAY_HOURS);
}
print info_admin($text); print info_admin($text);
print '<br>'; print '<br>';
@ -417,18 +461,20 @@ print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", "", $param, '
print "</tr>\n"; print "</tr>\n";
if ($num > 0) if ($num > 0) {
{
// Loop on each job // Loop on each job
$now = dol_now(); $now = dol_now();
$i = 0; $i = 0;
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($result); $obj = $db->fetch_object($result);
if (empty($obj)) break; if (empty($obj)) {
if (!verifCond($obj->test)) continue; // Discard line with test = false break;
}
if (!verifCond($obj->test)) {
continue; // Discard line with test = false
}
$object->id = $obj->rowid; $object->id = $obj->rowid;
$object->ref = $obj->rowid; $object->ref = $obj->rowid;
@ -450,8 +496,7 @@ if ($num > 0)
// Label // Label
print '<td class="tdoverflowmax300">'; print '<td class="tdoverflowmax300">';
if (!empty($obj->label)) if (!empty($obj->label)) {
{
$object->ref = $langs->trans($obj->label); $object->ref = $langs->trans($obj->label);
print '<span title="'.dol_escape_htmltag($langs->trans($obj->label)).'">'.$object->getNomUrl(0, '', 1).'</span>'; print '<span title="'.dol_escape_htmltag($langs->trans($obj->label)).'">'.$object->getNomUrl(0, '', 1).'</span>';
$object->ref = $obj->rowid; $object->ref = $obj->rowid;
@ -466,8 +511,7 @@ if ($num > 0)
print '</td>'; print '</td>';
print '<td>'; print '<td>';
if ($obj->jobtype == 'method') if ($obj->jobtype == 'method') {
{
$text = $langs->trans("CronClass"); $text = $langs->trans("CronClass");
$texttoshow = $langs->trans('CronModule').': '.$obj->module_name.'<br>'; $texttoshow = $langs->trans('CronModule').': '.$obj->module_name.'<br>';
$texttoshow .= $langs->trans('CronClass').': '.$obj->classesname.'<br>'; $texttoshow .= $langs->trans('CronClass').': '.$obj->classesname.'<br>';
@ -475,8 +519,7 @@ if ($num > 0)
$texttoshow .= $langs->trans('CronMethod').': '.$obj->methodename; $texttoshow .= $langs->trans('CronMethod').': '.$obj->methodename;
$texttoshow .= '<br>'.$langs->trans('CronArgs').': '.$obj->params; $texttoshow .= '<br>'.$langs->trans('CronArgs').': '.$obj->params;
$texttoshow .= '<br>'.$langs->trans('Comment').': '.$langs->trans($obj->note); $texttoshow .= '<br>'.$langs->trans('Comment').': '.$langs->trans($obj->note);
} elseif ($obj->jobtype == 'command') } elseif ($obj->jobtype == 'command') {
{
$text = $langs->trans('CronCommand'); $text = $langs->trans('CronCommand');
$texttoshow = $langs->trans('CronCommand').': '.dol_trunc($obj->command); $texttoshow = $langs->trans('CronCommand').': '.dol_trunc($obj->command);
$texttoshow .= '<br>'.$langs->trans('CronArgs').': '.$obj->params; $texttoshow .= '<br>'.$langs->trans('CronArgs').': '.$obj->params;
@ -486,28 +529,48 @@ if ($num > 0)
print '</td>'; print '</td>';
print '<td>'; print '<td>';
if ($obj->unitfrequency == "60") print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Minutes'); if ($obj->unitfrequency == "60") {
if ($obj->unitfrequency == "3600") print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Hours'); print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Minutes');
if ($obj->unitfrequency == "86400") print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Days'); }
if ($obj->unitfrequency == "604800") print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Weeks'); if ($obj->unitfrequency == "3600") {
print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Hours');
}
if ($obj->unitfrequency == "86400") {
print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Days');
}
if ($obj->unitfrequency == "604800") {
print $langs->trans('CronEach')." ".($obj->frequency)." ".$langs->trans('Weeks');
}
print '</td>'; print '</td>';
print '<td class="center">'; print '<td class="center">';
if (!empty($obj->datestart)) { print dol_print_date($db->jdate($obj->datestart), 'dayhour'); } if (!empty($obj->datestart)) {
print dol_print_date($db->jdate($obj->datestart), 'dayhour');
}
print '</td>'; print '</td>';
print '<td class="center">'; print '<td class="center">';
if (!empty($obj->dateend)) { print dol_print_date($db->jdate($obj->dateend), 'dayhour'); } if (!empty($obj->dateend)) {
print dol_print_date($db->jdate($obj->dateend), 'dayhour');
}
print '</td>'; print '</td>';
print '<td class="right">'; print '<td class="right">';
if (!empty($obj->nbrun)) { print $obj->nbrun; } else {print '0'; } if (!empty($obj->nbrun)) {
if (!empty($obj->maxrun)) { print ' <span class="'.$langs->trans("Max").'">/ '.$obj->maxrun.'</span>'; } print $obj->nbrun;
} else {
print '0';
}
if (!empty($obj->maxrun)) {
print ' <span class="'.$langs->trans("Max").'">/ '.$obj->maxrun.'</span>';
}
print '</td>'; print '</td>';
// Date start last run // Date start last run
print '<td class="center">'; print '<td class="center">';
if (!empty($datelastrun)) { print dol_print_date($datelastrun, 'dayhoursec'); } if (!empty($datelastrun)) {
print dol_print_date($datelastrun, 'dayhoursec');
}
print '</td>'; print '</td>';
// Duration // Duration
@ -521,27 +584,38 @@ if ($num > 0)
// Return code of last run // Return code of last run
print '<td class="center">'; print '<td class="center">';
if ($obj->lastresult != '') { if ($obj->lastresult != '') {
if (empty($obj->lastresult)) print $obj->lastresult; if (empty($obj->lastresult)) {
else print '<span class="error">'.dol_trunc($obj->lastresult).'</div>'; print $obj->lastresult;
} else {
print '<span class="error">'.dol_trunc($obj->lastresult).'</div>';
}
} }
print '</td>'; print '</td>';
// Output of last run // Output of last run
print '<td>'; print '<td>';
if (!empty($obj->lastoutput)) {print dol_trunc(nl2br($obj->lastoutput), 50); } if (!empty($obj->lastoutput)) {
print dol_trunc(nl2br($obj->lastoutput), 50);
}
print '</td>'; print '</td>';
print '<td class="center">'; print '<td class="center">';
if (!empty($obj->datenextrun)) { if (!empty($obj->datenextrun)) {
$datenextrun = $db->jdate($obj->datenextrun); $datenextrun = $db->jdate($obj->datenextrun);
if (empty($obj->status)) print '<span class="opacitymedium">'; if (empty($obj->status)) {
print dol_print_date($datenextrun, 'dayhoursec'); print '<span class="opacitymedium">';
if ($obj->status == Cronjob::STATUS_ENABLED) }
{ print dol_print_date($datenextrun, 'dayhoursec');
if ($obj->maxrun && $obj->nbrun >= $obj->maxrun) print img_warning($langs->trans("MaxRunReached")); if ($obj->status == Cronjob::STATUS_ENABLED) {
elseif ($datenextrun && $datenextrun < $now) print img_warning($langs->trans("Late")); if ($obj->maxrun && $obj->nbrun >= $obj->maxrun) {
print img_warning($langs->trans("MaxRunReached"));
} elseif ($datenextrun && $datenextrun < $now) {
print img_warning($langs->trans("Late"));
}
}
if (empty($obj->status)) {
print '</span>';
} }
if (empty($obj->status)) print '</span>';
} }
print '</td>'; print '</td>';
@ -553,20 +627,17 @@ if ($num > 0)
print '<td class="nowraponall right">'; print '<td class="nowraponall right">';
$backtopage = urlencode($_SERVER["PHP_SELF"].'?'.$param.($sortfield ? '&sortfield='.$sortfield : '').($sortorder ? '&sortorder='.$sortorder : '')); $backtopage = urlencode($_SERVER["PHP_SELF"].'?'.$param.($sortfield ? '&sortfield='.$sortfield : '').($sortorder ? '&sortorder='.$sortorder : ''));
if ($user->rights->cron->create) if ($user->rights->cron->create) {
{
print '<a class="editfielda" href="'.DOL_URL_ROOT."/cron/card.php?id=".$obj->rowid.'&action=edit&token='.newToken().($sortfield ? '&sortfield='.$sortfield : '').($sortorder ? '&sortorder='.$sortorder : '').$param; print '<a class="editfielda" href="'.DOL_URL_ROOT."/cron/card.php?id=".$obj->rowid.'&action=edit&token='.newToken().($sortfield ? '&sortfield='.$sortfield : '').($sortorder ? '&sortorder='.$sortorder : '').$param;
print "&backtopage=".$backtopage."\" title=\"".dol_escape_htmltag($langs->trans('Edit'))."\">".img_picto($langs->trans('Edit'), 'edit')."</a> &nbsp;"; print "&backtopage=".$backtopage."\" title=\"".dol_escape_htmltag($langs->trans('Edit'))."\">".img_picto($langs->trans('Edit'), 'edit')."</a> &nbsp;";
} }
if ($user->rights->cron->delete) if ($user->rights->cron->delete) {
{
print '<a class="reposition" href="'.$_SERVER["PHP_SELF"]."?id=".$obj->rowid.'&action=delete&token='.newToken().($page ? '&page='.$page : '').($sortfield ? '&sortfield='.$sortfield : '').($sortorder ? '&sortorder='.$sortorder : '').$param; print '<a class="reposition" href="'.$_SERVER["PHP_SELF"]."?id=".$obj->rowid.'&action=delete&token='.newToken().($page ? '&page='.$page : '').($sortfield ? '&sortfield='.$sortfield : '').($sortorder ? '&sortorder='.$sortorder : '').$param;
print "\" title=\"".dol_escape_htmltag($langs->trans('CronDelete'))."\">".img_picto($langs->trans('CronDelete'), 'delete', '', false, 0, 0, '', 'marginleftonly')."</a> &nbsp; "; print "\" title=\"".dol_escape_htmltag($langs->trans('CronDelete'))."\">".img_picto($langs->trans('CronDelete'), 'delete', '', false, 0, 0, '', 'marginleftonly')."</a> &nbsp; ";
} else { } else {
print "<a href=\"#\" title=\"".dol_escape_htmltag($langs->trans('NotEnoughPermissions'))."\">".img_picto($langs->trans('NotEnoughPermissions'), 'delete', '', false, 0, 0, '', 'marginleftonly')."</a> &nbsp; "; print "<a href=\"#\" title=\"".dol_escape_htmltag($langs->trans('NotEnoughPermissions'))."\">".img_picto($langs->trans('NotEnoughPermissions'), 'delete', '', false, 0, 0, '', 'marginleftonly')."</a> &nbsp; ";
} }
if ($user->rights->cron->execute) if ($user->rights->cron->execute) {
{
if (!empty($obj->status)) { if (!empty($obj->status)) {
print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$obj->rowid.'&action=execute'; print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$obj->rowid.'&action=execute';
print (empty($conf->global->CRON_KEY) ? '' : '&securitykey='.$conf->global->CRON_KEY); print (empty($conf->global->CRON_KEY) ? '' : '&securitykey='.$conf->global->CRON_KEY);
@ -579,10 +650,11 @@ if ($num > 0)
} else { } else {
print '<a href="#" class="cursornotallowed" title="'.dol_escape_htmltag($langs->trans('NotEnoughPermissions')).'">'.img_picto($langs->trans('NotEnoughPermissions'), "playdisabled", '', false, 0, 0, '', 'marginleftonly').'</a>'; print '<a href="#" class="cursornotallowed" title="'.dol_escape_htmltag($langs->trans('NotEnoughPermissions')).'">'.img_picto($langs->trans('NotEnoughPermissions'), "playdisabled", '', false, 0, 0, '', 'marginleftonly').'</a>';
} }
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($obj->rowid, $arrayofselected)) $selected = 1; if (in_array($obj->rowid, $arrayofselected)) {
$selected = 1;
}
print ' &nbsp; <input id="cb'.$obj->rowid.'" class="flat checkforselect valignmiddle" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; print ' &nbsp; <input id="cb'.$obj->rowid.'" class="flat checkforselect valignmiddle" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';

View File

@ -32,24 +32,42 @@
//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language
//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); define('NOTOKENRENEWAL', '1');
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); }
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
// For direct external download link, we don't need to load/check we are into a login session // For direct external download link, we don't need to load/check we are into a login session
if (isset($_GET["hashp"]) && !defined("NOLOGIN")) if (isset($_GET["hashp"]) && !defined("NOLOGIN")) {
{ if (!defined("NOLOGIN")) {
if (!defined("NOLOGIN")) define("NOLOGIN", 1); define("NOLOGIN", 1);
if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. }
if (!defined("NOIPCHECK")) define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip if (!defined("NOCSRFCHECK")) {
define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
}
if (!defined("NOIPCHECK")) {
define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
}
} }
// Some value of modulepart can be used to get resources that are public so no login are required. // Some value of modulepart can be used to get resources that are public so no login are required.
if ((isset($_GET["modulepart"]) && $_GET["modulepart"] == 'medias')) if ((isset($_GET["modulepart"]) && $_GET["modulepart"] == 'medias')) {
{ if (!defined("NOLOGIN")) {
if (!defined("NOLOGIN")) define("NOLOGIN", 1); define("NOLOGIN", 1);
if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", 1); // We accept to go on this page from external web site. }
if (!defined("NOIPCHECK")) define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip if (!defined("NOCSRFCHECK")) {
define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
}
if (!defined("NOIPCHECK")) {
define("NOIPCHECK", 1); // Do not check IP defined into conf $dolibarr_main_restrict_ip
}
} }
/** /**
@ -84,17 +102,26 @@ $urlsource = GETPOST('urlsource', 'alpha');
$entity = GETPOST('entity', 'int') ?GETPOST('entity', 'int') : $conf->entity; $entity = GETPOST('entity', 'int') ?GETPOST('entity', 'int') : $conf->entity;
// Security check // Security check
if (empty($modulepart) && empty($hashp)) accessforbidden('Bad link. Bad value for parameter modulepart', 0, 0, 1); if (empty($modulepart) && empty($hashp)) {
if (empty($original_file) && empty($hashp)) accessforbidden('Bad link. Missing identification to find file (original_file or hashp)', 0, 0, 1); accessforbidden('Bad link. Bad value for parameter modulepart', 0, 0, 1);
if ($modulepart == 'fckeditor') $modulepart = 'medias'; // For backward compatibility }
if (empty($original_file) && empty($hashp)) {
accessforbidden('Bad link. Missing identification to find file (original_file or hashp)', 0, 0, 1);
}
if ($modulepart == 'fckeditor') {
$modulepart = 'medias'; // For backward compatibility
}
$socid = 0; $socid = 0;
if ($user->socid > 0) $socid = $user->socid; if ($user->socid > 0) {
$socid = $user->socid;
}
// For some module part, dir may be privates // For some module part, dir may be privates
if (in_array($modulepart, array('facture_paiement', 'unpaid'))) if (in_array($modulepart, array('facture_paiement', 'unpaid'))) {
{ if (!$user->rights->societe->client->voir || $socid) {
if (!$user->rights->societe->client->voir || $socid) $original_file = 'private/'.$user->id.'/'.$original_file; // If user has no permission to see all, output dir is specific to user $original_file = 'private/'.$user->id.'/'.$original_file; // If user has no permission to see all, output dir is specific to user
}
} }
@ -111,25 +138,20 @@ if (in_array($modulepart, array('facture_paiement', 'unpaid')))
*/ */
// If we have a hash public (hashp), we guess the original_file. // If we have a hash public (hashp), we guess the original_file.
if (!empty($hashp)) if (!empty($hashp)) {
{
include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
$ecmfile = new EcmFiles($db); $ecmfile = new EcmFiles($db);
$result = $ecmfile->fetch(0, '', '', '', $hashp); $result = $ecmfile->fetch(0, '', '', '', $hashp);
if ($result > 0) if ($result > 0) {
{
$tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
// filepath can be 'users/X' or 'X/propale/PR11111' // filepath can be 'users/X' or 'X/propale/PR11111'
if (is_numeric($tmp[0])) // If first tmp is numeric, it is subdir of company for multicompany, we take next part. if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
{
$tmp = explode('/', $tmp[1], 2); $tmp = explode('/', $tmp[1], 2);
} }
$moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
if ($modulepart) // Not required, so often not defined, for link using public hashp parameter. if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter.
{ if ($moduleparttocheck == $modulepart) {
if ($moduleparttocheck == $modulepart)
{
// We remove first level of directory // We remove first level of directory
$original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
//var_dump($original_file); exit; //var_dump($original_file); exit;
@ -148,14 +170,23 @@ if (!empty($hashp))
// Define attachment (attachment=true to force choice popup 'open'/'save as') // Define attachment (attachment=true to force choice popup 'open'/'save as')
$attachment = true; $attachment = true;
if (preg_match('/\.(html|htm)$/i', $original_file)) $attachment = false; if (preg_match('/\.(html|htm)$/i', $original_file)) {
if (isset($_GET["attachment"])) $attachment = GETPOST("attachment", 'alpha') ?true:false; $attachment = false;
if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS)) $attachment = false; }
if (isset($_GET["attachment"])) {
$attachment = GETPOST("attachment", 'alpha') ?true:false;
}
if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS)) {
$attachment = false;
}
// Define mime type // Define mime type
$type = 'application/octet-stream'; // By default $type = 'application/octet-stream'; // By default
if (GETPOST('type', 'alpha')) $type = GETPOST('type', 'alpha'); if (GETPOST('type', 'alpha')) {
else $type = dol_mimetype($original_file); $type = GETPOST('type', 'alpha');
} else {
$type = dol_mimetype($original_file);
}
// Security: Force to octet-stream if file is a dangerous file. For example when it is a .noexe file // Security: Force to octet-stream if file is a dangerous file. For example when it is a .noexe file
// We do not force if file is a javascript to be able to get js from website module with <script src=" // We do not force if file is a javascript to be able to get js from website module with <script src="
// Note: Force whatever is $modulepart seems ok. // Note: Force whatever is $modulepart seems ok.
@ -170,7 +201,9 @@ $original_file = str_replace("../", "/", $original_file);
$refname = basename(dirname($original_file)."/"); $refname = basename(dirname($original_file)."/");
// Security check // Security check
if (empty($modulepart)) accessforbidden('Bad value for parameter modulepart'); if (empty($modulepart)) {
accessforbidden('Bad value for parameter modulepart');
}
// Check security and set return info with full path of file // Check security and set return info with full path of file
$check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $user, $refname); $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $user, $refname);
@ -179,26 +212,20 @@ $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
$fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name $fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name
//var_dump($fullpath_original_file);exit; //var_dump($fullpath_original_file);exit;
if (!empty($hashp)) if (!empty($hashp)) {
{
$accessallowed = 1; // When using hashp, link is public so we force $accessallowed $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
$sqlprotectagainstexternals = ''; $sqlprotectagainstexternals = '';
} else { } else {
// Basic protection (against external users only) // Basic protection (against external users only)
if ($user->socid > 0) if ($user->socid > 0) {
{ if ($sqlprotectagainstexternals) {
if ($sqlprotectagainstexternals)
{
$resql = $db->query($sqlprotectagainstexternals); $resql = $db->query($sqlprotectagainstexternals);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if ($user->socid != $obj->fk_soc) if ($user->socid != $obj->fk_soc) {
{
$accessallowed = 0; $accessallowed = 0;
break; break;
} }
@ -211,15 +238,13 @@ if (!empty($hashp))
// Security: // Security:
// Limit access if permissions are wrong // Limit access if permissions are wrong
if (!$accessallowed) if (!$accessallowed) {
{
accessforbidden(); accessforbidden();
} }
// Security: // Security:
// We refuse directory transversal change and pipes in file names // We refuse directory transversal change and pipes in file names
if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) if (preg_match('/\.\./', $fullpath_original_file) || preg_match('/[<>|]/', $fullpath_original_file)) {
{
dol_syslog("Refused to deliver file ".$fullpath_original_file); dol_syslog("Refused to deliver file ".$fullpath_original_file);
print "ErrorFileNameInvalid: ".dol_escape_htmltag($original_file); print "ErrorFileNameInvalid: ".dol_escape_htmltag($original_file);
exit; exit;
@ -236,8 +261,7 @@ dol_syslog("document.php download $fullpath_original_file filename=$filename con
$fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset
// This test if file exists should be useless. We keep it to find bug more easily // This test if file exists should be useless. We keep it to find bug more easily
if (!file_exists($fullpath_original_file_osencoded)) if (!file_exists($fullpath_original_file_osencoded)) {
{
dol_syslog("ErrorFileDoesNotExists: ".$fullpath_original_file); dol_syslog("ErrorFileDoesNotExists: ".$fullpath_original_file);
print "ErrorFileDoesNotExists: ".$original_file; print "ErrorFileDoesNotExists: ".$original_file;
exit; exit;
@ -263,10 +287,15 @@ if ($reshook < 0) {
// Permissions are ok and file found, so we return it // Permissions are ok and file found, so we return it
top_httphead($type); top_httphead($type);
header('Content-Description: File Transfer'); header('Content-Description: File Transfer');
if ($encoding) header('Content-Encoding: '.$encoding); if ($encoding) {
header('Content-Encoding: '.$encoding);
}
// Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open) // Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open)
if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"'); if ($attachment) {
else header('Content-Disposition: inline; filename="'.$filename.'"'); header('Content-Disposition: attachment; filename="'.$filename.'"');
} else {
header('Content-Disposition: inline; filename="'.$filename.'"');
}
// Ajout directives pour resoudre bug IE // Ajout directives pour resoudre bug IE
header('Cache-Control: Public, must-revalidate'); header('Cache-Control: Public, must-revalidate');
header('Pragma: public'); header('Pragma: public');
@ -278,7 +307,9 @@ if (!$attachment && !empty($conf->global->MAIN_USE_EXIF_ROTATION) && image_forma
$readfile = !$imgres; $readfile = !$imgres;
} }
if (is_object($db)) $db->close(); if (is_object($db)) {
$db->close();
}
// Send file now // Send file now
if ($readfile) { if ($readfile) {

View File

@ -41,18 +41,15 @@ $hookmanager->initHooks(array('index'));
*/ */
// Check if company name is defined (first install) // Check if company name is defined (first install)
if (!isset($conf->global->MAIN_INFO_SOCIETE_NOM) || empty($conf->global->MAIN_INFO_SOCIETE_NOM)) if (!isset($conf->global->MAIN_INFO_SOCIETE_NOM) || empty($conf->global->MAIN_INFO_SOCIETE_NOM)) {
{
header("Location: ".DOL_URL_ROOT."/admin/index.php?mainmenu=home&leftmenu=setup&mesg=setupnotcomplete"); header("Location: ".DOL_URL_ROOT."/admin/index.php?mainmenu=home&leftmenu=setup&mesg=setupnotcomplete");
exit; exit;
} }
if (count($conf->modules) <= (empty($conf->global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING) ? 1 : $conf->global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING)) // If only user module enabled if (count($conf->modules) <= (empty($conf->global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING) ? 1 : $conf->global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING)) { // If only user module enabled
{
header("Location: ".DOL_URL_ROOT."/admin/index.php?mainmenu=home&leftmenu=setup&mesg=setupnotcomplete"); header("Location: ".DOL_URL_ROOT."/admin/index.php?mainmenu=home&leftmenu=setup&mesg=setupnotcomplete");
exit; exit;
} }
if (GETPOST('addbox')) // Add box (when submit is done from a form when ajax disabled) if (GETPOST('addbox')) { // Add box (when submit is done from a form when ajax disabled)
{
require_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php';
$zone = GETPOST('areacode', 'aZ09'); $zone = GETPOST('areacode', 'aZ09');
$userid = GETPOST('userid', 'int'); $userid = GETPOST('userid', 'int');
@ -60,7 +57,9 @@ if (GETPOST('addbox')) // Add box (when submit is done from a form when ajax dis
$boxorder .= GETPOST('boxcombo', 'aZ09'); $boxorder .= GETPOST('boxcombo', 'aZ09');
$result = InfoBox::saveboxorder($db, $zone, $boxorder, $userid); $result = InfoBox::saveboxorder($db, $zone, $boxorder, $userid);
if ($result > 0) setEventMessages($langs->trans("BoxAdded"), null); if ($result > 0) {
setEventMessages($langs->trans("BoxAdded"), null);
}
} }
@ -68,11 +67,15 @@ if (GETPOST('addbox')) // Add box (when submit is done from a form when ajax dis
* View * View
*/ */
if (!isset($form) || !is_object($form)) $form = new Form($db); if (!isset($form) || !is_object($form)) {
$form = new Form($db);
}
// Title // Title
$title = $langs->trans("HomeArea").' - Dolibarr '.DOL_VERSION; $title = $langs->trans("HomeArea").' - Dolibarr '.DOL_VERSION;
if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = $langs->trans("HomeArea").' - '.$conf->global->MAIN_APPLICATION_TITLE; if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
$title = $langs->trans("HomeArea").' - '.$conf->global->MAIN_APPLICATION_TITLE;
}
llxHeader('', $title); llxHeader('', $title);
@ -82,11 +85,9 @@ $resultboxes = FormOther::getBoxesArea($user, "0"); // Load $resultboxes (select
print load_fiche_titre('&nbsp;', $resultboxes['selectboxlist'], '', 0, '', 'titleforhome'); print load_fiche_titre('&nbsp;', $resultboxes['selectboxlist'], '', 0, '', 'titleforhome');
if (!empty($conf->global->MAIN_MOTD)) if (!empty($conf->global->MAIN_MOTD)) {
{
$conf->global->MAIN_MOTD = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', '<br>', $conf->global->MAIN_MOTD); $conf->global->MAIN_MOTD = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', '<br>', $conf->global->MAIN_MOTD);
if (!empty($conf->global->MAIN_MOTD)) if (!empty($conf->global->MAIN_MOTD)) {
{
$substitutionarray = getCommonSubstitutionArray($langs); $substitutionarray = getCommonSubstitutionArray($langs);
complete_substitutions_array($substitutionarray, $langs); complete_substitutions_array($substitutionarray, $langs);
$texttoshow = make_substitutions($conf->global->MAIN_MOTD, $substitutionarray, $langs); $texttoshow = make_substitutions($conf->global->MAIN_MOTD, $substitutionarray, $langs);
@ -258,8 +259,12 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) {
$object = new stdClass(); $object = new stdClass();
$parameters = array(); $parameters = array();
$action = ''; $action = '';
$reshook = $hookmanager->executeHooks('addOpenElementsDashboardLine', $parameters, $object, $reshook = $hookmanager->executeHooks(
$action); // Note that $action and $object may have been modified by some hooks 'addOpenElementsDashboardLine',
$parameters,
$object,
$action
); // Note that $action and $object may have been modified by some hooks
if ($reshook == 0) { if ($reshook == 0) {
$dashboardlines = array_merge($dashboardlines, $hookmanager->resArray); $dashboardlines = array_merge($dashboardlines, $hookmanager->resArray);
} }
@ -414,8 +419,10 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) {
$boxwork .= '<th class="liste_titre"><div class="inline-block valignmiddle">'.$langs->trans("DolibarrWorkBoard").'</div>'; $boxwork .= '<th class="liste_titre"><div class="inline-block valignmiddle">'.$langs->trans("DolibarrWorkBoard").'</div>';
if ($showweather) { if ($showweather) {
if ($totallate > 0) { if ($totallate > 0) {
$text = $langs->transnoentitiesnoconv("WarningYouHaveAtLeastOneTaskLate").' ('.$langs->transnoentitiesnoconv("NActionsLate", $text = $langs->transnoentitiesnoconv("WarningYouHaveAtLeastOneTaskLate").' ('.$langs->transnoentitiesnoconv(
$totallate.(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '%' : '')).')'; "NActionsLate",
$totallate.(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '%' : '')
).')';
} else { } else {
$text = $langs->transnoentitiesnoconv("NoItemLate"); $text = $langs->transnoentitiesnoconv("NoItemLate");
} }
@ -457,17 +464,17 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) {
$globalStatsKey = $groupElement['globalStatsKey']; $globalStatsKey = $groupElement['globalStatsKey'];
$groupElement['globalStats'] = array(); $groupElement['globalStats'] = array();
if (is_array($keys) && in_array($globalStatsKey, $keys)) if (is_array($keys) && in_array($globalStatsKey, $keys)) {
{
// get key index of stats used in $includes, $classes, $keys, $icons, $titres, $links // get key index of stats used in $includes, $classes, $keys, $icons, $titres, $links
$keyIndex = array_search($globalStatsKey, $keys); $keyIndex = array_search($globalStatsKey, $keys);
$classe = (!empty($classes[$keyIndex]) ? $classes[$keyIndex] : ''); $classe = (!empty($classes[$keyIndex]) ? $classes[$keyIndex] : '');
if (isset($boardloaded[$classe]) && is_object($boardloaded[$classe])) if (isset($boardloaded[$classe]) && is_object($boardloaded[$classe])) {
{
$groupElement['globalStats']['total'] = $boardloaded[$classe]->nb[$globalStatsKey] ? $boardloaded[$classe]->nb[$globalStatsKey] : 0; $groupElement['globalStats']['total'] = $boardloaded[$classe]->nb[$globalStatsKey] ? $boardloaded[$classe]->nb[$globalStatsKey] : 0;
$nbTotal = doubleval($groupElement['globalStats']['total']); $nbTotal = doubleval($groupElement['globalStats']['total']);
if ($nbTotal >= 10000) { $nbTotal = round($nbTotal / 1000, 2).'k'; } if ($nbTotal >= 10000) {
$nbTotal = round($nbTotal / 1000, 2).'k';
}
$groupElement['globalStats']['text'] = $langs->trans('Total').' : '.$langs->trans($titres[$keyIndex]).' ('.$groupElement['globalStats']['total'].')'; $groupElement['globalStats']['text'] = $langs->trans('Total').' : '.$langs->trans($titres[$keyIndex]).' ('.$groupElement['globalStats']['total'].')';
$groupElement['globalStats']['total'] = $nbTotal; $groupElement['globalStats']['total'] = $nbTotal;
$groupElement['globalStats']['link'] = $links[$keyIndex]; $groupElement['globalStats']['link'] = $links[$keyIndex];
@ -554,8 +561,10 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) {
$text = ''; $text = '';
if ($totallate > 0) { if ($totallate > 0) {
$text = $langs->transnoentitiesnoconv("WarningYouHaveAtLeastOneTaskLate").' ('.$langs->transnoentitiesnoconv("NActionsLate", $text = $langs->transnoentitiesnoconv("WarningYouHaveAtLeastOneTaskLate").' ('.$langs->transnoentitiesnoconv(
$totallate.(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '%' : '')).')'; "NActionsLate",
$totallate.(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '%' : '')
).')';
} else { } else {
$text = $langs->transnoentitiesnoconv("NoItemLate"); $text = $langs->transnoentitiesnoconv("NoItemLate");
} }
@ -570,16 +579,24 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) {
$weatherDashBoard .= ' <div class="info-box-title">'.$langs->trans('GlobalOpenedElemView').'</div>'."\n"; $weatherDashBoard .= ' <div class="info-box-title">'.$langs->trans('GlobalOpenedElemView').'</div>'."\n";
if ($totallatePercentage > 0 && !empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) { if ($totallatePercentage > 0 && !empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) {
$weatherDashBoard .= ' <span class="info-box-number">'.$langs->transnoentitiesnoconv("NActionsLate", $weatherDashBoard .= ' <span class="info-box-number">'.$langs->transnoentitiesnoconv(
price($totallatePercentage).'%').'</span>'."\n"; "NActionsLate",
$weatherDashBoard .= ' <span class="progress-description">'.$langs->trans('NActionsLate', price($totallatePercentage).'%'
$totalLateNumber).'</span>'."\n"; ).'</span>'."\n";
$weatherDashBoard .= ' <span class="progress-description">'.$langs->trans(
'NActionsLate',
$totalLateNumber
).'</span>'."\n";
} else { } else {
$weatherDashBoard .= ' <span class="info-box-number">'.$langs->transnoentitiesnoconv("NActionsLate", $weatherDashBoard .= ' <span class="info-box-number">'.$langs->transnoentitiesnoconv(
$totalLateNumber).'</span>'."\n"; "NActionsLate",
$totalLateNumber
).'</span>'."\n";
if ($totallatePercentage > 0) { if ($totallatePercentage > 0) {
$weatherDashBoard .= ' <span class="progress-description">'.$langs->trans('NActionsLate', $weatherDashBoard .= ' <span class="progress-description">'.$langs->trans(
price($totallatePercentage).'%').'</span>'."\n"; 'NActionsLate',
price($totallatePercentage).'%'
).'</span>'."\n";
} }
} }
@ -627,8 +644,11 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) {
$boxwork .= '<div class="dashboardlinelatecoin nowrap">'; $boxwork .= '<div class="dashboardlinelatecoin nowrap">';
$boxwork .= '<a title="'.dol_escape_htmltag($textlate).'" class="valignmiddle dashboardlineindicatorlate'.($board->nbtodolate > 0 ? ' dashboardlineko' : ' dashboardlineok').'" href="'.((!$board->url_late) ? $board->url : $board->url_late).'">'; $boxwork .= '<a title="'.dol_escape_htmltag($textlate).'" class="valignmiddle dashboardlineindicatorlate'.($board->nbtodolate > 0 ? ' dashboardlineko' : ' dashboardlineok').'" href="'.((!$board->url_late) ? $board->url : $board->url_late).'">';
//$boxwork .= img_picto($textlate, "warning_white", 'class="valigntextbottom"').''; //$boxwork .= img_picto($textlate, "warning_white", 'class="valigntextbottom"').'';
$boxwork .= img_picto($textlate, "warning_white", $boxwork .= img_picto(
'class="inline-block hideonsmartphone valigntextbottom"').''; $textlate,
"warning_white",
'class="inline-block hideonsmartphone valigntextbottom"'
).'';
$boxwork .= '<span class="dashboardlineindicatorlate'.($board->nbtodolate > 0 ? ' dashboardlineko' : ' dashboardlineok').'">'; $boxwork .= '<span class="dashboardlineindicatorlate'.($board->nbtodolate > 0 ? ' dashboardlineko' : ' dashboardlineok').'">';
$boxwork .= $board->nbtodolate; $boxwork .= $board->nbtodolate;
$boxwork .= '</span>'; $boxwork .= '</span>';
@ -679,8 +699,7 @@ print '<div class="fichecenter fichecenterbis">';
$boxlist = '<div class="twocolumns">'; $boxlist = '<div class="twocolumns">';
$boxlist .= '<div class="firstcolumn fichehalfleft boxhalfleft" id="boxhalfleft">'; $boxlist .= '<div class="firstcolumn fichehalfleft boxhalfleft" id="boxhalfleft">';
if (!empty($nbworkboardcount)) if (!empty($nbworkboardcount)) {
{
$boxlist .= $boxwork; $boxlist .= $boxwork;
} }
@ -708,30 +727,26 @@ print '</div>';
*/ */
// Security warning repertoire install existe (si utilisateur admin) // Security warning repertoire install existe (si utilisateur admin)
if ($user->admin && empty($conf->global->MAIN_REMOVE_INSTALL_WARNING)) if ($user->admin && empty($conf->global->MAIN_REMOVE_INSTALL_WARNING)) {
{
$message = ''; $message = '';
// Check if install lock file is present // Check if install lock file is present
$lockfile = DOL_DATA_ROOT.'/install.lock'; $lockfile = DOL_DATA_ROOT.'/install.lock';
if (!empty($lockfile) && !file_exists($lockfile) && is_dir(DOL_DOCUMENT_ROOT."/install")) if (!empty($lockfile) && !file_exists($lockfile) && is_dir(DOL_DOCUMENT_ROOT."/install")) {
{
$langs->load("errors"); $langs->load("errors");
//if (! empty($message)) $message.='<br>'; //if (! empty($message)) $message.='<br>';
$message .= info_admin($langs->trans("WarningLockFileDoesNotExists", DOL_DATA_ROOT).' '.$langs->trans("WarningUntilDirRemoved", DOL_DOCUMENT_ROOT."/install"), 0, 0, '1', 'clearboth'); $message .= info_admin($langs->trans("WarningLockFileDoesNotExists", DOL_DATA_ROOT).' '.$langs->trans("WarningUntilDirRemoved", DOL_DOCUMENT_ROOT."/install"), 0, 0, '1', 'clearboth');
} }
// Conf files must be in read only mode // Conf files must be in read only mode
if (is_writable($conffile)) if (is_writable($conffile)) {
{
$langs->load("errors"); $langs->load("errors");
//$langs->load("other"); //$langs->load("other");
//if (! empty($message)) $message.='<br>'; //if (! empty($message)) $message.='<br>';
$message .= info_admin($langs->transnoentities("WarningConfFileMustBeReadOnly").' '.$langs->trans("WarningUntilDirRemoved", DOL_DOCUMENT_ROOT."/install"), 0, 0, '1', 'clearboth'); $message .= info_admin($langs->transnoentities("WarningConfFileMustBeReadOnly").' '.$langs->trans("WarningUntilDirRemoved", DOL_DOCUMENT_ROOT."/install"), 0, 0, '1', 'clearboth');
} }
if ($message) if ($message) {
{
print $message; print $message;
//$message.='<br>'; //$message.='<br>';
//print info_admin($langs->trans("WarningUntilDirRemoved",DOL_DOCUMENT_ROOT."/install")); //print info_admin($langs->trans("WarningUntilDirRemoved",DOL_DOCUMENT_ROOT."/install"));

View File

@ -231,7 +231,7 @@ if ($id > 0 || !empty($ref)) {
print_liste_field_titre("Company", $_SERVER["PHP_SELF"], "s.nom", "", $option, '', $sortfield, $sortorder); print_liste_field_titre("Company", $_SERVER["PHP_SELF"], "s.nom", "", $option, '', $sortfield, $sortorder);
print_liste_field_titre("DatePropal", $_SERVER["PHP_SELF"], "p.date_valid", "", $option, 'align="center"', $sortfield, $sortorder); print_liste_field_titre("DatePropal", $_SERVER["PHP_SELF"], "p.date_valid", "", $option, 'align="center"', $sortfield, $sortorder);
print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "d.qty", "", $option, 'align="center"', $sortfield, $sortorder); print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "d.qty", "", $option, 'align="center"', $sortfield, $sortorder);
print_liste_field_titre("AmountHT", $_SERVER["PHP_SELF"], "p.total", "", $option, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("AmountHT", $_SERVER["PHP_SELF"], "p.total_ht", "", $option, 'align="right"', $sortfield, $sortorder);
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "p.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "p.fk_statut", "", $option, 'align="right"', $sortfield, $sortorder);
print "</tr>\n"; print "</tr>\n";

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -70,12 +70,15 @@ class ReceptionStats extends Stats
//$this->where.= " AND c.fk_soc = s.rowid AND c.entity = ".$conf->entity; //$this->where.= " AND c.fk_soc = s.rowid AND c.entity = ".$conf->entity;
$this->where .= " AND c.entity = ".$conf->entity; $this->where .= " AND c.entity = ".$conf->entity;
if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; if (!$user->rights->societe->client->voir && !$this->socid) {
if ($this->socid) $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
{ }
if ($this->socid) {
$this->where .= " AND c.fk_soc = ".$this->socid; $this->where .= " AND c.fk_soc = ".$this->socid;
} }
if ($this->userid > 0) $this->where .= ' AND c.fk_user_author = '.$this->userid; if ($this->userid > 0) {
$this->where .= ' AND c.fk_user_author = '.$this->userid;
}
} }
/** /**
@ -114,7 +117,9 @@ class ReceptionStats extends Stats
$sql = "SELECT date_format(c.date_valid,'%Y') as dm, COUNT(*) as nb, SUM(c.".$this->field.")"; $sql = "SELECT date_format(c.date_valid,'%Y') as dm, COUNT(*) as nb, SUM(c.".$this->field.")";
$sql .= " FROM ".$this->from; $sql .= " FROM ".$this->from;
if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$this->socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE ".$this->where; $sql .= " WHERE ".$this->where;
$sql .= " GROUP BY dm"; $sql .= " GROUP BY dm";
$sql .= $this->db->order('dm', 'DESC'); $sql .= $this->db->order('dm', 'DESC');
@ -133,7 +138,9 @@ class ReceptionStats extends Stats
$sql = "SELECT date_format(c.date_valid,'%Y') as year, COUNT(*) as nb, SUM(c.".$this->field.") as total, AVG(".$this->field.") as avg"; $sql = "SELECT date_format(c.date_valid,'%Y') as year, COUNT(*) as nb, SUM(c.".$this->field.") as total, AVG(".$this->field.") as avg";
$sql .= " FROM ".$this->from; $sql .= " FROM ".$this->from;
if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$this->socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE ".$this->where; $sql .= " WHERE ".$this->where;
$sql .= " GROUP BY year"; $sql .= " GROUP BY year";
$sql .= $this->db->order('year', 'DESC'); $sql .= $this->db->order('year', 'DESC');

View File

@ -44,17 +44,17 @@ $ref = GETPOST('ref', 'alpha');
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
// Security check // Security check
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'reception', $id, ''); $result = restrictedArea($user, 'reception', $id, '');
$object = new Reception($db); $object = new Reception($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$object->fetch($id, $ref); $object->fetch($id, $ref);
$object->fetch_thirdparty(); $object->fetch_thirdparty();
if (!empty($object->origin)) if (!empty($object->origin)) {
{
$origin = $object->origin; $origin = $object->origin;
$object->fetch_origin(); $object->fetch_origin();
@ -62,8 +62,7 @@ if ($id > 0 || !empty($ref))
} }
// Linked documents // Linked documents
if ($origin == 'order_supplier' && $object->$typeobject->id && !empty($conf->fournisseur->enabled)) if ($origin == 'order_supplier' && $object->$typeobject->id && !empty($conf->fournisseur->enabled)) {
{
$objectsrc = new CommandeFournisseur($db); $objectsrc = new CommandeFournisseur($db);
$objectsrc->fetch($object->$typeobject->id); $objectsrc->fetch($object->$typeobject->id);
} }
@ -74,22 +73,18 @@ if ($id > 0 || !empty($ref))
* Actions * Actions
*/ */
if ($action == 'addcontact' && $user->rights->reception->creer) if ($action == 'addcontact' && $user->rights->reception->creer) {
{ if ($result > 0 && $id > 0) {
if ($result > 0 && $id > 0)
{
$contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int'));
$typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
$result = $objectsrc->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); $result = $objectsrc->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
} }
if ($result >= 0) if ($result >= 0) {
{
header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
exit; exit;
} else { } else {
if ($objectsrc->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') if ($objectsrc->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
{
$langs->load("errors"); $langs->load("errors");
$mesg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); $mesg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
} else { } else {
@ -98,21 +93,14 @@ if ($action == 'addcontact' && $user->rights->reception->creer)
} }
setEventMessages($mesg, $mesgs, 'errors'); setEventMessages($mesg, $mesgs, 'errors');
} }
} } elseif ($action == 'swapstatut' && $user->rights->reception->creer) {
// bascule du statut d'un contact
// bascule du statut d'un contact
elseif ($action == 'swapstatut' && $user->rights->reception->creer)
{
$result = $objectsrc->swapContactStatus(GETPOST('ligne')); $result = $objectsrc->swapContactStatus(GETPOST('ligne'));
} } elseif ($action == 'deletecontact' && $user->rights->reception->creer) {
// Efface un contact
// Efface un contact
elseif ($action == 'deletecontact' && $user->rights->reception->creer)
{
$result = $objectsrc->delete_contact(GETPOST("lineid")); $result = $objectsrc->delete_contact(GETPOST("lineid"));
if ($result >= 0) if ($result >= 0) {
{
header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
exit; exit;
} else { } else {
@ -147,8 +135,7 @@ $userstatic = new User($db);
/* */ /* */
/* *************************************************************************** */ /* *************************************************************************** */
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$langs->trans("OrderCard"); $langs->trans("OrderCard");
$head = reception_prepare_head($object); $head = reception_prepare_head($object);
@ -210,8 +197,7 @@ if ($id > 0 || !empty($ref))
print '<table class="border centpercent">'; print '<table class="border centpercent">';
// Linked documents // Linked documents
if ($origin == 'order_supplier' && $object->$typeobject->id && !empty($conf->fournisseur->enabled)) if ($origin == 'order_supplier' && $object->$typeobject->id && !empty($conf->fournisseur->enabled)) {
{
print '<tr><td class="titlefield">'; print '<tr><td class="titlefield">';
$objectsrc = new CommandeFournisseur($db); $objectsrc = new CommandeFournisseur($db);
$objectsrc->fetch($object->$typeobject->id); $objectsrc->fetch($object->$typeobject->id);
@ -221,8 +207,7 @@ if ($id > 0 || !empty($ref))
print "</td>\n"; print "</td>\n";
print '</tr>'; print '</tr>';
} }
if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) {
{
print '<tr><td class="titlefield">'; print '<tr><td class="titlefield">';
$objectsrc = new Propal($db); $objectsrc = new Propal($db);
$objectsrc->fetch($object->$typeobject->id); $objectsrc->fetch($object->$typeobject->id);
@ -256,10 +241,11 @@ if ($id > 0 || !empty($ref))
// Contacts lines (modules that overwrite templates must declare this into descriptor) // Contacts lines (modules that overwrite templates must declare this into descriptor)
$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
foreach ($dirtpls as $reldir) foreach ($dirtpls as $reldir) {
{
$res = @include dol_buildpath($reldir.'/contacts.tpl.php'); $res = @include dol_buildpath($reldir.'/contacts.tpl.php');
if ($res) break; if ($res) {
break;
}
} }
} }

View File

@ -53,8 +53,7 @@ print load_fiche_titre($langs->trans("ReceptionsArea"), '', 'dollyrevert');
print '<div class="fichecenter"><div class="fichethirdleft">'; print '<div class="fichecenter"><div class="fichethirdleft">';
if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo
{
print '<form method="post" action="list.php">'; print '<form method="post" action="list.php">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
@ -79,30 +78,28 @@ $sql .= " FROM ".MAIN_DB_PREFIX."reception as e";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON e.rowid = el.fk_target AND el.targettype = 'reception'"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON e.rowid = el.fk_target AND el.targettype = 'reception'";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseur as c ON el.fk_source = c.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseur as c ON el.fk_source = c.rowid";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = e.fk_soc"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = e.fk_soc";
if (!$user->rights->societe->client->voir && !$socid) if (!$user->rights->societe->client->voir && !$socid) {
{
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON e.fk_soc = sc.fk_soc"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON e.fk_soc = sc.fk_soc";
$sql .= $clause." sc.fk_user = ".$user->id; $sql .= $clause." sc.fk_user = ".$user->id;
$clause = " AND "; $clause = " AND ";
} }
$sql .= $clause." e.fk_statut = 0"; $sql .= $clause." e.fk_statut = 0";
$sql .= " AND e.entity IN (".getEntity('reception').")"; $sql .= " AND e.entity IN (".getEntity('reception').")";
if ($socid) $sql .= " AND c.fk_soc = ".$socid; if ($socid) {
$sql .= " AND c.fk_soc = ".$socid;
}
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
print '<th colspan="3">'.$langs->trans("ReceptionsToValidate").'</th></tr>'; print '<th colspan="3">'.$langs->trans("ReceptionsToValidate").'</th></tr>';
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
if ($num) if ($num) {
{
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$reception->id = $obj->rowid; $reception->id = $obj->rowid;
@ -116,7 +113,9 @@ if ($resql)
print '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$obj->socid.'">'.$obj->name.'</a>'; print '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$obj->socid.'">'.$obj->name.'</a>';
print '</td>'; print '</td>';
print '<td>'; print '<td>';
if ($obj->commande_fournisseur_id) print '<a href="'.DOL_URL_ROOT.'/commande_fournisseur/card.php?id='.$obj->commande_fournisseur_id.'">'.$obj->commande_fournisseur_ref.'</a>'; if ($obj->commande_fournisseur_id) {
print '<a href="'.DOL_URL_ROOT.'/commande_fournisseur/card.php?id='.$obj->commande_fournisseur_id.'">'.$obj->commande_fournisseur_ref.'</a>';
}
print '</td></tr>'; print '</td></tr>';
$i++; $i++;
} }
@ -144,27 +143,30 @@ $sql .= " FROM ".MAIN_DB_PREFIX."reception as e";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON e.rowid = el.fk_target AND el.targettype = 'reception' AND el.sourcetype IN ('order_supplier')"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON e.rowid = el.fk_target AND el.targettype = 'reception' AND el.sourcetype IN ('order_supplier')";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseur as c ON el.fk_source = c.rowid AND el.sourcetype IN ('order_supplier') AND el.targettype = 'reception'"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseur as c ON el.fk_source = c.rowid AND el.sourcetype IN ('order_supplier') AND el.targettype = 'reception'";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = e.fk_soc"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = e.fk_soc";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON e.fk_soc = sc.fk_soc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON e.fk_soc = sc.fk_soc";
}
$sql .= " WHERE e.entity IN (".getEntity('reception').")"; $sql .= " WHERE e.entity IN (".getEntity('reception').")";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND sc.fk_user = ".$user->id;
}
$sql .= " AND e.fk_statut = 1"; $sql .= " AND e.fk_statut = 1";
if ($socid) $sql .= " AND c.fk_soc = ".$socid; if ($socid) {
$sql .= " AND c.fk_soc = ".$socid;
}
$sql .= " ORDER BY e.date_delivery DESC"; $sql .= " ORDER BY e.date_delivery DESC";
$sql .= $db->plimit($max, 0); $sql .= $db->plimit($max, 0);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
if ($num) if ($num) {
{
$i = 0; $i = 0;
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
print '<th colspan="3">'.$langs->trans("LastReceptions", $num).'</th></tr>'; print '<th colspan="3">'.$langs->trans("LastReceptions", $num).'</th></tr>';
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$reception->id = $obj->rowid; $reception->id = $obj->rowid;
@ -176,19 +178,22 @@ if ($resql)
print '</td>'; print '</td>';
print '<td><a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$obj->socid.'">'.img_object($langs->trans("ShowCompany"), "company").' '.$obj->name.'</a></td>'; print '<td><a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$obj->socid.'">'.img_object($langs->trans("ShowCompany"), "company").' '.$obj->name.'</a></td>';
print '<td>'; print '<td>';
if ($obj->commande_fournisseur_id > 0) if ($obj->commande_fournisseur_id > 0) {
{
$orderstatic->id = $obj->commande_fournisseur_id; $orderstatic->id = $obj->commande_fournisseur_id;
$orderstatic->ref = $obj->commande_fournisseur_ref; $orderstatic->ref = $obj->commande_fournisseur_ref;
print $orderstatic->getNomUrl(1); print $orderstatic->getNomUrl(1);
} else print '&nbsp;'; } else {
print '&nbsp;';
}
print '</td></tr>'; print '</td></tr>';
$i++; $i++;
} }
print "</table></div><br>"; print "</table></div><br>";
} }
$db->free($resql); $db->free($resql);
} else dol_print_error($db); } else {
dol_print_error($db);
}
@ -199,19 +204,23 @@ if ($resql)
$sql = "SELECT c.rowid, c.ref, c.ref_supplier as ref_supplier, c.fk_statut as status, c.billed as billed, s.nom as name, s.rowid as socid"; $sql = "SELECT c.rowid, c.ref, c.ref_supplier as ref_supplier, c.fk_statut as status, c.billed as billed, s.nom as name, s.rowid as socid";
$sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c,"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c,";
$sql .= " ".MAIN_DB_PREFIX."societe as s"; $sql .= " ".MAIN_DB_PREFIX."societe as s";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " WHERE c.fk_soc = s.rowid";
$sql .= " AND c.entity IN (".getEntity('supplier_order').")"; $sql .= " AND c.entity IN (".getEntity('supplier_order').")";
$sql .= " AND c.fk_statut IN (".CommandeFournisseur::STATUS_ORDERSENT.", ".CommandeFournisseur::STATUS_RECEIVED_PARTIALLY.")"; $sql .= " AND c.fk_statut IN (".CommandeFournisseur::STATUS_ORDERSENT.", ".CommandeFournisseur::STATUS_RECEIVED_PARTIALLY.")";
if ($socid > 0) $sql .= " AND c.fk_soc = ".$socid; if ($socid > 0) {
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; $sql .= " AND c.fk_soc = ".$socid;
}
if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
$sql .= " ORDER BY c.rowid ASC"; $sql .= " ORDER BY c.rowid ASC";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
if ($num) if ($num) {
{
$langs->load("orders"); $langs->load("orders");
$i = 0; $i = 0;
@ -219,8 +228,7 @@ if ($resql)
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
print '<th colspan="3">'.$langs->trans("SuppliersOrdersToProcess").' <span class="badge">'.$num.'</span></th></tr>'; print '<th colspan="3">'.$langs->trans("SuppliersOrdersToProcess").' <span class="badge">'.$num.'</span></th></tr>';
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$orderstatic->id = $obj->rowid; $orderstatic->id = $obj->rowid;

View File

@ -42,7 +42,9 @@ $toselect = GETPOST('toselect', 'array');
// Security check // Security check
$receptionid = GETPOST('id', 'int'); $receptionid = GETPOST('id', 'int');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'reception', $receptionid, ''); $result = restrictedArea($user, 'reception', $receptionid, '');
$diroutputmassaction = $conf->reception->dir_output.'/temp/massgeneration/'.$user->id; $diroutputmassaction = $conf->reception->dir_output.'/temp/massgeneration/'.$user->id;
@ -64,9 +66,15 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (!$sortfield) $sortfield = "e.ref"; if (!$sortfield) {
if (!$sortorder) $sortorder = "DESC"; $sortfield = "e.ref";
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 }
if (!$sortorder) {
$sortorder = "DESC";
}
if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
@ -92,7 +100,9 @@ $fieldstosearchall = array(
's.nom'=>"ThirdParty", 's.nom'=>"ThirdParty",
'e.note_public'=>'NotePublic', 'e.note_public'=>'NotePublic',
); );
if (empty($user->socid)) $fieldstosearchall["e.note_private"] = "NotePrivate"; if (empty($user->socid)) {
$fieldstosearchall["e.note_private"] = "NotePrivate";
}
$checkedtypetiers = 0; $checkedtypetiers = 0;
$arrayfields = array( $arrayfields = array(
@ -124,18 +134,23 @@ $error = 0;
* Actions * Actions
*/ */
if (GETPOST('cancel')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel')) {
if (!GETPOST('confirmmassaction') && $massaction != 'confirm_createbills') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction') && $massaction != 'confirm_createbills') {
$massaction = '';
}
$parameters = array('socid'=>$socid); $parameters = array('socid'=>$socid);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$search_ref_supplier = ''; $search_ref_supplier = '';
$search_ref_rcp = ''; $search_ref_rcp = '';
$search_ref_liv = ''; $search_ref_liv = '';
@ -150,8 +165,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
$search_array_options = array(); $search_array_options = array();
} }
if (empty($reshook)) if (empty($reshook)) {
{
if ($massaction == 'confirm_createbills') { if ($massaction == 'confirm_createbills') {
$receptions = GETPOST('toselect', 'array'); $receptions = GETPOST('toselect', 'array');
$createbills_onebythird = GETPOST('createbills_onebythird', 'int'); $createbills_onebythird = GETPOST('createbills_onebythird', 'int');
@ -164,8 +178,7 @@ if (empty($reshook))
$db->begin(); $db->begin();
$errors = array(); $errors = array();
foreach ($receptions as $id_reception) foreach ($receptions as $id_reception) {
{
$rcp = new Reception($db); $rcp = new Reception($db);
// On ne facture que les réceptions validées // On ne facture que les réceptions validées
if ($rcp->fetch($id_reception) <= 0 || $rcp->statut != 1) { if ($rcp->fetch($id_reception) <= 0 || $rcp->statut != 1) {
@ -177,18 +190,21 @@ if (empty($reshook))
$object = new FactureFournisseur($db); $object = new FactureFournisseur($db);
if (!empty($createbills_onebythird) && !empty($TFactThird[$rcp->socid])) { if (!empty($createbills_onebythird) && !empty($TFactThird[$rcp->socid])) {
$object = $TFactThird[$rcp->socid]; // If option "one bill per third" is set, we use already created reception. $object = $TFactThird[$rcp->socid]; // If option "one bill per third" is set, we use already created reception.
if (empty($object->rowid) && $object->id != null)$object->rowid = $object->id; if (empty($object->rowid) && $object->id != null) {
if (!empty($object->rowid))$object->fetchObjectLinked(); $object->rowid = $object->id;
}
if (!empty($object->rowid)) {
$object->fetchObjectLinked();
}
$rcp->fetchObjectLinked(); $rcp->fetchObjectLinked();
if (count($rcp->linkedObjectsIds['reception']) > 0) if (count($rcp->linkedObjectsIds['reception']) > 0) {
{ foreach ($rcp->linkedObjectsIds['reception'] as $key => $value) {
foreach ($rcp->linkedObjectsIds['reception'] as $key => $value) if (empty($object->linkedObjectsIds['reception']) || !in_array($value, $object->linkedObjectsIds['reception'])) { //Dont try to link if already linked
{
if (empty($object->linkedObjectsIds['reception']) || !in_array($value, $object->linkedObjectsIds['reception']))//Dont try to link if already linked
$object->add_object_linked('reception', $value); // add supplier order linked object $object->add_object_linked('reception', $value); // add supplier order linked object
} }
} }
}
} else { } else {
$object->socid = $rcp->socid; $object->socid = $rcp->socid;
$object->type = FactureFournisseur::TYPE_STANDARD; $object->type = FactureFournisseur::TYPE_STANDARD;
@ -202,8 +218,7 @@ if (empty($reshook))
$object->ref_supplier = $rcp->ref_supplier; $object->ref_supplier = $rcp->ref_supplier;
$datefacture = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
if (empty($datefacture)) if (empty($datefacture)) {
{
$datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y"));
} }
@ -212,10 +227,8 @@ if (empty($reshook))
$object->origin_id = $id_reception; $object->origin_id = $id_reception;
$rcp->fetchObjectLinked(); $rcp->fetchObjectLinked();
if (count($rcp->linkedObjectsIds['reception']) > 0) if (count($rcp->linkedObjectsIds['reception']) > 0) {
{ foreach ($rcp->linkedObjectsIds['reception'] as $key => $value) {
foreach ($rcp->linkedObjectsIds['reception'] as $key => $value)
{
$object->linked_objects['reception'] = $value; $object->linked_objects['reception'] = $value;
} }
} }
@ -231,23 +244,19 @@ if (empty($reshook))
} }
} }
if ($object->id > 0) if ($object->id > 0) {
{
if (!empty($createbills_onebythird) && !empty($TFactThird[$rcp->socid])) { //cause function create already add object linked for facturefournisseur if (!empty($createbills_onebythird) && !empty($TFactThird[$rcp->socid])) { //cause function create already add object linked for facturefournisseur
$res = $object->add_object_linked($object->origin, $id_reception); $res = $object->add_object_linked($object->origin, $id_reception);
if ($res == 0) if ($res == 0) {
{
$errors[] = $object->error; $errors[] = $object->error;
$error++; $error++;
} }
} }
if (!$error) if (!$error) {
{
$lines = $rcp->lines; $lines = $rcp->lines;
if (empty($lines) && method_exists($rcp, 'fetch_lines')) if (empty($lines) && method_exists($rcp, 'fetch_lines')) {
{
$rcp->fetch_lines(); $rcp->fetch_lines();
$lines = $rcp->lines; $lines = $rcp->lines;
} }
@ -255,11 +264,9 @@ if (empty($reshook))
$fk_parent_line = 0; $fk_parent_line = 0;
$num = count($lines); $num = count($lines);
for ($i = 0; $i < $num; $i++) for ($i = 0; $i < $num; $i++) {
{
$desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle);
if ($lines[$i]->subprice < 0) if ($lines[$i]->subprice < 0) {
{
// Negative line, we create a discount line // Negative line, we create a discount line
$discount = new DiscountAbsolute($db); $discount = new DiscountAbsolute($db);
$discount->fk_soc = $object->socid; $discount->fk_soc = $object->socid;
@ -270,8 +277,7 @@ if (empty($reshook))
$discount->fk_user = $user->id; $discount->fk_user = $user->id;
$discount->description = $desc; $discount->description = $desc;
$discountid = $discount->create($user); $discountid = $discount->create($user);
if ($discountid > 0) if ($discountid > 0) {
{
$result = $object->insert_discount($discountid); $result = $object->insert_discount($discountid);
//$result=$discount->link_to_invoice($lineid,$id); //$result=$discount->link_to_invoice($lineid,$id);
} else { } else {
@ -284,17 +290,28 @@ if (empty($reshook))
$product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
// Date start // Date start
$date_start = false; $date_start = false;
if ($lines[$i]->date_debut_prevue) $date_start = $lines[$i]->date_debut_prevue; if ($lines[$i]->date_debut_prevue) {
if ($lines[$i]->date_debut_reel) $date_start = $lines[$i]->date_debut_reel; $date_start = $lines[$i]->date_debut_prevue;
if ($lines[$i]->date_start) $date_start = $lines[$i]->date_start; }
if ($lines[$i]->date_debut_reel) {
$date_start = $lines[$i]->date_debut_reel;
}
if ($lines[$i]->date_start) {
$date_start = $lines[$i]->date_start;
}
//Date end //Date end
$date_end = false; $date_end = false;
if ($lines[$i]->date_fin_prevue) $date_end = $lines[$i]->date_fin_prevue; if ($lines[$i]->date_fin_prevue) {
if ($lines[$i]->date_fin_reel) $date_end = $lines[$i]->date_fin_reel; $date_end = $lines[$i]->date_fin_prevue;
if ($lines[$i]->date_end) $date_end = $lines[$i]->date_end; }
if ($lines[$i]->date_fin_reel) {
$date_end = $lines[$i]->date_fin_reel;
}
if ($lines[$i]->date_end) {
$date_end = $lines[$i]->date_end;
}
// Reset fk_parent_line for no child products and special product // Reset fk_parent_line for no child products and special product
if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
{
$fk_parent_line = 0; $fk_parent_line = 0;
} }
$result = $object->addline( $result = $object->addline(
@ -323,8 +340,7 @@ if (empty($reshook))
$rcp->add_object_linked('facture_fourn_det', $result); $rcp->add_object_linked('facture_fourn_det', $result);
if ($result > 0) if ($result > 0) {
{
$lineid = $result; $lineid = $result;
} else { } else {
$lineid = 0; $lineid = 0;
@ -332,8 +348,7 @@ if (empty($reshook))
break; break;
} }
// Defined the new fk_parent_line // Defined the new fk_parent_line
if ($result > 0 && $lines[$i]->product_type == 9) if ($result > 0 && $lines[$i]->product_type == 9) {
{
$fk_parent_line = $result; $fk_parent_line = $result;
} }
} }
@ -343,22 +358,22 @@ if (empty($reshook))
//$rcp->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module. //$rcp->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module.
if (!empty($createbills_onebythird) && empty($TFactThird[$rcp->socid])) $TFactThird[$rcp->socid] = $object; if (!empty($createbills_onebythird) && empty($TFactThird[$rcp->socid])) {
else $TFact[$object->id] = $object; $TFactThird[$rcp->socid] = $object;
} else {
$TFact[$object->id] = $object;
}
} }
// Build doc with all invoices // Build doc with all invoices
$TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird;
$toselect = array(); $toselect = array();
if (!$error && $validate_invoices) if (!$error && $validate_invoices) {
{
$massaction = $action = 'builddoc'; $massaction = $action = 'builddoc';
foreach ($TAllFact as &$object) foreach ($TAllFact as &$object) {
{
$result = $object->validate($user); $result = $object->validate($user);
if ($result <= 0) if ($result <= 0) {
{
$error++; $error++;
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
break; break;
@ -376,8 +391,7 @@ if (empty($reshook))
$massaction = $action = 'confirm_createbills'; $massaction = $action = 'confirm_createbills';
} }
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
setEventMessage($langs->trans('BillCreated', $nb_bills_created)); setEventMessage($langs->trans('BillCreated', $nb_bills_created));
} else { } else {
@ -413,60 +427,85 @@ $sql .= " state.code_departement as state_code, state.nom as state_name,";
$sql .= ' e.date_creation as date_creation, e.tms as date_update'; $sql .= ' e.date_creation as date_creation, e.tms as date_update';
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) { if (!empty($extrafields->attributes[$object->table_element]['label'])) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
}
} }
// Add fields from hooks // Add fields from hooks
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint; $sql .= $hookmanager->resPrint;
$sql .= " FROM ".MAIN_DB_PREFIX."reception as e"; $sql .= " FROM ".MAIN_DB_PREFIX."reception as e";
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (e.rowid = ef.fk_object)"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (e.rowid = ef.fk_object)";
}
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = e.fk_soc"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = e.fk_soc";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as ee ON e.rowid = ee.fk_source AND ee.sourcetype = 'reception' AND ee.targettype = 'delivery'"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as ee ON e.rowid = ee.fk_source AND ee.sourcetype = 'reception' AND ee.targettype = 'delivery'";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."delivery as l ON l.rowid = ee.fk_target"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."delivery as l ON l.rowid = ee.fk_target";
if (!$user->rights->societe->client->voir && !$socid) // Internal user with no permission to see all if (!$user->rights->societe->client->voir && !$socid) { // Internal user with no permission to see all
{
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
} }
$sql .= " WHERE e.entity IN (".getEntity('reception').")"; $sql .= " WHERE e.entity IN (".getEntity('reception').")";
if (!$user->rights->societe->client->voir && !$socid) // Internal user with no permission to see all if (!$user->rights->societe->client->voir && !$socid) { // Internal user with no permission to see all
{
$sql .= " AND e.fk_soc = sc.fk_soc"; $sql .= " AND e.fk_soc = sc.fk_soc";
$sql .= " AND sc.fk_user = ".$user->id; $sql .= " AND sc.fk_user = ".$user->id;
} }
if ($socid) if ($socid) {
{
$sql .= " AND e.fk_soc = ".$socid; $sql .= " AND e.fk_soc = ".$socid;
} }
if ($search_status <> '' && $search_status >= 0) { if ($search_status <> '' && $search_status >= 0) {
$sql .= " AND e.fk_statut = ".$search_status; $sql .= " AND e.fk_statut = ".$search_status;
} }
if ($search_billed != '' && $search_billed >= 0) $sql .= ' AND e.billed = '.$search_billed; if ($search_billed != '' && $search_billed >= 0) {
if ($search_town) $sql .= natural_search('s.town', $search_town); $sql .= ' AND e.billed = '.$search_billed;
if ($search_zip) $sql .= natural_search("s.zip", $search_zip); }
if ($search_state) $sql .= natural_search("state.nom", $search_state); if ($search_town) {
if ($search_country) $sql .= " AND s.fk_pays IN (".$search_country.')'; $sql .= natural_search('s.town', $search_town);
if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; }
if ($search_ref_rcp) $sql .= natural_search('e.ref', $search_ref_rcp); if ($search_zip) {
if ($search_ref_liv) $sql .= natural_search('l.ref', $search_ref_liv); $sql .= natural_search("s.zip", $search_zip);
if ($search_company) $sql .= natural_search('s.nom', $search_company); }
if ($search_ref_supplier) $sql .= natural_search('e.ref_supplier', $search_ref_supplier); if ($search_state) {
if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); $sql .= natural_search("state.nom", $search_state);
}
if ($search_country) {
$sql .= " AND s.fk_pays IN (".$search_country.')';
}
if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) {
$sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')';
}
if ($search_ref_rcp) {
$sql .= natural_search('e.ref', $search_ref_rcp);
}
if ($search_ref_liv) {
$sql .= natural_search('l.ref', $search_ref_liv);
}
if ($search_company) {
$sql .= natural_search('s.nom', $search_company);
}
if ($search_ref_supplier) {
$sql .= natural_search('e.ref_supplier', $search_ref_supplier);
}
if ($sall) {
$sql .= natural_search(array_keys($fieldstosearchall), $sall);
}
// Add where from extra fields // Add where from extra fields
foreach ($search_array_options as $key => $val) foreach ($search_array_options as $key => $val) {
{
$crit = $val; $crit = $val;
$tmpkey = preg_replace('/search_options_/', '', $key); $tmpkey = preg_replace('/search_options_/', '', $key);
$typ = $extrafields->attributes[$object->table_element]['type'][$tmpkey]; $typ = $extrafields->attributes[$object->table_element]['type'][$tmpkey];
$mode = 0; $mode = 0;
if (in_array($typ, array('int', 'double', 'real'))) $mode = 1; // Search on a numeric if (in_array($typ, array('int', 'double', 'real'))) {
if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode = 2; // Search on a foreign key int $mode = 1; // Search on a numeric
if ($crit != '' && (!in_array($typ, array('select', 'sellist')) || $crit != '0')) }
{ if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') {
$mode = 2; // Search on a foreign key int
}
if ($crit != '' && (!in_array($typ, array('select', 'sellist')) || $crit != '0')) {
$sql .= natural_search('ef.'.$tmpkey, $crit, $mode); $sql .= natural_search('ef.'.$tmpkey, $crit, $mode);
} }
} }
@ -476,8 +515,7 @@ $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // No
$sql .= $hookmanager->resPrint; $sql .= $hookmanager->resPrint;
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result); $nbtotalofrecords = $db->num_rows($result);
} }
@ -499,27 +537,58 @@ $reception = new Reception($db);
$arrayofselected = is_array($toselect) ? $toselect : array(); $arrayofselected = is_array($toselect) ? $toselect : array();
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($sall) $param .= "&amp;sall=".urlencode($sall); }
if ($search_ref_rcp) $param .= "&amp;search_ref_rcp=".urlencode($search_ref_rcp); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($search_ref_liv) $param .= "&amp;search_ref_liv=".urlencode($search_ref_liv); $param .= '&limit='.urlencode($limit);
if ($search_company) $param .= "&amp;search_company=".urlencode($search_company); }
if ($optioncss != '') $param .= '&amp;optioncss='.urlencode($optioncss); if ($sall) {
if ($search_billed != '' && $search_billed >= 0) $param .= "&amp;search_billed=".urlencode($search_billed); $param .= "&amp;sall=".urlencode($sall);
if ($search_town) $param .= "&amp;search_town=".urlencode($search_town); }
if ($search_zip) $param .= "&amp;search_zip=".urlencode($search_zip); if ($search_ref_rcp) {
if ($search_state) $param .= "&amp;search_state=".urlencode($search_state); $param .= "&amp;search_ref_rcp=".urlencode($search_ref_rcp);
if ($search_status != '') $param .= "&amp;search_status=".urlencode($search_status); }
if ($search_country) $param .= "&amp;search_country=".urlencode($search_country); if ($search_ref_liv) {
if ($search_type_thirdparty) $param .= "&amp;search_type_thirdparty=".urlencode($search_type_thirdparty); $param .= "&amp;search_ref_liv=".urlencode($search_ref_liv);
if ($search_ref_supplier) $param .= "&amp;search_ref_supplier=".urlencode($search_ref_supplier); }
if ($search_company) {
$param .= "&amp;search_company=".urlencode($search_company);
}
if ($optioncss != '') {
$param .= '&amp;optioncss='.urlencode($optioncss);
}
if ($search_billed != '' && $search_billed >= 0) {
$param .= "&amp;search_billed=".urlencode($search_billed);
}
if ($search_town) {
$param .= "&amp;search_town=".urlencode($search_town);
}
if ($search_zip) {
$param .= "&amp;search_zip=".urlencode($search_zip);
}
if ($search_state) {
$param .= "&amp;search_state=".urlencode($search_state);
}
if ($search_status != '') {
$param .= "&amp;search_status=".urlencode($search_status);
}
if ($search_country) {
$param .= "&amp;search_country=".urlencode($search_country);
}
if ($search_type_thirdparty) {
$param .= "&amp;search_type_thirdparty=".urlencode($search_type_thirdparty);
}
if ($search_ref_supplier) {
$param .= "&amp;search_ref_supplier=".urlencode($search_ref_supplier);
}
// Add $param from extra fields // Add $param from extra fields
foreach ($search_array_options as $key => $val) foreach ($search_array_options as $key => $val) {
{
$crit = $val; $crit = $val;
$tmpkey = preg_replace('/search_options_/', '', $key); $tmpkey = preg_replace('/search_options_/', '', $key);
if ($val != '') $param .= '&search_options_'.$tmpkey.'='.urlencode($val); if ($val != '') {
$param .= '&search_options_'.$tmpkey.'='.urlencode($val);
}
} }
@ -527,14 +596,20 @@ $arrayofmassactions = array(
// 'presend'=>$langs->trans("SendByMail"), // 'presend'=>$langs->trans("SendByMail"),
); );
if ($user->rights->fournisseur->facture->creer)$arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisSupplier"); if ($user->rights->fournisseur->facture->creer) {
if ($massaction == 'createbills') $arrayofmassactions = array(); $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisSupplier");
}
if ($massaction == 'createbills') {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
//$massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); //$massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge")));
$i = 0; $i = 0;
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'."\n"; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'."\n";
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@ -543,9 +618,7 @@ print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
print_barre_liste($langs->trans('ListOfReceptions'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'dollyrevert', 0, '', '', $limit, 0, 0, 1); print_barre_liste($langs->trans('ListOfReceptions'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'dollyrevert', 0, '', '', $limit, 0, 0, 1);
if ($massaction == 'createbills') {
if ($massaction == 'createbills')
{
//var_dump($_REQUEST); //var_dump($_REQUEST);
print '<input type="hidden" name="massaction" value="confirm_createbills">'; print '<input type="hidden" name="massaction" value="confirm_createbills">';
@ -571,8 +644,7 @@ if ($massaction == 'createbills')
print $langs->trans('ValidateInvoices'); print $langs->trans('ValidateInvoices');
print '</td>'; print '</td>';
print '<td>'; print '<td>';
if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
{
print $form->selectyesno('validate_invoices', 0, 1, 1); print $form->selectyesno('validate_invoices', 0, 1, 1);
print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')'; print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')';
} else { } else {
@ -590,15 +662,15 @@ if ($massaction == 'createbills')
print '<br>'; print '<br>';
} }
if ($sall) if ($sall) {
{ foreach ($fieldstosearchall as $key => $val) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); $fieldstosearchall[$key] = $langs->trans($val);
}
print $langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall); print $langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall);
} }
$moreforfilter = ''; $moreforfilter = '';
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
$parameters = array('type'=>$type); $parameters = array('type'=>$type);
@ -619,65 +691,60 @@ print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" :
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre_filter">'; print '<tr class="liste_titre_filter">';
// Ref // Ref
if (!empty($arrayfields['e.ref']['checked'])) if (!empty($arrayfields['e.ref']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input class="flat" size="6" type="text" name="search_ref_rcp" value="'.$search_ref_rcp.'">'; print '<input class="flat" size="6" type="text" name="search_ref_rcp" value="'.$search_ref_rcp.'">';
print '</td>'; print '</td>';
} }
// Ref customer // Ref customer
if (!empty($arrayfields['e.ref_supplier']['checked'])) if (!empty($arrayfields['e.ref_supplier']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input class="flat" size="6" type="text" name="search_ref_supplier" value="'.$search_ref_supplier.'">'; print '<input class="flat" size="6" type="text" name="search_ref_supplier" value="'.$search_ref_supplier.'">';
print '</td>'; print '</td>';
} }
// Thirdparty // Thirdparty
if (!empty($arrayfields['s.nom']['checked'])) if (!empty($arrayfields['s.nom']['checked'])) {
{
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat" type="text" size="8" name="search_company" value="'.dol_escape_htmltag($search_company).'">'; print '<input class="flat" type="text" size="8" name="search_company" value="'.dol_escape_htmltag($search_company).'">';
print '</td>'; print '</td>';
} }
// Town // Town
if (!empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>'; if (!empty($arrayfields['s.town']['checked'])) {
print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>';
}
// Zip // Zip
if (!empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_zip" value="'.$search_zip.'"></td>'; if (!empty($arrayfields['s.zip']['checked'])) {
print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_zip" value="'.$search_zip.'"></td>';
}
// State // State
if (!empty($arrayfields['state.nom']['checked'])) if (!empty($arrayfields['state.nom']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">';
print '</td>'; print '</td>';
} }
// Country // Country
if (!empty($arrayfields['country.code_iso']['checked'])) if (!empty($arrayfields['country.code_iso']['checked'])) {
{
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100');
print '</td>'; print '</td>';
} }
// Company type // Company type
if (!empty($arrayfields['typent.code']['checked'])) if (!empty($arrayfields['typent.code']['checked'])) {
{
print '<td class="liste_titre maxwidthonsmartphone center">'; print '<td class="liste_titre maxwidthonsmartphone center">';
print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1);
print '</td>'; print '</td>';
} }
// Date delivery planned // Date delivery planned
if (!empty($arrayfields['e.date_delivery']['checked'])) if (!empty($arrayfields['e.date_delivery']['checked'])) {
{
print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>';
} }
if (!empty($arrayfields['l.ref']['checked'])) if (!empty($arrayfields['l.ref']['checked'])) {
{
// Delivery ref // Delivery ref
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input class="flat" size="10" type="text" name="search_ref_liv" value="'.$search_ref_liv.'"'; print '<input class="flat" size="10" type="text" name="search_ref_liv" value="'.$search_ref_liv.'"';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['l.date_delivery']['checked'])) if (!empty($arrayfields['l.date_delivery']['checked'])) {
{
// Date received // Date received
print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>';
} }
@ -689,27 +756,23 @@ $parameters = array('arrayfields'=>$arrayfields);
$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
// Date creation // Date creation
if (!empty($arrayfields['e.datec']['checked'])) if (!empty($arrayfields['e.datec']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
// Date modification // Date modification
if (!empty($arrayfields['e.tms']['checked'])) if (!empty($arrayfields['e.tms']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
// Status // Status
if (!empty($arrayfields['e.fk_statut']['checked'])) if (!empty($arrayfields['e.fk_statut']['checked'])) {
{
print '<td class="liste_titre maxwidthonsmartphone right">'; print '<td class="liste_titre maxwidthonsmartphone right">';
print $form->selectarray('search_status', array('0'=>$langs->trans('StatusReceptionDraftShort'), '1'=>$langs->trans('StatusReceptionValidatedShort'), '2'=>$langs->trans('StatusReceptionProcessedShort')), $search_status, 1); print $form->selectarray('search_status', array('0'=>$langs->trans('StatusReceptionDraftShort'), '1'=>$langs->trans('StatusReceptionValidatedShort'), '2'=>$langs->trans('StatusReceptionProcessedShort')), $search_status, 1);
print '</td>'; print '</td>';
} }
// Status billed // Status billed
if (!empty($arrayfields['e.billed']['checked'])) if (!empty($arrayfields['e.billed']['checked'])) {
{
print '<td class="liste_titre maxwidthonsmartphone center">'; print '<td class="liste_titre maxwidthonsmartphone center">';
print $form->selectyesno('search_billed', $search_billed, 1, 0, 1); print $form->selectyesno('search_billed', $search_billed, 1, 0, 1);
print '</td>'; print '</td>';
@ -722,34 +785,63 @@ print '</td>';
print "</tr>\n"; print "</tr>\n";
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
if (!empty($arrayfields['e.ref']['checked'])) print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['e.ref']['checked'])) {
if (!empty($arrayfields['e.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['e.ref_supplier']['label'], $_SERVER["PHP_SELF"], "e.ref_supplier", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder, 'left '); }
if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['e.ref_supplier']['checked'])) {
if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['e.ref_supplier']['label'], $_SERVER["PHP_SELF"], "e.ref_supplier", "", $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); }
if (!empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['s.nom']['checked'])) {
if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder, 'left ');
if (!empty($arrayfields['e.date_delivery']['checked'])) print_liste_field_titre($arrayfields['e.date_delivery']['label'], $_SERVER["PHP_SELF"], "e.date_delivery", "", $param, '', $sortfield, $sortorder, 'center '); }
if (!empty($arrayfields['l.ref']['checked'])) print_liste_field_titre($arrayfields['l.ref']['label'], $_SERVER["PHP_SELF"], "l.ref", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['s.town']['checked'])) {
if (!empty($arrayfields['l.date_delivery']['checked'])) print_liste_field_titre($arrayfields['l.date_delivery']['label'], $_SERVER["PHP_SELF"], "l.date_delivery", "", $param, '', $sortfield, $sortorder, 'center '); print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['s.zip']['checked'])) {
print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['state.nom']['checked'])) {
print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['country.code_iso']['checked'])) {
print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center ');
}
if (!empty($arrayfields['typent.code']['checked'])) {
print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center ');
}
if (!empty($arrayfields['e.date_delivery']['checked'])) {
print_liste_field_titre($arrayfields['e.date_delivery']['label'], $_SERVER["PHP_SELF"], "e.date_delivery", "", $param, '', $sortfield, $sortorder, 'center ');
}
if (!empty($arrayfields['l.ref']['checked'])) {
print_liste_field_titre($arrayfields['l.ref']['label'], $_SERVER["PHP_SELF"], "l.ref", "", $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['l.date_delivery']['checked'])) {
print_liste_field_titre($arrayfields['l.date_delivery']['label'], $_SERVER["PHP_SELF"], "l.date_delivery", "", $param, '', $sortfield, $sortorder, 'center ');
}
// Extra fields // Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
// Hook fields // Hook fields
$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if (!empty($arrayfields['e.datec']['checked'])) print_liste_field_titre($arrayfields['e.datec']['label'], $_SERVER["PHP_SELF"], "e.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); if (!empty($arrayfields['e.datec']['checked'])) {
if (!empty($arrayfields['e.tms']['checked'])) print_liste_field_titre($arrayfields['e.tms']['label'], $_SERVER["PHP_SELF"], "e.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); print_liste_field_titre($arrayfields['e.datec']['label'], $_SERVER["PHP_SELF"], "e.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
if (!empty($arrayfields['e.fk_statut']['checked'])) print_liste_field_titre($arrayfields['e.fk_statut']['label'], $_SERVER["PHP_SELF"], "e.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); }
if (!empty($arrayfields['e.billed']['checked'])) print_liste_field_titre($arrayfields['e.billed']['label'], $_SERVER["PHP_SELF"], "e.billed", "", $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['e.tms']['checked'])) {
print_liste_field_titre($arrayfields['e.tms']['label'], $_SERVER["PHP_SELF"], "e.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
}
if (!empty($arrayfields['e.fk_statut']['checked'])) {
print_liste_field_titre($arrayfields['e.fk_statut']['label'], $_SERVER["PHP_SELF"], "e.fk_statut", "", $param, '', $sortfield, $sortorder, 'right ');
}
if (!empty($arrayfields['e.billed']['checked'])) {
print_liste_field_titre($arrayfields['e.billed']['label'], $_SERVER["PHP_SELF"], "e.billed", "", $param, '', $sortfield, $sortorder, 'center ');
}
print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ');
print "</tr>\n"; print "</tr>\n";
$i = 0; $i = 0;
$totalarray = array(); $totalarray = array();
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$reception->id = $obj->rowid; $reception->id = $obj->rowid;
@ -763,8 +855,7 @@ while ($i < min($num, $limit))
print '<tr class="oddeven">'; print '<tr class="oddeven">';
// Ref // Ref
if (!empty($arrayfields['e.ref']['checked'])) if (!empty($arrayfields['e.ref']['checked'])) {
{
print "<td>"; print "<td>";
print $reception->getNomUrl(1); print $reception->getNomUrl(1);
$filename = dol_sanitizeFileName($reception->ref); $filename = dol_sanitizeFileName($reception->ref);
@ -773,70 +864,80 @@ while ($i < min($num, $limit))
print $formfile->getDocumentsLink($reception->element, $filename, $filedir); print $formfile->getDocumentsLink($reception->element, $filename, $filedir);
print "</td>\n"; print "</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Ref customer // Ref customer
if (!empty($arrayfields['e.ref_supplier']['checked'])) if (!empty($arrayfields['e.ref_supplier']['checked'])) {
{
print "<td>"; print "<td>";
print $obj->ref_supplier; print $obj->ref_supplier;
print "</td>\n"; print "</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Third party // Third party
if (!empty($arrayfields['s.nom']['checked'])) if (!empty($arrayfields['s.nom']['checked'])) {
{
print '<td>'; print '<td>';
print $companystatic->getNomUrl(1); print $companystatic->getNomUrl(1);
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Town // Town
if (!empty($arrayfields['s.town']['checked'])) if (!empty($arrayfields['s.town']['checked'])) {
{
print '<td class="nocellnopadd">'; print '<td class="nocellnopadd">';
print $obj->town; print $obj->town;
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Zip // Zip
if (!empty($arrayfields['s.zip']['checked'])) if (!empty($arrayfields['s.zip']['checked'])) {
{
print '<td class="nocellnopadd">'; print '<td class="nocellnopadd">';
print $obj->zip; print $obj->zip;
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// State // State
if (!empty($arrayfields['state.nom']['checked'])) if (!empty($arrayfields['state.nom']['checked'])) {
{
print "<td>".$obj->state_name."</td>\n"; print "<td>".$obj->state_name."</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Country // Country
if (!empty($arrayfields['country.code_iso']['checked'])) if (!empty($arrayfields['country.code_iso']['checked'])) {
{
print '<td class="center">'; print '<td class="center">';
$tmparray = getCountry($obj->fk_pays, 'all'); $tmparray = getCountry($obj->fk_pays, 'all');
print $tmparray['label']; print $tmparray['label'];
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Type ent // Type ent
if (!empty($arrayfields['typent.code']['checked'])) if (!empty($arrayfields['typent.code']['checked'])) {
{
print '<td class="center">'; print '<td class="center">';
if (count($typenArray) == 0) $typenArray = $formcompany->typent_array(1); if (count($typenArray) == 0) {
$typenArray = $formcompany->typent_array(1);
}
print $typenArray[$obj->typent_code]; print $typenArray[$obj->typent_code];
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Date delivery planed // Date delivery planed
if (!empty($arrayfields['e.date_delivery']['checked'])) if (!empty($arrayfields['e.date_delivery']['checked'])) {
{
print '<td class="center">'; print '<td class="center">';
print dol_print_date($db->jdate($obj->delivery_date), "day"); print dol_print_date($db->jdate($obj->delivery_date), "day");
/*$now = time(); /*$now = time();
@ -846,22 +947,21 @@ while ($i < min($num, $limit))
print "</td>\n"; print "</td>\n";
} }
if (!empty($arrayfields['l.ref']['checked']) || !empty($arrayfields['l.date_delivery']['checked'])) if (!empty($arrayfields['l.ref']['checked']) || !empty($arrayfields['l.date_delivery']['checked'])) {
{
$reception->fetchObjectLinked($reception->id, $reception->element); $reception->fetchObjectLinked($reception->id, $reception->element);
$receiving = ''; $receiving = '';
if (count($reception->linkedObjects['delivery']) > 0) $receiving = reset($reception->linkedObjects['delivery']); if (count($reception->linkedObjects['delivery']) > 0) {
$receiving = reset($reception->linkedObjects['delivery']);
}
if (!empty($arrayfields['l.ref']['checked'])) if (!empty($arrayfields['l.ref']['checked'])) {
{
// Ref // Ref
print '<td>'; print '<td>';
print !empty($receiving) ? $receiving->getNomUrl($db) : ''; print !empty($receiving) ? $receiving->getNomUrl($db) : '';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['l.date_delivery']['checked'])) if (!empty($arrayfields['l.date_delivery']['checked'])) {
{
// Date received // Date received
print '<td class="center">'; print '<td class="center">';
print dol_print_date($db->jdate($obj->date_reception), "day"); print dol_print_date($db->jdate($obj->date_reception), "day");
@ -877,44 +977,52 @@ while ($i < min($num, $limit))
$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
// Date creation // Date creation
if (!empty($arrayfields['e.datec']['checked'])) if (!empty($arrayfields['e.datec']['checked'])) {
{
print '<td class="center nowrap">'; print '<td class="center nowrap">';
print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); print dol_print_date($db->jdate($obj->date_creation), 'dayhour');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Date modification // Date modification
if (!empty($arrayfields['e.tms']['checked'])) if (!empty($arrayfields['e.tms']['checked'])) {
{
print '<td class="center nowrap">'; print '<td class="center nowrap">';
print dol_print_date($db->jdate($obj->date_update), 'dayhour'); print dol_print_date($db->jdate($obj->date_update), 'dayhour');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Status // Status
if (!empty($arrayfields['e.fk_statut']['checked'])) if (!empty($arrayfields['e.fk_statut']['checked'])) {
{
print '<td class="right nowrap">'.$reception->LibStatut($obj->fk_statut, 5).'</td>'; print '<td class="right nowrap">'.$reception->LibStatut($obj->fk_statut, 5).'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Billed // Billed
if (!empty($arrayfields['e.billed']['checked'])) if (!empty($arrayfields['e.billed']['checked'])) {
{
print '<td class="center">'.yn($obj->billed).'</td>'; print '<td class="center">'.yn($obj->billed).'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Action column // Action column
print '<td class="center">'; print '<td class="center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) {
{ // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
$selected = 0; $selected = 0;
if (in_array($obj->rowid, $arrayofselected)) $selected = 1; if (in_array($obj->rowid, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print "</tr>\n"; print "</tr>\n";
@ -935,7 +1043,6 @@ if ($num == 0) {
print "</table>"; print "</table>";
print "</div>"; print "</div>";
print '</form>'; print '</form>';
$db->free($resql); $db->free($resql);
llxFooter(); llxFooter();

View File

@ -48,30 +48,28 @@ $action = GETPOST('action', 'aZ09');
// Security check // Security check
$socid = ''; $socid = '';
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, $origin, $origin_id); $result = restrictedArea($user, $origin, $origin_id);
$object = new Reception($db); $object = new Reception($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$object->fetch($id, $ref); $object->fetch($id, $ref);
$object->fetch_thirdparty(); $object->fetch_thirdparty();
if (!empty($object->origin)) if (!empty($object->origin)) {
{
$typeobject = $object->origin; $typeobject = $object->origin;
$origin = $object->origin; $origin = $object->origin;
$object->fetch_origin(); $object->fetch_origin();
} }
// Linked documents // Linked documents
if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) {
{
$objectsrc = new Commande($db); $objectsrc = new Commande($db);
$objectsrc->fetch($object->$typeobject->id); $objectsrc->fetch($object->$typeobject->id);
} }
if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) {
{
$objectsrc = new Propal($db); $objectsrc = new Propal($db);
$objectsrc->fetch($object->$typeobject->id); $objectsrc->fetch($object->$typeobject->id);
} }
@ -95,8 +93,7 @@ llxHeader('', 'Reception');
$form = new Form($db); $form = new Form($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$head = reception_prepare_head($object); $head = reception_prepare_head($object);
print dol_get_fiche_head($head, 'note', $langs->trans("Reception"), -1, 'dollyrevert'); print dol_get_fiche_head($head, 'note', $langs->trans("Reception"), -1, 'dollyrevert');

View File

@ -35,8 +35,7 @@ $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height');
$userid = GETPOST('userid', 'int'); $userid = GETPOST('userid', 'int');
$socid = GETPOST('socid', 'int'); $socid = GETPOST('socid', 'int');
// Security check // Security check
if ($user->socid > 0) if ($user->socid > 0) {
{
$action = ''; $action = '';
$socid = $user->socid; $socid = $user->socid;
} }
@ -74,8 +73,7 @@ $data = $stats->getNbByMonthWithPrevYear($endyear, $startyear);
// $data = array(array('Lib',val1,val2,val3),...) // $data = array(array('Lib',val1,val2,val3),...)
if (!$user->rights->societe->client->voir || $user->socid) if (!$user->rights->societe->client->voir || $user->socid) {
{
$filenamenb = $dir.'/receptionsnbinyear-'.$user->id.'-'.$year.'.png'; $filenamenb = $dir.'/receptionsnbinyear-'.$user->id.'-'.$year.'.png';
} else { } else {
$filenamenb = $dir.'/receptionsnbinyear-'.$year.'.png'; $filenamenb = $dir.'/receptionsnbinyear-'.$year.'.png';
@ -83,12 +81,10 @@ if (!$user->rights->societe->client->voir || $user->socid)
$px1 = new DolGraph(); $px1 = new DolGraph();
$mesg = $px1->isGraphKo(); $mesg = $px1->isGraphKo();
if (!$mesg) if (!$mesg) {
{
$px1->SetData($data); $px1->SetData($data);
$i = $startyear; $legend = array(); $i = $startyear; $legend = array();
while ($i <= $endyear) while ($i <= $endyear) {
{
$legend[] = $i; $legend[] = $i;
$i++; $i++;
} }
@ -194,7 +190,9 @@ foreach ($data as $val) {
$arrayyears[$val['year']] = $val['year']; $arrayyears[$val['year']] = $val['year'];
} }
} }
if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; if (!count($arrayyears)) {
$arrayyears[$nowyear] = $nowyear;
}
$h = 0; $h = 0;
$head = array(); $head = array();
@ -231,8 +229,12 @@ print '<div class="fichecenter"><div class="fichethirdleft">';
print '</td></tr>'; print '</td></tr>';
// Year // Year
print '<tr><td class="left">'.$langs->trans("Year").'</td><td class="left">'; print '<tr><td class="left">'.$langs->trans("Year").'</td><td class="left">';
if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; if (!in_array($year, $arrayyears)) {
if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; $arrayyears[$year] = $year;
}
if (!in_array($nowyear, $arrayyears)) {
$arrayyears[$nowyear] = $nowyear;
}
arsort($arrayyears); arsort($arrayyears);
print $form->selectarray('year', $arrayyears, $year, 0); print $form->selectarray('year', $arrayyears, $year, 0);
print '</td></tr>'; print '</td></tr>';
@ -251,11 +253,9 @@ print '<td class="center">'.$langs->trans("AmountAverage").'</td>';*/
print '</tr>'; print '</tr>';
$oldyear = 0; $oldyear = 0;
foreach ($data as $val) foreach ($data as $val) {
{
$year = $val['year']; $year = $val['year'];
while (!empty($year) && $oldyear > $year + 1) while (!empty($year) && $oldyear > $year + 1) { // If we have empty year
{ // If we have empty year
$oldyear--; $oldyear--;
@ -270,8 +270,11 @@ foreach ($data as $val)
print '<tr class="oddeven" height="24">'; print '<tr class="oddeven" height="24">';
print '<td class="center">'; print '<td class="center">';
if ($year) print '<a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'">'.$year.'</a>'; if ($year) {
else print $langs->trans("ValidationDateNotDefinedEvenIfReceptionValidated"); print '<a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'">'.$year.'</a>';
} else {
print $langs->trans("ValidationDateNotDefinedEvenIfReceptionValidated");
}
print '</td>'; print '</td>';
print '<td class="right">'.$val['nb'].'</td>'; print '<td class="right">'.$val['nb'].'</td>';
/*print '<td class="right">'.price(price2num($val['total'],'MT'),1).'</td>'; /*print '<td class="right">'.price(price2num($val['total'],'MT'),1).'</td>';
@ -288,7 +291,9 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
// Show graphs // Show graphs
print '<table class="border centpercent"><tr valign="top"><td class="center">'; print '<table class="border centpercent"><tr valign="top"><td class="center">';
if ($mesg) { print $mesg; } else { if ($mesg) {
print $mesg;
} else {
print $px1->show(); print $px1->show();
print "<br>\n"; print "<br>\n";
/*print $px2->show(); /*print $px2->show();

View File

@ -53,8 +53,7 @@ $fileurl = DOL_URL_ROOT.'/viewimage.php?modulepart=receptionstats&file=reception
$px = new DolGraph(); $px = new DolGraph();
$mesg = $px->isGraphKo(); $mesg = $px->isGraphKo();
if (!$mesg) if (!$mesg) {
{
$px->SetData($data); $px->SetData($data);
$px->SetMaxValue($px->GetCeilMaxValue()); $px->SetMaxValue($px->GetCeilMaxValue());
$px->SetWidth($WIDTH); $px->SetWidth($WIDTH);

View File

@ -18,8 +18,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($conf) || !is_object($conf)) if (empty($conf) || !is_object($conf)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -42,16 +41,19 @@ $langs->load("receptions");
$linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1); $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1);
$total = 0; $ilink = 0; $total = 0; $ilink = 0;
foreach ($linkedObjectBlock as $key => $objectlink) foreach ($linkedObjectBlock as $key => $objectlink) {
{
$ilink++; $ilink++;
$trclass = 'oddeven'; $trclass = 'oddeven';
if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) {
$trclass .= ' liste_sub_total';
}
?> ?>
<tr class="<?php echo $trclass; ?>"> <tr class="<?php echo $trclass; ?>">
<td class="linkedcol-element"><?php echo $langs->trans("Reception"); ?> <td class="linkedcol-element"><?php echo $langs->trans("Reception"); ?>
<?php if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) print '<a class="objectlinked_importbtn" href="'.$objectlink->getNomUrl(0, '', 0, 1).'&amp;action=selectlines" data-element="'.$objectlink->element.'" data-id="'.$objectlink->id.'" > <i class="fa fa-indent"></i> </a'; ?> <?php if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) {
print '<a class="objectlinked_importbtn" href="'.$objectlink->getNomUrl(0, '', 0, 1).'&amp;action=selectlines" data-element="'.$objectlink->element.'" data-id="'.$objectlink->id.'" > <i class="fa fa-indent"></i> </a';
} ?>
</td> </td>
<td class="linkedcol-name nowraponall" ><?php echo $objectlink->getNomUrl(1); ?></td> <td class="linkedcol-name nowraponall" ><?php echo $objectlink->getNomUrl(1); ?></td>
<td class="linkedcol-ref center"></td> <td class="linkedcol-ref center"></td>
@ -75,8 +77,7 @@ foreach ($linkedObjectBlock as $key => $objectlink)
</tr> </tr>
<?php <?php
} }
if (count($linkedObjectBlock) > 1) if (count($linkedObjectBlock) > 1) {
{
?> ?>
<tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>">
<td><?php echo $langs->trans("Total"); ?></td> <td><?php echo $langs->trans("Total"); ?></td>

View File

@ -34,13 +34,17 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'recruitment_recruitmentcandidature'; $elementtype = 'recruitment_recruitmentcandidature';
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*
@ -73,8 +77,7 @@ print dol_get_fiche_end();
// Buttons // Buttons
if ($action != 'create' && $action != 'edit') if ($action != 'create' && $action != 'edit') {
{
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
print "</div>"; print "</div>";
@ -84,8 +87,7 @@ if ($action != 'create' && $action != 'edit')
/* /*
* Creation of an optional field * Creation of an optional field
*/ */
if ($action == 'create') if ($action == 'create') {
{
print '<br><div id="newattrib"></div>'; print '<br><div id="newattrib"></div>';
print load_fiche_titre($langs->trans('NewAttribute')); print load_fiche_titre($langs->trans('NewAttribute'));
@ -95,8 +97,7 @@ if ($action == 'create')
/* /*
* Edition of an optional field * Edition of an optional field
*/ */
if ($action == 'edit' && !empty($attrname)) if ($action == 'edit' && !empty($attrname)) {
{
print "<br>"; print "<br>";
print load_fiche_titre($langs->trans("FieldEdition", $attrname)); print load_fiche_titre($langs->trans("FieldEdition", $attrname));

View File

@ -34,13 +34,17 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'recruitment_recruitmentjobposition'; $elementtype = 'recruitment_recruitmentjobposition';
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*
@ -73,8 +77,7 @@ print dol_get_fiche_end();
// Buttons // Buttons
if ($action != 'create' && $action != 'edit') if ($action != 'create' && $action != 'edit') {
{
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
print "</div>"; print "</div>";
@ -84,8 +87,7 @@ if ($action != 'create' && $action != 'edit')
/* /*
* Creation of an optional field * Creation of an optional field
*/ */
if ($action == 'create') if ($action == 'create') {
{
print '<br><div id="newattrib"></div>'; print '<br><div id="newattrib"></div>';
print load_fiche_titre($langs->trans('NewAttribute')); print load_fiche_titre($langs->trans('NewAttribute'));
@ -95,8 +97,7 @@ if ($action == 'create')
/* /*
* Edition of an optional field * Edition of an optional field
*/ */
if ($action == 'edit' && !empty($attrname)) if ($action == 'edit' && !empty($attrname)) {
{
print "<br>"; print "<br>";
print load_fiche_titre($langs->trans("FieldEdition", $attrname)); print load_fiche_titre($langs->trans("FieldEdition", $attrname));

View File

@ -33,7 +33,9 @@ $langs->loadLangs(array("admin", "recruitment"));
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
$error = 0; $error = 0;
@ -43,8 +45,11 @@ $error = 0;
*/ */
if ($action == 'setRECRUITMENT_ENABLE_PUBLIC_INTERFACE') { if ($action == 'setRECRUITMENT_ENABLE_PUBLIC_INTERFACE') {
if (GETPOST('value')) dolibarr_set_const($db, 'RECRUITMENT_ENABLE_PUBLIC_INTERFACE', 1, 'chaine', 0, '', $conf->entity); if (GETPOST('value')) {
else dolibarr_set_const($db, 'RECRUITMENT_ENABLE_PUBLIC_INTERFACE', 0, 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, 'RECRUITMENT_ENABLE_PUBLIC_INTERFACE', 1, 'chaine', 0, '', $conf->entity);
} else {
dolibarr_set_const($db, 'RECRUITMENT_ENABLE_PUBLIC_INTERFACE', 0, 'chaine', 0, '', $conf->entity);
}
} }
if ($action == 'update') { if ($action == 'update') {
@ -52,7 +57,9 @@ if ($action == 'update') {
$res = dolibarr_set_const($db, "RECRUITMENT_ENABLE_PUBLIC_INTERFACE", $public, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "RECRUITMENT_ENABLE_PUBLIC_INTERFACE", $public, 'chaine', 0, '', $conf->entity);
if (!($res > 0)) $error++; if (!($res > 0)) {
$error++;
}
if (!$error) { if (!$error) {
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');

View File

@ -25,16 +25,30 @@
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
}
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; $i--; $j--;
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; }
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
}
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
}
// Try main.inc.php using relative path // Try main.inc.php using relative path
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; if (!$res && file_exists("../../main.inc.php")) {
if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../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");
}
global $langs, $user; global $langs, $user;
@ -47,7 +61,9 @@ require_once DOL_DOCUMENT_ROOT."/recruitment/class/recruitmentjobposition.class.
$langs->loadLangs(array("admin", "recruitment")); $langs->loadLangs(array("admin", "recruitment"));
// Access control // Access control
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
// Parameters // Parameters
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
@ -71,28 +87,28 @@ $setupnotempty = 0;
* Actions * Actions
*/ */
if ((float) DOL_VERSION >= 6) if ((float) DOL_VERSION >= 6) {
{
include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php';
} }
if ($action == 'updateMask') if ($action == 'updateMask') {
{
$maskconstorder = GETPOST('maskconstorder', 'alpha'); $maskconstorder = GETPOST('maskconstorder', 'alpha');
$maskorder = GETPOST('maskorder', 'alpha'); $maskorder = GETPOST('maskorder', 'alpha');
if ($maskconstorder) $res = dolibarr_set_const($db, $maskconstorder, $maskorder, 'chaine', 0, '', $conf->entity); if ($maskconstorder) {
$res = dolibarr_set_const($db, $maskconstorder, $maskorder, 'chaine', 0, '', $conf->entity);
}
if (!($res > 0)) $error++; if (!($res > 0)) {
$error++;
}
if (!$error) if (!$error) {
{
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
} else { } else {
setEventMessages($langs->trans("Error"), null, 'errors'); setEventMessages($langs->trans("Error"), null, 'errors');
} }
} elseif ($action == 'specimen') } elseif ($action == 'specimen') {
{
$modele = GETPOST('module', 'alpha'); $modele = GETPOST('module', 'alpha');
$tmpobjectkey = GETPOST('object'); $tmpobjectkey = GETPOST('object');
@ -102,25 +118,21 @@ if ($action == 'updateMask')
// Search template files // Search template files
$file = ''; $classname = ''; $filefound = 0; $file = ''; $classname = ''; $filefound = 0;
$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{
$file = dol_buildpath($reldir."core/modules/mymodule/doc/pdf_".$modele."_".strtolower($tmpobjectkey).".modules.php", 0); $file = dol_buildpath($reldir."core/modules/mymodule/doc/pdf_".$modele."_".strtolower($tmpobjectkey).".modules.php", 0);
if (file_exists($file)) if (file_exists($file)) {
{
$filefound = 1; $filefound = 1;
$classname = "pdf_".$modele; $classname = "pdf_".$modele;
break; break;
} }
} }
if ($filefound) if ($filefound) {
{
require_once $file; require_once $file;
$module = new $classname($db); $module = new $classname($db);
if ($module->write_file($tmpobject, $langs) > 0) if ($module->write_file($tmpobject, $langs) > 0) {
{
header("Location: ".DOL_URL_ROOT."/document.php?modulepart=".strtolower($tmpobjectkey)."&file=SPECIMEN.pdf"); header("Location: ".DOL_URL_ROOT."/document.php?modulepart=".strtolower($tmpobjectkey)."&file=SPECIMEN.pdf");
return; return;
} else { } else {
@ -131,10 +143,8 @@ if ($action == 'updateMask')
setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors');
dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR);
} }
} } elseif ($action == 'set') {
// Activate a model
// Activate a model
elseif ($action == 'set') {
$ret = addDocumentModel($value, $type, $label, $scandir); $ret = addDocumentModel($value, $type, $label, $scandir);
} elseif ($action == 'del') { } elseif ($action == 'del') {
$ret = delDocumentModel($value, $type); $ret = delDocumentModel($value, $type);
@ -142,12 +152,12 @@ elseif ($action == 'set') {
$tmpobjectkey = GETPOST('object'); $tmpobjectkey = GETPOST('object');
if (!empty($tmpobjectkey)) { if (!empty($tmpobjectkey)) {
$constforval = 'RECRUITMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; $constforval = 'RECRUITMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF';
if ($conf->global->$constforval == "$value") dolibarr_del_const($db, $constforval, $conf->entity); if ($conf->global->$constforval == "$value") {
dolibarr_del_const($db, $constforval, $conf->entity);
} }
} }
} }
} elseif ($action == 'setmod') {
elseif ($action == 'setmod') {
// TODO Check if numbering module chosen can be activated by calling method canBeActivated // TODO Check if numbering module chosen can be activated by calling method canBeActivated
$tmpobjectkey = GETPOST('object'); $tmpobjectkey = GETPOST('object');
if (!empty($tmpobjectkey)) { if (!empty($tmpobjectkey)) {
@ -155,10 +165,8 @@ elseif ($action == 'setmod') {
dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity);
} }
} } elseif ($action == 'setdoc') {
// Set default model
// Set default model
elseif ($action == 'setdoc') {
$tmpobjectkey = GETPOST('object'); $tmpobjectkey = GETPOST('object');
if (!empty($tmpobjectkey)) { if (!empty($tmpobjectkey)) {
$constforval = 'RECRUITMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; $constforval = 'RECRUITMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF';
@ -208,8 +216,7 @@ print dol_get_fiche_head($head, 'settings', '', -1, '');
//echo '<span class="opacitymedium">'.$langs->trans("RecruitmentSetupPage").'</span><br><br>'; //echo '<span class="opacitymedium">'.$langs->trans("RecruitmentSetupPage").'</span><br><br>';
if ($action == 'edit') if ($action == 'edit') {
{
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="action" value="update">';
@ -217,8 +224,7 @@ if ($action == 'edit')
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>'; print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
foreach ($arrayofparameters as $key => $val) foreach ($arrayofparameters as $key => $val) {
{
print '<tr class="oddeven"><td>'; print '<tr class="oddeven"><td>';
$tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : '');
print $form->textwithpicto($langs->trans($key), $tooltiphelp); print $form->textwithpicto($langs->trans($key), $tooltiphelp);
@ -233,13 +239,11 @@ if ($action == 'edit')
print '</form>'; print '</form>';
print '<br>'; print '<br>';
} else { } else {
if (!empty($arrayofparameters)) if (!empty($arrayofparameters)) {
{
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>'; print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
foreach ($arrayofparameters as $key => $val) foreach ($arrayofparameters as $key => $val) {
{
$setupnotempty++; $setupnotempty++;
print '<tr class="oddeven"><td>'; print '<tr class="oddeven"><td>';
@ -282,30 +286,28 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
clearstatcache(); clearstatcache();
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{
$dir = dol_buildpath($reldir."core/modules/".$moduledir); $dir = dol_buildpath($reldir."core/modules/".$moduledir);
if (is_dir($dir)) if (is_dir($dir)) {
{
$handle = opendir($dir); $handle = opendir($dir);
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false) if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php') {
{
if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php')
{
$file = substr($file, 0, dol_strlen($file) - 4); $file = substr($file, 0, dol_strlen($file) - 4);
require_once $dir.'/'.$file.'.php'; require_once $dir.'/'.$file.'.php';
$module = new $file($db); $module = new $file($db);
// Show modules according to features level // Show modules according to features level
if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; continue;
}
if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
continue;
}
if ($module->isEnabled()) if ($module->isEnabled()) {
{
dol_include_once('/'.$moduledir.'/class/'.strtolower($myTmpObjectKey).'.class.php'); dol_include_once('/'.$moduledir.'/class/'.strtolower($myTmpObjectKey).'.class.php');
print '<tr class="oddeven"><td>'.$module->name."</td><td>\n"; print '<tr class="oddeven"><td>'.$module->name."</td><td>\n";
@ -318,14 +320,16 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
if (preg_match('/^Error/', $tmp)) { if (preg_match('/^Error/', $tmp)) {
$langs->load("errors"); $langs->load("errors");
print '<div class="error">'.$langs->trans($tmp).'</div>'; print '<div class="error">'.$langs->trans($tmp).'</div>';
} elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); } elseif ($tmp == 'NotConfigured') {
else print $tmp; print $langs->trans($tmp);
} else {
print $tmp;
}
print '</td>'."\n"; print '</td>'."\n";
print '<td class="center">'; print '<td class="center">';
$constforvar = 'RECRUITMENT_'.strtoupper($myTmpObjectKey).'_ADDON'; $constforvar = 'RECRUITMENT_'.strtoupper($myTmpObjectKey).'_ADDON';
if ($conf->global->$constforvar == $file) if ($conf->global->$constforvar == $file) {
{
print img_picto($langs->trans("Activated"), 'switch_on'); print img_picto($langs->trans("Activated"), 'switch_on');
} else { } else {
print '<a href="'.$_SERVER["PHP_SELF"].'?action=setmod&token='.newToken().'&object='.strtolower($myTmpObjectKey).'&value='.urlencode($file).'">'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=setmod&token='.newToken().'&object='.strtolower($myTmpObjectKey).'&value='.urlencode($file).'">';
@ -345,8 +349,9 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval
$htmltooltip .= ''.$langs->trans("NextValue").': '; $htmltooltip .= ''.$langs->trans("NextValue").': ';
if ($nextval) { if ($nextval) {
if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') {
$nextval = $langs->trans($nextval); $nextval = $langs->trans($nextval);
}
$htmltooltip .= $nextval.'<br>'; $htmltooltip .= $nextval.'<br>';
} else { } else {
$htmltooltip .= $langs->trans($module->error).'<br>'; $htmltooltip .= $langs->trans($module->error).'<br>';
@ -387,8 +392,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
if ($resql) { if ($resql) {
$i = 0; $i = 0;
$num_rows = $db->num_rows($resql); $num_rows = $db->num_rows($resql);
while ($i < $num_rows) while ($i < $num_rows) {
{
$array = $db->fetch_array($resql); $array = $db->fetch_array($resql);
array_push($def, $array[0]); array_push($def, $array[0]);
$i++; $i++;
@ -410,31 +414,23 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
clearstatcache(); clearstatcache();
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{ foreach (array('', '/doc') as $valdir) {
foreach (array('', '/doc') as $valdir)
{
$realpath = $reldir."core/modules/".$moduledir.$valdir; $realpath = $reldir."core/modules/".$moduledir.$valdir;
$dir = dol_buildpath($realpath); $dir = dol_buildpath($realpath);
if (is_dir($dir)) if (is_dir($dir)) {
{
$handle = opendir($dir); $handle = opendir($dir);
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false)
{
$filelist[] = $file; $filelist[] = $file;
} }
closedir($handle); closedir($handle);
arsort($filelist); arsort($filelist);
foreach ($filelist as $file) foreach ($filelist as $file) {
{ if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) {
if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) if (file_exists($dir.'/'.$file)) {
{
if (file_exists($dir.'/'.$file))
{
$name = substr($file, 4, dol_strlen($file) - 16); $name = substr($file, 4, dol_strlen($file) - 16);
$classname = substr($file, 0, dol_strlen($file) - 12); $classname = substr($file, 0, dol_strlen($file) - 12);
@ -442,21 +438,26 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
$module = new $classname($db); $module = new $classname($db);
$modulequalified = 1; $modulequalified = 1;
if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0; $modulequalified = 0;
}
if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
$modulequalified = 0;
}
if ($modulequalified) if ($modulequalified) {
{
print '<tr class="oddeven"><td width="100">'; print '<tr class="oddeven"><td width="100">';
print (empty($module->name) ? $name : $module->name); print (empty($module->name) ? $name : $module->name);
print "</td><td>\n"; print "</td><td>\n";
if (method_exists($module, 'info')) print $module->info($langs); if (method_exists($module, 'info')) {
else print $module->description; print $module->info($langs);
} else {
print $module->description;
}
print '</td>'; print '</td>';
// Active // Active
if (in_array($name, $def)) if (in_array($name, $def)) {
{
print '<td class="center">'."\n"; print '<td class="center">'."\n";
print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&amp;token='.newToken().'&amp;value='.$name.'">'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&amp;token='.newToken().'&amp;value='.$name.'">';
print img_picto($langs->trans("Enabled"), 'switch_on'); print img_picto($langs->trans("Enabled"), 'switch_on');
@ -483,8 +484,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
// Info // Info
$htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip = ''.$langs->trans("Name").': '.$module->name;
$htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); $htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown"));
if ($module->type == 'pdf') if ($module->type == 'pdf') {
{
$htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
} }
$htmltooltip .= '<br>'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; $htmltooltip .= '<br>'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file;
@ -499,8 +499,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
// Preview // Preview
print '<td class="center">'; print '<td class="center">';
if ($module->type == 'pdf') if ($module->type == 'pdf') {
{
print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'&object='.$myTmpObjectKey.'">'.img_object($langs->trans("Preview"), 'generic').'</a>'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'&object='.$myTmpObjectKey.'">'.img_object($langs->trans("Preview"), 'generic').'</a>';
} else { } else {
print img_object($langs->trans("PreviewNotAvailable"), 'generic'); print img_object($langs->trans("PreviewNotAvailable"), 'generic');

View File

@ -25,16 +25,30 @@
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
}
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME // Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; $tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; $i--; $j--;
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; }
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
}
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
}
// Try main.inc.php using relative path // Try main.inc.php using relative path
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; if (!$res && file_exists("../../main.inc.php")) {
if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../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");
}
global $langs, $user; global $langs, $user;
@ -47,7 +61,9 @@ require_once DOL_DOCUMENT_ROOT."/recruitment/class/recruitmentjobposition.class.
$langs->loadLangs(array("admin", "recruitment")); $langs->loadLangs(array("admin", "recruitment"));
// Access control // Access control
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
// Parameters // Parameters
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
@ -71,28 +87,28 @@ $setupnotempty = 0;
* Actions * Actions
*/ */
if ((float) DOL_VERSION >= 6) if ((float) DOL_VERSION >= 6) {
{
include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php';
} }
if ($action == 'updateMask') if ($action == 'updateMask') {
{
$maskconstorder = GETPOST('maskconstorder', 'alpha'); $maskconstorder = GETPOST('maskconstorder', 'alpha');
$maskorder = GETPOST('maskorder', 'alpha'); $maskorder = GETPOST('maskorder', 'alpha');
if ($maskconstorder) $res = dolibarr_set_const($db, $maskconstorder, $maskorder, 'chaine', 0, '', $conf->entity); if ($maskconstorder) {
$res = dolibarr_set_const($db, $maskconstorder, $maskorder, 'chaine', 0, '', $conf->entity);
}
if (!($res > 0)) $error++; if (!($res > 0)) {
$error++;
}
if (!$error) if (!$error) {
{
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
} else { } else {
setEventMessages($langs->trans("Error"), null, 'errors'); setEventMessages($langs->trans("Error"), null, 'errors');
} }
} elseif ($action == 'specimen') } elseif ($action == 'specimen') {
{
$modele = GETPOST('module', 'alpha'); $modele = GETPOST('module', 'alpha');
$tmpobjectkey = GETPOST('object'); $tmpobjectkey = GETPOST('object');
@ -102,25 +118,21 @@ if ($action == 'updateMask')
// Search template files // Search template files
$file = ''; $classname = ''; $filefound = 0; $file = ''; $classname = ''; $filefound = 0;
$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{
$file = dol_buildpath($reldir."core/modules/mymodule/doc/pdf_".$modele."_".strtolower($tmpobjectkey).".modules.php", 0); $file = dol_buildpath($reldir."core/modules/mymodule/doc/pdf_".$modele."_".strtolower($tmpobjectkey).".modules.php", 0);
if (file_exists($file)) if (file_exists($file)) {
{
$filefound = 1; $filefound = 1;
$classname = "pdf_".$modele; $classname = "pdf_".$modele;
break; break;
} }
} }
if ($filefound) if ($filefound) {
{
require_once $file; require_once $file;
$module = new $classname($db); $module = new $classname($db);
if ($module->write_file($tmpobject, $langs) > 0) if ($module->write_file($tmpobject, $langs) > 0) {
{
header("Location: ".DOL_URL_ROOT."/document.php?modulepart=".strtolower($tmpobjectkey)."&file=SPECIMEN.pdf"); header("Location: ".DOL_URL_ROOT."/document.php?modulepart=".strtolower($tmpobjectkey)."&file=SPECIMEN.pdf");
return; return;
} else { } else {
@ -131,10 +143,8 @@ if ($action == 'updateMask')
setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors');
dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR);
} }
} } elseif ($action == 'set') {
// Activate a model
// Activate a model
elseif ($action == 'set') {
$ret = addDocumentModel($value, $type, $label, $scandir); $ret = addDocumentModel($value, $type, $label, $scandir);
} elseif ($action == 'del') { } elseif ($action == 'del') {
$tmpobjectkey = GETPOST('object'); $tmpobjectkey = GETPOST('object');
@ -142,11 +152,11 @@ elseif ($action == 'set') {
$ret = delDocumentModel($value, $type); $ret = delDocumentModel($value, $type);
if ($ret > 0) { if ($ret > 0) {
$constforval = 'RECRUITMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; $constforval = 'RECRUITMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF';
if ($conf->global->$constforval == "$value") dolibarr_del_const($db, $constforval, $conf->entity); if ($conf->global->$constforval == "$value") {
dolibarr_del_const($db, $constforval, $conf->entity);
} }
} }
} elseif ($action == 'setmod') {
elseif ($action == 'setmod') {
// TODO Check if numbering module chosen can be activated by calling method canBeActivated // TODO Check if numbering module chosen can be activated by calling method canBeActivated
$tmpobjectkey = GETPOST('object'); $tmpobjectkey = GETPOST('object');
if (!empty($tmpobjectkey)) { if (!empty($tmpobjectkey)) {
@ -154,10 +164,8 @@ elseif ($action == 'setmod') {
dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity);
} }
} } elseif ($action == 'setdoc') {
// Set default model
// Set default model
elseif ($action == 'setdoc') {
$tmpobjectkey = GETPOST('object'); $tmpobjectkey = GETPOST('object');
$constforval = 'RECRUITMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; $constforval = 'RECRUITMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF';
if (dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity)) { if (dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity)) {
@ -205,8 +213,7 @@ print dol_get_fiche_head($head, 'settings_candidatures', '', -1, '');
//echo '<span class="opacitymedium">'.$langs->trans("RecruitmentSetupPage").'</span><br><br>'; //echo '<span class="opacitymedium">'.$langs->trans("RecruitmentSetupPage").'</span><br><br>';
if ($action == 'edit') if ($action == 'edit') {
{
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="action" value="update">';
@ -214,8 +221,7 @@ if ($action == 'edit')
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>'; print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
foreach ($arrayofparameters as $key => $val) foreach ($arrayofparameters as $key => $val) {
{
print '<tr class="oddeven"><td>'; print '<tr class="oddeven"><td>';
$tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : '');
print $form->textwithpicto($langs->trans($key), $tooltiphelp); print $form->textwithpicto($langs->trans($key), $tooltiphelp);
@ -230,13 +236,11 @@ if ($action == 'edit')
print '</form>'; print '</form>';
print '<br>'; print '<br>';
} else { } else {
if (!empty($arrayofparameters)) if (!empty($arrayofparameters)) {
{
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>'; print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
foreach ($arrayofparameters as $key => $val) foreach ($arrayofparameters as $key => $val) {
{
$setupnotempty++; $setupnotempty++;
print '<tr class="oddeven"><td>'; print '<tr class="oddeven"><td>';
@ -279,19 +283,14 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
clearstatcache(); clearstatcache();
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{
$dir = dol_buildpath($reldir."core/modules/".$moduledir); $dir = dol_buildpath($reldir."core/modules/".$moduledir);
if (is_dir($dir)) if (is_dir($dir)) {
{
$handle = opendir($dir); $handle = opendir($dir);
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false) if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php') {
{
if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php')
{
$file = substr($file, 0, dol_strlen($file) - 4); $file = substr($file, 0, dol_strlen($file) - 4);
require_once $dir.'/'.$file.'.php'; require_once $dir.'/'.$file.'.php';
@ -299,11 +298,14 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
$module = new $file($db); $module = new $file($db);
// Show modules according to features level // Show modules according to features level
if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; continue;
}
if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
continue;
}
if ($module->isEnabled()) if ($module->isEnabled()) {
{
dol_include_once('/'.$moduledir.'/class/'.strtolower($myTmpObjectKey).'.class.php'); dol_include_once('/'.$moduledir.'/class/'.strtolower($myTmpObjectKey).'.class.php');
print '<tr class="oddeven"><td>'.$module->name."</td><td>\n"; print '<tr class="oddeven"><td>'.$module->name."</td><td>\n";
@ -316,14 +318,16 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
if (preg_match('/^Error/', $tmp)) { if (preg_match('/^Error/', $tmp)) {
$langs->load("errors"); $langs->load("errors");
print '<div class="error">'.$langs->trans($tmp).'</div>'; print '<div class="error">'.$langs->trans($tmp).'</div>';
} elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); } elseif ($tmp == 'NotConfigured') {
else print $tmp; print $langs->trans($tmp);
} else {
print $tmp;
}
print '</td>'."\n"; print '</td>'."\n";
print '<td class="center">'; print '<td class="center">';
$constforvar = 'RECRUITMENT_'.strtoupper($myTmpObjectKey).'_ADDON'; $constforvar = 'RECRUITMENT_'.strtoupper($myTmpObjectKey).'_ADDON';
if ($conf->global->$constforvar == $file) if ($conf->global->$constforvar == $file) {
{
print img_picto($langs->trans("Activated"), 'switch_on'); print img_picto($langs->trans("Activated"), 'switch_on');
} else { } else {
print '<a href="'.$_SERVER["PHP_SELF"].'?action=setmod&token='.newToken().'&object='.strtolower($myTmpObjectKey).'&value='.urlencode($file).'">'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=setmod&token='.newToken().'&object='.strtolower($myTmpObjectKey).'&value='.urlencode($file).'">';
@ -343,8 +347,9 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval
$htmltooltip .= ''.$langs->trans("NextValue").': '; $htmltooltip .= ''.$langs->trans("NextValue").': ';
if ($nextval) { if ($nextval) {
if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') {
$nextval = $langs->trans($nextval); $nextval = $langs->trans($nextval);
}
$htmltooltip .= $nextval.'<br>'; $htmltooltip .= $nextval.'<br>';
} else { } else {
$htmltooltip .= $langs->trans($module->error).'<br>'; $htmltooltip .= $langs->trans($module->error).'<br>';
@ -382,12 +387,10 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
$sql .= " WHERE type = '".$db->escape($type)."'"; $sql .= " WHERE type = '".$db->escape($type)."'";
$sql .= " AND entity = ".$conf->entity; $sql .= " AND entity = ".$conf->entity;
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$i = 0; $i = 0;
$num_rows = $db->num_rows($resql); $num_rows = $db->num_rows($resql);
while ($i < $num_rows) while ($i < $num_rows) {
{
$array = $db->fetch_array($resql); $array = $db->fetch_array($resql);
array_push($def, $array[0]); array_push($def, $array[0]);
$i++; $i++;
@ -409,31 +412,23 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
clearstatcache(); clearstatcache();
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{ foreach (array('', '/doc') as $valdir) {
foreach (array('', '/doc') as $valdir)
{
$realpath = $reldir."core/modules/".$moduledir.$valdir; $realpath = $reldir."core/modules/".$moduledir.$valdir;
$dir = dol_buildpath($realpath); $dir = dol_buildpath($realpath);
if (is_dir($dir)) if (is_dir($dir)) {
{
$handle = opendir($dir); $handle = opendir($dir);
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false)
{
$filelist[] = $file; $filelist[] = $file;
} }
closedir($handle); closedir($handle);
arsort($filelist); arsort($filelist);
foreach ($filelist as $file) foreach ($filelist as $file) {
{ if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) {
if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) if (file_exists($dir.'/'.$file)) {
{
if (file_exists($dir.'/'.$file))
{
$name = substr($file, 4, dol_strlen($file) - 16); $name = substr($file, 4, dol_strlen($file) - 16);
$classname = substr($file, 0, dol_strlen($file) - 12); $classname = substr($file, 0, dol_strlen($file) - 12);
@ -441,21 +436,26 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
$module = new $classname($db); $module = new $classname($db);
$modulequalified = 1; $modulequalified = 1;
if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0; $modulequalified = 0;
}
if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
$modulequalified = 0;
}
if ($modulequalified) if ($modulequalified) {
{
print '<tr class="oddeven"><td width="100">'; print '<tr class="oddeven"><td width="100">';
print (empty($module->name) ? $name : $module->name); print (empty($module->name) ? $name : $module->name);
print "</td><td>\n"; print "</td><td>\n";
if (method_exists($module, 'info')) print $module->info($langs); if (method_exists($module, 'info')) {
else print $module->description; print $module->info($langs);
} else {
print $module->description;
}
print '</td>'; print '</td>';
// Active // Active
if (in_array($name, $def)) if (in_array($name, $def)) {
{
print '<td class="center">'."\n"; print '<td class="center">'."\n";
print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&amp;token='.newToken().'&amp;value='.$name.'">'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&amp;token='.newToken().'&amp;value='.$name.'">';
print img_picto($langs->trans("Enabled"), 'switch_on'); print img_picto($langs->trans("Enabled"), 'switch_on');
@ -482,8 +482,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
// Info // Info
$htmltooltip = ''.$langs->trans("Name").': '.$module->name; $htmltooltip = ''.$langs->trans("Name").': '.$module->name;
$htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); $htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown"));
if ($module->type == 'pdf') if ($module->type == 'pdf') {
{
$htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
} }
$htmltooltip .= '<br>'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; $htmltooltip .= '<br>'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file;
@ -498,8 +497,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
// Preview // Preview
print '<td class="center">'; print '<td class="center">';
if ($module->type == 'pdf') if ($module->type == 'pdf') {
{
print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'&object='.$myTmpObjectKey.'">'.img_object($langs->trans("Preview"), 'generic').'</a>'; print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'&object='.$myTmpObjectKey.'">'.img_object($langs->trans("Preview"), 'generic').'</a>';
} else { } else {
print img_object($langs->trans("PreviewNotAvailable"), 'generic'); print img_object($langs->trans("PreviewNotAvailable"), 'generic');

View File

@ -164,8 +164,12 @@ class RecruitmentCandidature extends CommonObject
$this->db = $db; $this->db = $db;
if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; $this->fields['rowid']['visible'] = 0;
}
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
$this->fields['entity']['enabled'] = 0;
}
// Example to show how to set values of fields definition dynamically // Example to show how to set values of fields definition dynamically
/*if ($user->rights->recruitment->recruitmentcandidature->read) { /*if ($user->rights->recruitment->recruitmentcandidature->read) {
@ -174,23 +178,17 @@ class RecruitmentCandidature extends CommonObject
}*/ }*/
// Unset fields that are disabled // Unset fields that are disabled
foreach ($this->fields as $key => $val) foreach ($this->fields as $key => $val) {
{ if (isset($val['enabled']) && empty($val['enabled'])) {
if (isset($val['enabled']) && empty($val['enabled']))
{
unset($this->fields[$key]); unset($this->fields[$key]);
} }
} }
// Translate some data of arrayofkeyval // Translate some data of arrayofkeyval
if (is_object($langs)) if (is_object($langs)) {
{ foreach ($this->fields as $key => $val) {
foreach ($this->fields as $key => $val) if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
{ foreach ($val['arrayofkeyval'] as $key2 => $val2) {
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
{
foreach ($val['arrayofkeyval'] as $key2 => $val2)
{
$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
} }
} }
@ -230,7 +228,9 @@ class RecruitmentCandidature extends CommonObject
// Load source object // Load source object
$result = $object->fetchCommon($fromid); $result = $object->fetchCommon($fromid);
if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); if ($result > 0 && !empty($object->table_element_line)) {
$object->fetchLines();
}
// get lines so they will be clone // get lines so they will be clone
//foreach($this->lines as $line) //foreach($this->lines as $line)
@ -242,22 +242,29 @@ class RecruitmentCandidature extends CommonObject
unset($object->import_key); unset($object->import_key);
// Clear fields // Clear fields
if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; if (property_exists($object, 'ref')) {
if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
if (property_exists($object, 'status')) { $object->status = self::STATUS_DRAFT; } }
if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); } if (property_exists($object, 'label')) {
if (property_exists($object, 'date_modification')) { $object->date_modification = null; } $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
}
if (property_exists($object, 'status')) {
$object->status = self::STATUS_DRAFT;
}
if (property_exists($object, 'date_creation')) {
$object->date_creation = dol_now();
}
if (property_exists($object, 'date_modification')) {
$object->date_modification = null;
}
// ... // ...
// Clear extrafields that are unique // Clear extrafields that are unique
if (is_array($object->array_options) && count($object->array_options) > 0) if (is_array($object->array_options) && count($object->array_options) > 0) {
{
$extrafields->fetch_name_optionals_label($this->table_element); $extrafields->fetch_name_optionals_label($this->table_element);
foreach ($object->array_options as $key => $option) foreach ($object->array_options as $key => $option) {
{
$shortkey = preg_replace('/options_/', '', $key); $shortkey = preg_replace('/options_/', '', $key);
if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
{
//var_dump($key); var_dump($clonedObj->array_options[$key]); exit; //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
unset($object->array_options[$key]); unset($object->array_options[$key]);
} }
@ -273,24 +280,21 @@ class RecruitmentCandidature extends CommonObject
$this->errors = $object->errors; $this->errors = $object->errors;
} }
if (!$error) if (!$error) {
{
// copy internal contacts // copy internal contacts
if ($this->copy_linked_contact($object, 'internal') < 0) if ($this->copy_linked_contact($object, 'internal') < 0) {
{
$error++; $error++;
} }
} }
if (!$error) if (!$error) {
{
// copy external contacts if same company // copy external contacts if same company
if (property_exists($this, 'socid') && $this->socid == $object->socid) if (property_exists($this, 'socid') && $this->socid == $object->socid) {
{ if ($this->copy_linked_contact($object, 'external') < 0) {
if ($this->copy_linked_contact($object, 'external') < 0)
$error++; $error++;
} }
} }
}
unset($object->context['createfromclone']); unset($object->context['createfromclone']);
@ -315,9 +319,13 @@ class RecruitmentCandidature extends CommonObject
public function fetch($id, $ref = null, $email_msgid = '') public function fetch($id, $ref = null, $email_msgid = '')
{ {
$morewhere = ''; $morewhere = '';
if ($email_msgid) $morewhere = " AND email_msgid = '".$this->db->escape($email_msgid)."'"; if ($email_msgid) {
$morewhere = " AND email_msgid = '".$this->db->escape($email_msgid)."'";
}
$result = $this->fetchCommon($id, $ref, $morewhere); $result = $this->fetchCommon($id, $ref, $morewhere);
if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); if ($result > 0 && !empty($this->table_element_line)) {
$this->fetchLines();
}
return $result; return $result;
} }
@ -357,8 +365,11 @@ class RecruitmentCandidature extends CommonObject
$sql = 'SELECT '; $sql = 'SELECT ';
$sql .= $this->getFieldList(); $sql .= $this->getFieldList();
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
else $sql .= ' WHERE 1 = 1'; $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
} else {
$sql .= ' WHERE 1 = 1';
}
// Manage filter // Manage filter
$sqlwhere = array(); $sqlwhere = array();
if (count($filter) > 0) { if (count($filter) > 0) {
@ -391,8 +402,7 @@ class RecruitmentCandidature extends CommonObject
if ($resql) { if ($resql) {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < ($limit ? min($limit, $num) : $num)) while ($i < ($limit ? min($limit, $num) : $num)) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$record = new self($this->db); $record = new self($this->db);
@ -448,8 +458,7 @@ class RecruitmentCandidature extends CommonObject
*/ */
public function deleteLine(User $user, $idline, $notrigger = false) public function deleteLine(User $user, $idline, $notrigger = false)
{ {
if ($this->status < 0) if ($this->status < 0) {
{
$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
return -2; return -2;
} }
@ -474,8 +483,7 @@ class RecruitmentCandidature extends CommonObject
$error = 0; $error = 0;
// Protection // Protection
if ($this->status == self::STATUS_VALIDATED) if ($this->status == self::STATUS_VALIDATED) {
{
dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
return 0; return 0;
} }
@ -493,8 +501,7 @@ class RecruitmentCandidature extends CommonObject
$this->db->begin(); $this->db->begin();
// Define new ref // Define new ref
if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
{
$num = $this->getNextNumRef(); $num = $this->getNextNumRef();
} else { } else {
$num = $this->ref; $num = $this->ref;
@ -506,57 +513,58 @@ class RecruitmentCandidature extends CommonObject
$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
$sql .= " SET ref = '".$this->db->escape($num)."',"; $sql .= " SET ref = '".$this->db->escape($num)."',";
$sql .= " status = ".self::STATUS_VALIDATED; $sql .= " status = ".self::STATUS_VALIDATED;
if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."',"; if (!empty($this->fields['date_validation'])) {
if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".$user->id; $sql .= ", date_validation = '".$this->db->idate($now)."',";
}
if (!empty($this->fields['fk_user_valid'])) {
$sql .= ", fk_user_valid = ".$user->id;
}
$sql .= " WHERE rowid = ".$this->id; $sql .= " WHERE rowid = ".$this->id;
dol_syslog(get_class($this)."::validate()", LOG_DEBUG); dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($this->db); dol_print_error($this->db);
$this->error = $this->db->lasterror(); $this->error = $this->db->lasterror();
$error++; $error++;
} }
if (!$error && !$notrigger) if (!$error && !$notrigger) {
{
// Call trigger // Call trigger
$result = $this->call_trigger('RECRUITMENTCANDIDATURE_VALIDATE', $user); $result = $this->call_trigger('RECRUITMENTCANDIDATURE_VALIDATE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
} }
if (!$error) if (!$error) {
{
$this->oldref = $this->ref; $this->oldref = $this->ref;
// Rename directory if dir was a temporary ref // Rename directory if dir was a temporary ref
if (preg_match('/^[\(]?PROV/i', $this->ref)) if (preg_match('/^[\(]?PROV/i', $this->ref)) {
{
// Now we rename also files into index // Now we rename also files into index
$sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'recruitmentcandidature/".$this->db->escape($this->newref)."'"; $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'recruitmentcandidature/".$this->db->escape($this->newref)."'";
$sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'recruitmentcandidature/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'recruitmentcandidature/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->error = $this->db->lasterror(); } if (!$resql) {
$error++; $this->error = $this->db->lasterror();
}
// We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
$oldref = dol_sanitizeFileName($this->ref); $oldref = dol_sanitizeFileName($this->ref);
$newref = dol_sanitizeFileName($num); $newref = dol_sanitizeFileName($num);
$dirsource = $conf->recruitment->dir_output.'/recruitmentcandidature/'.$oldref; $dirsource = $conf->recruitment->dir_output.'/recruitmentcandidature/'.$oldref;
$dirdest = $conf->recruitment->dir_output.'/recruitmentcandidature/'.$newref; $dirdest = $conf->recruitment->dir_output.'/recruitmentcandidature/'.$newref;
if (!$error && file_exists($dirsource)) if (!$error && file_exists($dirsource)) {
{
dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
if (@rename($dirsource, $dirdest)) if (@rename($dirsource, $dirdest)) {
{
dol_syslog("Rename ok"); dol_syslog("Rename ok");
// Rename docs starting with $oldref with $newref // Rename docs starting with $oldref with $newref
$listoffiles = dol_dir_list($conf->recruitment->dir_output.'/recruitmentcandidature/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); $listoffiles = dol_dir_list($conf->recruitment->dir_output.'/recruitmentcandidature/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
foreach ($listoffiles as $fileentry) foreach ($listoffiles as $fileentry) {
{
$dirsource = $fileentry['name']; $dirsource = $fileentry['name'];
$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
$dirsource = $fileentry['path'].'/'.$dirsource; $dirsource = $fileentry['path'].'/'.$dirsource;
@ -569,14 +577,12 @@ class RecruitmentCandidature extends CommonObject
} }
// Set new ref and current status // Set new ref and current status
if (!$error) if (!$error) {
{
$this->ref = $num; $this->ref = $num;
$this->status = self::STATUS_VALIDATED; $this->status = self::STATUS_VALIDATED;
} }
if (!$error) if (!$error) {
{
$this->db->commit(); $this->db->commit();
return 1; return 1;
} else { } else {
@ -596,8 +602,7 @@ class RecruitmentCandidature extends CommonObject
public function setDraft($user, $notrigger = 0) public function setDraft($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status <= self::STATUS_DRAFT) if ($this->status <= self::STATUS_DRAFT) {
{
return 0; return 0;
} }
@ -621,8 +626,7 @@ class RecruitmentCandidature extends CommonObject
public function cancel($user, $notrigger = 0) public function cancel($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status != self::STATUS_VALIDATED) if ($this->status != self::STATUS_VALIDATED) {
{
return 0; return 0;
} }
@ -646,8 +650,7 @@ class RecruitmentCandidature extends CommonObject
public function reopen($user, $notrigger = 0) public function reopen($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status != self::STATUS_REFUSED && $this->status != self::STATUS_CANCELED && $this->status != self::STATUS_CONTRACT_REFUSED) if ($this->status != self::STATUS_REFUSED && $this->status != self::STATUS_CANCELED && $this->status != self::STATUS_CONTRACT_REFUSED) {
{
return 0; return 0;
} }
@ -675,7 +678,9 @@ class RecruitmentCandidature extends CommonObject
{ {
global $conf, $langs, $hookmanager; global $conf, $langs, $hookmanager;
if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips if (!empty($conf->dol_no_mouse_hover)) {
$notooltip = 1; // Force disable tooltips
}
$result = ''; $result = '';
@ -690,25 +695,28 @@ class RecruitmentCandidature extends CommonObject
$url = dol_buildpath('/recruitment/recruitmentcandidature_card.php', 1).'?id='.$this->id; $url = dol_buildpath('/recruitment/recruitmentcandidature_card.php', 1).'?id='.$this->id;
if ($option != 'nolink') if ($option != 'nolink') {
{
// Add param to save lastsearch_values or not // Add param to save lastsearch_values or not
$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; $add_save_lastsearch_values = 1;
}
if ($add_save_lastsearch_values) {
$url .= '&save_lastsearch_values=1';
}
} }
$linkclose = ''; $linkclose = '';
if (empty($notooltip)) if (empty($notooltip)) {
{ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label = $langs->trans("ShowRecruitmentCandidature"); $label = $langs->trans("ShowRecruitmentCandidature");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } else {
$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
}
$linkstart = '<a href="'.$url.'"'; $linkstart = '<a href="'.$url.'"';
$linkstart .= $linkclose.'>'; $linkstart .= $linkclose.'>';
@ -717,7 +725,9 @@ class RecruitmentCandidature extends CommonObject
$result .= $linkstart; $result .= $linkstart;
if (empty($this->showphoto_on_popup)) { if (empty($this->showphoto_on_popup)) {
if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); if ($withpicto) {
$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
}
} else { } else {
if ($withpicto) { if ($withpicto) {
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
@ -743,7 +753,9 @@ class RecruitmentCandidature extends CommonObject
} }
} }
if ($withpicto != 2) $result .= $this->ref; if ($withpicto != 2) {
$result .= $this->ref;
}
$result .= $linkend; $result .= $linkend;
//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
@ -752,8 +764,11 @@ class RecruitmentCandidature extends CommonObject
$hookmanager->initHooks(array('recruitmentcandidaturedao')); $hookmanager->initHooks(array('recruitmentcandidaturedao'));
$parameters = array('id'=>$this->id, 'getnomurl'=>$result); $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $result = $hookmanager->resPrint; if ($reshook > 0) {
else $result .= $hookmanager->resPrint; $result = $hookmanager->resPrint;
} else {
$result .= $hookmanager->resPrint;
}
return $result; return $result;
} }
@ -780,8 +795,7 @@ class RecruitmentCandidature extends CommonObject
public function LibStatut($status, $mode = 0) public function LibStatut($status, $mode = 0)
{ {
// phpcs:enable // phpcs:enable
if (empty($this->labelStatus) || empty($this->labelStatusShort)) if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
{
global $langs; global $langs;
//$langs->load("recruitment@recruitment"); //$langs->load("recruitment@recruitment");
$this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
@ -802,7 +816,9 @@ class RecruitmentCandidature extends CommonObject
$statusType = 'status'.$status; $statusType = 'status'.$status;
//if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
if ($status == self::STATUS_CANCELED) $statusType = 'status6'; if ($status == self::STATUS_CANCELED) {
$statusType = 'status6';
}
return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
} }
@ -820,28 +836,23 @@ class RecruitmentCandidature extends CommonObject
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
$sql .= ' WHERE t.rowid = '.$id; $sql .= ' WHERE t.rowid = '.$id;
$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);
$this->id = $obj->rowid; $this->id = $obj->rowid;
if ($obj->fk_user_author) if ($obj->fk_user_author) {
{
$cuser = new User($this->db); $cuser = new User($this->db);
$cuser->fetch($obj->fk_user_author); $cuser->fetch($obj->fk_user_author);
$this->user_creation = $cuser; $this->user_creation = $cuser;
} }
if ($obj->fk_user_valid) if ($obj->fk_user_valid) {
{
$vuser = new User($this->db); $vuser = new User($this->db);
$vuser->fetch($obj->fk_user_valid); $vuser->fetch($obj->fk_user_valid);
$this->user_validation = $vuser; $this->user_validation = $vuser;
} }
if ($obj->fk_user_cloture) if ($obj->fk_user_cloture) {
{
$cluser = new User($this->db); $cluser = new User($this->db);
$cluser->fetch($obj->fk_user_cloture); $cluser->fetch($obj->fk_user_cloture);
$this->user_cloture = $cluser; $this->user_cloture = $cluser;
@ -881,8 +892,7 @@ class RecruitmentCandidature extends CommonObject
$objectline = new RecruitmentCandidatureLine($this->db); $objectline = new RecruitmentCandidatureLine($this->db);
$result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_recruitmentcandidature = '.$this->id)); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_recruitmentcandidature = '.$this->id));
if (is_numeric($result)) if (is_numeric($result)) {
{
$this->error = $this->error; $this->error = $this->error;
$this->errors = $this->errors; $this->errors = $this->errors;
return $result; return $result;
@ -906,8 +916,7 @@ class RecruitmentCandidature extends CommonObject
$conf->global->RECRUITMENT_RECRUITMENTCANDIDATURE_ADDON = 'mod_recruitmentcandidature_standard'; $conf->global->RECRUITMENT_RECRUITMENTCANDIDATURE_ADDON = 'mod_recruitmentcandidature_standard';
} }
if (!empty($conf->global->RECRUITMENT_RECRUITMENTCANDIDATURE_ADDON)) if (!empty($conf->global->RECRUITMENT_RECRUITMENTCANDIDATURE_ADDON)) {
{
$mybool = false; $mybool = false;
$file = $conf->global->RECRUITMENT_RECRUITMENTCANDIDATURE_ADDON.".php"; $file = $conf->global->RECRUITMENT_RECRUITMENTCANDIDATURE_ADDON.".php";
@ -915,16 +924,14 @@ class RecruitmentCandidature extends CommonObject
// Include file with class // Include file with class
$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{
$dir = dol_buildpath($reldir."core/modules/recruitment/"); $dir = dol_buildpath($reldir."core/modules/recruitment/");
// Load file with numbering class (if found) // Load file with numbering class (if found)
$mybool |= @include_once $dir.$file; $mybool |= @include_once $dir.$file;
} }
if ($mybool === false) if ($mybool === false) {
{
dol_print_error('', "Failed to include file ".$file); dol_print_error('', "Failed to include file ".$file);
return ''; return '';
} }
@ -933,8 +940,7 @@ class RecruitmentCandidature extends CommonObject
$obj = new $classname(); $obj = new $classname();
$numref = $obj->getNextValue($this); $numref = $obj->getNextValue($this);
if ($numref != '' && $numref != '-1') if ($numref != '' && $numref != '-1') {
{
return $numref; return $numref;
} else { } else {
$this->error = $obj->error; $this->error = $obj->error;
@ -972,8 +978,7 @@ class RecruitmentCandidature extends CommonObject
$langs->load("recruitment@recruitment"); $langs->load("recruitment@recruitment");
if (!dol_strlen($modele)) { if (!dol_strlen($modele)) {
if (!empty($conf->global->RECRUITMENTCANDIDATURE_ADDON_PDF)) if (!empty($conf->global->RECRUITMENTCANDIDATURE_ADDON_PDF)) {
{
$modele = $conf->global->RECRUITMENTCANDIDATURE_ADDON_PDF; $modele = $conf->global->RECRUITMENTCANDIDATURE_ADDON_PDF;
} else { } else {
$modele = ''; // No default value. For job application, we allow to disable all PDF generation $modele = ''; // No default value. For job application, we allow to disable all PDF generation

View File

@ -179,8 +179,12 @@ class RecruitmentJobPosition extends CommonObject
$this->db = $db; $this->db = $db;
if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; $this->fields['rowid']['visible'] = 0;
}
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
$this->fields['entity']['enabled'] = 0;
}
// Example to show how to set values of fields definition dynamically // Example to show how to set values of fields definition dynamically
/*if ($user->rights->recruitment->recruitmentjobposition->read) { /*if ($user->rights->recruitment->recruitmentjobposition->read) {
@ -189,23 +193,17 @@ class RecruitmentJobPosition extends CommonObject
}*/ }*/
// Unset fields that are disabled // Unset fields that are disabled
foreach ($this->fields as $key => $val) foreach ($this->fields as $key => $val) {
{ if (isset($val['enabled']) && empty($val['enabled'])) {
if (isset($val['enabled']) && empty($val['enabled']))
{
unset($this->fields[$key]); unset($this->fields[$key]);
} }
} }
// Translate some data of arrayofkeyval // Translate some data of arrayofkeyval
if (is_object($langs)) if (is_object($langs)) {
{ foreach ($this->fields as $key => $val) {
foreach ($this->fields as $key => $val) if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
{ foreach ($val['arrayofkeyval'] as $key2 => $val2) {
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
{
foreach ($val['arrayofkeyval'] as $key2 => $val2)
{
$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
} }
} }
@ -245,7 +243,9 @@ class RecruitmentJobPosition extends CommonObject
// Load source object // Load source object
$result = $object->fetchCommon($fromid); $result = $object->fetchCommon($fromid);
if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); if ($result > 0 && !empty($object->table_element_line)) {
$object->fetchLines();
}
// get lines so they will be clone // get lines so they will be clone
//foreach($this->lines as $line) //foreach($this->lines as $line)
@ -257,21 +257,28 @@ class RecruitmentJobPosition extends CommonObject
unset($object->import_key); unset($object->import_key);
// Clear fields // Clear fields
if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; if (property_exists($object, 'ref')) {
if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
if (property_exists($object, 'status')) { $object->status = self::STATUS_DRAFT; } }
if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); } if (property_exists($object, 'label')) {
if (property_exists($object, 'date_modification')) { $object->date_modification = null; } $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
}
if (property_exists($object, 'status')) {
$object->status = self::STATUS_DRAFT;
}
if (property_exists($object, 'date_creation')) {
$object->date_creation = dol_now();
}
if (property_exists($object, 'date_modification')) {
$object->date_modification = null;
}
// ... // ...
// Clear extrafields that are unique // Clear extrafields that are unique
if (is_array($object->array_options) && count($object->array_options) > 0) if (is_array($object->array_options) && count($object->array_options) > 0) {
{
$extrafields->fetch_name_optionals_label($this->table_element); $extrafields->fetch_name_optionals_label($this->table_element);
foreach ($object->array_options as $key => $option) foreach ($object->array_options as $key => $option) {
{
$shortkey = preg_replace('/options_/', '', $key); $shortkey = preg_replace('/options_/', '', $key);
if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
{
//var_dump($key); var_dump($clonedObj->array_options[$key]); exit; //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
unset($object->array_options[$key]); unset($object->array_options[$key]);
} }
@ -287,24 +294,21 @@ class RecruitmentJobPosition extends CommonObject
$this->errors = $object->errors; $this->errors = $object->errors;
} }
if (!$error) if (!$error) {
{
// copy internal contacts // copy internal contacts
if ($this->copy_linked_contact($object, 'internal') < 0) if ($this->copy_linked_contact($object, 'internal') < 0) {
{
$error++; $error++;
} }
} }
if (!$error) if (!$error) {
{
// copy external contacts if same company // copy external contacts if same company
if (property_exists($this, 'socid') && $this->socid == $object->socid) if (property_exists($this, 'socid') && $this->socid == $object->socid) {
{ if ($this->copy_linked_contact($object, 'external') < 0) {
if ($this->copy_linked_contact($object, 'external') < 0)
$error++; $error++;
} }
} }
}
unset($object->context['createfromclone']); unset($object->context['createfromclone']);
@ -328,7 +332,9 @@ class RecruitmentJobPosition extends CommonObject
public function fetch($id, $ref = null) public function fetch($id, $ref = null)
{ {
$result = $this->fetchCommon($id, $ref); $result = $this->fetchCommon($id, $ref);
if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); if ($result > 0 && !empty($this->table_element_line)) {
$this->fetchLines();
}
return $result; return $result;
} }
@ -368,8 +374,11 @@ class RecruitmentJobPosition extends CommonObject
$sql = 'SELECT '; $sql = 'SELECT ';
$sql .= $this->getFieldList(); $sql .= $this->getFieldList();
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
else $sql .= ' WHERE 1 = 1'; $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
} else {
$sql .= ' WHERE 1 = 1';
}
// Manage filter // Manage filter
$sqlwhere = array(); $sqlwhere = array();
if (count($filter) > 0) { if (count($filter) > 0) {
@ -402,8 +411,7 @@ class RecruitmentJobPosition extends CommonObject
if ($resql) { if ($resql) {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < ($limit ? min($limit, $num) : $num)) while ($i < ($limit ? min($limit, $num) : $num)) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$record = new self($this->db); $record = new self($this->db);
@ -459,8 +467,7 @@ class RecruitmentJobPosition extends CommonObject
*/ */
public function deleteLine(User $user, $idline, $notrigger = false) public function deleteLine(User $user, $idline, $notrigger = false)
{ {
if ($this->status < 0) if ($this->status < 0) {
{
$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
return -2; return -2;
} }
@ -485,8 +492,7 @@ class RecruitmentJobPosition extends CommonObject
$error = 0; $error = 0;
// Protection // Protection
if ($this->status == self::STATUS_VALIDATED) if ($this->status == self::STATUS_VALIDATED) {
{
dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
return 0; return 0;
} }
@ -504,8 +510,7 @@ class RecruitmentJobPosition extends CommonObject
$this->db->begin(); $this->db->begin();
// Define new ref // Define new ref
if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
{
$num = $this->getNextNumRef(); $num = $this->getNextNumRef();
} else { } else {
$num = $this->ref; $num = $this->ref;
@ -517,57 +522,58 @@ class RecruitmentJobPosition extends CommonObject
$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
$sql .= " SET ref = '".$this->db->escape($num)."',"; $sql .= " SET ref = '".$this->db->escape($num)."',";
$sql .= " status = ".self::STATUS_VALIDATED; $sql .= " status = ".self::STATUS_VALIDATED;
if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."',"; if (!empty($this->fields['date_validation'])) {
if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".$user->id; $sql .= ", date_validation = '".$this->db->idate($now)."',";
}
if (!empty($this->fields['fk_user_valid'])) {
$sql .= ", fk_user_valid = ".$user->id;
}
$sql .= " WHERE rowid = ".$this->id; $sql .= " WHERE rowid = ".$this->id;
dol_syslog(get_class($this)."::validate()", LOG_DEBUG); dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($this->db); dol_print_error($this->db);
$this->error = $this->db->lasterror(); $this->error = $this->db->lasterror();
$error++; $error++;
} }
if (!$error && !$notrigger) if (!$error && !$notrigger) {
{
// Call trigger // Call trigger
$result = $this->call_trigger('RECRUITMENTJOBPOSITION_VALIDATE', $user); $result = $this->call_trigger('RECRUITMENTJOBPOSITION_VALIDATE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
} }
if (!$error) if (!$error) {
{
$this->oldref = $this->ref; $this->oldref = $this->ref;
// Rename directory if dir was a temporary ref // Rename directory if dir was a temporary ref
if (preg_match('/^[\(]?PROV/i', $this->ref)) if (preg_match('/^[\(]?PROV/i', $this->ref)) {
{
// Now we rename also files into index // Now we rename also files into index
$sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'recruitmentjobposition/".$this->db->escape($this->newref)."'"; $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'recruitmentjobposition/".$this->db->escape($this->newref)."'";
$sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'recruitmentjobposition/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'recruitmentjobposition/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->error = $this->db->lasterror(); } if (!$resql) {
$error++; $this->error = $this->db->lasterror();
}
// We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
$oldref = dol_sanitizeFileName($this->ref); $oldref = dol_sanitizeFileName($this->ref);
$newref = dol_sanitizeFileName($num); $newref = dol_sanitizeFileName($num);
$dirsource = $conf->recruitment->dir_output.'/recruitmentjobposition/'.$oldref; $dirsource = $conf->recruitment->dir_output.'/recruitmentjobposition/'.$oldref;
$dirdest = $conf->recruitment->dir_output.'/recruitmentjobposition/'.$newref; $dirdest = $conf->recruitment->dir_output.'/recruitmentjobposition/'.$newref;
if (!$error && file_exists($dirsource)) if (!$error && file_exists($dirsource)) {
{
dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
if (@rename($dirsource, $dirdest)) if (@rename($dirsource, $dirdest)) {
{
dol_syslog("Rename ok"); dol_syslog("Rename ok");
// Rename docs starting with $oldref with $newref // Rename docs starting with $oldref with $newref
$listoffiles = dol_dir_list($conf->recruitment->dir_output.'/recruitmentjobposition/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); $listoffiles = dol_dir_list($conf->recruitment->dir_output.'/recruitmentjobposition/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
foreach ($listoffiles as $fileentry) foreach ($listoffiles as $fileentry) {
{
$dirsource = $fileentry['name']; $dirsource = $fileentry['name'];
$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
$dirsource = $fileentry['path'].'/'.$dirsource; $dirsource = $fileentry['path'].'/'.$dirsource;
@ -580,14 +586,12 @@ class RecruitmentJobPosition extends CommonObject
} }
// Set new ref and current status // Set new ref and current status
if (!$error) if (!$error) {
{
$this->ref = $num; $this->ref = $num;
$this->status = self::STATUS_VALIDATED; $this->status = self::STATUS_VALIDATED;
} }
if (!$error) if (!$error) {
{
$this->db->commit(); $this->db->commit();
return 1; return 1;
} else { } else {
@ -607,8 +611,7 @@ class RecruitmentJobPosition extends CommonObject
public function setDraft($user, $notrigger = 0) public function setDraft($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status <= self::STATUS_DRAFT) if ($this->status <= self::STATUS_DRAFT) {
{
return 0; return 0;
} }
@ -632,8 +635,7 @@ class RecruitmentJobPosition extends CommonObject
public function cancel($user, $notrigger = 0) public function cancel($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status != self::STATUS_VALIDATED) if ($this->status != self::STATUS_VALIDATED) {
{
return 0; return 0;
} }
@ -673,30 +675,25 @@ class RecruitmentJobPosition extends CommonObject
$sql .= " WHERE rowid = ".$this->id; $sql .= " WHERE rowid = ".$this->id;
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$modelpdf = $this->model_pdf; $modelpdf = $this->model_pdf;
$triggerName = 'RECRUITMENTJOB_CLOSE_REFUSED'; $triggerName = 'RECRUITMENTJOB_CLOSE_REFUSED';
if ($status == self::STATUS_RECRUITED) if ($status == self::STATUS_RECRUITED) {
{
$triggerName = 'RECRUITMENTJOB_CLOSE_RECRUITED'; $triggerName = 'RECRUITMENTJOB_CLOSE_RECRUITED';
$modelpdf = $this->model_pdf; $modelpdf = $this->model_pdf;
if ($result < 0) if ($result < 0) {
{
$this->error = $this->db->lasterror(); $this->error = $this->db->lasterror();
$this->db->rollback(); $this->db->rollback();
return -2; return -2;
} }
} }
if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
{
// Define output language // Define output language
$outputlangs = $langs; $outputlangs = $langs;
if (!empty($conf->global->MAIN_MULTILANGS)) if (!empty($conf->global->MAIN_MULTILANGS)) {
{
$outputlangs = new Translate("", $conf); $outputlangs = new Translate("", $conf);
$newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang); $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
$outputlangs->setDefaultLang($newlang); $outputlangs->setDefaultLang($newlang);
@ -705,24 +702,23 @@ class RecruitmentJobPosition extends CommonObject
$this->generateDocument($modelpdf, $outputlangs); $this->generateDocument($modelpdf, $outputlangs);
} }
if (!$error) if (!$error) {
{
$this->oldcopy = clone $this; $this->oldcopy = clone $this;
$this->status = $status; $this->status = $status;
$this->date_cloture = $now; $this->date_cloture = $now;
$this->note_private = $newprivatenote; $this->note_private = $newprivatenote;
} }
if (!$notrigger && empty($error)) if (!$notrigger && empty($error)) {
{
// Call trigger // Call trigger
$result = $this->call_trigger($triggerName, $user); $result = $this->call_trigger($triggerName, $user);
if ($result < 0) { $error++; } if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
if (!$error) if (!$error) {
{
$this->db->commit(); $this->db->commit();
return 1; return 1;
} else { } else {
@ -750,8 +746,7 @@ class RecruitmentJobPosition extends CommonObject
public function reopen($user, $notrigger = 0) public function reopen($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status != self::STATUS_CANCELED) if ($this->status != self::STATUS_CANCELED) {
{
return 0; return 0;
} }
@ -779,7 +774,9 @@ class RecruitmentJobPosition extends CommonObject
{ {
global $conf, $langs, $hookmanager; global $conf, $langs, $hookmanager;
if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips if (!empty($conf->dol_no_mouse_hover)) {
$notooltip = 1; // Force disable tooltips
}
$result = ''; $result = '';
@ -793,25 +790,28 @@ class RecruitmentJobPosition extends CommonObject
$url = dol_buildpath('/recruitment/recruitmentjobposition_card.php', 1).'?id='.$this->id; $url = dol_buildpath('/recruitment/recruitmentjobposition_card.php', 1).'?id='.$this->id;
if ($option != 'nolink') if ($option != 'nolink') {
{
// Add param to save lastsearch_values or not // Add param to save lastsearch_values or not
$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; $add_save_lastsearch_values = 1;
}
if ($add_save_lastsearch_values) {
$url .= '&save_lastsearch_values=1';
}
} }
$linkclose = ''; $linkclose = '';
if (empty($notooltip)) if (empty($notooltip)) {
{ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label = $langs->trans("ShowRecruitmentJobPosition"); $label = $langs->trans("ShowRecruitmentJobPosition");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } else {
$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
}
$linkstart = '<a href="'.$url.'"'; $linkstart = '<a href="'.$url.'"';
$linkstart .= $linkclose.'>'; $linkstart .= $linkclose.'>';
@ -820,7 +820,9 @@ class RecruitmentJobPosition extends CommonObject
$result .= $linkstart; $result .= $linkstart;
if (empty($this->showphoto_on_popup)) { if (empty($this->showphoto_on_popup)) {
if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); if ($withpicto) {
$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
}
} else { } else {
if ($withpicto) { if ($withpicto) {
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
@ -846,7 +848,9 @@ class RecruitmentJobPosition extends CommonObject
} }
} }
if ($withpicto != 2) $result .= $this->ref; if ($withpicto != 2) {
$result .= $this->ref;
}
$result .= $linkend; $result .= $linkend;
//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
@ -855,8 +859,11 @@ class RecruitmentJobPosition extends CommonObject
$hookmanager->initHooks(array('recruitmentjobpositiondao')); $hookmanager->initHooks(array('recruitmentjobpositiondao'));
$parameters = array('id'=>$this->id, 'getnomurl'=>$result); $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $result = $hookmanager->resPrint; if ($reshook > 0) {
else $result .= $hookmanager->resPrint; $result = $hookmanager->resPrint;
} else {
$result .= $hookmanager->resPrint;
}
return $result; return $result;
} }
@ -883,8 +890,7 @@ class RecruitmentJobPosition extends CommonObject
public function LibStatut($status, $mode = 0) public function LibStatut($status, $mode = 0)
{ {
// phpcs:enable // phpcs:enable
if (empty($this->labelStatus) || empty($this->labelStatusShort)) if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
{
global $langs; global $langs;
//$langs->load("recruitment"); //$langs->load("recruitment");
$this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
@ -898,9 +904,15 @@ class RecruitmentJobPosition extends CommonObject
} }
$statusType = 'status'.$status; $statusType = 'status'.$status;
if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; if ($status == self::STATUS_VALIDATED) {
if ($status == self::STATUS_RECRUITED) $statusType = 'status6'; $statusType = 'status4';
if ($status == self::STATUS_CANCELED) $statusType = 'status9'; }
if ($status == self::STATUS_RECRUITED) {
$statusType = 'status6';
}
if ($status == self::STATUS_CANCELED) {
$statusType = 'status9';
}
return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
} }
@ -918,28 +930,23 @@ class RecruitmentJobPosition extends CommonObject
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
$sql .= ' WHERE t.rowid = '.$id; $sql .= ' WHERE t.rowid = '.$id;
$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);
$this->id = $obj->rowid; $this->id = $obj->rowid;
if ($obj->fk_user_author) if ($obj->fk_user_author) {
{
$cuser = new User($this->db); $cuser = new User($this->db);
$cuser->fetch($obj->fk_user_author); $cuser->fetch($obj->fk_user_author);
$this->user_creation = $cuser; $this->user_creation = $cuser;
} }
if ($obj->fk_user_valid) if ($obj->fk_user_valid) {
{
$vuser = new User($this->db); $vuser = new User($this->db);
$vuser->fetch($obj->fk_user_valid); $vuser->fetch($obj->fk_user_valid);
$this->user_validation = $vuser; $this->user_validation = $vuser;
} }
if ($obj->fk_user_cloture) if ($obj->fk_user_cloture) {
{
$cluser = new User($this->db); $cluser = new User($this->db);
$cluser->fetch($obj->fk_user_cloture); $cluser->fetch($obj->fk_user_cloture);
$this->user_cloture = $cluser; $this->user_cloture = $cluser;
@ -993,8 +1000,7 @@ class RecruitmentJobPosition extends CommonObject
$conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON = 'mod_recruitmentjobposition_standard'; $conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON = 'mod_recruitmentjobposition_standard';
} }
if (!empty($conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON)) if (!empty($conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON)) {
{
$mybool = false; $mybool = false;
$file = $conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON.".php"; $file = $conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON.".php";
@ -1002,16 +1008,14 @@ class RecruitmentJobPosition extends CommonObject
// Include file with class // Include file with class
$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{
$dir = dol_buildpath($reldir."core/modules/recruitment/"); $dir = dol_buildpath($reldir."core/modules/recruitment/");
// Load file with numbering class (if found) // Load file with numbering class (if found)
$mybool |= @include_once $dir.$file; $mybool |= @include_once $dir.$file;
} }
if ($mybool === false) if ($mybool === false) {
{
dol_print_error('', "Failed to include file ".$file); dol_print_error('', "Failed to include file ".$file);
return ''; return '';
} }
@ -1020,8 +1024,7 @@ class RecruitmentJobPosition extends CommonObject
$obj = new $classname(); $obj = new $classname();
$numref = $obj->getNextValue($this); $numref = $obj->getNextValue($this);
if ($numref != '' && $numref != '-1') if ($numref != '' && $numref != '-1') {
{
return $numref; return $numref;
} else { } else {
$this->error = $obj->error; $this->error = $obj->error;

View File

@ -98,7 +98,9 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
// Recupere emetteur // Recupere emetteur
$this->emetteur = $mysoc; $this->emetteur = $mysoc;
if (!$this->emetteur->country_code) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined if (!$this->emetteur->country_code) {
$this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined
}
} }
@ -129,8 +131,7 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
$texttitle = $langs->trans("ListOfDirectories"); $texttitle = $langs->trans("ListOfDirectories");
$listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON_PDF_ODT_PATH))); $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON_PDF_ODT_PATH)));
$listoffiles = array(); $listoffiles = array();
foreach ($listofdir as $key=>$tmpdir) foreach ($listofdir as $key => $tmpdir) {
{
$tmpdir = trim($tmpdir); $tmpdir = trim($tmpdir);
$tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
if (!$tmpdir) { if (!$tmpdir) {
@ -140,7 +141,9 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
$texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0); $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0);
} else { } else {
$tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)'); $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)');
if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); if (count($tmpfiles)) {
$listoffiles = array_merge($listoffiles, $tmpfiles);
}
} }
} }
$texthelp = $langs->trans("ListOfDirectoriesForModelGenODT"); $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT");
@ -159,8 +162,7 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
// Scan directories // Scan directories
$nbofiles = count($listoffiles); $nbofiles = count($listoffiles);
if (!empty($conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON_PDF_ODT_PATH)) if (!empty($conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON_PDF_ODT_PATH)) {
{
$texte .= $langs->trans("NumberOfModelFilesFound").': <b>'; $texte .= $langs->trans("NumberOfModelFilesFound").': <b>';
//$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':''; //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
$texte .= count($listoffiles); $texte .= count($listoffiles);
@ -168,11 +170,9 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
$texte .= '</b>'; $texte .= '</b>';
} }
if ($nbofiles) if ($nbofiles) {
{
$texte .= '<div id="div_'.get_class($this).'" class="hidden">'; $texte .= '<div id="div_'.get_class($this).'" class="hidden">';
foreach ($listoffiles as $file) foreach ($listoffiles as $file) {
{
$texte .= $file['name'].'<br>'; $texte .= $file['name'].'<br>';
} }
$texte .= '</div>'; $texte .= '</div>';
@ -208,37 +208,34 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
// phpcs:enable // phpcs:enable
global $user, $langs, $conf, $mysoc, $hookmanager; global $user, $langs, $conf, $mysoc, $hookmanager;
if (empty($srctemplatepath)) if (empty($srctemplatepath)) {
{
dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
return -1; return -1;
} }
// Add odtgeneration hook // Add odtgeneration hook
if (!is_object($hookmanager)) if (!is_object($hookmanager)) {
{
include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
$hookmanager = new HookManager($this->db); $hookmanager = new HookManager($this->db);
} }
$hookmanager->initHooks(array('odtgeneration')); $hookmanager->initHooks(array('odtgeneration'));
global $action; global $action;
if (!is_object($outputlangs)) $outputlangs = $langs; if (!is_object($outputlangs)) {
$outputlangs = $langs;
}
$sav_charset_output = $outputlangs->charset_output; $sav_charset_output = $outputlangs->charset_output;
$outputlangs->charset_output = 'UTF-8'; $outputlangs->charset_output = 'UTF-8';
$outputlangs->loadLangs(array("main", "dict", "companies", "bills")); $outputlangs->loadLangs(array("main", "dict", "companies", "bills"));
if ($conf->commande->dir_output) if ($conf->commande->dir_output) {
{
// If $object is id instead of object // If $object is id instead of object
if (!is_object($object)) if (!is_object($object)) {
{
$id = $object; $id = $object;
$object = new Commande($this->db); $object = new Commande($this->db);
$result = $object->fetch($id); $result = $object->fetch($id);
if ($result < 0) if ($result < 0) {
{
dol_print_error($this->db, $object->error); dol_print_error($this->db, $object->error);
return -1; return -1;
} }
@ -246,20 +243,19 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
$dir = $conf->commande->multidir_output[isset($object->entity) ? $object->entity : 1]; $dir = $conf->commande->multidir_output[isset($object->entity) ? $object->entity : 1];
$objectref = dol_sanitizeFileName($object->ref); $objectref = dol_sanitizeFileName($object->ref);
if (!preg_match('/specimen/i', $objectref)) $dir .= "/".$objectref; if (!preg_match('/specimen/i', $objectref)) {
$dir .= "/".$objectref;
}
$file = $dir."/".$objectref.".odt"; $file = $dir."/".$objectref.".odt";
if (!file_exists($dir)) if (!file_exists($dir)) {
{ if (dol_mkdir($dir) < 0) {
if (dol_mkdir($dir) < 0)
{
$this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
return -1; return -1;
} }
} }
if (file_exists($dir)) if (file_exists($dir)) {
{
//print "srctemplatepath=".$srctemplatepath; // Src filename //print "srctemplatepath=".$srctemplatepath; // Src filename
$newfile = basename($srctemplatepath); $newfile = basename($srctemplatepath);
$newfiletmp = preg_replace('/\.od(t|s)/i', '', $newfile); $newfiletmp = preg_replace('/\.od(t|s)/i', '', $newfile);
@ -269,10 +265,11 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
//$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt'; //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
// Get extension (ods or odt) // Get extension (ods or odt)
$newfileformat = substr($newfile, strrpos($newfile, '.') + 1); $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
if (!empty($conf->global->MAIN_DOC_USE_TIMING)) if (!empty($conf->global->MAIN_DOC_USE_TIMING)) {
{
$format = $conf->global->MAIN_DOC_USE_TIMING; $format = $conf->global->MAIN_DOC_USE_TIMING;
if ($format == '1') $format = '%Y%m%d%H%M%S'; if ($format == '1') {
$format = '%Y%m%d%H%M%S';
}
$filename = $newfiletmp.'-'.dol_print_date(dol_now(), $format).'.'.$newfileformat; $filename = $newfiletmp.'-'.dol_print_date(dol_now(), $format).'.'.$newfileformat;
} else { } else {
$filename = $newfiletmp.'.'.$newfileformat; $filename = $newfiletmp.'.'.$newfileformat;
@ -289,16 +286,14 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
// If CUSTOMER contact defined on order, we use it // If CUSTOMER contact defined on order, we use it
$usecontact = false; $usecontact = false;
$arrayidcontact = $object->getIdContact('external', 'CUSTOMER'); $arrayidcontact = $object->getIdContact('external', 'CUSTOMER');
if (count($arrayidcontact) > 0) if (count($arrayidcontact) > 0) {
{
$usecontact = true; $usecontact = true;
$result = $object->fetch_contact($arrayidcontact[0]); $result = $object->fetch_contact($arrayidcontact[0]);
} }
// Recipient name // Recipient name
$contactobject = null; $contactobject = null;
if (!empty($usecontact)) if (!empty($usecontact)) {
{
if ($usecontact && ($object->contact->fk_soc != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)))) { if ($usecontact && ($object->contact->fk_soc != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)))) {
$socobject = $object->contact; $socobject = $object->contact;
} else { } else {
@ -326,8 +321,7 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
// Line of free text // Line of free text
$newfreetext = ''; $newfreetext = '';
$paramfreetext = 'ORDER_FREE_TEXT'; $paramfreetext = 'ORDER_FREE_TEXT';
if (!empty($conf->global->$paramfreetext)) if (!empty($conf->global->$paramfreetext)) {
{
$newfreetext = make_substitutions($conf->global->$paramfreetext, $substitutionarray); $newfreetext = make_substitutions($conf->global->$paramfreetext, $substitutionarray);
} }
@ -343,8 +337,7 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
'DELIMITER_RIGHT' => '}' 'DELIMITER_RIGHT' => '}'
) )
); );
} catch (Exception $e) } catch (Exception $e) {
{
$this->error = $e->getMessage(); $this->error = $e->getMessage();
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
return -1; return -1;
@ -359,8 +352,7 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
// Make substitutions into odt of freetext // Make substitutions into odt of freetext
try { try {
$odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8'); $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
} catch (OdfException $e) } catch (OdfException $e) {
{
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
} }
@ -374,7 +366,9 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
$array_other = $this->get_substitutionarray_other($outputlangs); $array_other = $this->get_substitutionarray_other($outputlangs);
// retrieve contact information for use in object as contact_xxx tags // retrieve contact information for use in object as contact_xxx tags
$array_thirdparty_contact = array(); $array_thirdparty_contact = array();
if ($usecontact && is_object($contactobject)) $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact'); if ($usecontact && is_object($contactobject)) {
$array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact');
}
$tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_thirdparty_contact); $tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_thirdparty_contact);
complete_substitutions_array($tmparray, $outputlangs, $object); complete_substitutions_array($tmparray, $outputlangs, $object);
@ -383,19 +377,20 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
$parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray); $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray);
$reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
foreach ($tmparray as $key=>$value) foreach ($tmparray as $key => $value) {
{
try { try {
if (preg_match('/logo$/', $key)) { if (preg_match('/logo$/', $key)) {
// Image // Image
if (file_exists($value)) $odfHandler->setImage($key, $value); if (file_exists($value)) {
else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); $odfHandler->setImage($key, $value);
} else {
$odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
}
} else { } else {
// Text // Text
$odfHandler->setVars($key, $value, true, 'UTF-8'); $odfHandler->setVars($key, $value, true, 'UTF-8');
} }
} catch (OdfException $e) } catch (OdfException $e) {
{
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
} }
} }
@ -404,32 +399,26 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
$foundtagforlines = 1; $foundtagforlines = 1;
try { try {
$listlines = $odfHandler->setSegment('lines'); $listlines = $odfHandler->setSegment('lines');
} catch (OdfException $e) } catch (OdfException $e) {
{
// We may arrive here if tags for lines not present into template // We may arrive here if tags for lines not present into template
$foundtagforlines = 0; $foundtagforlines = 0;
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
} }
if ($foundtagforlines) if ($foundtagforlines) {
{
$linenumber = 0; $linenumber = 0;
foreach ($object->lines as $line) foreach ($object->lines as $line) {
{
$linenumber++; $linenumber++;
$tmparray = $this->get_substitutionarray_lines($line, $outputlangs, $linenumber); $tmparray = $this->get_substitutionarray_lines($line, $outputlangs, $linenumber);
complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines"); complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
// Call the ODTSubstitutionLine hook // Call the ODTSubstitutionLine hook
$parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray, 'line'=>$line); $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray, 'line'=>$line);
$reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
foreach ($tmparray as $key => $val) foreach ($tmparray as $key => $val) {
{
try { try {
$listlines->setVars($key, $val, true, 'UTF-8'); $listlines->setVars($key, $val, true, 'UTF-8');
} catch (OdfException $e) } catch (OdfException $e) {
{
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
} catch (SegmentException $e) } catch (SegmentException $e) {
{
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
} }
} }
@ -437,8 +426,7 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
} }
$odfHandler->mergeSegment($listlines); $odfHandler->mergeSegment($listlines);
} }
} catch (OdfException $e) } catch (OdfException $e) {
{
$this->error = $e->getMessage(); $this->error = $e->getMessage();
dol_syslog($this->error, LOG_WARNING); dol_syslog($this->error, LOG_WARNING);
return -1; return -1;
@ -446,12 +434,10 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
// Replace labels translated // Replace labels translated
$tmparray = $outputlangs->get_translations_for_substitutions(); $tmparray = $outputlangs->get_translations_for_substitutions();
foreach ($tmparray as $key=>$value) foreach ($tmparray as $key => $value) {
{
try { try {
$odfHandler->setVars($key, $value, true, 'UTF-8'); $odfHandler->setVars($key, $value, true, 'UTF-8');
} catch (OdfException $e) } catch (OdfException $e) {
{
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
} }
} }
@ -483,8 +469,9 @@ class doc_generic_recruitmentjobposition_odt extends ModelePDFRecruitmentJobPosi
$parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray); $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray);
$reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
if (!empty($conf->global->MAIN_UMASK)) if (!empty($conf->global->MAIN_UMASK)) {
@chmod($file, octdec($conf->global->MAIN_UMASK)); @chmod($file, octdec($conf->global->MAIN_UMASK));
}
$odfHandler = null; // Destroy object $odfHandler = null; // Destroy object

View File

@ -174,7 +174,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
// Get source company // Get source company
$this->emetteur = $mysoc; $this->emetteur = $mysoc;
if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined if (empty($this->emetteur->country_code)) {
$this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined
}
// Define position of columns // Define position of columns
$this->posxdesc = $this->marge_gauche + 1; // used for notes ans other stuff $this->posxdesc = $this->marge_gauche + 1; // used for notes ans other stuff
@ -212,9 +214,13 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
dol_syslog("write_file outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); dol_syslog("write_file outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
if (!is_object($outputlangs)) $outputlangs = $langs; if (!is_object($outputlangs)) {
$outputlangs = $langs;
}
// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; if (!empty($conf->global->MAIN_USE_FPDF)) {
$outputlangs->charset_output = 'ISO-8859-1';
}
// Load translation files required by the page // Load translation files required by the page
$outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies")); $outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies"));
@ -291,13 +297,11 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
//if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; //if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva;
if ($conf->recruitment->dir_output.'/recruitmentjobposition') if ($conf->recruitment->dir_output.'/recruitmentjobposition') {
{
$object->fetch_thirdparty(); $object->fetch_thirdparty();
// Definition of $dir and $file // Definition of $dir and $file
if ($object->specimen) if ($object->specimen) {
{
$dir = $conf->recruitment->dir_output.'/recruitmentjobposition'; $dir = $conf->recruitment->dir_output.'/recruitmentjobposition';
$file = $dir."/SPECIMEN.pdf"; $file = $dir."/SPECIMEN.pdf";
} else { } else {
@ -305,20 +309,16 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$dir = $conf->recruitment->dir_output.'/recruitmentjobposition/'.$objectref; $dir = $conf->recruitment->dir_output.'/recruitmentjobposition/'.$objectref;
$file = $dir."/".$objectref.".pdf"; $file = $dir."/".$objectref.".pdf";
} }
if (!file_exists($dir)) if (!file_exists($dir)) {
{ if (dol_mkdir($dir) < 0) {
if (dol_mkdir($dir) < 0)
{
$this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
return 0; return 0;
} }
} }
if (file_exists($dir)) if (file_exists($dir)) {
{
// Add pdfgeneration hook // Add pdfgeneration hook
if (!is_object($hookmanager)) if (!is_object($hookmanager)) {
{
include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
$hookmanager = new HookManager($this->db); $hookmanager = new HookManager($this->db);
} }
@ -339,16 +339,14 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page
$heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin) $heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin)
if (class_exists('TCPDF')) if (class_exists('TCPDF')) {
{
$pdf->setPrintHeader(false); $pdf->setPrintHeader(false);
$pdf->setPrintFooter(false); $pdf->setPrintFooter(false);
} }
$pdf->SetFont(pdf_getPDFFont($outputlangs)); $pdf->SetFont(pdf_getPDFFont($outputlangs));
// Set path to the background PDF File // Set path to the background PDF File
if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) {
{
$pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND);
$tplidx = $pdf->importPage(1); $tplidx = $pdf->importPage(1);
} }
@ -362,7 +360,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$pdf->SetCreator("Dolibarr ".DOL_VERSION); $pdf->SetCreator("Dolibarr ".DOL_VERSION);
$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$object->label." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$object->label." ".$outputlangs->convToOutputCharset($object->thirdparty->name));
if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
$pdf->SetCompression(false);
}
// Set certificate // Set certificate
$cert = empty($user->conf->CERTIFICATE_CRT) ? '' : $user->conf->CERTIFICATE_CRT; $cert = empty($user->conf->CERTIFICATE_CRT) ? '' : $user->conf->CERTIFICATE_CRT;
@ -385,7 +385,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
// New page // New page
$pdf->AddPage(); $pdf->AddPage();
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
$pdf->useTemplate($tplidx);
}
$pagenb++; $pagenb++;
$top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs, $outputlangsbis); $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs, $outputlangsbis);
@ -397,7 +399,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10);
$tab_height = 130 - $top_shift; $tab_height = 130 - $top_shift;
$tab_height_newpage = 150; $tab_height_newpage = 150;
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $tab_height_newpage -= $top_shift; if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
$tab_height_newpage -= $top_shift;
}
$nexY = $tab_top - 1; $nexY = $tab_top - 1;
@ -405,14 +409,12 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$notetoshow = empty($object->note_public) ? '' : $object->note_public; $notetoshow = empty($object->note_public) ? '' : $object->note_public;
// Extrafields in note // Extrafields in note
$extranote = $this->getExtrafieldsInHtml($object, $outputlangs); $extranote = $this->getExtrafieldsInHtml($object, $outputlangs);
if (!empty($extranote)) if (!empty($extranote)) {
{
$notetoshow = dol_concatdesc($notetoshow, $extranote); $notetoshow = dol_concatdesc($notetoshow, $extranote);
} }
$pagenb = $pdf->getPage(); $pagenb = $pdf->getPage();
if ($notetoshow) if ($notetoshow) {
{
$tab_top -= 2; $tab_top -= 2;
$tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite; $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite;
@ -431,16 +433,19 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$pageposafternote = $pdf->getPage(); $pageposafternote = $pdf->getPage();
$posyafter = $pdf->GetY(); $posyafter = $pdf->GetY();
if ($pageposafternote > $pageposbeforenote) if ($pageposafternote > $pageposbeforenote) {
{
$pdf->rollbackTransaction(true); $pdf->rollbackTransaction(true);
// prepare pages to receive notes // prepare pages to receive notes
while ($pagenb < $pageposafternote) { while ($pagenb < $pageposafternote) {
$pdf->AddPage(); $pdf->AddPage();
$pagenb++; $pagenb++;
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); $pdf->useTemplate($tplidx);
}
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
$this->_pagehead($pdf, $object, 0, $outputlangs);
}
// $this->_pagefoot($pdf,$object,$outputlangs,1); // $this->_pagefoot($pdf,$object,$outputlangs,1);
$pdf->setTopMargin($tab_top_newpage); $pdf->setTopMargin($tab_top_newpage);
// The only function to edit the bottom margin of current page to set it. // The only function to edit the bottom margin of current page to set it.
@ -456,8 +461,7 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$posyafter = $pdf->GetY(); $posyafter = $pdf->GetY();
if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) // There is no space left for total+free text if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) { // There is no space left for total+free text
{
$pdf->AddPage('', '', true); $pdf->AddPage('', '', true);
$pagenb++; $pagenb++;
$pageposafternote++; $pageposafternote++;
@ -494,8 +498,12 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
// apply note frame to last page // apply note frame to last page
$pdf->setPage($pageposafternote); $pdf->setPage($pageposafternote);
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); $pdf->useTemplate($tplidx);
}
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
$this->_pagehead($pdf, $object, 0, $outputlangs);
}
$height_note = $posyafter - $tab_top_newpage; $height_note = $posyafter - $tab_top_newpage;
$pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1);
} else // No pagebreak } else // No pagebreak
@ -505,15 +513,18 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$height_note = $posyafter - $tab_top; $height_note = $posyafter - $tab_top;
$pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1);
if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) {
{
// not enough space, need to add page // not enough space, need to add page
$pdf->AddPage('', '', true); $pdf->AddPage('', '', true);
$pagenb++; $pagenb++;
$pageposafternote++; $pageposafternote++;
$pdf->setPage($pageposafternote); $pdf->setPage($pageposafternote);
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); $pdf->useTemplate($tplidx);
}
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
$this->_pagehead($pdf, $object, 0, $outputlangs);
}
$posyafter = $tab_top_newpage; $posyafter = $tab_top_newpage;
} }
@ -538,15 +549,16 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
// Loop on each lines // Loop on each lines
$pageposbeforeprintlines = $pdf->getPage(); $pageposbeforeprintlines = $pdf->getPage();
$pagenb = $pageposbeforeprintlines; $pagenb = $pageposbeforeprintlines;
for ($i = 0; $i < $nblines; $i++) for ($i = 0; $i < $nblines; $i++) {
{
$curY = $nexY; $curY = $nexY;
$pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage
$pdf->SetTextColor(0, 0, 0); $pdf->SetTextColor(0, 0, 0);
// Define size of image if we need it // Define size of image if we need it
$imglinesize = array(); $imglinesize = array();
if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); if (!empty($realpatharray[$i])) {
$imglinesize = pdf_getSizeForImage($realpatharray[$i]);
}
$pdf->setTopMargin($tab_top_newpage); $pdf->setTopMargin($tab_top_newpage);
$pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it.
@ -555,25 +567,26 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$showpricebeforepagebreak = 1; $showpricebeforepagebreak = 1;
$posYAfterImage = 0; $posYAfterImage = 0;
if ($this->getColumnStatus('photo')) if ($this->getColumnStatus('photo')) {
{
// We start with Photo of product line // We start with Photo of product line
if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // If photo too high, we moved completely on new page
{
$pdf->AddPage('', '', true); $pdf->AddPage('', '', true);
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
$pdf->useTemplate($tplidx);
}
$pdf->setPage($pageposbefore + 1); $pdf->setPage($pageposbefore + 1);
$curY = $tab_top_newpage; $curY = $tab_top_newpage;
// Allows data in the first page if description is long enough to break in multiples pages // Allows data in the first page if description is long enough to break in multiples pages
if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) {
$showpricebeforepagebreak = 1; $showpricebeforepagebreak = 1;
else $showpricebeforepagebreak = 0; } else {
$showpricebeforepagebreak = 0;
}
} }
if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) {
{
$pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi
// $pdf->Image does not increase value return by getY, so we save it manually // $pdf->Image does not increase value return by getY, so we save it manually
$posYAfterImage = $curY + $imglinesize['height']; $posYAfterImage = $curY + $imglinesize['height'];
@ -581,15 +594,13 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
} }
// Description of product line // Description of product line
if ($this->getColumnStatus('desc')) if ($this->getColumnStatus('desc')) {
{
$pdf->startTransaction(); $pdf->startTransaction();
$this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc);
$pageposafter = $pdf->getPage(); $pageposafter = $pdf->getPage();
if ($pageposafter > $pageposbefore) // There is a pagebreak if ($pageposafter > $pageposbefore) { // There is a pagebreak
{
$pdf->rollbackTransaction(true); $pdf->rollbackTransaction(true);
$pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it.
@ -598,20 +609,22 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$pageposafter = $pdf->getPage(); $pageposafter = $pdf->getPage();
$posyafter = $pdf->GetY(); $posyafter = $pdf->GetY();
//var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit;
if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // There is no space left for total+free text
{ if ($i == ($nblines - 1)) { // No more lines, and no space left to show total, so we create a new page
if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page
{
$pdf->AddPage('', '', true); $pdf->AddPage('', '', true);
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
$pdf->useTemplate($tplidx);
}
$pdf->setPage($pageposafter + 1); $pdf->setPage($pageposafter + 1);
} }
} else { } else {
// We found a page break // We found a page break
// Allows data in the first page if description is long enough to break in multiples pages // Allows data in the first page if description is long enough to break in multiples pages
if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) {
$showpricebeforepagebreak = 1; $showpricebeforepagebreak = 1;
else $showpricebeforepagebreak = 0; } else {
$showpricebeforepagebreak = 0;
}
} }
} else // No pagebreak } else // No pagebreak
{ {
@ -659,7 +672,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$pagenb++; $pagenb++;
$pdf->setPage($pagenb); $pdf->setPage($pagenb);
$pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it.
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
$this->_pagehead($pdf, $object, 0, $outputlangs);
}
} }
if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) {
@ -671,15 +686,18 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$this->_pagefoot($pdf, $object, $outputlangs, 1); $this->_pagefoot($pdf, $object, $outputlangs, 1);
// New page // New page
$pdf->AddPage(); $pdf->AddPage();
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
$pdf->useTemplate($tplidx);
}
$pagenb++; $pagenb++;
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
$this->_pagehead($pdf, $object, 0, $outputlangs);
}
} }
} }
// Show square // Show square
if ($pagenb == $pageposbeforeprintlines) if ($pagenb == $pageposbeforeprintlines) {
{
$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code, $outputlangsbis); $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code, $outputlangsbis);
$bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
} else { } else {
@ -703,7 +721,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
// Pagefoot // Pagefoot
$this->_pagefoot($pdf, $object, $outputlangs); $this->_pagefoot($pdf, $object, $outputlangs);
if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages(); if (method_exists($pdf, 'AliasNbPages')) {
$pdf->AliasNbPages();
}
$pdf->Close(); $pdf->Close();
@ -714,14 +734,14 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs);
global $action; global $action;
$reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) if ($reshook < 0) {
{
$this->error = $hookmanager->error; $this->error = $hookmanager->error;
$this->errors = $hookmanager->errors; $this->errors = $hookmanager->errors;
} }
if (!empty($conf->global->MAIN_UMASK)) if (!empty($conf->global->MAIN_UMASK)) {
@chmod($file, octdec($conf->global->MAIN_UMASK)); @chmod($file, octdec($conf->global->MAIN_UMASK));
}
$this->result = array('fullpath'=>$file); $this->result = array('fullpath'=>$file);
@ -771,7 +791,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
// Force to disable hidetop and hidebottom // Force to disable hidetop and hidebottom
$hidebottom = 0; $hidebottom = 0;
if ($hidetop) $hidetop = -1; if ($hidetop) {
$hidetop = -1;
}
$currency = !empty($currency) ? $currency : $conf->currency; $currency = !empty($currency) ? $currency : $conf->currency;
$default_font_size = pdf_getPDFFontSize($outputlangs); $default_font_size = pdf_getPDFFontSize($outputlangs);
@ -780,8 +802,7 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$pdf->SetTextColor(0, 0, 0); $pdf->SetTextColor(0, 0, 0);
$pdf->SetFont('', '', $default_font_size - 2); $pdf->SetFont('', '', $default_font_size - 2);
if (empty($hidetop)) if (empty($hidetop)) {
{
//$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230'; //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230';
if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) { if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) {
$pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
@ -825,8 +846,7 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
pdf_pagehead($pdf, $outputlangs, $this->page_hauteur); pdf_pagehead($pdf, $outputlangs, $this->page_hauteur);
// Show Draft Watermark // Show Draft Watermark
if ($object->statut == $object::STATUS_DRAFT && (!empty($conf->global->FACTURE_DRAFT_WATERMARK))) if ($object->statut == $object::STATUS_DRAFT && (!empty($conf->global->FACTURE_DRAFT_WATERMARK))) {
{
pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->FACTURE_DRAFT_WATERMARK); pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->FACTURE_DRAFT_WATERMARK);
} }
@ -841,20 +861,18 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$pdf->SetXY($this->marge_gauche, $posy); $pdf->SetXY($this->marge_gauche, $posy);
// Logo // Logo
if (empty($conf->global->PDF_DISABLE_MYCOMPANY_LOGO)) if (empty($conf->global->PDF_DISABLE_MYCOMPANY_LOGO)) {
{ if ($this->emetteur->logo) {
if ($this->emetteur->logo)
{
$logodir = $conf->mycompany->dir_output; $logodir = $conf->mycompany->dir_output;
if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; if (!empty($conf->mycompany->multidir_output[$object->entity])) {
if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) $logodir = $conf->mycompany->multidir_output[$object->entity];
{ }
if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) {
$logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small; $logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small;
} else { } else {
$logo = $logodir.'/logos/'.$this->emetteur->logo; $logo = $logodir.'/logos/'.$this->emetteur->logo;
} }
if (is_readable($logo)) if (is_readable($logo)) {
{
$height = pdf_getHeightForLogo($logo); $height = pdf_getHeightForLogo($logo);
$pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto)
} else { } else {
@ -885,8 +903,7 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$pdf->SetXY($posx, $posy); $pdf->SetXY($posx, $posy);
$pdf->SetTextColor(0, 0, 60); $pdf->SetTextColor(0, 0, 60);
$textref = $outputlangs->transnoentities("Ref")." : ".$outputlangs->convToOutputCharset($object->ref); $textref = $outputlangs->transnoentities("Ref")." : ".$outputlangs->convToOutputCharset($object->ref);
if ($object->statut == $object::STATUS_DRAFT) if ($object->statut == $object::STATUS_DRAFT) {
{
$pdf->SetTextColor(128, 0, 0); $pdf->SetTextColor(128, 0, 0);
$textref .= ' - '.$outputlangs->transnoentities("NotValidated"); $textref .= ' - '.$outputlangs->transnoentities("NotValidated");
} }
@ -895,19 +912,16 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$posy += 1; $posy += 1;
$pdf->SetFont('', '', $default_font_size - 2); $pdf->SetFont('', '', $default_font_size - 2);
if ($object->ref_client) if ($object->ref_client) {
{
$posy += 4; $posy += 4;
$pdf->SetXY($posx, $posy); $pdf->SetXY($posx, $posy);
$pdf->SetTextColor(0, 0, 60); $pdf->SetTextColor(0, 0, 60);
$pdf->MultiCell($w, 3, $outputlangs->transnoentities("RefCustomer")." : ".$outputlangs->convToOutputCharset($object->ref_client), '', 'R'); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("RefCustomer")." : ".$outputlangs->convToOutputCharset($object->ref_client), '', 'R');
} }
if (!empty($conf->global->PDF_SHOW_PROJECT_TITLE)) if (!empty($conf->global->PDF_SHOW_PROJECT_TITLE)) {
{
$object->fetch_projet(); $object->fetch_projet();
if (!empty($object->project->ref)) if (!empty($object->project->ref)) {
{
$posy += 3; $posy += 3;
$pdf->SetXY($posx, $posy); $pdf->SetXY($posx, $posy);
$pdf->SetTextColor(0, 0, 60); $pdf->SetTextColor(0, 0, 60);
@ -915,11 +929,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
} }
} }
if (!empty($conf->global->PDF_SHOW_PROJECT)) if (!empty($conf->global->PDF_SHOW_PROJECT)) {
{
$object->fetch_projet(); $object->fetch_projet();
if (!empty($object->project->ref)) if (!empty($object->project->ref)) {
{
$posy += 3; $posy += 3;
$pdf->SetXY($posx, $posy); $pdf->SetXY($posx, $posy);
$pdf->SetTextColor(0, 0, 60); $pdf->SetTextColor(0, 0, 60);
@ -937,8 +949,7 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
} }
$pdf->MultiCell($w, 3, $title." : ".dol_print_date($object->date_creation, "day", false, $outputlangs), '', 'R'); $pdf->MultiCell($w, 3, $title." : ".dol_print_date($object->date_creation, "day", false, $outputlangs), '', 'R');
if ($object->thirdparty->code_client) if ($object->thirdparty->code_client) {
{
$posy += 3; $posy += 3;
$pdf->SetXY($posx, $posy); $pdf->SetXY($posx, $posy);
$pdf->SetTextColor(0, 0, 60); $pdf->SetTextColor(0, 0, 60);
@ -951,13 +962,11 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
// Show list of linked objects // Show list of linked objects
$current_y = $pdf->getY(); $current_y = $pdf->getY();
$posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, $w, 3, 'R', $default_font_size); $posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, $w, 3, 'R', $default_font_size);
if ($current_y < $pdf->getY()) if ($current_y < $pdf->getY()) {
{
$top_shift = $pdf->getY() - $current_y; $top_shift = $pdf->getY() - $current_y;
} }
if ($showaddress) if ($showaddress) {
{
// Sender properties // Sender properties
$carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object);
@ -965,7 +974,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
$posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
$posy += $top_shift; $posy += $top_shift;
$posx = $this->marge_gauche; $posx = $this->marge_gauche;
if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80; if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) {
$posx = $this->page_largeur - $this->marge_droite - 80;
}
$hautcadre = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40; $hautcadre = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40;
$widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82; $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82;
@ -995,8 +1006,7 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
// If BILLING contact defined on invoice, we use it // If BILLING contact defined on invoice, we use it
$usecontact = false; $usecontact = false;
$arrayidcontact = $object->getIdContact('external', 'BILLING'); $arrayidcontact = $object->getIdContact('external', 'BILLING');
if (count($arrayidcontact) > 0) if (count($arrayidcontact) > 0) {
{
$usecontact = true; $usecontact = true;
$result = $object->fetch_contact($arrayidcontact[0]); $result = $object->fetch_contact($arrayidcontact[0]);
} }
@ -1258,11 +1268,9 @@ class pdf_standard_recruitmentjobposition extends ModelePDFRecruitmentJobPositio
); );
$reshook = $hookmanager->executeHooks('defineColumnField', $parameters, $this); // Note that $object may have been modified by hook $reshook = $hookmanager->executeHooks('defineColumnField', $parameters, $this); // Note that $object may have been modified by hook
if ($reshook < 0) if ($reshook < 0) {
{
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
} elseif (empty($reshook)) } elseif (empty($reshook)) {
{
$this->cols = array_replace($this->cols, $hookmanager->resArray); // array_replace is used to preserve keys $this->cols = array_replace($this->cols, $hookmanager->resArray); // array_replace is used to preserve keys
} else { } else {
$this->cols = $hookmanager->resArray; $this->cols = $hookmanager->resArray;

View File

@ -96,13 +96,13 @@ class mod_recruitmentcandidature_standard extends ModeleNumRefRecruitmentCandida
} }
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$row = $db->fetch_row($resql); $row = $db->fetch_row($resql);
if ($row) { $coyymm = substr($row[0], 0, 6); $max = $row[0]; } if ($row) {
$coyymm = substr($row[0], 0, 6); $max = $row[0];
} }
if ($coyymm && !preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) }
{ if ($coyymm && !preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) {
$langs->load("errors"); $langs->load("errors");
$this->error = $langs->trans('ErrorNumRefModel', $max); $this->error = $langs->trans('ErrorNumRefModel', $max);
return false; return false;
@ -133,11 +133,13 @@ class mod_recruitmentcandidature_standard extends ModeleNumRefRecruitmentCandida
} }
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if ($obj) $max = intval($obj->max); if ($obj) {
else $max = 0; $max = intval($obj->max);
} else {
$max = 0;
}
} else { } else {
dol_syslog("mod_recruitmentcandidature_standard::getNextValue", LOG_DEBUG); dol_syslog("mod_recruitmentcandidature_standard::getNextValue", LOG_DEBUG);
return -1; return -1;
@ -147,8 +149,11 @@ class mod_recruitmentcandidature_standard extends ModeleNumRefRecruitmentCandida
$date = $object->date_creation; $date = $object->date_creation;
$yymm = strftime("%y%m", $date); $yymm = strftime("%y%m", $date);
if ($max >= (pow(10, 4) - 1)) $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is if ($max >= (pow(10, 4) - 1)) {
else $num = sprintf("%04s", $max + 1); $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is
} else {
$num = sprintf("%04s", $max + 1);
}
dol_syslog("mod_recruitmentcandidature_standard::getNextValue return ".$this->prefix.$yymm."-".$num); dol_syslog("mod_recruitmentcandidature_standard::getNextValue return ".$this->prefix.$yymm."-".$num);
return $this->prefix.$yymm."-".$num; return $this->prefix.$yymm."-".$num;

Some files were not shown because too many files have changed in this diff Show More