';
@@ -372,7 +371,7 @@ if ($action == 'create') // Create. Seems to no be used
print '
';
print '
';
- print '
';
+ print '';
print '';
- if ($action == 'editdate_livraison')
+ if ($action == 'editdate_delivery')
{
- print '';
} else {
@@ -455,21 +454,21 @@ if ($action == 'create') // Create. Seems to no be used
if (!empty($conf->incoterm->enabled))
{
print ' ';
- print '';
- print $langs->trans('IncotermLabel');
- print ' ';
- if ($user->rights->expedition->delivery->creer) print ''.img_edit().' ';
- else print ' ';
- print '
';
- print ' ';
- print '';
+ print '';
+ print $langs->trans('IncotermLabel');
+ print ' ';
+ if ($user->rights->expedition->delivery->creer) print ''.img_edit().' ';
+ else print ' ';
+ print '
';
+ print ' ';
+ print '';
if ($action != 'editincoterm')
{
print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
} else {
print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
}
- print ' ';
+ print '';
}
/* A delivery note should be just more properties of a shipment, so notes are on shipment
@@ -629,7 +628,7 @@ if ($action == 'create') // Create. Seems to no be used
print "
\n";
- dol_fiche_end();
+ print dol_get_fiche_end();
//if ($object->statut == 0) // only if draft
// print '
';
@@ -691,9 +690,9 @@ if ($action == 'create') // Create. Seems to no be used
$shipment = new Expedition($db);
$shipment->fetch($object->origin_id);
- // Show links to link elements
- //$linktoelem = $form->showLinkToObjectBlock($object, null, array('order'));
- $somethingshown = $form->showLinkedObjectBlock($object, '');
+ // Show links to link elements
+ //$linktoelem = $form->showLinkToObjectBlock($object, null, array('order'));
+ $somethingshown = $form->showLinkedObjectBlock($object, '');
}
diff --git a/htdocs/delivery/class/delivery.class.php b/htdocs/delivery/class/delivery.class.php
index c8f044c9294..3c4d53f53e7 100644
--- a/htdocs/delivery/class/delivery.class.php
+++ b/htdocs/delivery/class/delivery.class.php
@@ -67,19 +67,19 @@ class Delivery extends CommonObject
*/
public $picto = 'sending';
- /**
- * @var int draft status
- */
- public $draft;
+ /**
+ * @var int draft status
+ */
+ public $draft;
- /**
- * @var int thirdparty id
- */
- public $socid;
+ /**
+ * @var int thirdparty id
+ */
+ public $socid;
- /**
- * @var string ref custome
- */
+ /**
+ * @var string ref custome
+ */
public $ref_customer;
/**
@@ -88,8 +88,8 @@ class Delivery extends CommonObject
public $date_delivery;
/**
- * @var integer|string date_creation
- */
+ * @var integer|string date_creation
+ */
public $date_creation;
/**
@@ -97,9 +97,9 @@ class Delivery extends CommonObject
*/
public $date_valid;
- /**
- * @var string model pdf
- */
+ /**
+ * @var string model pdf
+ */
public $model_pdf;
@@ -108,7 +108,7 @@ class Delivery extends CommonObject
*
* @param DoliDB $db Database handler
*/
- public function __construct($db)
+ public function __construct($db)
{
$this->db = $db;
$this->lines = array();
@@ -126,7 +126,7 @@ class Delivery extends CommonObject
* @param User $user Objet du user qui cree
* @return int <0 si erreur, id delivery cree si ok
*/
- public function create($user)
+ public function create($user)
{
global $conf;
@@ -136,7 +136,7 @@ class Delivery extends CommonObject
$error = 0;
- $now = dol_now();
+ $now = dol_now();
/* Delivery note as draft On positionne en mode draft le bon de livraison */
$this->draft = 1;
@@ -170,8 +170,8 @@ class Delivery extends CommonObject
$sql .= ", ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
$sql .= ", ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
$sql .= ", ".(!empty($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
- $sql .= ", ".(int) $this->fk_incoterms;
- $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
+ $sql .= ", ".(int) $this->fk_incoterms;
+ $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
$sql .= ")";
dol_syslog("Delivery::create", LOG_DEBUG);
@@ -256,7 +256,7 @@ class Delivery extends CommonObject
}
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Create a line
*
@@ -266,9 +266,9 @@ class Delivery extends CommonObject
* @param string $description Description
* @return int <0 if KO, >0 if OK
*/
- public function create_line($origin_id, $qty, $fk_product, $description)
- {
- // phpcs:enable
+ public function create_line($origin_id, $qty, $fk_product, $description)
+ {
+ // phpcs:enable
$error = 0;
$idprod = $fk_product;
$j = 0;
@@ -298,7 +298,7 @@ class Delivery extends CommonObject
* @param int $id Id of object to load
* @return integer
*/
- public function fetch($id)
+ public function fetch($id)
{
global $conf;
@@ -306,8 +306,8 @@ class Delivery extends CommonObject
$sql .= " l.total_ht, l.fk_statut, l.fk_user_valid, l.note_private, l.note_public";
$sql .= ", l.date_delivery, l.fk_address, l.model_pdf";
$sql .= ", el.fk_source as origin_id, el.sourcetype as origin";
- $sql .= ', l.fk_incoterms, l.location_incoterms';
- $sql .= ", i.libelle as label_incoterms";
+ $sql .= ', l.fk_incoterms, l.location_incoterms';
+ $sql .= ", i.libelle as label_incoterms";
$sql .= " FROM ".MAIN_DB_PREFIX."delivery as l";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = l.rowid AND el.targettype = '".$this->db->escape($this->element)."'";
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON l.fk_incoterms = i.rowid';
@@ -336,7 +336,7 @@ class Delivery extends CommonObject
$this->note_private = $obj->note_private;
$this->note_public = $obj->note_public;
$this->model_pdf = $obj->model_pdf;
- $this->modelpdf = $obj->model_pdf; // deprecated
+ $this->modelpdf = $obj->model_pdf; // deprecated
$this->origin = $obj->origin; // May be 'shipping'
$this->origin_id = $obj->origin_id; // May be id of shipping
@@ -374,14 +374,14 @@ class Delivery extends CommonObject
/**
* Validate object and update stock if option enabled
*
- * @param User $user Object user that validate
- * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
- * @return int
+ * @param User $user Object user that validate
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int
*/
- public function valid($user, $notrigger = 0)
+ public function valid($user, $notrigger = 0)
{
global $conf, $langs;
- require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
dol_syslog(get_class($this)."::valid begin");
@@ -389,8 +389,8 @@ class Delivery extends CommonObject
$error = 0;
- if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery->creer))
- || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery_advance->validate)))
+ if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery->creer))
+ || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery_advance->validate)))
{
if (!empty($conf->global->DELIVERY_ADDON_NUMBER))
{
@@ -409,12 +409,12 @@ class Delivery extends CommonObject
$soc->fetch($this->socid);
if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
- {
- $numref = $objMod->delivery_get_num($soc, $this);
- } else {
- $numref = $this->ref;
- }
- $this->newref = dol_sanitizeFileName($numref);
+ {
+ $numref = $objMod->delivery_get_num($soc, $this);
+ } else {
+ $numref = $this->ref;
+ }
+ $this->newref = dol_sanitizeFileName($numref);
// Test if is not already in valid status. If so, we stop to avoid decrementing the stock twice.
$sql = "SELECT ref";
@@ -442,24 +442,24 @@ class Delivery extends CommonObject
$sql .= " AND fk_statut = 0";
$resql = $this->db->query($sql);
- if (!$resql)
- {
- dol_print_error($this->db);
- $this->error = $this->db->lasterror();
- $error++;
- }
+ if (!$resql)
+ {
+ dol_print_error($this->db);
+ $this->error = $this->db->lasterror();
+ $error++;
+ }
- if (!$error && !$notrigger)
- {
- // Call trigger
- $result = $this->call_trigger('DELIVERY_VALIDATE', $user);
- if ($result < 0) $error++;
- // End call triggers
- }
+ if (!$error && !$notrigger)
+ {
+ // Call trigger
+ $result = $this->call_trigger('DELIVERY_VALIDATE', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ }
if (!$error)
{
- $this->oldref = $this->ref;
+ $this->oldref = $this->ref;
// Rename directory if dir was a temporary ref
if (preg_match('/^[\(]?PROV/i', $this->ref))
@@ -481,17 +481,17 @@ class Delivery extends CommonObject
if (@rename($dirsource, $dirdest))
{
- dol_syslog("Rename ok");
- // Rename docs starting with $oldref with $newref
- $listoffiles = dol_dir_list($conf->expedition->dir_output.'/receipt/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
- foreach ($listoffiles as $fileentry)
- {
- $dirsource = $fileentry['name'];
- $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
- $dirsource = $fileentry['path'].'/'.$dirsource;
- $dirdest = $fileentry['path'].'/'.$dirdest;
- @rename($dirsource, $dirdest);
- }
+ dol_syslog("Rename ok");
+ // Rename docs starting with $oldref with $newref
+ $listoffiles = dol_dir_list($conf->expedition->dir_output.'/receipt/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
+ foreach ($listoffiles as $fileentry)
+ {
+ $dirsource = $fileentry['name'];
+ $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
+ $dirsource = $fileentry['path'].'/'.$dirsource;
+ $dirdest = $fileentry['path'].'/'.$dirdest;
+ @rename($dirsource, $dirdest);
+ }
}
}
}
@@ -506,14 +506,14 @@ class Delivery extends CommonObject
dol_syslog(get_class($this)."::valid ok");
}
- if (!$error)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
+ if (!$error)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
}
}
} else {
@@ -523,7 +523,7 @@ class Delivery extends CommonObject
}
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Creating the delivery slip from an existing shipment
*
@@ -531,9 +531,9 @@ class Delivery extends CommonObject
* @param int $sending_id Id of the expedition that serves as a model
* @return integer
*/
- public function create_from_sending($user, $sending_id)
+ public function create_from_sending($user, $sending_id)
{
- // phpcs:enable
+ // phpcs:enable
$expedition = new Expedition($this->db);
$result = $expedition->fetch($sending_id);
@@ -542,13 +542,12 @@ class Delivery extends CommonObject
$num = count($expedition->lines);
for ($i = 0; $i < $num; $i++)
{
- $line = new DeliveryLigne($this->db);
+ $line = new DeliveryLine($this->db);
$line->origin_line_id = $expedition->lines[$i]->origin_line_id;
- $line->libelle = $expedition->lines[$i]->libelle;
+ $line->label = $expedition->lines[$i]->label;
$line->description = $expedition->lines[$i]->description;
$line->qty = $expedition->lines[$i]->qty_shipped;
$line->fk_product = $expedition->lines[$i]->fk_product;
- $line->ref = $expedition->lines[$i]->ref;
$this->lines[$i] = $line;
}
@@ -561,7 +560,7 @@ class Delivery extends CommonObject
$this->date_delivery = $expedition->date_delivery;
$this->fk_delivery_address = $expedition->fk_delivery_address;
$this->socid = $expedition->socid;
- $this->ref_customer = $expedition->ref_customer;
+ $this->ref_customer = $expedition->ref_customer;
//Incoterms
$this->fk_incoterms = $expedition->fk_incoterms;
@@ -570,7 +569,7 @@ class Delivery extends CommonObject
return $this->create($user);
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Update a livraison line (only extrafields)
*
@@ -578,15 +577,15 @@ class Delivery extends CommonObject
* @param array $array_options extrafields array
* @return int <0 if KO, >0 if OK
*/
- public function update_line($id, $array_options = 0)
+ public function update_line($id, $array_options = 0)
{
- // phpcs:enable
+ // phpcs:enable
global $conf;
$error = 0;
if ($id > 0 && !$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) // For avoid conflicts if trigger used
{
- $line = new DeliveryLigne($this->db);
+ $line = new DeliveryLine($this->db);
$line->array_options = $array_options;
$line->id = $id;
$result = $line->insertExtraFields();
@@ -610,10 +609,10 @@ class Delivery extends CommonObject
* @param int $qty Qty
* @return void
*/
- public function addline($origin_id, $qty)
+ public function addline($origin_id, $qty)
{
$num = count($this->lines);
- $line = new DeliveryLigne($this->db);
+ $line = new DeliveryLine($this->db);
$line->origin_id = $origin_id;
$line->qty = $qty;
@@ -627,7 +626,7 @@ class Delivery extends CommonObject
* @param int $lineid Line id
* @return integer|null
*/
- public function deleteline($lineid)
+ public function deleteline($lineid)
{
if ($this->statut == 0)
{
@@ -650,11 +649,11 @@ class Delivery extends CommonObject
*
* @return integer
*/
- public function delete()
+ public function delete()
{
global $conf, $langs, $user;
- require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$this->db->begin();
$error = 0;
@@ -698,14 +697,14 @@ class Delivery extends CommonObject
}
}
- // Call trigger
- $result = $this->call_trigger('DELIVERY_DELETE', $user);
- if ($result < 0)
- {
- $this->db->rollback();
- return -4;
- }
- // End call triggers
+ // Call trigger
+ $result = $this->call_trigger('DELIVERY_DELETE', $user);
+ if ($result < 0)
+ {
+ $this->db->rollback();
+ return -4;
+ }
+ // End call triggers
return 1;
} else {
@@ -729,10 +728,10 @@ class Delivery extends CommonObject
* Return clicable name (with picto eventually)
*
* @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
- * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
* @return string Chaine avec URL
*/
- public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1)
+ public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1)
{
global $langs;
@@ -743,16 +742,16 @@ class Delivery extends CommonObject
$url = DOL_URL_ROOT.'/delivery/card.php?id='.$this->id;
- //if ($option !== 'nolink')
- //{
- // Add param to save lastsearch_values or not
- $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 ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
- //}
+ //if ($option !== 'nolink')
+ //{
+ // Add param to save lastsearch_values or not
+ $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 ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
+ //}
- $linkstart = '
';
+ $linkstart = ' ';
$linkend = ' ';
if ($withpicto) $result .= ($linkstart.img_object($label, $this->picto, 'class="classfortooltip"').$linkend);
@@ -761,15 +760,15 @@ class Delivery extends CommonObject
return $result;
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Load lines
*
* @return void
*/
- public function fetch_lines()
+ public function fetch_lines()
{
- // phpcs:enable
+ // phpcs:enable
$this->lines = array();
$sql = "SELECT ld.rowid, ld.fk_product, ld.description, ld.subprice, ld.total_ht, ld.qty as qty_shipped, ld.fk_origin_line, ";
@@ -789,7 +788,7 @@ class Delivery extends CommonObject
$i = 0;
while ($i < $num)
{
- $line = new DeliveryLigne($this->db);
+ $line = new DeliveryLine($this->db);
$obj = $this->db->fetch_object($resql);
@@ -826,6 +825,7 @@ class Delivery extends CommonObject
$line->volume_units = $obj->volume_units;
$line->fk_unit = $obj->fk_unit;
+ $line->fetch_optionals();
$this->lines[$i] = $line;
@@ -844,12 +844,12 @@ class Delivery extends CommonObject
* @param int $mode Mode
* @return string Label
*/
- public function getLibStatut($mode = 0)
+ public function getLibStatut($mode = 0)
{
return $this->LibStatut($this->statut, $mode);
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Renvoi le libelle d'un statut donne
*
@@ -857,9 +857,9 @@ class Delivery extends CommonObject
* @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
* @return string Label
*/
- public function LibStatut($status, $mode)
+ public function LibStatut($status, $mode)
{
- // phpcs:enable
+ // phpcs:enable
global $langs;
if (empty($this->labelStatus) || empty($this->labelStatusShort))
@@ -883,19 +883,19 @@ class Delivery extends CommonObject
/**
- * Initialise an instance with random values.
- * Used to build previews or test instances.
- * id must be 0 if object instance is a specimen.
- *
- * @return void
+ * Initialise an instance with random values.
+ * Used to build previews or test instances.
+ * id must be 0 if object instance is a specimen.
+ *
+ * @return void
*/
- public function initAsSpecimen()
+ public function initAsSpecimen()
{
global $user, $langs, $conf;
$now = dol_now();
- // Load array of products prodids
+ // Load array of products prodids
$num_prods = 0;
$prodids = array();
$sql = "SELECT rowid";
@@ -927,7 +927,7 @@ class Delivery extends CommonObject
$this->note_private = 'Private note';
$i = 0;
- $line = new DeliveryLigne($this->db);
+ $line = new DeliveryLine($this->db);
$line->fk_product = $prodids[0];
$line->qty_asked = 10;
$line->qty_shipped = 9;
@@ -946,17 +946,17 @@ class Delivery extends CommonObject
* @return array Product remaining to be delivered
* TODO use new function
*/
- public function getRemainingDelivered()
+ public function getRemainingDelivered()
{
global $langs;
// Get the linked object
$this->fetchObjectLinked('', '', $this->id, $this->element);
- //var_dump($this->linkedObjectIds);
+ //var_dump($this->linkedObjectsIds);
// Get the product ref and qty in source
$sqlSourceLine = "SELECT st.rowid, st.description, st.qty";
$sqlSourceLine .= ", p.ref, p.label";
- $sqlSourceLine .= " FROM ".MAIN_DB_PREFIX.$this->linkedObjectIds[0]['type']."det as st";
+ $sqlSourceLine .= " FROM ".MAIN_DB_PREFIX.$this->linkedObjectsIds[0]['type']."det as st";
$sqlSourceLine .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON st.fk_product = p.rowid";
$sqlSourceLine .= " WHERE fk_".$this->linked_object[0]['type']." = ".$this->linked_object[0]['linkid'];
@@ -1012,14 +1012,14 @@ class Delivery extends CommonObject
}
}
- /**
+ /**
* Set the planned delivery date
*
* @param User $user Objet utilisateur qui modifie
* @param integer $delivery_date Delivery date
* @return int <0 if KO, >0 if OK
*/
- public function setDeliveryDate($user, $delivery_date)
+ public function setDeliveryDate($user, $delivery_date)
{
if ($user->rights->expedition->creer)
{
@@ -1097,25 +1097,35 @@ class Delivery extends CommonObject
/**
* Management class of delivery note lines
*/
-class DeliveryLigne extends CommonObjectLine
+class DeliveryLine extends CommonObjectLine
{
- /**
- * @var DoliDB Database handler.
- */
- public $db;
+ /**
+ * @var DoliDB Database handler.
+ */
+ public $db;
- // From llx_expeditiondet
- public $qty;
- public $qty_asked;
- public $qty_shipped;
- public $price;
- public $fk_product;
- public $origin_id;
+ /**
+ * @var string ID to identify managed object
+ */
+ public $element = 'deliverydet';
- /**
- * @var string delivery note lines label
- */
- public $label;
+ /**
+ * @var string Name of table without prefix where object is stored
+ */
+ public $table_element = 'deliverydet';
+
+ // From llx_expeditiondet
+ public $qty;
+ public $qty_asked;
+ public $qty_shipped;
+ public $price;
+ public $fk_product;
+ public $origin_id;
+
+ /**
+ * @var string delivery note lines label
+ */
+ public $label;
/**
* @var string product description
@@ -1133,26 +1143,18 @@ class DeliveryLigne extends CommonObjectLine
*/
public $libelle;
+ public $origin_line_id;
+
public $product_ref;
public $product_label;
/**
- * @var string ID to identify managed object
+ * Constructor
+ *
+ * @param DoliDB $db Database handler
*/
- public $element = 'deliverydet';
-
- /**
- * @var string Name of table without prefix where object is stored
- */
- public $table_element = 'deliverydet';
-
- /**
- * Constructor
- *
- * @param DoliDB $db Database handler
- */
- public function __construct($db)
- {
- $this->db = $db;
- }
+ public function __construct($db)
+ {
+ $this->db = $db;
+ }
}
diff --git a/htdocs/document.php b/htdocs/document.php
index a608dfe820e..c48a0363f78 100644
--- a/htdocs/document.php
+++ b/htdocs/document.php
@@ -153,7 +153,7 @@ if (isset($_GET["attachment"])) $attachment = GETPOST("attachment", 'alpha') ?tr
if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS)) $attachment = false;
// Define mime type
-$type = 'application/octet-stream'; // By default
+$type = 'application/octet-stream'; // By default
if (GETPOST('type', 'alpha')) $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
@@ -243,6 +243,23 @@ if (!file_exists($fullpath_original_file_osencoded))
exit;
}
+// Hooks
+if (!is_object($hookmanager)) {
+ include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
+ $hookmanager = new HookManager($this->db);
+}
+$hookmanager->initHooks(array('document'));
+$parameters = array('ecmfile' => $ecmfile, 'modulepart' => $modulepart, 'original_file' => $original_file,
+ 'entity' => $entity, 'refname' => $refname, 'fullpath_original_file' => $fullpath_original_file,
+ 'filename' => $filename, 'fullpath_original_file_osencoded' => $fullpath_original_file_osencoded);
+$reshook = $hookmanager->executeHooks('downloadDocument', $parameters); // Note that $action and $object may have been
+if ($reshook < 0) {
+ $errors = $hookmanager->error . (is_array($hookmanager->errors) ? (!empty($hookmanager->error) ? ', ' : '') . join($separator, $hookmanager->errors) : '');
+ dol_syslog("document.php - Errors when executing the hook 'downloadDocument' : " . $errors);
+ print "ErrorDownloadDocumentHooks: " . $errors;
+ exit;
+}
+
// Permissions are ok and file found, so we return it
top_httphead($type);
header('Content-Description: File Transfer');
diff --git a/htdocs/don/admin/donation.php b/htdocs/don/admin/donation.php
index c9a08d093ab..78a3d50dfcc 100644
--- a/htdocs/don/admin/donation.php
+++ b/htdocs/don/admin/donation.php
@@ -51,33 +51,33 @@ $type = 'donation';
if ($action == 'specimen')
{
- $modele = GETPOST('module', 'alpha');
+ $modele = GETPOST('module', 'alpha');
- $don = new Don($db);
- $don->initAsSpecimen();
+ $don = new Don($db);
+ $don->initAsSpecimen();
- // Search template files
- $dir = DOL_DOCUMENT_ROOT."/core/modules/dons/";
- $file = $modele.".modules.php";
- if (file_exists($dir.$file))
- {
- $classname = $modele;
- require_once $dir.$file;
+ // Search template files
+ $dir = DOL_DOCUMENT_ROOT."/core/modules/dons/";
+ $file = $modele.".modules.php";
+ if (file_exists($dir.$file))
+ {
+ $classname = $modele;
+ require_once $dir.$file;
- $obj = new $classname($db);
+ $obj = new $classname($db);
- if ($obj->write_file($don, $langs) > 0)
- {
- header("Location: ".DOL_URL_ROOT."/document.php?modulepart=donation&file=SPECIMEN.html");
- return;
- } else {
- setEventMessages($obj->error, $obj->errors, 'errors');
- dol_syslog($obj->error, LOG_ERR);
- }
- } else {
- setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors');
- dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR);
- }
+ if ($obj->write_file($don, $langs) > 0)
+ {
+ header("Location: ".DOL_URL_ROOT."/document.php?modulepart=donation&file=SPECIMEN.html");
+ return;
+ } else {
+ setEventMessages($obj->error, $obj->errors, 'errors');
+ dol_syslog($obj->error, LOG_ERR);
+ }
+ } else {
+ setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors');
+ dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR);
+ }
}
// Set default model
@@ -107,7 +107,7 @@ elseif ($action == 'set')
$ret = delDocumentModel($value, $type);
if ($ret > 0)
{
- if ($conf->global->DON_ADDON_MODEL == "$value") dolibarr_del_const($db, 'DON_ADDON_MODEL', $conf->entity);
+ if ($conf->global->DON_ADDON_MODEL == "$value") dolibarr_del_const($db, 'DON_ADDON_MODEL', $conf->entity);
}
}
@@ -116,32 +116,32 @@ if ($action == 'set_DONATION_ACCOUNTINGACCOUNT')
{
$account = GETPOST('DONATION_ACCOUNTINGACCOUNT', 'alpha');
- $res = dolibarr_set_const($db, "DONATION_ACCOUNTINGACCOUNT", $account, 'chaine', 0, '', $conf->entity);
+ $res = dolibarr_set_const($db, "DONATION_ACCOUNTINGACCOUNT", $account, 'chaine', 0, '', $conf->entity);
if (!$res > 0) $error++;
if (!$error)
- {
- setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
- } else {
- setEventMessages($langs->trans("Error"), null, 'errors');
- }
+ {
+ setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
+ } else {
+ setEventMessages($langs->trans("Error"), null, 'errors');
+ }
}
if ($action == 'set_DONATION_MESSAGE')
{
$freemessage = GETPOST('DONATION_MESSAGE', 'restricthtml'); // No alpha here, we want exact string
- $res = dolibarr_set_const($db, "DONATION_MESSAGE", $freemessage, 'chaine', 0, '', $conf->entity);
+ $res = dolibarr_set_const($db, "DONATION_MESSAGE", $freemessage, 'chaine', 0, '', $conf->entity);
if (!$res > 0) $error++;
if (!$error)
- {
- setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
- } else {
- setEventMessages($langs->trans("Error"), null, 'errors');
- }
+ {
+ setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
+ } else {
+ setEventMessages($langs->trans("Error"), null, 'errors');
+ }
}
/*
@@ -149,26 +149,26 @@ if ($action == 'set_DONATION_MESSAGE')
*/
if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg))
{
- $code = $reg[1];
- if (dolibarr_set_const($db, $code, 1, 'chaine', 0, '', $conf->entity) > 0)
- {
- header("Location: ".$_SERVER["PHP_SELF"]);
- exit;
- } else {
- dol_print_error($db);
- }
+ $code = $reg[1];
+ if (dolibarr_set_const($db, $code, 1, 'chaine', 0, '', $conf->entity) > 0)
+ {
+ header("Location: ".$_SERVER["PHP_SELF"]);
+ exit;
+ } else {
+ dol_print_error($db);
+ }
}
if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg))
{
- $code = $reg[1];
- if (dolibarr_del_const($db, $code, $conf->entity) > 0)
- {
- header("Location: ".$_SERVER["PHP_SELF"]);
- exit;
- } else {
- dol_print_error($db);
- }
+ $code = $reg[1];
+ if (dolibarr_del_const($db, $code, $conf->entity) > 0)
+ {
+ header("Location: ".$_SERVER["PHP_SELF"]);
+ exit;
+ } else {
+ dol_print_error($db);
+ }
}
/*
@@ -332,10 +332,10 @@ print $form->textwithpicto($langs->trans("DonationUserThirdparties"), $langs->tr
print '';
print '
';
if ($conf->use_javascript_ajax) {
- print ajax_constantonoff('DONATION_USE_THIRDPARTIES');
+ print ajax_constantonoff('DONATION_USE_THIRDPARTIES');
} else {
- $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
- print $form->selectarray("DONATION_USE_THIRDPARTIES", $arrval, $conf->global->DONATION_USE_THIRDPARTIES);
+ $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
+ print $form->selectarray("DONATION_USE_THIRDPARTIES", $arrval, $conf->global->DONATION_USE_THIRDPARTIES);
}
print " \n";
print "\n";
@@ -387,34 +387,34 @@ if (preg_match('/fr/i', $conf->global->MAIN_INFO_SOCIETE_COUNTRY))
print '
';
print ''.$langs->trans("DONATION_ART200").' ';
print '';
- if ($conf->use_javascript_ajax) {
- print ajax_constantonoff('DONATION_ART200');
- } else {
- $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
- print $form->selectarray("DONATION_ART200", $arrval, $conf->global->DONATION_ART200);
- }
+ if ($conf->use_javascript_ajax) {
+ print ajax_constantonoff('DONATION_ART200');
+ } else {
+ $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
+ print $form->selectarray("DONATION_ART200", $arrval, $conf->global->DONATION_ART200);
+ }
print ' ';
print '
';
print ''.$langs->trans("DONATION_ART238").' ';
print '';
- if ($conf->use_javascript_ajax) {
- print ajax_constantonoff('DONATION_ART238');
- } else {
- $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
- print $form->selectarray("DONATION_ART238", $arrval, $conf->global->DONATION_ART238);
- }
+ if ($conf->use_javascript_ajax) {
+ print ajax_constantonoff('DONATION_ART238');
+ } else {
+ $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
+ print $form->selectarray("DONATION_ART238", $arrval, $conf->global->DONATION_ART238);
+ }
print ' ';
print '
';
print ''.$langs->trans("DONATION_ART978").' ';
print '';
- if ($conf->use_javascript_ajax) {
- print ajax_constantonoff('DONATION_ART978');
- } else {
- $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
- print $form->selectarray("DONATION_ART978", $arrval, $conf->global->DONATION_ART978);
- }
+ if ($conf->use_javascript_ajax) {
+ print ajax_constantonoff('DONATION_ART978');
+ } else {
+ $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
+ print $form->selectarray("DONATION_ART978", $arrval, $conf->global->DONATION_ART978);
+ }
print ' ';
print "\n";
}
diff --git a/htdocs/don/admin/donation_extrafields.php b/htdocs/don/admin/donation_extrafields.php
index d210f4399bc..6062d4fca26 100644
--- a/htdocs/don/admin/donation_extrafields.php
+++ b/htdocs/don/admin/donation_extrafields.php
@@ -70,7 +70,7 @@ print dol_get_fiche_head($head, 'attributes', $langs->trans("Donations"), -1, 'p
require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
-dol_fiche_end();
+print dol_get_fiche_end();
// Buttons
diff --git a/htdocs/don/card.php b/htdocs/don/card.php
index 48af083a5fb..cec185e757e 100644
--- a/htdocs/don/card.php
+++ b/htdocs/don/card.php
@@ -39,8 +39,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
if (!empty($conf->projet->enabled)) {
- require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
- require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
+ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
+ require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
}
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
@@ -49,7 +49,9 @@ $langs->loadLangs(array("bills", "companies", "donations"));
$id = GETPOST('rowid') ?GETPOST('rowid', 'int') : GETPOST('id', 'int');
$action = GETPOST('action', 'aZ09');
$cancel = GETPOST('cancel', 'alpha');
-$amount = GETPOST('amount');
+$confirm = GETPOST('confirm', 'alpha');
+
+$amount = price2num(GETPOST('amount', 'alphanohtml'), 'MT');
$donation_date = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
$projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0);
@@ -65,14 +67,52 @@ $extrafields->fetch_name_optionals_label($object->table_element);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$hookmanager->initHooks(array('doncard', 'globalcard'));
+$upload_dir = $conf->don->dir_output;
+$permissiontoadd = $user->rights->don->creer;
+
/*
* Actions
*/
+$parameters = array();
+
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+// Action reopen object
+if ($action == 'confirm_reopen' && $confirm == 'yes' && $permissiontoadd)
+{
+ $object->fetch($id);
+
+ $result = $object->reopen($user);
+ if ($result >= 0)
+ {
+ // Define output language
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
+ if (method_exists($object, 'generateDocument')) {
+ $outputlangs = $langs;
+ $newlang = '';
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
+ if (!empty($newlang)) {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ $model = $object->model_pdf;
+ $ret = $object->fetch($id); // Reload to get new records
+
+ $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+ }
+
+ header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id);
+ exit;
+ } else {
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
+}
+
if ($action == 'update')
{
if (!empty($cancel))
@@ -83,12 +123,12 @@ if ($action == 'update')
$error = 0;
- if (empty($donation_date))
- {
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
- $action = "create";
- $error++;
- }
+ if (empty($donation_date))
+ {
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
+ $action = "create";
+ $error++;
+ }
if (empty($amount))
{
@@ -139,12 +179,12 @@ if ($action == 'add')
$error = 0;
- if (empty($donation_date))
- {
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
- $action = "create";
- $error++;
- }
+ if (empty($donation_date))
+ {
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
+ $action = "create";
+ $error++;
+ }
if (empty($amount))
{
@@ -155,7 +195,7 @@ if ($action == 'add')
if (!$error)
{
- $object->socid = GETPOST("socid", 'int');
+ $object->socid = GETPOST("socid", 'int');
$object->firstname = GETPOST("firstname", 'alpha');
$object->lastname = GETPOST("lastname", 'alpha');
$object->societe = GETPOST("societe", 'alpha');
@@ -165,7 +205,7 @@ if ($action == 'add')
$object->town = GETPOST("town", 'alpha');
$object->country_id = GETPOST('country_id', 'int');
$object->email = GETPOST('email', 'alpha');
- $object->date = $donation_date;
+ $object->date = $donation_date;
$object->note_private = GETPOST("note_private", 'restricthtml');
$object->note_public = GETPOST("note_public", 'restricthtml');
$object->public = GETPOST("public", 'alpha');
@@ -173,7 +213,7 @@ if ($action == 'add')
$object->modepaymentid = GETPOST('modepayment', 'int');
// Fill array 'array_options' with data from add form
- $ret = $extrafields->setOptionalsFromPost(null, $object);
+ $ret = $extrafields->setOptionalsFromPost(null, $object);
if ($ret < 0) $error++;
$res = $object->create($user);
@@ -188,16 +228,16 @@ if ($action == 'add')
}
if ($action == 'confirm_delete' && GETPOST("confirm") == "yes" && $user->rights->don->supprimer)
{
- $object->fetch($id);
- $result = $object->delete($user);
- if ($result > 0)
- {
- header("Location: index.php");
- exit;
- } else {
- dol_syslog($object->error, LOG_DEBUG);
- setEventMessages($object->error, $object->errors, 'errors');
- }
+ $object->fetch($id);
+ $result = $object->delete($user);
+ if ($result > 0)
+ {
+ header("Location: index.php");
+ exit;
+ } else {
+ dol_syslog($object->error, LOG_DEBUG);
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
}
if ($action == 'valid_promesse')
{
@@ -209,19 +249,19 @@ if ($action == 'valid_promesse')
header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
exit;
} else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
}
if ($action == 'set_cancel')
{
$object->fetch($id);
if ($object->set_cancel($id) >= 0)
- {
- header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
- exit;
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
+ {
+ header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
+ exit;
+ } else {
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
}
if ($action == 'set_paid')
{
@@ -231,8 +271,8 @@ if ($action == 'set_paid')
header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
exit;
} else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
} elseif ($action == 'classin' && $user->rights->don->creer)
{
$object->fetch($id);
@@ -240,8 +280,6 @@ if ($action == 'set_paid')
}
// Actions to build doc
-$upload_dir = $conf->don->dir_output;
-$permissiontoadd = $user->rights->don->creer;
include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
@@ -351,11 +389,12 @@ if ($action == 'create')
print '
';
print $form->select_company($soc->id, 'socid', '(s.client = 1 OR s.client = 3) AND status=1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300');
// Option to reload page to retrieve customer informations. Note, this clear other input
- if (!empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE))
+ if (!empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED))
{
print '\n";
- }
+ print "\t});\n";
+ print "\n";
+ }
print load_fiche_titre($langs->trans("DoPayment"));
@@ -206,17 +206,17 @@ if ($action == 'create' || empty($action))
print ' ';
print ' ';
- print dol_get_fiche_head(null, '0', '', -1);
+ print dol_get_fiche_head(null, '0', '', -1);
- $linkback = '';
- // $linkback = '' . $langs->trans("BackToList") . ' ';
+ $linkback = '';
+ // $linkback = '' . $langs->trans("BackToList") . ' ';
- dol_banner_tab($expensereport, 'ref', $linkback, 1, 'ref', 'ref', '');
+ dol_banner_tab($expensereport, 'ref', $linkback, 1, 'ref', 'ref', '');
- print '';
- print '
';
+ print '
';
+ print '
';
- print '
'."\n";
+ print ''."\n";
print ''.$langs->trans("Period").' '.get_date_range($expensereport->date_debut, $expensereport->date_fin, "", $langs, 0).' ';
print ''.$langs->trans("Amount").' '.price($expensereport->total_ttc, 0, $outputlangs, 1, -1, -1, $conf->currency).' ';
@@ -224,7 +224,7 @@ if ($action == 'create' || empty($action))
$sql = "SELECT sum(p.amount) as total";
$sql .= " FROM ".MAIN_DB_PREFIX."payment_expensereport as p, ".MAIN_DB_PREFIX."expensereport as e";
$sql .= " WHERE p.fk_expensereport = e.rowid AND p.fk_expensereport = ".$id;
- $sql .= ' AND e.entity IN ('.getEntity('expensereport').')';
+ $sql .= ' AND e.entity IN ('.getEntity('expensereport').')';
$resql = $db->query($sql);
if ($resql)
{
@@ -235,17 +235,17 @@ if ($action == 'create' || empty($action))
print ''.$langs->trans("AlreadyPaid").' '.price($sumpaid, 0, $outputlangs, 1, -1, -1, $conf->currency).' ';
print ''.$langs->trans("RemainderToPay").' '.price($total - $sumpaid, 0, $outputlangs, 1, -1, -1, $conf->currency).' ';
- print '
';
+ print '
';
- print '
';
+ print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
- print dol_get_fiche_head();
+ print dol_get_fiche_head();
- print ''."\n";
+ print ''."\n";
- print ''.$langs->trans("Date").' ';
+ print ' '.$langs->trans("Date").' ';
$datepaid = dol_mktime(12, 0, 0, GETPOST("remonth", 'int'), GETPOST("reday", 'int'), GETPOST("reyear", 'int'));
$datepayment = ($datepaid == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datepaid);
print $form->selectDate($datepayment, '', '', '', 0, "add_payment", 1, 1);
@@ -259,11 +259,11 @@ if ($action == 'create' || empty($action))
if (!empty($conf->banque->enabled))
{
- print ' ';
- print ''.$langs->trans('AccountToDebit').' ';
- print '';
- $form->select_comptes(GETPOSTISSET("accountid") ? GETPOST("accountid", "int") : $expensereport->accountid, "accountid", 0, '', 2); // Show open bank account list
- print ' ';
+ print '';
+ print ''.$langs->trans('AccountToDebit').' ';
+ print '';
+ $form->select_comptes(GETPOSTISSET("accountid") ? GETPOST("accountid", "int") : $expensereport->accountid, "accountid", 0, '', 2); // Show open bank account list
+ print ' ';
}
// Number
@@ -279,7 +279,7 @@ if ($action == 'create' || empty($action))
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
print ' ';
diff --git a/htdocs/expensereport/stats/index.php b/htdocs/expensereport/stats/index.php
index b789fc57345..b0e5c7aed95 100644
--- a/htdocs/expensereport/stats/index.php
+++ b/htdocs/expensereport/stats/index.php
@@ -148,38 +148,38 @@ $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear);
if (!$user->rights->societe->client->voir || $user->socid)
{
- $filename_avg = $dir.'/ordersaverage-'.$user->id.'-'.$year.'.png';
- if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png';
- if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png';
+ $filename_avg = $dir.'/ordersaverage-'.$user->id.'-'.$year.'.png';
+ if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png';
+ if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png';
} else {
- $filename_avg = $dir.'/ordersaverage-'.$year.'.png';
- if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png';
- if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png';
+ $filename_avg = $dir.'/ordersaverage-'.$year.'.png';
+ if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png';
+ if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png';
}
$px3 = new DolGraph();
$mesg = $px3->isGraphKo();
if (!$mesg)
{
- $px3->SetData($data);
- $i = $startyear; $legend = array();
- while ($i <= $endyear)
- {
- $legend[] = $i;
- $i++;
- }
- $px3->SetLegend($legend);
- $px3->SetYLabel($langs->trans("AmountAverage"));
- $px3->SetMaxValue($px3->GetCeilMaxValue());
- $px3->SetMinValue($px3->GetFloorMinValue());
- $px3->SetWidth($WIDTH);
- $px3->SetHeight($HEIGHT);
- $px3->SetShading(3);
- $px3->SetHorizTickIncrement(1);
- $px3->mode = 'depth';
- $px3->SetTitle($langs->trans("AmountAverage"));
+ $px3->SetData($data);
+ $i = $startyear; $legend = array();
+ while ($i <= $endyear)
+ {
+ $legend[] = $i;
+ $i++;
+ }
+ $px3->SetLegend($legend);
+ $px3->SetYLabel($langs->trans("AmountAverage"));
+ $px3->SetMaxValue($px3->GetCeilMaxValue());
+ $px3->SetMinValue($px3->GetFloorMinValue());
+ $px3->SetWidth($WIDTH);
+ $px3->SetHeight($HEIGHT);
+ $px3->SetShading(3);
+ $px3->SetHorizTickIncrement(1);
+ $px3->mode = 'depth';
+ $px3->SetTitle($langs->trans("AmountAverage"));
- $px3->draw($filename_avg, $fileurl_avg);
+ $px3->draw($filename_avg, $fileurl_avg);
}
@@ -187,7 +187,7 @@ if (!$mesg)
$data = $stats->getAllByYear();
$arrayyears = array();
foreach ($data as $val) {
- $arrayyears[$val['year']] = $val['year'];
+ $arrayyears[$val['year']] = $val['year'];
}
if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear;
@@ -288,11 +288,11 @@ print '';
// Show graphs
print '
';
if ($mesg) { print $mesg; } else {
- print $px1->show();
+ print $px1->show();
print " \n";
print $px2->show();
- print " \n";
- print $px3->show();
+ print " \n";
+ print $px3->show();
}
print '
';
@@ -301,7 +301,7 @@ print '
';
print '
';
-dol_fiche_end();
+print dol_get_fiche_end();
// End of page
llxFooter();
diff --git a/htdocs/expensereport/tpl/expensereport_addfile.tpl.php b/htdocs/expensereport/tpl/expensereport_addfile.tpl.php
index c1e9a4e0d90..9b2cd49faec 100644
--- a/htdocs/expensereport/tpl/expensereport_addfile.tpl.php
+++ b/htdocs/expensereport/tpl/expensereport_addfile.tpl.php
@@ -11,30 +11,30 @@ $permission = $user->rights->expensereport->creer;
$savingdocmask = '';
if (empty($conf->global->MAIN_DISABLE_SUGGEST_REF_AS_PREFIX))
{
- //var_dump($modulepart);
- if (in_array($modulepart, array('facture_fournisseur', 'commande_fournisseur', 'facture', 'commande', 'propal', 'supplier_proposal', 'ficheinter', 'contract', 'expedition', 'project', 'project_task', 'expensereport', 'tax', 'produit', 'product_batch')))
- {
- $savingdocmask = dol_sanitizeFileName($object->ref).'-__file__';
- }
+ //var_dump($modulepart);
+ if (in_array($modulepart, array('facture_fournisseur', 'commande_fournisseur', 'facture', 'commande', 'propal', 'supplier_proposal', 'ficheinter', 'contract', 'expedition', 'project', 'project_task', 'expensereport', 'tax', 'produit', 'product_batch')))
+ {
+ $savingdocmask = dol_sanitizeFileName($object->ref).'-__file__';
+ }
}
// Show upload form (document and links)
$formfile->form_attach_new_file(
- $_SERVER["PHP_SELF"].'?id='.$object->id,
- 'none',
- 0,
- 0,
- $permission,
- $conf->browser->layout == 'phone' ? 40 : 60,
- $object,
- '',
- 1,
- $savingdocmask,
- 0,
- 'formuserfile',
- 'accept',
- '',
- 1
- );
+ $_SERVER["PHP_SELF"].'?id='.$object->id,
+ 'none',
+ 0,
+ 0,
+ $permission,
+ $conf->browser->layout == 'phone' ? 40 : 60,
+ $object,
+ '',
+ 1,
+ $savingdocmask,
+ 0,
+ 'formuserfile',
+ 'accept',
+ '',
+ 1
+ );
print '';
diff --git a/htdocs/expensereport/tpl/expensereport_linktofile.tpl.php b/htdocs/expensereport/tpl/expensereport_linktofile.tpl.php
index f4f460719a0..04bb2a71990 100644
--- a/htdocs/expensereport/tpl/expensereport_linktofile.tpl.php
+++ b/htdocs/expensereport/tpl/expensereport_linktofile.tpl.php
@@ -2,137 +2,137 @@
// Add line to select existing file
if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES))
{
- print ''."\n";
+ print ''."\n";
- require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
- require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
- require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
- $upload_dir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref);
- $arrayoffiles = dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png|'.preg_quote(dol_sanitizeFileName($object->ref.'.pdf'), '/').')$');
- $nbFiles = count($arrayoffiles);
- $nbLinks = Link::count($db, $object->element, $object->id);
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
+ require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
+ $upload_dir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref);
+ $arrayoffiles = dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png|'.preg_quote(dol_sanitizeFileName($object->ref.'.pdf'), '/').')$');
+ $nbFiles = count($arrayoffiles);
+ $nbLinks = Link::count($db, $object->element, $object->id);
- if ($nbFiles > 0)
- {
- print 'global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ' style="display: none"' : '').'>';
- print '';
- //print ''.$langs->trans("AttachTheNewLineToTheDocument").' ';
- $modulepart = 'expensereport'; $maxheightmini = 48;
- $relativepath = (!empty($object->ref) ?dol_sanitizeFileName($object->ref) : '').'/';
- $filei = 0;
- foreach ($arrayoffiles as $file)
- {
- $urlforhref = array();
- $filei++;
+ if ($nbFiles > 0)
+ {
+ print ' global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ' style="display: none"' : '').'>';
+ print '';
+ //print ''.$langs->trans("AttachTheNewLineToTheDocument").' ';
+ $modulepart = 'expensereport'; $maxheightmini = 48;
+ $relativepath = (!empty($object->ref) ?dol_sanitizeFileName($object->ref) : '').'/';
+ $filei = 0;
+ foreach ($arrayoffiles as $file)
+ {
+ $urlforhref = array();
+ $filei++;
- print '';
- $fileinfo = pathinfo($file['fullname']);
- if (image_format_supported($file['name']) > 0)
- {
- $minifile = getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case however) than original
- //print $file['path'].'/'.$minifile.'
';
- $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity));
- if (empty($urlforhref)) {
- $urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($fileinfo['relativename'].'.'.strtolower($fileinfo['extension']));
- print '
';
- } else {
- print ' ';
- }
- print '';
- print '
';
- print '
';
- print ' ';
- } else {
- $error = 0;
- $thumbshown = '';
+ print '
';
+ $fileinfo = pathinfo($file['fullname']);
+ if (image_format_supported($file['name']) > 0)
+ {
+ $minifile = getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case however) than original
+ //print $file['path'].'/'.$minifile.'
';
+ $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity));
+ if (empty($urlforhref)) {
+ $urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($fileinfo['relativename'].'.'.strtolower($fileinfo['extension']));
+ print '
';
+ } else {
+ print ' ';
+ }
+ print '';
+ print '
';
+ print '
';
+ print ' ';
+ } else {
+ $error = 0;
+ $thumbshown = '';
- if (preg_match('/\.pdf$/i', $file['name']))
- {
- $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity));
+ if (preg_match('/\.pdf$/i', $file['name']))
+ {
+ $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity));
- $filepdf = $conf->expensereport->dir_output.'/'.$relativepath.$file['name'];
- $fileimage = $conf->expensereport->dir_output.'/'.$relativepath.$file['name'].'_preview.png';
- $relativepathimage = $relativepath.$file['name'].'_preview.png';
+ $filepdf = $conf->expensereport->dir_output.'/'.$relativepath.$file['name'];
+ $fileimage = $conf->expensereport->dir_output.'/'.$relativepath.$file['name'].'_preview.png';
+ $relativepathimage = $relativepath.$file['name'].'_preview.png';
- $pdfexists = file_exists($filepdf);
+ $pdfexists = file_exists($filepdf);
- if ($pdfexists)
- {
- // Conversion du PDF en image png si fichier png non existant
- if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf)))
- {
- if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here.
- {
- include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
- $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
- if ($ret < 0) $error++;
- }
- }
- }
+ if ($pdfexists)
+ {
+ // Conversion du PDF en image png si fichier png non existant
+ if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf)))
+ {
+ if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here.
+ {
+ include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+ $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
+ if ($ret < 0) $error++;
+ }
+ }
+ }
- if ($pdfexists && !$error)
- {
- $heightforphotref = 70;
- if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60;
- // If the preview file is found
- if (file_exists($fileimage))
- {
- $thumbshown = '
';
- }
- }
- }
+ if ($pdfexists && !$error)
+ {
+ $heightforphotref = 70;
+ if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60;
+ // If the preview file is found
+ if (file_exists($fileimage))
+ {
+ $thumbshown = '
';
+ }
+ }
+ }
- if (empty($urlforhref) || empty($thumbshown)) {
- print '
';
- } else {
- print ' ';
- }
- print '';
+ if (empty($urlforhref) || empty($thumbshown)) {
+ print '
';
+ } else {
+ print ' ';
+ }
+ print '';
- print $thumbshown ? $thumbshown : img_mime($minifile);
+ print $thumbshown ? $thumbshown : img_mime($minifile);
- print '
';
- }
- print '
';
- $checked = '';
- //var_dump(GETPOST($file['relativename'])); var_dump($file['relativename']); var_dump($_FILES['userfile']['name']);
- // If a file was just uploaded, we check to preselect it
- if (is_array($_FILES['userfile']['name'])) {
- foreach ($_FILES['userfile']['name'] as $tmpfile)
- {
- if ($file['relativename'] == (GETPOST('savingdocmask', 'alpha') ? dol_sanitizeFileName($object->ref.'-') : '').$tmpfile)
- {
- $checked = ' checked';
- break;
- } elseif ($file['relativename'] && in_array($file['relativename'], GETPOST('attachfile', 'array'))) {
- $checked = ' checked';
- break;
- }
- }
- }
- // If we edit a line already linked, then $filenamelinked is defined to the filename (without path) of linked file
- if (!empty($filenamelinked) && $filenamelinked == $file['relativename'])
- {
- $checked = ' checked';
- }
- print '
';
- print ' '.$file['relativename'].' ';
- print '
';
+ print '
';
+ }
+ print '
';
+ $checked = '';
+ //var_dump(GETPOST($file['relativename'])); var_dump($file['relativename']); var_dump($_FILES['userfile']['name']);
+ // If a file was just uploaded, we check to preselect it
+ if (is_array($_FILES['userfile']['name'])) {
+ foreach ($_FILES['userfile']['name'] as $tmpfile)
+ {
+ if ($file['relativename'] == (GETPOST('savingdocmask', 'alpha') ? dol_sanitizeFileName($object->ref.'-') : '').$tmpfile)
+ {
+ $checked = ' checked';
+ break;
+ } elseif ($file['relativename'] && in_array($file['relativename'], GETPOST('attachfile', 'array'))) {
+ $checked = ' checked';
+ break;
+ }
+ }
+ }
+ // If we edit a line already linked, then $filenamelinked is defined to the filename (without path) of linked file
+ if (!empty($filenamelinked) && $filenamelinked == $file['relativename'])
+ {
+ $checked = ' checked';
+ }
+ print '
';
+ print ' '.$file['relativename'].' ';
+ print '
';
- print '
';
- }
+ print '
';
+ }
- print '';
+ print '';
- print ' ';
- } else {
- print 'global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ' style="display: none"' : '').'>';
- print '';
- print ''.$langs->trans("NoFilesUploadedYet").' ';
- print ' ';
- }
+ print '';
+ } else {
+ print 'global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ' style="display: none"' : '').'>';
+ print '';
+ print ''.$langs->trans("NoFilesUploadedYet").' ';
+ print ' ';
+ }
}
diff --git a/htdocs/exports/class/export.class.php b/htdocs/exports/class/export.class.php
index 89ae2103476..9b666af779c 100644
--- a/htdocs/exports/class/export.class.php
+++ b/htdocs/exports/class/export.class.php
@@ -31,33 +31,33 @@
class Export
{
/**
- * @var DoliDB Database handler.
- */
- public $db;
+ * @var DoliDB Database handler.
+ */
+ public $db;
- public $array_export_code = array(); // Tableau de "idmodule_numlot"
- public $array_export_module = array(); // Tableau de "nom de modules"
- public $array_export_label = array(); // Tableau de "libelle de lots"
- public $array_export_sql_start = array(); // Tableau des "requetes sql"
- public $array_export_sql_end = array(); // Tableau des "requetes sql"
- public $array_export_sql_order = array(); // Tableau des "requetes sql"
+ public $array_export_code = array(); // Tableau de "idmodule_numlot"
+ public $array_export_module = array(); // Tableau de "nom de modules"
+ public $array_export_label = array(); // Tableau de "libelle de lots"
+ public $array_export_sql_start = array(); // Tableau des "requetes sql"
+ public $array_export_sql_end = array(); // Tableau des "requetes sql"
+ public $array_export_sql_order = array(); // Tableau des "requetes sql"
- public $array_export_fields = array(); // Tableau des listes de champ+libelle a exporter
- public $array_export_TypeFields = array(); // Tableau des listes de champ+Type de filtre
- public $array_export_FilterValue = array(); // Tableau des listes de champ+Valeur a filtrer
- public $array_export_entities = array(); // Tableau des listes de champ+alias a exporter
- public $array_export_dependencies = array(); // array of list of entities that must take care of the DISTINCT if a field is added into export
- public $array_export_special = array(); // array of special operations to do on field
- public $array_export_examplevalues = array(); // array with examples for fields
+ public $array_export_fields = array(); // Tableau des listes de champ+libelle a exporter
+ public $array_export_TypeFields = array(); // Tableau des listes de champ+Type de filtre
+ public $array_export_FilterValue = array(); // Tableau des listes de champ+Valeur a filtrer
+ public $array_export_entities = array(); // Tableau des listes de champ+alias a exporter
+ public $array_export_dependencies = array(); // array of list of entities that must take care of the DISTINCT if a field is added into export
+ public $array_export_special = array(); // array of special operations to do on field
+ public $array_export_examplevalues = array(); // array with examples for fields
public $array_export_help = array(); // array with tooltip help for fields
- // To store export modules
- public $hexa; // List of fields in the export profile
- public $hexafiltervalue; // List of search criteria in the export profile
- public $datatoexport;
- public $model_name; // Name of export profile
+ // To store export modules
+ public $hexa; // List of fields in the export profile
+ public $hexafiltervalue; // List of search criteria in the export profile
+ public $datatoexport;
+ public $model_name; // Name of export profile
- public $sqlusedforexport;
+ public $sqlusedforexport;
/**
@@ -65,13 +65,13 @@ class Export
*
* @param DoliDB $db Database handler
*/
- public function __construct($db)
- {
- $this->db = $db;
- }
+ public function __construct($db)
+ {
+ $this->db = $db;
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Load an exportable dataset
*
@@ -79,19 +79,19 @@ class Export
* @param string $filter Load a particular dataset only
* @return int <0 if KO, >0 if OK
*/
- public function load_arrays($user, $filter = '')
- {
- // phpcs:enable
- global $langs, $conf, $mysoc;
+ public function load_arrays($user, $filter = '')
+ {
+ // phpcs:enable
+ global $langs, $conf, $mysoc;
- dol_syslog(get_class($this)."::load_arrays user=".$user->id." filter=".$filter);
+ dol_syslog(get_class($this)."::load_arrays user=".$user->id." filter=".$filter);
- $i = 0;
+ $i = 0;
- // Define list of modules directories into modulesdir
- require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+ // Define list of modules directories into modulesdir
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
- $modulesdir = dolGetModulesDirs();
+ $modulesdir = dolGetModulesDirs();
foreach ($modulesdir as $dir)
{
@@ -99,8 +99,8 @@ class Export
$handle = @opendir(dol_osencode($dir));
if (is_resource($handle))
{
- // Search module files
- while (($file = readdir($handle)) !== false)
+ // Search module files
+ while (($file = readdir($handle)) !== false)
{
if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg))
{
@@ -122,30 +122,30 @@ class Export
if (isset($module->export_code) && is_array($module->export_code))
{
- foreach ($module->export_code as $r => $value)
+ foreach ($module->export_code as $r => $value)
{
- //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).' ';
- if ($filter && ($filter != $module->export_code[$r])) continue;
+ //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).' ';
+ if ($filter && ($filter != $module->export_code[$r])) continue;
- // Test if condition to show are ok
- if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) continue;
+ // Test if condition to show are ok
+ if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) continue;
- // Test if permissions are ok
+ // Test if permissions are ok
$bool = true;
if (isset($module->export_permission))
{
foreach ($module->export_permission[$r] as $val)
{
- $perm = $val;
- //print_r("$perm[0]-$perm[1]-$perm[2] ");
- if (!empty($perm[2]))
- {
- $bool = $user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]};
- } else {
- $bool = $user->rights->{$perm[0]}->{$perm[1]};
- }
- if ($perm[0] == 'user' && $user->admin) $bool = true;
- if (!$bool) break;
+ $perm = $val;
+ //print_r("$perm[0]-$perm[1]-$perm[2] ");
+ if (!empty($perm[2]))
+ {
+ $bool = $user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]};
+ } else {
+ $bool = $user->rights->{$perm[0]}->{$perm[1]};
+ }
+ if ($perm[0] == 'user' && $user->admin) $bool = true;
+ if (!$bool) break;
}
}
//print $bool." $perm[0]"." ";
@@ -183,10 +183,10 @@ class Export
$this->array_export_dependencies[$i] = (!empty($module->export_dependencies_array[$r]) ? $module->export_dependencies_array[$r] : '');
// Tableau des operations speciales sur champ
$this->array_export_special[$i] = (!empty($module->export_special_array[$r]) ? $module->export_special_array[$r] : '');
- // Array of examples
- $this->array_export_examplevalues[$i] = $module->export_examplevalues_array[$r];
- // Array of help tooltips
- $this->array_export_help[$i] = (!empty($module->export_help_array[$r]) ? $module->export_help_array[$r] : '');
+ // Array of examples
+ $this->array_export_examplevalues[$i] = $module->export_examplevalues_array[$r];
+ // Array of help tooltips
+ $this->array_export_help[$i] = (!empty($module->export_help_array[$r]) ? $module->export_help_array[$r] : '');
// Requete sql du dataset
$this->array_export_sql_start[$i] = $module->export_sql_start[$r];
@@ -202,15 +202,15 @@ class Export
}
}
}
- closedir($handle);
+ closedir($handle);
}
}
return 1;
- }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Build the sql export request.
* Arrays this->array_export_xxx are already loaded for required datatoexport
@@ -220,9 +220,9 @@ class Export
* @param array $array_filterValue Filter records on array of value for fields
* @return string SQL String. Example "select s.rowid as r_rowid, s.status as s_status from ..."
*/
- public function build_sql($indice, $array_selected, $array_filterValue)
- {
- // phpcs:enable
+ public function build_sql($indice, $array_selected, $array_filterValue)
+ {
+ // phpcs:enable
// Build the sql request
$sql = $this->array_export_sql_start[$indice];
$i = 0;
@@ -231,7 +231,7 @@ class Export
foreach ($this->array_export_fields[$indice] as $key => $value)
{
if (!array_key_exists($key, $array_selected)) continue; // Field not selected
- if (preg_match('/^none\./', $key)) continue; // A field that must not appears into SQL
+ if (preg_match('/^none\./', $key)) continue; // A field that must not appears into SQL
if ($i > 0) $sql .= ', ';
else $i++;
@@ -252,7 +252,7 @@ class Export
// Loop on each condition to add
foreach ($array_filterValue as $key => $value)
{
- if (preg_match('/GROUP_CONCAT/i', $key)) continue;
+ if (preg_match('/GROUP_CONCAT/i', $key)) continue;
if ($value != '') $sqlWhere .= " and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
}
$sql .= $sqlWhere;
@@ -264,17 +264,17 @@ class Export
// Add the HAVING part.
if (is_array($array_filterValue) && !empty($array_filterValue))
{
- // Loop on each condition to add
- foreach ($array_filterValue as $key => $value)
- {
- if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
- }
+ // Loop on each condition to add
+ foreach ($array_filterValue as $key => $value)
+ {
+ if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
+ }
}
return $sql;
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Build the conditionnal string from filter the query
*
@@ -283,9 +283,9 @@ class Export
* @param string $ValueField Value of the field for filter. Must not be ''
* @return string sql string of then field ex : "field='xxx'>"
*/
- public function build_filterQuery($TypeField, $NameField, $ValueField)
- {
- // phpcs:enable
+ public function build_filterQuery($TypeField, $NameField, $ValueField)
+ {
+ // phpcs:enable
//print $TypeField." ".$NameField." ".$ValueField;
$InfoFieldList = explode(":", $TypeField);
// build the input field on depend of the type of file
@@ -332,13 +332,13 @@ class Export
if (is_numeric($ValueField))
$szFilterQuery = " ".$NameField."=".$ValueField;
else {
- if (!(strpos($ValueField, '%') === false))
- $szFilterQuery = " ".$NameField." LIKE '".$ValueField."'";
- else $szFilterQuery = " ".$NameField." = '".$ValueField."'";
+ if (!(strpos($ValueField, '%') === false))
+ $szFilterQuery = " ".$NameField." LIKE '".$ValueField."'";
+ else $szFilterQuery = " ".$NameField." = '".$ValueField."'";
}
break;
default:
- dol_syslog("Error we try to forge an sql export request with a condition on a field with type ".$InfoFieldList[0]." (defined into module descriptor) but this type is unknown/not supported. It looks like a bug into module descriptor.", LOG_ERR);
+ dol_syslog("Error we try to forge an sql export request with a condition on a field with type ".$InfoFieldList[0]." (defined into module descriptor) but this type is unknown/not supported. It looks like a bug into module descriptor.", LOG_ERR);
}
return $szFilterQuery;
@@ -352,16 +352,16 @@ class Export
* @param string $Sens Comparison operator
* @return string
*/
- public function conditionDate($Field, $Value, $Sens)
- {
+ public function conditionDate($Field, $Value, $Sens)
+ {
// TODO date_format is forbidden, not performant and not portable. Use instead BETWEEN
if (strlen($Value) == 4) $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$Value."'";
elseif (strlen($Value) == 6) $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'";
else $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value;
return $Condition;
- }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Build an input field used to filter the query
*
@@ -370,9 +370,9 @@ class Export
* @param string $ValueField Initial value of the field to filter
* @return string html string of the input field ex : " "
*/
- public function build_filterField($TypeField, $NameField, $ValueField)
- {
- // phpcs:enable
+ public function build_filterField($TypeField, $NameField, $ValueField)
+ {
+ // phpcs:enable
global $conf, $langs;
$szFilterField = '';
@@ -389,7 +389,7 @@ class Export
case 'Numeric':
case 'Number':
// Must be a string text to allow to use comparison strings like "<= 999"
- $szFilterField = ' ';
+ $szFilterField = ' ';
break;
case 'Status':
$szFilterField = ' ';
@@ -476,17 +476,17 @@ class Export
}
return $szFilterField;
- }
+ }
- /**
- * Build an input field used to filter the query
- *
- * @param string $TypeField Type of Field to filter
- * @return string html string of the input field ex : " "
- */
- public function genDocFilter($TypeField)
- {
- global $langs;
+ /**
+ * Build an input field used to filter the query
+ *
+ * @param string $TypeField Type of Field to filter
+ * @return string html string of the input field ex : " "
+ */
+ public function genDocFilter($TypeField)
+ {
+ global $langs;
$szMsg = '';
$InfoFieldList = explode(":", $TypeField);
@@ -511,7 +511,7 @@ class Export
return $szMsg;
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Build export file.
* File is built into directory $conf->export->dir_temp.'/'.$user->id
@@ -525,9 +525,9 @@ class Export
* @param string $sqlquery If set, transmit the sql request for select (otherwise, sql request is generated from arrays)
* @return int <0 if KO, >0 if OK
*/
- public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '')
- {
- // phpcs:enable
+ public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '')
+ {
+ // phpcs:enable
global $conf, $langs, $mysoc;
$indice = 0;
@@ -551,7 +551,7 @@ class Export
$objmodel = new $classname($this->db);
if (!empty($sqlquery)) $sql = $sqlquery;
- else {
+ else {
// Define value for indice from $datatoexport
$foundindice = 0;
foreach ($this->array_export_code as $key => $dataset)
@@ -569,7 +569,7 @@ class Export
$this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
return -1;
}
- $sql = $this->build_sql($indice, $array_selected, $array_filterValue);
+ $sql = $this->build_sql($indice, $array_selected, $array_filterValue);
}
// Run the sql
@@ -637,26 +637,26 @@ class Export
$remaintopay = '';
if ($obj->f_rowid > 0)
{
- global $tmpobjforcomputecall;
- if (!is_object($tmpobjforcomputecall))
- {
- include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
- $tmpobjforcomputecall = new Facture($this->db);
- }
- $tmpobjforcomputecall->id = $obj->f_rowid;
- $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
- $tmpobjforcomputecall->close_code = $obj->f_close_code;
- $remaintopay = $tmpobjforcomputecall->getRemainToPay();
+ global $tmpobjforcomputecall;
+ if (!is_object($tmpobjforcomputecall))
+ {
+ include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
+ $tmpobjforcomputecall = new Facture($this->db);
+ }
+ $tmpobjforcomputecall->id = $obj->f_rowid;
+ $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
+ $tmpobjforcomputecall->close_code = $obj->f_close_code;
+ $remaintopay = $tmpobjforcomputecall->getRemainToPay();
}
$obj->$alias = $remaintopay;
} else {
- // TODO FIXME Export of compute field does not work. $obj containt $obj->alias_field and formulat will contains $obj->field
- $computestring = $this->array_export_special[$indice][$key];
- $tmp = dol_eval($computestring, 1, 0);
- $obj->$alias = $tmp;
+ // TODO FIXME Export of compute field does not work. $obj containt $obj->alias_field and formulat will contains $obj->field
+ $computestring = $this->array_export_special[$indice][$key];
+ $tmp = dol_eval($computestring, 1, 0);
+ $obj->$alias = $tmp;
- $this->error = "ERROPNOTSUPPORTED. Operation ".$this->array_export_special[$indice][$key]." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
- return -1;
+ $this->error = "ERROPNOTSUPPORTED. Operation ".$this->array_export_special[$indice][$key]." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
+ return -1;
}
}
}
@@ -670,7 +670,7 @@ class Export
// Close file
$objmodel->close_file();
- return 1;
+ return 1;
} else {
$this->error = $objmodel->error;
dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
@@ -688,7 +688,7 @@ class Export
* @param User $user Object user that save
* @return int <0 if KO, >0 if OK
*/
- public function create($user)
+ public function create($user)
{
global $conf;
@@ -732,8 +732,8 @@ class Export
* @param int $id Id of profil to load
* @return int <0 if KO, >0 if OK
*/
- public function fetch($id)
- {
+ public function fetch($id)
+ {
$sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
$sql .= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
$sql .= ' WHERE em.rowid = '.((int) $id);
@@ -801,16 +801,16 @@ class Export
}
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Output list all export models
* TODO Move this into a class htmlxxx.class.php
*
* @return void
*/
- public function list_export_model()
- {
- // phpcs:enable
+ public function list_export_model()
+ {
+ // phpcs:enable
global $conf, $langs;
$sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
@@ -852,8 +852,8 @@ class Export
$i++;
}
- } else {
- dol_print_error($this->db);
- }
- }
+ } else {
+ dol_print_error($this->db);
+ }
+ }
}
diff --git a/htdocs/exports/export.php b/htdocs/exports/export.php
index 412167c55f2..2889e383817 100644
--- a/htdocs/exports/export.php
+++ b/htdocs/exports/export.php
@@ -41,24 +41,24 @@ $langs->loadlangs(array('admin', 'exports', 'other', 'users', 'companies', 'proj
$entitytoicon = array(
'invoice' => 'bill',
- 'invoice_line' => 'bill',
+ 'invoice_line' => 'bill',
'order' => 'order',
- 'order_line' => 'order',
+ 'order_line' => 'order',
'propal' => 'propal',
- 'propal_line' => 'propal',
+ 'propal_line' => 'propal',
'intervention' => 'intervention',
- 'inter_line' => 'intervention',
+ 'inter_line' => 'intervention',
'member' => 'user',
- 'member_type' => 'group',
- 'subscription' => 'payment',
- 'payment' => 'payment',
+ 'member_type' => 'group',
+ 'subscription' => 'payment',
+ 'payment' => 'payment',
'tax' => 'generic',
- 'tax_type' => 'generic',
- 'stock' => 'generic',
- 'other' => 'generic',
+ 'tax_type' => 'generic',
+ 'stock' => 'generic',
+ 'other' => 'generic',
'account' => 'account',
'product' => 'product',
- 'virtualproduct'=>'product',
+ 'virtualproduct'=>'product',
'subproduct' => 'product',
'product_supplier_ref' => 'product',
'warehouse' => 'stock',
@@ -66,36 +66,36 @@ $entitytoicon = array(
'stockbatch' => 'stock',
'category' => 'category',
'shipment' => 'sending',
- 'shipment_line'=> 'sending',
- 'reception'=> 'sending',
- 'reception_line'=> 'sending',
+ 'shipment_line'=> 'sending',
+ 'reception'=> 'sending',
+ 'reception_line'=> 'sending',
'expensereport'=> 'trip',
- 'expensereport_line'=> 'trip',
+ 'expensereport_line'=> 'trip',
'holiday' => 'holiday',
- 'contract_line' => 'contract',
- 'translation' => 'generic',
- 'bomm' => 'bom',
- 'bomline' => 'bom'
+ 'contract_line' => 'contract',
+ 'translation' => 'generic',
+ 'bomm' => 'bom',
+ 'bomline' => 'bom'
);
// Translation code
$entitytolang = array(
'user' => 'User',
'company' => 'Company',
- 'contact' => 'Contact',
+ 'contact' => 'Contact',
'invoice' => 'Bill',
- 'invoice_line' => 'InvoiceLine',
+ 'invoice_line' => 'InvoiceLine',
'order' => 'Order',
- 'order_line' => 'OrderLine',
- 'propal' => 'Proposal',
- 'propal_line' => 'ProposalLine',
+ 'order_line' => 'OrderLine',
+ 'propal' => 'Proposal',
+ 'propal_line' => 'ProposalLine',
'intervention' => 'Intervention',
- 'inter_line' => 'InterLine',
+ 'inter_line' => 'InterLine',
'member' => 'Member',
- 'member_type' => 'MemberType',
- 'subscription' => 'Subscription',
+ 'member_type' => 'MemberType',
+ 'subscription' => 'Subscription',
'tax' => 'SocialContribution',
- 'tax_type' => 'DictionarySocialContributions',
+ 'tax_type' => 'DictionarySocialContributions',
'account' => 'BankTransactions',
'payment' => 'Payment',
'product' => 'Product',
@@ -103,28 +103,28 @@ $entitytolang = array(
'subproduct' => 'SubProduct',
'product_supplier_ref' => 'SupplierPrices',
'service' => 'Service',
- 'stock' => 'Stock',
+ 'stock' => 'Stock',
'movement' => 'StockMovement',
'batch' => 'Batch',
'stockbatch' => 'StockDetailPerBatch',
'warehouse' => 'Warehouse',
'category' => 'Category',
'other' => 'Other',
- 'trip' => 'TripsAndExpenses',
- 'shipment' => 'Shipments',
- 'shipment_line'=> 'ShipmentLine',
- 'project' => 'Projects',
- 'projecttask' => 'Tasks',
- 'task_time' => 'TaskTimeSpent',
+ 'trip' => 'TripsAndExpenses',
+ 'shipment' => 'Shipments',
+ 'shipment_line'=> 'ShipmentLine',
+ 'project' => 'Projects',
+ 'projecttask' => 'Tasks',
+ 'task_time' => 'TaskTimeSpent',
'action' => 'Event',
'expensereport'=> 'ExpenseReport',
'expensereport_line'=> 'ExpenseReportLine',
'holiday' => 'TitreRequestCP',
'contract' => 'Contract',
- 'contract_line'=> 'ContractLine',
- 'translation' => 'Translation',
- 'bom' => 'BOM',
- 'bomline' => 'BOMLine'
+ 'contract_line'=> 'ContractLine',
+ 'translation' => 'Translation',
+ 'bom' => 'BOM',
+ 'bomline' => 'BOMLine'
);
$array_selected = isset($_SESSION["export_selected_fields"]) ? $_SESSION["export_selected_fields"] : array();
@@ -162,121 +162,121 @@ if ($action == 'selectfield') // Selection of field at step 2
{
$fieldsarray = $objexport->array_export_fields[0];
$fieldsentitiesarray = $objexport->array_export_entities[0];
- $fieldsdependenciesarray = $objexport->array_export_dependencies[0];
+ $fieldsdependenciesarray = $objexport->array_export_dependencies[0];
- if ($field == 'all')
- {
+ if ($field == 'all')
+ {
foreach ($fieldsarray as $key=>$val)
{
if (!empty($array_selected[$key])) continue; // If already selected, check next
$array_selected[$key] = count($array_selected) + 1;
- //print_r($array_selected);
- $_SESSION["export_selected_fields"] = $array_selected;
+ //print_r($array_selected);
+ $_SESSION["export_selected_fields"] = $array_selected;
}
- } else {
- $warnings = array();
+ } else {
+ $warnings = array();
- $array_selected[$field] = count($array_selected) + 1; // We tag the key $field as "selected"
- // We check if there is a dependency to activate
- /*var_dump($field);
+ $array_selected[$field] = count($array_selected) + 1; // We tag the key $field as "selected"
+ // We check if there is a dependency to activate
+ /*var_dump($field);
var_dump($fieldsentitiesarray[$field]);
var_dump($fieldsdependenciesarray);*/
- $listofdependencies = array();
- if (!empty($fieldsentitiesarray[$field]) && !empty($fieldsdependenciesarray[$fieldsentitiesarray[$field]]))
- {
- // We found a dependency on the type of field
- $tmp = $fieldsdependenciesarray[$fieldsentitiesarray[$field]]; // $fieldsdependenciesarray=array('element'=>'fd.rowid') or array('element'=>array('fd.rowid','ab.rowid'))
- if (is_array($tmp)) $listofdependencies = $tmp;
- else $listofdependencies = array($tmp);
- } elseif (!empty($field) && !empty($fieldsdependenciesarray[$field]))
- {
- // We found a dependency on a dedicated field
- $tmp = $fieldsdependenciesarray[$field]; // $fieldsdependenciesarray=array('fd.fieldx'=>'fd.rowid') or array('fd.fieldx'=>array('fd.rowid','ab.rowid'))
- if (is_array($tmp)) $listofdependencies = $tmp;
- else $listofdependencies = array($tmp);
- }
+ $listofdependencies = array();
+ if (!empty($fieldsentitiesarray[$field]) && !empty($fieldsdependenciesarray[$fieldsentitiesarray[$field]]))
+ {
+ // We found a dependency on the type of field
+ $tmp = $fieldsdependenciesarray[$fieldsentitiesarray[$field]]; // $fieldsdependenciesarray=array('element'=>'fd.rowid') or array('element'=>array('fd.rowid','ab.rowid'))
+ if (is_array($tmp)) $listofdependencies = $tmp;
+ else $listofdependencies = array($tmp);
+ } elseif (!empty($field) && !empty($fieldsdependenciesarray[$field]))
+ {
+ // We found a dependency on a dedicated field
+ $tmp = $fieldsdependenciesarray[$field]; // $fieldsdependenciesarray=array('fd.fieldx'=>'fd.rowid') or array('fd.fieldx'=>array('fd.rowid','ab.rowid'))
+ if (is_array($tmp)) $listofdependencies = $tmp;
+ else $listofdependencies = array($tmp);
+ }
- if (count($listofdependencies))
- {
- foreach ($listofdependencies as $fieldid)
- {
- if (empty($array_selected[$fieldid]))
- {
- $array_selected[$fieldid] = count($array_selected) + 1; // We tag the key $fieldid as "selected"
- $warnings[] = $langs->trans("ExportFieldAutomaticallyAdded", $langs->transnoentitiesnoconv($fieldsarray[$fieldid]));
- }
- }
- }
- //print_r($array_selected);
- $_SESSION["export_selected_fields"] = $array_selected;
+ if (count($listofdependencies))
+ {
+ foreach ($listofdependencies as $fieldid)
+ {
+ if (empty($array_selected[$fieldid]))
+ {
+ $array_selected[$fieldid] = count($array_selected) + 1; // We tag the key $fieldid as "selected"
+ $warnings[] = $langs->trans("ExportFieldAutomaticallyAdded", $langs->transnoentitiesnoconv($fieldsarray[$fieldid]));
+ }
+ }
+ }
+ //print_r($array_selected);
+ $_SESSION["export_selected_fields"] = $array_selected;
- setEventMessages($warnings, null, 'warnings');
- }
+ setEventMessages($warnings, null, 'warnings');
+ }
}
if ($action == 'unselectfield')
{
- if ($_GET["field"] == 'all')
- {
+ if ($_GET["field"] == 'all')
+ {
$array_selected = array();
$_SESSION["export_selected_fields"] = $array_selected;
- } else {
- unset($array_selected[$_GET["field"]]);
- // Renumber fields of array_selected (from 1 to nb_elements)
- asort($array_selected);
- $i = 0;
- $array_selected_save = $array_selected;
- foreach ($array_selected as $code=>$value)
- {
- $i++;
- $array_selected[$code] = $i;
- //print "x $code x $i y ";
- }
- $_SESSION["export_selected_fields"] = $array_selected;
- }
+ } else {
+ unset($array_selected[$_GET["field"]]);
+ // Renumber fields of array_selected (from 1 to nb_elements)
+ asort($array_selected);
+ $i = 0;
+ $array_selected_save = $array_selected;
+ foreach ($array_selected as $code=>$value)
+ {
+ $i++;
+ $array_selected[$code] = $i;
+ //print "x $code x $i y ";
+ }
+ $_SESSION["export_selected_fields"] = $array_selected;
+ }
}
if ($action == 'downfield' || $action == 'upfield')
{
- $pos = $array_selected[$_GET["field"]];
- if ($action == 'downfield') $newpos = $pos + 1;
- if ($action == 'upfield') $newpos = $pos - 1;
- // Recherche code avec qui switcher
- $newcode = "";
- foreach ($array_selected as $code=>$value)
- {
- if ($value == $newpos)
- {
- $newcode = $code;
- break;
- }
- }
- //print("Switch pos=$pos (code=".$_GET["field"].") and newpos=$newpos (code=$newcode)");
- if ($newcode) // Si newcode trouve (protection contre resoumission de page)
- {
- $array_selected[$_GET["field"]] = $newpos;
- $array_selected[$newcode] = $pos;
- $_SESSION["export_selected_fields"] = $array_selected;
- }
+ $pos = $array_selected[$_GET["field"]];
+ if ($action == 'downfield') $newpos = $pos + 1;
+ if ($action == 'upfield') $newpos = $pos - 1;
+ // Recherche code avec qui switcher
+ $newcode = "";
+ foreach ($array_selected as $code=>$value)
+ {
+ if ($value == $newpos)
+ {
+ $newcode = $code;
+ break;
+ }
+ }
+ //print("Switch pos=$pos (code=".$_GET["field"].") and newpos=$newpos (code=$newcode)");
+ if ($newcode) // Si newcode trouve (protection contre resoumission de page)
+ {
+ $array_selected[$_GET["field"]] = $newpos;
+ $array_selected[$newcode] = $pos;
+ $_SESSION["export_selected_fields"] = $array_selected;
+ }
}
if ($step == 1 || $action == 'cleanselect')
{
- $_SESSION["export_selected_fields"] = array();
- $_SESSION["export_filtered_fields"] = array();
- $array_selected = array();
- $array_filtervalue = array();
+ $_SESSION["export_selected_fields"] = array();
+ $_SESSION["export_filtered_fields"] = array();
+ $array_selected = array();
+ $array_filtervalue = array();
}
if ($action == 'builddoc')
{
- $max_execution_time_for_export = (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");
- if ($max_time && $max_time < $max_execution_time_for_export)
- {
- @ini_set("max_execution_time", $max_execution_time_for_export); // This work only if safe mode is off. also web servers has timeout of 300
- }
+ $max_execution_time_for_export = (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");
+ if ($max_time && $max_time < $max_execution_time_for_export)
+ {
+ @ini_set("max_execution_time", $max_execution_time_for_export); // This work only if safe mode is off. also web servers has timeout of 300
+ }
- // Build export file
+ // Build export file
$result = $objexport->build_file($user, GETPOST('model', 'alpha'), $datatoexport, $array_selected, $array_filtervalue);
if ($result < 0)
{
@@ -284,8 +284,8 @@ if ($action == 'builddoc')
$sqlusedforexport = $objexport->sqlusedforexport;
} else {
setEventMessages($langs->trans("FileSuccessfullyBuilt"), null, 'mesgs');
- $sqlusedforexport = $objexport->sqlusedforexport;
- }
+ $sqlusedforexport = $objexport->sqlusedforexport;
+ }
}
// Delete file
@@ -334,12 +334,12 @@ if ($action == 'add_export_model')
}
}
- $objexport->model_name = $export_name;
- $objexport->datatoexport = $datatoexport;
- $objexport->hexa = $hexa;
- $objexport->hexafiltervalue = $hexafiltervalue;
+ $objexport->model_name = $export_name;
+ $objexport->datatoexport = $datatoexport;
+ $objexport->hexa = $hexa;
+ $objexport->hexafiltervalue = $hexafiltervalue;
- $result = $objexport->create($user);
+ $result = $objexport->create($user);
if ($result >= 0)
{
setEventMessages($langs->trans("ExportModelSaved", $objexport->model_name), null, 'mesgs');
@@ -357,15 +357,15 @@ if ($action == 'add_export_model')
// Reload a predefined export model
if ($step == 2 && $action == 'select_model')
{
- $_SESSION["export_selected_fields"] = array();
- $_SESSION["export_filtered_fields"] = array();
+ $_SESSION["export_selected_fields"] = array();
+ $_SESSION["export_filtered_fields"] = array();
- $array_selected = array();
- $array_filtervalue = array();
+ $array_selected = array();
+ $array_filtervalue = array();
- $result = $objexport->fetch($exportmodelid);
- if ($result > 0)
- {
+ $result = $objexport->fetch($exportmodelid);
+ if ($result > 0)
+ {
$fieldsarray = preg_split("/,(?! [^(]*\))/", $objexport->hexa);
$i = 1;
foreach ($fieldsarray as $val)
@@ -384,7 +384,7 @@ if ($step == 2 && $action == 'select_model')
$i++;
}
$_SESSION["export_filtered_fields"] = $array_filtervalue;
- }
+ }
}
// Get form with filters
@@ -419,143 +419,143 @@ if ($step == 4 && $action == 'submitFormField')
if ($step == 1 || !$datatoexport)
{
- llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones');
+ llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones');
- $h = 0;
+ $h = 0;
- $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
- $head[$h][1] = $langs->trans("Step")." 1";
- $hselected = $h;
- $h++;
+ $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
+ $head[$h][1] = $langs->trans("Step")." 1";
+ $hselected = $h;
+ $h++;
- print dol_get_fiche_head($head, $hselected, $langs->trans("NewExport"), -1);
+ print dol_get_fiche_head($head, $hselected, $langs->trans("NewExport"), -1);
- print ''.$langs->trans("SelectExportDataSet").'
';
+ print ''.$langs->trans("SelectExportDataSet").'
';
- // Affiche les modules d'exports
- print ''; // You can use div-table-responsive-no-min if you dont need reserved height for your table
- print '
';
- print '';
- print ''.$langs->trans("Module").' ';
- print ''.$langs->trans("ExportableDatas").' ';
- print ' ';
- print ' ';
+ // Affiche les modules d'exports
+ print ''; // You can use div-table-responsive-no-min if you dont need reserved height for your table
+ print '
';
+ print '';
+ print ''.$langs->trans("Module").' ';
+ print ''.$langs->trans("ExportableDatas").' ';
+ print ' ';
+ print ' ';
- if (count($objexport->array_export_module))
- {
- $sortedarrayofmodules = dol_sort_array($objexport->array_export_module, 'module_position', 'asc', 0, 0, 1);
- foreach ($sortedarrayofmodules as $key => $value)
- {
- print '';
- //print img_object($objexport->array_export_module[$key]->getName(),$export->array_export_module[$key]->picto).' ';
- print $objexport->array_export_module[$key]->getName();
- print ' ';
+ if (count($objexport->array_export_module))
+ {
+ $sortedarrayofmodules = dol_sort_array($objexport->array_export_module, 'module_position', 'asc', 0, 0, 1);
+ foreach ($sortedarrayofmodules as $key => $value)
+ {
+ print ' ';
+ //print img_object($objexport->array_export_module[$key]->getName(),$export->array_export_module[$key]->picto).' ';
+ print $objexport->array_export_module[$key]->getName();
+ print ' ';
$icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[$key]);
$label = $objexport->array_export_label[$key];
- //print $value.'-'.$icon.'-'.$label." ";
+ //print $value.'-'.$icon.'-'.$label." ";
print img_object($objexport->array_export_module[$key]->getName(), $icon).' ';
- print $label;
- print ' ';
- if ($objexport->array_export_perms[$key])
- {
- print ''.img_picto($langs->trans("NewExport"), 'next', 'class="fa-15x"').' ';
- } else {
- print $langs->trans("NotEnoughPermissions");
- }
- print ' ';
- }
- } else {
- print ''.$langs->trans("NoExportableData").' ';
- }
- print '
';
- print '
';
+ print $label;
+ print '';
+ if ($objexport->array_export_perms[$key])
+ {
+ print ''.img_picto($langs->trans("NewExport"), 'next', 'class="fa-15x"').' ';
+ } else {
+ print $langs->trans("NotEnoughPermissions");
+ }
+ print ' ';
+ }
+ } else {
+ print ''.$langs->trans("NoExportableData").' ';
+ }
+ print '
';
+ print '
';
- print '';
+ print '';
}
if ($step == 2 && $datatoexport)
{
- llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones');
+ llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones');
- $h = 0;
+ $h = 0;
- $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
- $head[$h][1] = $langs->trans("Step")." 1";
- $h++;
+ $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
+ $head[$h][1] = $langs->trans("Step")." 1";
+ $h++;
- $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport;
- $head[$h][1] = $langs->trans("Step")." 2";
- $hselected = $h;
- $h++;
+ $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport;
+ $head[$h][1] = $langs->trans("Step")." 2";
+ $hselected = $h;
+ $h++;
- print dol_get_fiche_head($head, $hselected, $langs->trans("NewExport"), -2);
+ print dol_get_fiche_head($head, $hselected, $langs->trans("NewExport"), -2);
- print '';
- print '
';
+ print '
';
+ print '
';
- print '
';
+ print '';
- // Module
- print ''.$langs->trans("Module").' ';
- print '';
- //print img_object($objexport->array_export_module[0]->getName(),$objexport->array_export_module[0]->picto).' ';
- print $objexport->array_export_module[0]->getName();
- print ' ';
+ // Module
+ print ''.$langs->trans("Module").' ';
+ print '';
+ //print img_object($objexport->array_export_module[0]->getName(),$objexport->array_export_module[0]->picto).' ';
+ print $objexport->array_export_module[0]->getName();
+ print ' ';
- // Lot de donnees a exporter
- print ''.$langs->trans("DatasetToExport").' ';
- print '';
+ // Lot de donnees a exporter
+ print ' '.$langs->trans("DatasetToExport").' ';
+ print '';
$icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]);
- $label = $objexport->array_export_label[0];
- //print $value.'-'.$icon.'-'.$label." ";
- print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
- print $label;
- print ' ';
+ $label = $objexport->array_export_label[0];
+ //print $value.'-'.$icon.'-'.$label." ";
+ print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
+ print $label;
+ print '';
- print '
';
- print '';
+ print '
';
+ print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
- print '
';
+ print '
';
- // Combo list of export models
- print '
';
+ // Combo list of export models
+ print '
';
- print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
- print '
';
- print '';
+ print ''; // You can use div-table-responsive-no-min if you dont need reserved height for your table
+ print '
';
+ print '';
print ''.$langs->trans("Entities").' ';
- print ''.$langs->trans("ExportableFields").' ';
- print '';
- print ''.$langs->trans("All")." ";
- print ' / ';
- print ''.$langs->trans("None")." ";
- print ' ';
- print ''.$langs->trans("ExportedFields").' ';
- print ' ';
+ print ''.$langs->trans("ExportableFields").' ';
+ print '';
+ print ''.$langs->trans("All")." ";
+ print ' / ';
+ print ''.$langs->trans("None")." ";
+ print ' ';
+ print ''.$langs->trans("ExportedFields").' ';
+ print '';
- // Champs exportables
- $fieldsarray = $objexport->array_export_fields[0];
- // Select request if all fields are selected
- $sqlmaxforexport = $objexport->build_sql(0, array(), array());
+ // Champs exportables
+ $fieldsarray = $objexport->array_export_fields[0];
+ // Select request if all fields are selected
+ $sqlmaxforexport = $objexport->build_sql(0, array(), array());
// $this->array_export_module[0]=$module;
// $this->array_export_code[0]=$module->export_code[$r];
@@ -565,48 +565,48 @@ if ($step == 2 && $datatoexport)
// $this->array_export_entities[0]=$module->export_fields_entities[$r];
// $this->array_export_alias[0]=$module->export_fields_alias[$r];
- $i = 0;
+ $i = 0;
- foreach ($fieldsarray as $code=>$label)
- {
- print '';
+ foreach ($fieldsarray as $code=>$label)
+ {
+ print ' ';
- $i++;
+ $i++;
- $entity = (!empty($objexport->array_export_entities[0][$code]) ? $objexport->array_export_entities[0][$code] : $objexport->array_export_icon[0]);
- $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
- $entitylang = (!empty($entitytolang[$entity]) ? $entitytolang[$entity] : $entity);
+ $entity = (!empty($objexport->array_export_entities[0][$code]) ? $objexport->array_export_entities[0][$code] : $objexport->array_export_icon[0]);
+ $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
+ $entitylang = (!empty($entitytolang[$entity]) ? $entitytolang[$entity] : $entity);
- print '';
- // If value of entityicon=entitylang='icon:Label'
- //print $code.'-'.$label.'-'.$entity;
+ print ' ';
+ // If value of entityicon=entitylang='icon:Label'
+ //print $code.'-'.$label.'-'.$entity;
- $tmparray = explode(':', $entityicon);
- if (count($tmparray) >= 2)
- {
- $entityicon = $tmparray[0];
- $entitylang = $tmparray[1];
- }
- print img_object('', $entityicon).' '.$langs->trans($entitylang);
- print ' ';
+ $tmparray = explode(':', $entityicon);
+ if (count($tmparray) >= 2)
+ {
+ $entityicon = $tmparray[0];
+ $entitylang = $tmparray[1];
+ }
+ print img_object('', $entityicon).' '.$langs->trans($entitylang);
+ print '';
- $text = (empty($objexport->array_export_special[0][$code]) ? '' : '').$langs->trans($label).(empty($objexport->array_export_special[0][$code]) ? '' : ' ');
+ $text = (empty($objexport->array_export_special[0][$code]) ? '' : '').$langs->trans($label).(empty($objexport->array_export_special[0][$code]) ? '' : ' ');
- $tablename = getablenamefromfield($code, $sqlmaxforexport);
- $htmltext = ''.$langs->trans("Name").": ".$text.' ';
- if (!empty($objexport->array_export_special[0][$code]))
- {
- $htmltext .= ''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$objexport->array_export_special[0][$code]." ";
- } else {
- $htmltext .= ''.$langs->trans("Table")." -> ".$langs->trans("Field").": ".$tablename." -> ".preg_replace('/^.*\./', '', $code)." ";
- }
+ $tablename = getablenamefromfield($code, $sqlmaxforexport);
+ $htmltext = ''.$langs->trans("Name").": ".$text.' ';
+ if (!empty($objexport->array_export_special[0][$code]))
+ {
+ $htmltext .= ''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$objexport->array_export_special[0][$code]." ";
+ } else {
+ $htmltext .= ''.$langs->trans("Table")." -> ".$langs->trans("Field").": ".$tablename." -> ".preg_replace('/^.*\./', '', $code)." ";
+ }
if (!empty($objexport->array_export_examplevalues[0][$code]))
{
- $htmltext .= ''.$langs->trans("SourceExample").': '.$objexport->array_export_examplevalues[0][$code].' ';
+ $htmltext .= ''.$langs->trans("SourceExample").': '.$objexport->array_export_examplevalues[0][$code].' ';
}
- if (!empty($objexport->array_export_TypeFields[0][$code]))
+ if (!empty($objexport->array_export_TypeFields[0][$code]))
{
- $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].' ';
+ $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].' ';
}
if (!empty($objexport->array_export_help[0][$code]))
{
@@ -614,38 +614,38 @@ if ($step == 2 && $datatoexport)
}
if (isset($array_selected[$code]) && $array_selected[$code])
- {
- // Selected fields
- print ' ';
- print ''.img_left('default', 0, 'style="max-width: 20px"').' ';
- print '';
- //print $text.'-'.$htmltext." ";
- print $form->textwithpicto($text, $htmltext);
- //print ' ('.$code.')';
- print ' ';
- } else {
- // Fields not selected
- print '';
+ {
+ // Selected fields
+ print ' ';
+ print ''.img_left('default', 0, 'style="max-width: 20px"').' ';
+ print '';
//print $text.'-'.$htmltext." ";
print $form->textwithpicto($text, $htmltext);
//print ' ('.$code.')';
- print ' ';
- print ''.img_right('default', 0, 'style="max-width: 20px"').' ';
- print ' ';
- }
+ print '';
+ } else {
+ // Fields not selected
+ print '';
+ //print $text.'-'.$htmltext." ";
+ print $form->textwithpicto($text, $htmltext);
+ //print ' ('.$code.')';
+ print ' ';
+ print ''.img_right('default', 0, 'style="max-width: 20px"').' ';
+ print ' ';
+ }
- print ' ';
- }
+ print '';
+ }
- print '
';
- print '
';
+ print '
';
+ print '
';
- /*
+ /*
* Barre d'action
*/
- print '
';
+ print '
';
- if (count($array_selected))
+ if (count($array_selected))
{
// If filters exist
if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
@@ -658,19 +658,19 @@ if ($step == 2 && $datatoexport)
print '
'.$langs->trans("NextStep").' ';
}
- print '
';
+ print '
';
}
if ($step == 3 && $datatoexport)
{
- if (count($array_selected) < 1) // This occurs when going back to page after sessecion expired
- {
- // Switch to step 2
- header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport);
- exit;
- }
+ if (count($array_selected) < 1) // This occurs when going back to page after sessecion expired
+ {
+ // Switch to step 2
+ header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport);
+ exit;
+ }
- llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones');
+ llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones');
$h = 0;
@@ -689,8 +689,8 @@ if ($step == 3 && $datatoexport)
print dol_get_fiche_head($head, $hselected, $langs->trans("NewExport"), -2);
- print '
';
- print '
';
+ print '
';
+ print '
';
print '
';
// Module
@@ -735,7 +735,7 @@ if ($step == 3 && $datatoexport)
print ''; // You can use div-table-responsive-no-min if you dont need reserved height for your table
- print '
';
+ print '';
print '';
print ''.$langs->trans("Entities").' ';
//print ''.$langs->trans("ExportableFields").' ';
@@ -782,19 +782,19 @@ if ($step == 3 && $datatoexport)
$tablename = getablenamefromfield($code, $sqlmaxforexport);
$htmltext = ''.$langs->trans("Name").': '.$text.' ';
- if (!empty($objexport->array_export_special[0][$code]))
+ if (!empty($objexport->array_export_special[0][$code]))
{
- $htmltext .= ''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$objexport->array_export_special[0][$code]." ";
+ $htmltext .= ''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$objexport->array_export_special[0][$code]." ";
} else {
- $htmltext .= ''.$langs->trans("Table")." -> ".$langs->trans("Field").": ".$tablename." -> ".preg_replace('/^.*\./', '', $code)." ";
+ $htmltext .= ''.$langs->trans("Table")." -> ".$langs->trans("Field").": ".$tablename." -> ".preg_replace('/^.*\./', '', $code)." ";
}
if (!empty($objexport->array_export_examplevalues[0][$code]))
{
- $htmltext .= ''.$langs->trans("SourceExample").': '.$objexport->array_export_examplevalues[0][$code].' ';
+ $htmltext .= ''.$langs->trans("SourceExample").': '.$objexport->array_export_examplevalues[0][$code].' ';
}
if (!empty($objexport->array_export_TypeFields[0][$code]))
{
- $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].' ';
+ $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].' ';
}
if (!empty($objexport->array_export_help[0][$code]))
{
@@ -824,7 +824,7 @@ if ($step == 3 && $datatoexport)
}
print '
';
- print '';
+ print '';
print '';
@@ -839,214 +839,214 @@ if ($step == 3 && $datatoexport)
if ($step == 4 && $datatoexport)
{
- if (count($array_selected) < 1) // This occurs when going back to page after sessecion expired
- {
- // Switch to step 2
- header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport);
- exit;
- }
+ if (count($array_selected) < 1) // This occurs when going back to page after sessecion expired
+ {
+ // Switch to step 2
+ header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport);
+ exit;
+ }
- asort($array_selected);
+ asort($array_selected);
- llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones');
+ llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones');
- $stepoffset = 0;
- $h = 0;
+ $stepoffset = 0;
+ $h = 0;
- $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
- $head[$h][1] = $langs->trans("Step")." 1";
- $h++;
+ $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
+ $head[$h][1] = $langs->trans("Step")." 1";
+ $h++;
- $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport;
- $head[$h][1] = $langs->trans("Step")." 2";
- $h++;
+ $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport;
+ $head[$h][1] = $langs->trans("Step")." 2";
+ $h++;
- // If filters exist
- if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
- {
- $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport;
- $head[$h][1] = $langs->trans("Step")." 3";
- $h++;
- $stepoffset++;
- }
+ // If filters exist
+ if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
+ {
+ $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport;
+ $head[$h][1] = $langs->trans("Step")." 3";
+ $h++;
+ $stepoffset++;
+ }
- $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=4&datatoexport='.$datatoexport;
- $head[$h][1] = $langs->trans("Step")." ".(3 + $stepoffset);
- $hselected = $h;
- $h++;
+ $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=4&datatoexport='.$datatoexport;
+ $head[$h][1] = $langs->trans("Step")." ".(3 + $stepoffset);
+ $hselected = $h;
+ $h++;
- print dol_get_fiche_head($head, $hselected, $langs->trans("NewExport"), -2);
+ print dol_get_fiche_head($head, $hselected, $langs->trans("NewExport"), -2);
- print '';
- print '
';
- print '
';
+ print '';
+ print '
';
+ print '
';
- // Module
- print ''.$langs->trans("Module").' ';
- print '';
- //print img_object($objexport->array_export_module[0]->getName(),$objexport->array_export_module[0]->picto).' ';
- print $objexport->array_export_module[0]->getName();
- print ' ';
+ // Module
+ print ''.$langs->trans("Module").' ';
+ print '';
+ //print img_object($objexport->array_export_module[0]->getName(),$objexport->array_export_module[0]->picto).' ';
+ print $objexport->array_export_module[0]->getName();
+ print ' ';
- // Lot de donnees a exporter
- print ''.$langs->trans("DatasetToExport").' ';
- print '';
+ // Lot de donnees a exporter
+ print ' '.$langs->trans("DatasetToExport").' ';
+ print '';
$icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]);
- print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
- print $objexport->array_export_label[0];
- print ' ';
+ print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
+ print $objexport->array_export_label[0];
+ print '';
- // List of exported fields
- print ''.$langs->trans("ExportedFields").' ';
- $list = '';
- foreach ($array_selected as $code=>$value)
- {
- $list .= (!empty($list) ? ', ' : '');
- $list .= $langs->trans($objexport->array_export_fields[0][$code]);
- }
- print ''.$list.' ';
- print ' ';
+ // List of exported fields
+ print ''.$langs->trans("ExportedFields").' ';
+ $list = '';
+ foreach ($array_selected as $code=>$value)
+ {
+ $list .= (!empty($list) ? ', ' : '');
+ $list .= $langs->trans($objexport->array_export_fields[0][$code]);
+ }
+ print ''.$list.' ';
+ print ' ';
- // List of filtered fiels
- if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
- {
- print ''.$langs->trans("FilteredFields").' ';
- $list = '';
- if (!empty($array_filtervalue))
- {
- foreach ($array_filtervalue as $code=>$value)
- {
- if (isset($objexport->array_export_fields[0][$code]))
- {
- $list .= ($list ? ', ' : '');
- if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '');
- else $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'";
- }
- }
- }
- print ''.(!empty($list) ? $list : ''.$langs->trans("None").' ').' ';
- print ' ';
- }
+ // List of filtered fiels
+ if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
+ {
+ print ''.$langs->trans("FilteredFields").' ';
+ $list = '';
+ if (!empty($array_filtervalue))
+ {
+ foreach ($array_filtervalue as $code=>$value)
+ {
+ if (isset($objexport->array_export_fields[0][$code]))
+ {
+ $list .= ($list ? ', ' : '');
+ if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '');
+ else $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'";
+ }
+ }
+ }
+ print ''.(!empty($list) ? $list : ''.$langs->trans("None").' ').' ';
+ print ' ';
+ }
- print '
';
- print '
';
+ print '
';
+ print '
';
- print ' ';
+ print ' ';
- // Select request if all fields are selected
- $sqlmaxforexport = $objexport->build_sql(0, array(), array());
+ // Select request if all fields are selected
+ $sqlmaxforexport = $objexport->build_sql(0, array(), array());
- print ''.$langs->trans("ChooseFieldsOrdersAndTitle").'
';
+ print ''.$langs->trans("ChooseFieldsOrdersAndTitle").'
';
- print ''; // You can use div-table-responsive-no-min if you dont need reserved height for your table
- print '
';
- print '';
- print ''.$langs->trans("Entities").' ';
- print ''.$langs->trans("ExportedFields").' ';
- print ''.$langs->trans("Position").' ';
- //print ' ';
- //print ''.$langs->trans("FieldsTitle").' ';
- print ' ';
+ print ''; // You can use div-table-responsive-no-min if you dont need reserved height for your table
+ print '
';
+ print '';
+ print ''.$langs->trans("Entities").' ';
+ print ''.$langs->trans("ExportedFields").' ';
+ print ''.$langs->trans("Position").' ';
+ //print ' ';
+ //print ''.$langs->trans("FieldsTitle").' ';
+ print ' ';
- foreach ($array_selected as $code=>$value)
- {
- print '';
+ foreach ($array_selected as $code=>$value)
+ {
+ print ' ';
- $entity = (!empty($objexport->array_export_entities[0][$code]) ? $objexport->array_export_entities[0][$code] : $objexport->array_export_icon[0]);
- $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
- $entitylang = (!empty($entitytolang[$entity]) ? $entitytolang[$entity] : $entity);
+ $entity = (!empty($objexport->array_export_entities[0][$code]) ? $objexport->array_export_entities[0][$code] : $objexport->array_export_icon[0]);
+ $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
+ $entitylang = (!empty($entitytolang[$entity]) ? $entitytolang[$entity] : $entity);
- print '';
- // If value of entityicon=entitylang='icon:Label'
- $tmparray = explode(':', $entityicon);
- if (count($tmparray) >= 2)
- {
- $entityicon = $tmparray[0];
- $entitylang = $tmparray[1];
- }
- print img_object('', $entityicon).' '.$langs->trans($entitylang);
- print ' ';
+ print '';
+ // If value of entityicon=entitylang='icon:Label'
+ $tmparray = explode(':', $entityicon);
+ if (count($tmparray) >= 2)
+ {
+ $entityicon = $tmparray[0];
+ $entitylang = $tmparray[1];
+ }
+ print img_object('', $entityicon).' '.$langs->trans($entitylang);
+ print ' ';
- $labelName = $objexport->array_export_fields[0][$code];
+ $labelName = $objexport->array_export_fields[0][$code];
$text = (empty($objexport->array_export_special[0][$code]) ? '' : '').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code]) ? '' : ' ');
- $tablename = getablenamefromfield($code, $sqlmaxforexport);
- $htmltext = ''.$langs->trans("Name").': '.$text.' ';
- if (!empty($objexport->array_export_special[0][$code]))
- {
- $htmltext .= ''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$objexport->array_export_special[0][$code]." ";
- } else {
- $htmltext .= ''.$langs->trans("Table")." -> ".$langs->trans("Field").": ".$tablename." -> ".preg_replace('/^.*\./', '', $code)." ";
- }
- if (!empty($objexport->array_export_examplevalues[0][$code]))
- {
- $htmltext .= ''.$langs->trans("SourceExample").': '.$objexport->array_export_examplevalues[0][$code].' ';
- }
- if (!empty($objexport->array_export_TypeFields[0][$code]))
- {
- $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].' ';
- }
- if (!empty($objexport->array_export_help[0][$code]))
- {
- $htmltext .= ''.$langs->trans("Help").': '.$langs->trans($objexport->array_export_help[0][$code]).' ';
- }
+ $tablename = getablenamefromfield($code, $sqlmaxforexport);
+ $htmltext = ''.$langs->trans("Name").': '.$text.' ';
+ if (!empty($objexport->array_export_special[0][$code]))
+ {
+ $htmltext .= ''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$objexport->array_export_special[0][$code]." ";
+ } else {
+ $htmltext .= ''.$langs->trans("Table")." -> ".$langs->trans("Field").": ".$tablename." -> ".preg_replace('/^.*\./', '', $code)." ";
+ }
+ if (!empty($objexport->array_export_examplevalues[0][$code]))
+ {
+ $htmltext .= ''.$langs->trans("SourceExample").': '.$objexport->array_export_examplevalues[0][$code].' ';
+ }
+ if (!empty($objexport->array_export_TypeFields[0][$code]))
+ {
+ $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].' ';
+ }
+ if (!empty($objexport->array_export_help[0][$code]))
+ {
+ $htmltext .= ''.$langs->trans("Help").': '.$langs->trans($objexport->array_export_help[0][$code]).' ';
+ }
- print '';
- print $form->textwithpicto($text, $htmltext);
+ print ' ';
+ print $form->textwithpicto($text, $htmltext);
//print ' ('.$code.')';
- print ' ';
+ print '';
- print '';
- print $value.' ';
- print ' ';
- if ($value < count($array_selected)) print ''.img_down().' ';
- if ($value > 1) print ''.img_up().' ';
- print ' ';
+ print '';
+ print $value.' ';
+ print ' ';
+ if ($value < count($array_selected)) print ''.img_down().' ';
+ if ($value > 1) print ''.img_up().' ';
+ print ' ';
- //print ' ';
- //print ''.$langs->trans($objexport->array_export_fields[0][$code]).' ';
+ //print ' ';
+ //print ''.$langs->trans($objexport->array_export_fields[0][$code]).' ';
- print ' ';
- }
+ print '';
+ }
- print '
';
- print '
';
+ print '
';
+ print '
';
- print '';
+ print '';
- /*
+ /*
* Barre d'action
*
*/
- print '';
// Area for profils export
if (count($array_selected))
- {
+ {
print ' ';
print '';
- print ''.$langs->trans("SaveExportModel").' ';
- print '
';
+ print ''.$langs->trans("SaveExportModel").' ';
+ print '';
print '';
- }
+ print '';
+ }
}
if ($step == 5 && $datatoexport)
{
- if (count($array_selected) < 1) // This occurs when going back to page after sessecion expired
- {
- // Switch to step 2
- header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport);
- exit;
- }
+ if (count($array_selected) < 1) // This occurs when going back to page after sessecion expired
+ {
+ // Switch to step 2
+ header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport);
+ exit;
+ }
asort($array_selected);
- llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones');
+ llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones');
- $h = 0;
- $stepoffset = 0;
+ $h = 0;
+ $stepoffset = 0;
- $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
- $head[$h][1] = $langs->trans("Step")." 1";
- $h++;
+ $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
+ $head[$h][1] = $langs->trans("Step")." 1";
+ $h++;
- $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport;
- $head[$h][1] = $langs->trans("Step")." 2";
- $h++;
+ $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport;
+ $head[$h][1] = $langs->trans("Step")." 2";
+ $h++;
- // si le filtrage est parametre pour l'export ou pas
- if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
- {
- $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport;
- $head[$h][1] = $langs->trans("Step")." 3";
- $h++;
- $stepoffset++;
- }
+ // si le filtrage est parametre pour l'export ou pas
+ if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
+ {
+ $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport;
+ $head[$h][1] = $langs->trans("Step")." 3";
+ $h++;
+ $stepoffset++;
+ }
- $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=4&datatoexport='.$datatoexport;
- $head[$h][1] = $langs->trans("Step")." ".(3 + $stepoffset);
- $h++;
+ $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=4&datatoexport='.$datatoexport;
+ $head[$h][1] = $langs->trans("Step")." ".(3 + $stepoffset);
+ $h++;
- $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=5&datatoexport='.$datatoexport;
- $head[$h][1] = $langs->trans("Step")." ".(4 + $stepoffset);
- $hselected = $h;
- $h++;
+ $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=5&datatoexport='.$datatoexport;
+ $head[$h][1] = $langs->trans("Step")." ".(4 + $stepoffset);
+ $hselected = $h;
+ $h++;
- print dol_get_fiche_head($head, $hselected, $langs->trans("NewExport"), -2);
+ print dol_get_fiche_head($head, $hselected, $langs->trans("NewExport"), -2);
- /*
+ /*
* Confirmation suppression fichier
*/
- if ($action == 'remove_file')
- {
- print $form->formconfirm($_SERVER["PHP_SELF"].'?step=5&datatoexport='.$datatoexport.'&file='.urlencode(GETPOST("file")), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1);
- }
+ if ($action == 'remove_file')
+ {
+ print $form->formconfirm($_SERVER["PHP_SELF"].'?step=5&datatoexport='.$datatoexport.'&file='.urlencode(GETPOST("file")), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1);
+ }
- print '';
- print '
';
+ print '
';
+ print '
';
- print '
';
+ print '';
- // Module
- print ''.$langs->trans("Module").' ';
- print '';
- //print img_object($objexport->array_export_module[0]->getName(),$objexport->array_export_module[0]->picto).' ';
- print $objexport->array_export_module[0]->getName();
- print ' ';
+ // Module
+ print ''.$langs->trans("Module").' ';
+ print '';
+ //print img_object($objexport->array_export_module[0]->getName(),$objexport->array_export_module[0]->picto).' ';
+ print $objexport->array_export_module[0]->getName();
+ print ' ';
- // Dataset to export
- print ''.$langs->trans("DatasetToExport").' ';
- print '';
+ // Dataset to export
+ print ' '.$langs->trans("DatasetToExport").' ';
+ print '';
$icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]);
- print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
- print $objexport->array_export_label[0];
- print ' ';
+ print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
+ print $objexport->array_export_label[0];
+ print '';
- // List of exported fields
- print ''.$langs->trans("ExportedFields").' ';
- $list = '';
- foreach ($array_selected as $code=>$label)
- {
- $list .= (!empty($list) ? ', ' : '');
- $list .= $langs->trans($objexport->array_export_fields[0][$code]);
- }
- print ''.$list.' ';
+ // List of exported fields
+ print ''.$langs->trans("ExportedFields").' ';
+ $list = '';
+ foreach ($array_selected as $code=>$label)
+ {
+ $list .= (!empty($list) ? ', ' : '');
+ $list .= $langs->trans($objexport->array_export_fields[0][$code]);
+ }
+ print ''.$list.' ';
- // List of filtered fields
- if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
- {
- print ''.$langs->trans("FilteredFields").' ';
- $list = '';
- if (!empty($array_filtervalue))
- {
- foreach ($array_filtervalue as $code=>$value)
- {
- if (isset($objexport->array_export_fields[0][$code]))
- {
- $list .= ($list ? ', ' : '');
- if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '');
- else $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'";
- }
- }
- }
- print ''.(!empty($list) ? $list : ''.$langs->trans("None").' ').' ';
- print ' ';
- }
+ // List of filtered fields
+ if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
+ {
+ print ''.$langs->trans("FilteredFields").' ';
+ $list = '';
+ if (!empty($array_filtervalue))
+ {
+ foreach ($array_filtervalue as $code=>$value)
+ {
+ if (isset($objexport->array_export_fields[0][$code]))
+ {
+ $list .= ($list ? ', ' : '');
+ if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '');
+ else $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'";
+ }
+ }
+ }
+ print ''.(!empty($list) ? $list : ''.$langs->trans("None").' ').' ';
+ print ' ';
+ }
- print '
';
- print '';
+ print '
';
+ print '
';
- print '
';
+ print '
';
- // List of available export formats
- $htmltabloflibs = '
';
- $htmltabloflibs .= '';
- $htmltabloflibs .= ''.$langs->trans("AvailableFormats").' ';
- $htmltabloflibs .= ''.$langs->trans("LibraryUsed").' ';
- $htmltabloflibs .= ''.$langs->trans("LibraryVersion").' ';
- $htmltabloflibs .= ' '."\n";
+ // List of available export formats
+ $htmltabloflibs = '';
+ $htmltabloflibs .= '';
+ $htmltabloflibs .= ''.$langs->trans("AvailableFormats").' ';
+ $htmltabloflibs .= ''.$langs->trans("LibraryUsed").' ';
+ $htmltabloflibs .= ''.$langs->trans("LibraryVersion").' ';
+ $htmltabloflibs .= ' '."\n";
- $liste = $objmodelexport->liste_modeles($db);
- $listeall = $liste;
- foreach ($listeall as $key => $val)
- {
- if (preg_match('/__\(Disabled\)__/', $listeall[$key]))
- {
- $listeall[$key] = preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $listeall[$key]);
- unset($liste[$key]);
- }
+ $liste = $objmodelexport->liste_modeles($db);
+ $listeall = $liste;
+ foreach ($listeall as $key => $val)
+ {
+ if (preg_match('/__\(Disabled\)__/', $listeall[$key]))
+ {
+ $listeall[$key] = preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $listeall[$key]);
+ unset($liste[$key]);
+ }
- $htmltabloflibs .= '';
- $htmltabloflibs .= ''.img_picto_common($key, $objmodelexport->getPictoForKey($key)).' ';
- $text = $objmodelexport->getDriverDescForKey($key);
- $label = $listeall[$key];
- $htmltabloflibs .= $form->textwithpicto($label, $text).' ';
- $htmltabloflibs .= ''.$objmodelexport->getLibLabelForKey($key).' ';
- $htmltabloflibs .= ''.$objmodelexport->getLibVersionForKey($key).' ';
- $htmltabloflibs .= ' '."\n";
- }
- $htmltabloflibs .= '
';
+ $htmltabloflibs .= '';
+ $htmltabloflibs .= ''.img_picto_common($key, $objmodelexport->getPictoForKey($key)).' ';
+ $text = $objmodelexport->getDriverDescForKey($key);
+ $label = $listeall[$key];
+ $htmltabloflibs .= $form->textwithpicto($label, $text).' ';
+ $htmltabloflibs .= ''.$objmodelexport->getLibLabelForKey($key).' ';
+ $htmltabloflibs .= ''.$objmodelexport->getLibVersionForKey($key).' ';
+ $htmltabloflibs .= ' '."\n";
+ }
+ $htmltabloflibs .= '
';
- print '
'.$form->textwithpicto($langs->trans("NowClickToGenerateToBuildExportFile"), $htmltabloflibs, 1, 'help', '', 0, 2, 'helphonformat').' ';
- //print $htmltabloflibs;
- print '
';
+ print '
'.$form->textwithpicto($langs->trans("NowClickToGenerateToBuildExportFile"), $htmltabloflibs, 1, 'help', '', 0, 2, 'helphonformat').' ';
+ //print $htmltabloflibs;
+ print '
';
- print '
';
+ print '';
- if ($sqlusedforexport && $user->admin)
- {
- print info_admin($langs->trans("SQLUsedForExport").': '.$sqlusedforexport, 0, 0, 1, '', 'TechnicalInformation');
- }
+ if ($sqlusedforexport && $user->admin)
+ {
+ print info_admin($langs->trans("SQLUsedForExport").': '.$sqlusedforexport, 0, 0, 1, '', 'TechnicalInformation');
+ }
- if (!is_dir($conf->export->dir_temp)) dol_mkdir($conf->export->dir_temp);
+ if (!is_dir($conf->export->dir_temp)) dol_mkdir($conf->export->dir_temp);
- // Show existing generated documents
- // NB: La fonction show_documents rescanne les modules qd genallowed=1, sinon prend $liste
- print $formfile->showdocuments('export', '', $upload_dir, $_SERVER["PHP_SELF"].'?step=5&datatoexport='.$datatoexport, $liste, 1, (!empty($_POST['model']) ? $_POST['model'] : 'csv'), 1, 1, 0, 0, 0, '', 'none', '', '', '');
+ // Show existing generated documents
+ // NB: La fonction show_documents rescanne les modules qd genallowed=1, sinon prend $liste
+ print $formfile->showdocuments('export', '', $upload_dir, $_SERVER["PHP_SELF"].'?step=5&datatoexport='.$datatoexport, $liste, 1, (!empty($_POST['model']) ? $_POST['model'] : 'csv'), 1, 1, 0, 0, 0, '', 'none', '', '', '');
}
llxFooter();
diff --git a/htdocs/exports/index.php b/htdocs/exports/index.php
index 0210ee608b0..79655a19b2f 100644
--- a/htdocs/exports/index.php
+++ b/htdocs/exports/index.php
@@ -50,7 +50,7 @@ print ' ';
print '';
if (count($export->array_export_code))
{
- print dolGetButtonTitle($langs->trans('NewExport'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/exports/export.php?leftmenu=export', '', $user->rights->export->creer);
+ print dolGetButtonTitle($langs->trans('NewExport'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/exports/export.php?leftmenu=export', '', $user->rights->export->creer);
}
print '
';
print ' ';
@@ -73,10 +73,10 @@ $liste = $model->liste_modeles($db); // This is not a static method for exports
foreach ($liste as $key => $val)
{
- if (preg_match('/__\(Disabled\)__/', $liste[$key]))
- {
- $liste[$key] = preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $liste[$key]);
- }
+ if (preg_match('/__\(Disabled\)__/', $liste[$key]))
+ {
+ $liste[$key] = preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $liste[$key]);
+ }
print '';
print ''.img_picto_common($model->getDriverLabelForKey($key), $model->getPictoForKey($key)).' ';
diff --git a/htdocs/fichinter/admin/fichinter_extrafields.php b/htdocs/fichinter/admin/fichinter_extrafields.php
index 84dfeb7cfd3..0fa5a930f05 100644
--- a/htdocs/fichinter/admin/fichinter_extrafields.php
+++ b/htdocs/fichinter/admin/fichinter_extrafields.php
@@ -73,7 +73,7 @@ print dol_get_fiche_head($head, 'attributes', $langs->trans("Interventions"), -1
require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
-dol_fiche_end();
+print dol_get_fiche_end();
// Buttons
diff --git a/htdocs/fichinter/admin/fichinterdet_extrafields.php b/htdocs/fichinter/admin/fichinterdet_extrafields.php
index 5a13bdb4b32..f648548c3b4 100644
--- a/htdocs/fichinter/admin/fichinterdet_extrafields.php
+++ b/htdocs/fichinter/admin/fichinterdet_extrafields.php
@@ -74,15 +74,15 @@ print dol_get_fiche_head($head, 'attributesdet', $langs->trans("Interventions"),
require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php';
-dol_fiche_end();
+print dol_get_fiche_end();
// Buttons
if ($action != 'create' && $action != 'edit')
{
- print '";
+ print '";
}
@@ -97,7 +97,7 @@ if ($action == 'create')
print '
';
print load_fiche_titre($langs->trans('NewAttribute'));
- require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php';
+ require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php';
}
/* ************************************************************************** */
@@ -107,10 +107,10 @@ if ($action == 'create')
/* ************************************************************************** */
if ($action == 'edit' && !empty($attrname))
{
- print " ";
- print load_fiche_titre($langs->trans("FieldEdition", $attrname));
+ print " ";
+ print load_fiche_titre($langs->trans("FieldEdition", $attrname));
- require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php';
+ require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php';
}
llxFooter();
diff --git a/htdocs/fichinter/card-rec.php b/htdocs/fichinter/card-rec.php
index 0a4bbfe922f..975a5dc9698 100644
--- a/htdocs/fichinter/card-rec.php
+++ b/htdocs/fichinter/card-rec.php
@@ -277,7 +277,7 @@ if ($action == 'create') {
// Title
print ' '.$langs->trans("Title").' ';
- print ' ';
+ print ' ';
print ' ';
// Note
@@ -417,7 +417,7 @@ if ($action == 'create') {
print "
\n";
- dol_fiche_end();
+ print dol_get_fiche_end();
print '
';
print ' ';
@@ -438,7 +438,7 @@ if ($action == 'create') {
print '';
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
print '
';
print '
';
@@ -484,11 +484,11 @@ if ($action == 'create') {
$morehtmlref .= '
';
} else {
- $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+ $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
}
} else {
if (!empty($object->fk_project)) {
@@ -543,15 +543,15 @@ if ($action == 'create') {
print '
';
if ($action == 'contrat') {
$formcontract = new Formcontract($db);
- $formcontract->formSelectContract($_SERVER["PHP_SELF"].'?id='.$object->id, $object->socid, $object->fk_contrat, 'contratid', 0, 1);
+ $formcontract->formSelectContract($_SERVER["PHP_SELF"].'?id='.$object->id, $object->socid, $object->fk_contrat, 'contratid', 0, 1);
} else {
if ($object->fk_contrat) {
$contratstatic = new Contrat($db);
$contratstatic->fetch($object->fk_contrat);
print $contratstatic->getNomUrl(0, '', 1);
} else {
- print " ";
- }
+ print " ";
+ }
}
print ' ';
print '';
@@ -633,7 +633,7 @@ if ($action == 'create') {
if ($object->frequency > 0) {
print '
';
if (empty($conf->cron->enabled)) {
- $txtinfoadmin = $langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name"));
+ $txtinfoadmin = $langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name"));
print info_admin($txtinfoadmin);
}
print '
';
@@ -765,20 +765,20 @@ if ($action == 'create') {
$i = 0;
print '
';
print '';
- print_liste_field_titre("Ref", $_SERVER['PHP_SELF'], "f.titre", "", "", 'width="200px"', $sortfield, $sortorder, 'left ');
- print_liste_field_titre("Company", $_SERVER['PHP_SELF'], "s.nom", "", "", 'width="200px"', $sortfield, $sortorder, 'left ');
- if (!empty($conf->contrat->enabled)) {
- print_liste_field_titre("Contract", $_SERVER['PHP_SELF'], "f.fk_contrat", "", "", 'width="100px"', $sortfield, $sortorder, 'left ');
- }
- if (!empty($conf->projet->enabled)) {
- print_liste_field_titre("Project", $_SERVER['PHP_SELF'], "f.fk_project", "", "", 'width="100px"', $sortfield, $sortorder, 'left ');
- }
- print_liste_field_titre("Duration", $_SERVER['PHP_SELF'], 'f.duree', '', '', 'width="50px"', $sortfield, $sortorder, 'right ');
- // Recurring or not
- print_liste_field_titre("Frequency", $_SERVER['PHP_SELF'], "f.frequency", "", "", 'width="100px"', $sortfield, $sortorder, 'center ');
- print_liste_field_titre("NbOfGenerationDone", $_SERVER['PHP_SELF'], "f.nb_gen_done", "", "", 'width="100px"', $sortfield, $sortorder, 'center ');
- print_liste_field_titre("DateLastGeneration", $_SERVER['PHP_SELF'], "f.date_last_gen", "", "", 'width="100px"', $sortfield, $sortorder, 'center ');
- print_liste_field_titre("NextDateToIntervention", $_SERVER['PHP_SELF'], "f.date_when", "", "", 'width="100px"', $sortfield, $sortorder, 'center ');
+ print_liste_field_titre("Ref", $_SERVER['PHP_SELF'], "f.titre", "", "", 'width="200px"', $sortfield, $sortorder, 'left ');
+ print_liste_field_titre("Company", $_SERVER['PHP_SELF'], "s.nom", "", "", 'width="200px"', $sortfield, $sortorder, 'left ');
+ if (!empty($conf->contrat->enabled)) {
+ print_liste_field_titre("Contract", $_SERVER['PHP_SELF'], "f.fk_contrat", "", "", 'width="100px"', $sortfield, $sortorder, 'left ');
+ }
+ if (!empty($conf->projet->enabled)) {
+ print_liste_field_titre("Project", $_SERVER['PHP_SELF'], "f.fk_project", "", "", 'width="100px"', $sortfield, $sortorder, 'left ');
+ }
+ print_liste_field_titre("Duration", $_SERVER['PHP_SELF'], 'f.duree', '', '', 'width="50px"', $sortfield, $sortorder, 'right ');
+ // Recurring or not
+ print_liste_field_titre("Frequency", $_SERVER['PHP_SELF'], "f.frequency", "", "", 'width="100px"', $sortfield, $sortorder, 'center ');
+ print_liste_field_titre("NbOfGenerationDone", $_SERVER['PHP_SELF'], "f.nb_gen_done", "", "", 'width="100px"', $sortfield, $sortorder, 'center ');
+ print_liste_field_titre("DateLastGeneration", $_SERVER['PHP_SELF'], "f.date_last_gen", "", "", 'width="100px"', $sortfield, $sortorder, 'center ');
+ print_liste_field_titre("NextDateToIntervention", $_SERVER['PHP_SELF'], "f.date_when", "", "", 'width="100px"', $sortfield, $sortorder, 'center ');
print ' ';
print " \n";
diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php
index 720e6fe71f3..da1de06cc16 100644
--- a/htdocs/fichinter/card.php
+++ b/htdocs/fichinter/card.php
@@ -1012,7 +1012,7 @@ if ($action == 'create')
print ' ';
}
- dol_fiche_end();
+ print dol_get_fiche_end();
print '';
print ' ';
@@ -1053,7 +1053,7 @@ if ($action == 'create')
print '';
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
print '
';
print '
';
@@ -1588,7 +1588,7 @@ if ($action == 'create')
print ''."\n";
}
- dol_fiche_end();
+ print dol_get_fiche_end();
print "\n";
diff --git a/htdocs/fichinter/class/api_interventions.class.php b/htdocs/fichinter/class/api_interventions.class.php
index c2328e5cfd3..7046a61e2d5 100644
--- a/htdocs/fichinter/class/api_interventions.class.php
+++ b/htdocs/fichinter/class/api_interventions.class.php
@@ -29,193 +29,193 @@
class Interventions extends DolibarrApi
{
- /**
- * @var array $FIELDS Mandatory fields, checked when create and update object
- */
- static $FIELDS = array(
- 'socid',
- 'fk_project',
- 'description',
- );
+ /**
+ * @var array $FIELDS Mandatory fields, checked when create and update object
+ */
+ static $FIELDS = array(
+ 'socid',
+ 'fk_project',
+ 'description',
+ );
- /**
- * @var array $FIELDS Mandatory fields, checked when create and update object
- */
- static $FIELDSLINE = array(
- 'description',
- 'date',
- 'duree',
- );
+ /**
+ * @var array $FIELDS Mandatory fields, checked when create and update object
+ */
+ static $FIELDSLINE = array(
+ 'description',
+ 'date',
+ 'duree',
+ );
- /**
- * @var fichinter $fichinter {@type fichinter}
- */
- public $fichinter;
+ /**
+ * @var fichinter $fichinter {@type fichinter}
+ */
+ public $fichinter;
- /**
- * Constructor
- */
- public function __construct()
- {
- global $db, $conf;
- $this->db = $db;
- $this->fichinter = new Fichinter($this->db);
- }
+ /**
+ * Constructor
+ */
+ public function __construct()
+ {
+ global $db, $conf;
+ $this->db = $db;
+ $this->fichinter = new Fichinter($this->db);
+ }
- /**
- * Get properties of a Expense Report object
- *
- * Return an array with Expense Report information
- *
- * @param int $id ID of Expense Report
- * @return array|mixed Data without useless information
- *
- * @throws RestException
- */
- public function get($id)
- {
- if (!DolibarrApiAccess::$user->rights->ficheinter->lire) {
- throw new RestException(401);
- }
+ /**
+ * Get properties of a Expense Report object
+ *
+ * Return an array with Expense Report information
+ *
+ * @param int $id ID of Expense Report
+ * @return array|mixed Data without useless information
+ *
+ * @throws RestException
+ */
+ public function get($id)
+ {
+ if (!DolibarrApiAccess::$user->rights->ficheinter->lire) {
+ throw new RestException(401);
+ }
- $result = $this->fichinter->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Intervention not found');
- }
+ $result = $this->fichinter->fetch($id);
+ if (!$result) {
+ throw new RestException(404, 'Intervention not found');
+ }
- if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
+ if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
- $this->fichinter->fetchObjectLinked();
- return $this->_cleanObjectDatas($this->fichinter);
- }
+ $this->fichinter->fetchObjectLinked();
+ return $this->_cleanObjectDatas($this->fichinter);
+ }
- /**
- * List of interventions
- *
- * Return a list of interventions
- *
- * @param string $sortfield Sort field
- * @param string $sortorder Sort order
- * @param int $limit Limit for list
- * @param int $page Page number
- * @param string $thirdparty_ids Thirdparty ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
- * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
- * @return array Array of order objects
- *
- * @throws RestException
- */
- public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '')
- {
- global $db, $conf;
+ /**
+ * List of interventions
+ *
+ * Return a list of interventions
+ *
+ * @param string $sortfield Sort field
+ * @param string $sortorder Sort order
+ * @param int $limit Limit for list
+ * @param int $page Page number
+ * @param string $thirdparty_ids Thirdparty ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
+ * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
+ * @return array Array of order objects
+ *
+ * @throws RestException
+ */
+ public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '')
+ {
+ global $db, $conf;
- $obj_ret = array();
+ $obj_ret = array();
- // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
- $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
+ // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
+ $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
- // If the internal user must only see his customers, force searching by him
- $search_sale = 0;
- if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
+ // If the internal user must only see his customers, force searching by him
+ $search_sale = 0;
+ if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
- $sql = "SELECT t.rowid";
- if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
- $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as t";
+ $sql = "SELECT t.rowid";
+ if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
+ $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as t";
- if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
+ if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
- $sql .= ' WHERE t.entity IN ('.getEntity('intervention').')';
- if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
- if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
- if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
- // Insert sale filter
- if ($search_sale > 0) {
- $sql .= " AND sc.fk_user = ".$search_sale;
- }
- // Add sql filters
- if ($sqlfilters)
- {
- if (!DolibarrApi::_checkFilters($sqlfilters))
- {
- throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
- }
- $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
- $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
- }
+ $sql .= ' WHERE t.entity IN ('.getEntity('intervention').')';
+ if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
+ if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
+ if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
+ // Insert sale filter
+ if ($search_sale > 0) {
+ $sql .= " AND sc.fk_user = ".$search_sale;
+ }
+ // Add sql filters
+ if ($sqlfilters)
+ {
+ if (!DolibarrApi::_checkFilters($sqlfilters))
+ {
+ throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
+ }
+ $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
+ $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
+ }
- $sql .= $this->db->order($sortfield, $sortorder);
- if ($limit) {
- if ($page < 0)
- {
- $page = 0;
- }
- $offset = $limit * $page;
+ $sql .= $this->db->order($sortfield, $sortorder);
+ if ($limit) {
+ if ($page < 0)
+ {
+ $page = 0;
+ }
+ $offset = $limit * $page;
- $sql .= $this->db->plimit($limit + 1, $offset);
- }
+ $sql .= $this->db->plimit($limit + 1, $offset);
+ }
- dol_syslog("API Rest request");
- $result = $this->db->query($sql);
+ dol_syslog("API Rest request");
+ $result = $this->db->query($sql);
- if ($result)
- {
- $num = $this->db->num_rows($result);
- $min = min($num, ($limit <= 0 ? $num : $limit));
- $i = 0;
- while ($i < $min)
- {
- $obj = $this->db->fetch_object($result);
- $fichinter_static = new Fichinter($this->db);
- if ($fichinter_static->fetch($obj->rowid)) {
- $obj_ret[] = $this->_cleanObjectDatas($fichinter_static);
- }
- $i++;
- }
- } else {
- throw new RestException(503, 'Error when retrieve intervention list : '.$this->db->lasterror());
- }
- if (!count($obj_ret)) {
- throw new RestException(404, 'No intervention found');
- }
- return $obj_ret;
- }
+ if ($result)
+ {
+ $num = $this->db->num_rows($result);
+ $min = min($num, ($limit <= 0 ? $num : $limit));
+ $i = 0;
+ while ($i < $min)
+ {
+ $obj = $this->db->fetch_object($result);
+ $fichinter_static = new Fichinter($this->db);
+ if ($fichinter_static->fetch($obj->rowid)) {
+ $obj_ret[] = $this->_cleanObjectDatas($fichinter_static);
+ }
+ $i++;
+ }
+ } else {
+ throw new RestException(503, 'Error when retrieve intervention list : '.$this->db->lasterror());
+ }
+ if (!count($obj_ret)) {
+ throw new RestException(404, 'No intervention found');
+ }
+ return $obj_ret;
+ }
- /**
- * Create intervention object
- *
- * @param array $request_data Request data
- * @return int ID of intervention
- */
- public function post($request_data = null)
- {
- if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
- throw new RestException(401, "Insuffisant rights");
- }
- // Check mandatory fields
- $result = $this->_validate($request_data);
- foreach ($request_data as $field => $value) {
- $this->fichinter->$field = $value;
- }
+ /**
+ * Create intervention object
+ *
+ * @param array $request_data Request data
+ * @return int ID of intervention
+ */
+ public function post($request_data = null)
+ {
+ if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
+ throw new RestException(401, "Insuffisant rights");
+ }
+ // Check mandatory fields
+ $result = $this->_validate($request_data);
+ foreach ($request_data as $field => $value) {
+ $this->fichinter->$field = $value;
+ }
- if ($this->fichinter->create(DolibarrApiAccess::$user) < 0) {
- throw new RestException(500, "Error creating intervention", array_merge(array($this->fichinter->error), $this->fichinter->errors));
- }
+ if ($this->fichinter->create(DolibarrApiAccess::$user) < 0) {
+ throw new RestException(500, "Error creating intervention", array_merge(array($this->fichinter->error), $this->fichinter->errors));
+ }
- return $this->fichinter->id;
- }
+ return $this->fichinter->id;
+ }
- /**
- * Get lines of an intervention
- *
- * @param int $id Id of intervention
- *
- * @url GET {id}/lines
- *
- * @return int
- */
- /* TODO
+ /**
+ * Get lines of an intervention
+ *
+ * @param int $id Id of intervention
+ *
+ * @url GET {id}/lines
+ *
+ * @return int
+ */
+ /* TODO
public function getLines($id)
{
if(! DolibarrApiAccess::$user->rights->ficheinter->lire) {
@@ -239,218 +239,218 @@ class Interventions extends DolibarrApi
}
*/
- /**
- * Add a line to given intervention
- *
- * @param int $id Id of intervention to update
- * @param array $request_data Request data
- *
- * @url POST {id}/lines
- *
- * @return int
- */
- public function postLine($id, $request_data = null)
- {
- if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
- throw new RestException(401, "Insuffisant rights");
- }
- // Check mandatory fields
- $result = $this->_validateLine($request_data);
+ /**
+ * Add a line to given intervention
+ *
+ * @param int $id Id of intervention to update
+ * @param array $request_data Request data
+ *
+ * @url POST {id}/lines
+ *
+ * @return int
+ */
+ public function postLine($id, $request_data = null)
+ {
+ if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
+ throw new RestException(401, "Insuffisant rights");
+ }
+ // Check mandatory fields
+ $result = $this->_validateLine($request_data);
- foreach ($request_data as $field => $value) {
- $this->fichinter->$field = $value;
- }
+ foreach ($request_data as $field => $value) {
+ $this->fichinter->$field = $value;
+ }
- if (!$result) {
- throw new RestException(404, 'Intervention not found');
- }
+ if (!$result) {
+ throw new RestException(404, 'Intervention not found');
+ }
- if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
+ if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
- $updateRes = $this->fichinter->addLine(
- DolibarrApiAccess::$user,
- $id,
- $this->fichinter->description,
- $this->fichinter->date,
- $this->fichinter->duree
- );
+ $updateRes = $this->fichinter->addLine(
+ DolibarrApiAccess::$user,
+ $id,
+ $this->fichinter->description,
+ $this->fichinter->date,
+ $this->fichinter->duree
+ );
- if ($updateRes > 0) {
- return $updateRes;
- } else {
- throw new RestException(400, $this->fichinter->error);
- }
- }
+ if ($updateRes > 0) {
+ return $updateRes;
+ } else {
+ throw new RestException(400, $this->fichinter->error);
+ }
+ }
- /**
- * Delete order
- *
- * @param int $id Order ID
- * @return array
- */
- public function delete($id)
- {
- if (!DolibarrApiAccess::$user->rights->ficheinter->supprimer) {
- throw new RestException(401);
- }
- $result = $this->fichinter->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Intervention not found');
- }
+ /**
+ * Delete order
+ *
+ * @param int $id Order ID
+ * @return array
+ */
+ public function delete($id)
+ {
+ if (!DolibarrApiAccess::$user->rights->ficheinter->supprimer) {
+ throw new RestException(401);
+ }
+ $result = $this->fichinter->fetch($id);
+ if (!$result) {
+ throw new RestException(404, 'Intervention not found');
+ }
- if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
+ if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
- if (!$this->fichinter->delete(DolibarrApiAccess::$user)) {
- throw new RestException(500, 'Error when delete intervention : '.$this->fichinter->error);
- }
+ if (!$this->fichinter->delete(DolibarrApiAccess::$user)) {
+ throw new RestException(500, 'Error when delete intervention : '.$this->fichinter->error);
+ }
- return array(
- 'success' => array(
- 'code' => 200,
- 'message' => 'Intervention deleted'
- )
- );
- }
+ return array(
+ 'success' => array(
+ 'code' => 200,
+ 'message' => 'Intervention deleted'
+ )
+ );
+ }
- /**
- * Validate an intervention
- *
- * If you get a bad value for param notrigger check, provide this in body
- * {
- * "notrigger": 0
- * }
- *
- * @param int $id Intervention ID
- * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
- *
- * @url POST {id}/validate
- *
- * @return array
- */
- public function validate($id, $notrigger = 0)
- {
- if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
- throw new RestException(401, "Insuffisant rights");
- }
- $result = $this->fichinter->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Intervention not found');
- }
+ /**
+ * Validate an intervention
+ *
+ * If you get a bad value for param notrigger check, provide this in body
+ * {
+ * "notrigger": 0
+ * }
+ *
+ * @param int $id Intervention ID
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ *
+ * @url POST {id}/validate
+ *
+ * @return array
+ */
+ public function validate($id, $notrigger = 0)
+ {
+ if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
+ throw new RestException(401, "Insuffisant rights");
+ }
+ $result = $this->fichinter->fetch($id);
+ if (!$result) {
+ throw new RestException(404, 'Intervention not found');
+ }
- if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
+ if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
- $result = $this->fichinter->setValid(DolibarrApiAccess::$user, $notrigger);
- if ($result == 0) {
- throw new RestException(304, 'Error nothing done. May be object is already validated');
- }
- if ($result < 0) {
- throw new RestException(500, 'Error when validating Intervention: '.$this->commande->error);
- }
+ $result = $this->fichinter->setValid(DolibarrApiAccess::$user, $notrigger);
+ if ($result == 0) {
+ throw new RestException(304, 'Error nothing done. May be object is already validated');
+ }
+ if ($result < 0) {
+ throw new RestException(500, 'Error when validating Intervention: '.$this->commande->error);
+ }
- $this->fichinter->fetchObjectLinked();
+ $this->fichinter->fetchObjectLinked();
- return $this->_cleanObjectDatas($this->fichinter);
- }
+ return $this->_cleanObjectDatas($this->fichinter);
+ }
- /**
- * Close an intervention
- *
- * @param int $id Intervention ID
- *
- * @url POST {id}/close
- *
- * @return array
- */
- public function closeFichinter($id)
- {
- if (!DolibarrApiAccess::$user->rights->ficheinter->creer)
- {
- throw new RestException(401, "Insuffisant rights");
- }
- $result = $this->fichinter->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Intervention not found');
- }
+ /**
+ * Close an intervention
+ *
+ * @param int $id Intervention ID
+ *
+ * @url POST {id}/close
+ *
+ * @return array
+ */
+ public function closeFichinter($id)
+ {
+ if (!DolibarrApiAccess::$user->rights->ficheinter->creer)
+ {
+ throw new RestException(401, "Insuffisant rights");
+ }
+ $result = $this->fichinter->fetch($id);
+ if (!$result) {
+ throw new RestException(404, 'Intervention not found');
+ }
- if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
+ if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
- $result = $this->fichinter->setStatut(3);
+ $result = $this->fichinter->setStatut(3);
- if ($result == 0) {
- throw new RestException(304, 'Error nothing done. May be object is already closed');
- }
- if ($result < 0) {
- throw new RestException(500, 'Error when closing Intervention: '.$this->fichinter->error);
- }
+ if ($result == 0) {
+ throw new RestException(304, 'Error nothing done. May be object is already closed');
+ }
+ if ($result < 0) {
+ throw new RestException(500, 'Error when closing Intervention: '.$this->fichinter->error);
+ }
- $this->fichinter->fetchObjectLinked();
+ $this->fichinter->fetchObjectLinked();
- return $this->_cleanObjectDatas($this->fichinter);
- }
+ return $this->_cleanObjectDatas($this->fichinter);
+ }
- /**
- * Validate fields before create or update object
- *
- * @param array $data Data to validate
- * @return array
- *
- * @throws RestException
- */
- private function _validate($data)
- {
- $fichinter = array();
- foreach (Interventions::$FIELDS as $field) {
- if (!isset($data[$field]))
- throw new RestException(400, "$field field missing");
- $fichinter[$field] = $data[$field];
- }
- return $fichinter;
- }
+ /**
+ * Validate fields before create or update object
+ *
+ * @param array $data Data to validate
+ * @return array
+ *
+ * @throws RestException
+ */
+ private function _validate($data)
+ {
+ $fichinter = array();
+ foreach (Interventions::$FIELDS as $field) {
+ if (!isset($data[$field]))
+ throw new RestException(400, "$field field missing");
+ $fichinter[$field] = $data[$field];
+ }
+ return $fichinter;
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
- /**
- * Clean sensible object datas
- *
- * @param object $object Object to clean
- * @return array Array of cleaned object properties
- */
- protected function _cleanObjectDatas($object)
- {
- // phpcs:enable
- $object = parent::_cleanObjectDatas($object);
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
+ /**
+ * Clean sensible object datas
+ *
+ * @param Object $object Object to clean
+ * @return Object Object with cleaned properties
+ */
+ protected function _cleanObjectDatas($object)
+ {
+ // phpcs:enable
+ $object = parent::_cleanObjectDatas($object);
- unset($object->statuts_short);
- unset($object->statuts_logo);
- unset($object->statuts);
+ unset($object->statuts_short);
+ unset($object->statuts_logo);
+ unset($object->statuts);
- return $object;
- }
+ return $object;
+ }
- /**
- * Validate fields before create or update object
- *
- * @param array $data Data to validate
- * @return array
- *
- * @throws RestException
- */
- private function _validateLine($data)
- {
- $fichinter = array();
- foreach (Interventions::$FIELDSLINE as $field) {
- if (!isset($data[$field]))
- throw new RestException(400, "$field field missing");
- $fichinter[$field] = $data[$field];
- }
- return $fichinter;
- }
+ /**
+ * Validate fields before create or update object
+ *
+ * @param array $data Data to validate
+ * @return array
+ *
+ * @throws RestException
+ */
+ private function _validateLine($data)
+ {
+ $fichinter = array();
+ foreach (Interventions::$FIELDSLINE as $field) {
+ if (!isset($data[$field]))
+ throw new RestException(400, "$field field missing");
+ $fichinter[$field] = $data[$field];
+ }
+ return $fichinter;
+ }
}
diff --git a/htdocs/fichinter/class/fichinter.class.php b/htdocs/fichinter/class/fichinter.class.php
index 2e79edd8b9e..71cc3c40da5 100644
--- a/htdocs/fichinter/class/fichinter.class.php
+++ b/htdocs/fichinter/class/fichinter.class.php
@@ -6,7 +6,7 @@
* Copyright (C) 2015 Marcos García
* Copyright (C) 2015-2020 Charlene Benke
* Copyright (C) 2018 Nicolas ZABOURI
- * Copyright (C) 2018-2019 Frédéric France
+ * Copyright (C) 2018-2020 Frédéric France
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -100,11 +100,11 @@ class Fichinter extends CommonObject
public $author;
/**
- * Date creation record (datec)
- *
- * @var integer
- */
- public $datec;
+ * Date creation record (datec)
+ *
+ * @var integer
+ */
+ public $datec;
public $datev;
public $dateo;
@@ -112,11 +112,11 @@ class Fichinter extends CommonObject
public $datet;
/**
- * Date modification record (tms)
- *
- * @var integer
- */
- public $datem;
+ * Date modification record (tms)
+ *
+ * @var integer
+ */
+ public $datem;
public $duration;
public $statut = 0; // 0=draft, 1=validated, 2=invoiced, 3=Terminate
@@ -127,13 +127,13 @@ class Fichinter extends CommonObject
public $description;
/**
- * @var int ID
- */
+ * @var int ID
+ */
public $fk_contrat = 0;
/**
- * @var int ID
- */
+ * @var int ID
+ */
public $fk_project = 0;
public $extraparams = array();
@@ -165,22 +165,22 @@ class Fichinter extends CommonObject
*
* @param DoliDB $db Database handler
*/
- public function __construct($db)
- {
+ public function __construct($db)
+ {
$this->db = $db;
$this->products = array();
- }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Load indicators into this->nb for board
*
* @return int <0 if KO, >0 if OK
*/
- public function load_state_board()
+ public function load_state_board()
{
- // phpcs:enable
+ // phpcs:enable
global $user;
$this->nb = array();
@@ -220,11 +220,11 @@ class Fichinter extends CommonObject
* @param int $notrigger Disable all triggers
* @return int <0 if KO, >0 if OK
*/
- public function create($user, $notrigger = 0)
+ public function create($user, $notrigger = 0)
{
global $conf, $langs;
- $error = 0;
+ $error = 0;
dol_syslog(get_class($this)."::create ref=".$this->ref);
@@ -352,9 +352,9 @@ class Fichinter extends CommonObject
* @param int $notrigger Disable all triggers
* @return int <0 if KO, >0 if OK
*/
- public function update($user, $notrigger = 0)
+ public function update($user, $notrigger = 0)
{
- global $conf;
+ global $conf;
if (!is_numeric($this->duration)) {
$this->duration = 0;
@@ -412,7 +412,7 @@ class Fichinter extends CommonObject
* @param string $ref Ref of intervention
* @return int <0 if KO, >0 if OK
*/
- public function fetch($rowid, $ref = '')
+ public function fetch($rowid, $ref = '')
{
$sql = "SELECT f.rowid, f.ref, f.description, f.fk_soc, f.fk_statut,";
$sql .= " f.datec, f.dateo, f.datee, f.datet, f.fk_user_author,";
@@ -449,7 +449,7 @@ class Fichinter extends CommonObject
$this->note_public = $obj->note_public;
$this->note_private = $obj->note_private;
$this->model_pdf = $obj->model_pdf;
- $this->modelpdf = $obj->model_pdf; // deprecated
+ $this->modelpdf = $obj->model_pdf; // deprecated
$this->fk_contrat = $obj->fk_contrat;
$this->user_creation = $obj->fk_user_author;
@@ -484,7 +484,7 @@ class Fichinter extends CommonObject
* @param User $user User that set draft
* @return int <0 if KO, >0 if OK
*/
- public function setDraft($user)
+ public function setDraft($user)
{
global $langs, $conf;
@@ -493,7 +493,7 @@ class Fichinter extends CommonObject
// Protection
if ($this->statut <= self::STATUS_DRAFT)
{
- return 0;
+ return 0;
}
dol_syslog(get_class($this)."::setDraft", LOG_DEBUG);
@@ -507,23 +507,23 @@ class Fichinter extends CommonObject
$resql = $this->db->query($sql);
if ($resql)
{
- if (!$error) {
- $this->oldcopy = clone $this;
- }
-
- if (!$error) {
- // Call trigger
- $result = $this->call_trigger('FICHINTER_UNVALIDATE', $user);
- if ($result < 0) $error++;
- }
+ if (!$error) {
+ $this->oldcopy = clone $this;
+ }
if (!$error) {
- $this->statut = self::STATUS_DRAFT;
- $this->db->commit();
- return 1;
+ // Call trigger
+ $result = $this->call_trigger('FICHINTER_UNVALIDATE', $user);
+ if ($result < 0) $error++;
+ }
+
+ if (!$error) {
+ $this->statut = self::STATUS_DRAFT;
+ $this->db->commit();
+ return 1;
} else {
- $this->db->rollback();
- return -1;
+ $this->db->rollback();
+ return -1;
}
} else {
$this->db->rollback();
@@ -539,7 +539,7 @@ class Fichinter extends CommonObject
* @param int $notrigger 1=Does not execute triggers, 0= execute triggers
* @return int <0 if KO, >0 if OK
*/
- public function setValid($user, $notrigger = 0)
+ public function setValid($user, $notrigger = 0)
{
global $conf;
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
@@ -635,10 +635,6 @@ class Fichinter extends CommonObject
$this->statut = 1;
$this->brouillon = 0;
$this->date_validation = $now;
- }
-
- if (!$error)
- {
$this->db->commit();
return 1;
} else {
@@ -681,7 +677,7 @@ class Fichinter extends CommonObject
* @param int $hidedetails Hide details of lines
* @param int $hidedesc Hide description
* @param int $hideref Hide ref
- * @param null|array $moreparams Array to provide more information
+ * @param null|array $moreparams Array to provide more information
* @return int 0 if KO, 1 if OK
*/
public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
@@ -716,7 +712,7 @@ class Fichinter extends CommonObject
return $this->LibStatut((isset($this->statut) ? $this->statut : $this->status), $mode);
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Returns the label of a status
*
@@ -726,7 +722,7 @@ class Fichinter extends CommonObject
*/
public function LibStatut($status, $mode = 0)
{
- // phpcs:enable
+ // phpcs:enable
// Init/load array of translation of status
if (empty($this->statuts) || empty($this->statuts_short) || empty($this->statuts_logo))
{
@@ -765,11 +761,11 @@ class Fichinter extends CommonObject
$result = '';
- $label = img_picto('', $this->picto).' '.$langs->trans("Intervention").' ';
- $label .= ''.$langs->trans('Ref').': '.$this->ref;
+ $label = img_picto('', $this->picto).' '.$langs->trans("Intervention").' ';
if (isset($this->status)) {
- $label .= ''.$langs->trans("Status").": ".$this->getLibStatut(5);
+ $label .= ' '.$this->getLibStatut(5);
}
+ $label .= ''.$langs->trans('Ref').': '.$this->ref;
$url = DOL_URL_ROOT.'/fichinter/card.php?id='.$this->id;
@@ -970,14 +966,13 @@ class Fichinter extends CommonObject
}
}
- if (!$error)
- {
- $main = MAIN_DB_PREFIX.'fichinterdet';
- $ef = $main."_extrafields";
- $sql = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_fichinter = ".$this->id.")";
+ if (!$error) {
+ $main = MAIN_DB_PREFIX.'fichinterdet';
+ $ef = $main."_extrafields";
+ $sql = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_fichinter = ".$this->id.")";
- $resql = $this->db->query($sql);
- if (!$resql) $error++;
+ $resql = $this->db->query($sql);
+ if (!$resql) $error++;
}
if (!$error)
@@ -1051,17 +1046,17 @@ class Fichinter extends CommonObject
}
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Defines a delivery date of intervention
*
* @param User $user Object user who define
* @param integer $date_delivery date of delivery
* @return int <0 if ko, >0 if ok
- */
- public function set_date_delivery($user, $date_delivery)
- {
- // phpcs:enable
+ */
+ public function set_date_delivery($user, $date_delivery)
+ {
+ // phpcs:enable
global $conf;
if ($user->rights->ficheinter->creer)
@@ -1083,7 +1078,7 @@ class Fichinter extends CommonObject
}
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Define the label of the intervention
*
@@ -1091,9 +1086,9 @@ class Fichinter extends CommonObject
* @param string $description description
* @return int <0 if KO, >0 if OK
*/
- public function set_description($user, $description)
+ public function set_description($user, $description)
{
- // phpcs:enable
+ // phpcs:enable
global $conf;
if ($user->rights->ficheinter->creer)
@@ -1116,7 +1111,7 @@ class Fichinter extends CommonObject
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Link intervention to a contract
*
@@ -1124,9 +1119,9 @@ class Fichinter extends CommonObject
* @param int $contractid Description
* @return int <0 if ko, >0 if ok
*/
- public function set_contrat($user, $contractid)
- {
- // phpcs:enable
+ public function set_contrat($user, $contractid)
+ {
+ // phpcs:enable
global $conf;
if ($user->rights->ficheinter->creer)
@@ -1320,15 +1315,15 @@ class Fichinter extends CommonObject
}
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Load array lines ->lines
*
* @return int <0 if KO, >0 if OK
*/
- public function fetch_lines()
- {
- // phpcs:enable
+ public function fetch_lines()
+ {
+ // phpcs:enable
$this->lines = array();
$sql = 'SELECT rowid, fk_fichinter, description, duree, date, rang';
@@ -1356,6 +1351,7 @@ class Fichinter extends CommonObject
$line->datei = $this->db->jdate($objp->date);
$line->rang = $objp->rang;
$line->product_type = 1;
+ $line->fetch_optionals();
$this->lines[$i] = $line;
@@ -1394,9 +1390,9 @@ class Fichinter extends CommonObject
class FichinterLigne extends CommonObjectLine
{
/**
- * @var DoliDB Database handler.
- */
- public $db;
+ * @var DoliDB Database handler.
+ */
+ public $db;
/**
* @var string Error code (or message)
@@ -1405,8 +1401,8 @@ class FichinterLigne extends CommonObjectLine
// From llx_fichinterdet
/**
- * @var int ID
- */
+ * @var int ID
+ */
public $fk_fichinter;
public $desc; // Description ligne
@@ -1484,7 +1480,7 @@ class FichinterLigne extends CommonObjectLine
{
global $langs, $conf;
- $error = 0;
+ $error = 0;
dol_syslog("FichinterLigne::insert rang=".$this->rang);
@@ -1576,9 +1572,9 @@ class FichinterLigne extends CommonObjectLine
{
global $langs, $conf;
- $error = 0;
+ $error = 0;
- $this->db->begin();
+ $this->db->begin();
// Mise a jour ligne en base
$sql = "UPDATE ".MAIN_DB_PREFIX."fichinterdet SET";
@@ -1629,7 +1625,7 @@ class FichinterLigne extends CommonObjectLine
}
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Update total duration into llx_fichinter
*
@@ -1637,7 +1633,7 @@ class FichinterLigne extends CommonObjectLine
*/
public function update_total()
{
- // phpcs:enable
+ // phpcs:enable
global $conf;
$this->db->begin();
@@ -1696,7 +1692,7 @@ class FichinterLigne extends CommonObjectLine
dol_syslog(get_class($this)."::deleteline lineid=".$this->id);
$this->db->begin();
- $result = $this->deleteExtraFields();
+ $result = $this->deleteExtraFields();
if ($result < 0) {
$error++;
$this->db->rollback();
diff --git a/htdocs/fichinter/class/fichinterstats.class.php b/htdocs/fichinter/class/fichinterstats.class.php
index 608b7d75f25..5df841bf6f2 100644
--- a/htdocs/fichinter/class/fichinterstats.class.php
+++ b/htdocs/fichinter/class/fichinterstats.class.php
@@ -33,183 +33,183 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
*/
class FichinterStats extends Stats
{
- /**
- * @var string Name of table without prefix where object is stored
- */
- public $table_element;
+ /**
+ * @var string Name of table without prefix where object is stored
+ */
+ public $table_element;
- public $socid;
- public $userid;
+ public $socid;
+ public $userid;
- public $from;
- public $field;
- public $where;
+ public $from;
+ public $field;
+ public $where;
- /**
- * Constructor
- *
- * @param DoliDB $db Database handler
- * @param int $socid Id third party for filter. This value must be forced during the new to external user company if user is an external user.
- * @param string $mode Option ('customer', 'supplier')
- * @param int $userid Id user for filter (creation user)
- */
- public function __construct($db, $socid, $mode, $userid = 0)
- {
- global $user, $conf;
+ /**
+ * Constructor
+ *
+ * @param DoliDB $db Database handler
+ * @param int $socid Id third party for filter. This value must be forced during the new to external user company if user is an external user.
+ * @param string $mode Option ('customer', 'supplier')
+ * @param int $userid Id user for filter (creation user)
+ */
+ public function __construct($db, $socid, $mode, $userid = 0)
+ {
+ global $user, $conf;
- $this->db = $db;
+ $this->db = $db;
- $this->socid = ($socid > 0 ? $socid : 0);
- $this->userid = $userid;
- $this->cachefilesuffix = $mode;
+ $this->socid = ($socid > 0 ? $socid : 0);
+ $this->userid = $userid;
+ $this->cachefilesuffix = $mode;
- if ($mode == 'customer')
- {
- $object = new Fichinter($this->db);
- $this->from = MAIN_DB_PREFIX.$object->table_element." as c";
- $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl";
- $this->field = '0';
- $this->field_line = '0';
- //$this->where.= " AND c.fk_statut > 0"; // Not draft and not cancelled
- }
- if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
- $this->where .= ($this->where ? ' AND ' : '')."c.entity IN (".getEntity('fichinter').')';
+ if ($mode == 'customer')
+ {
+ $object = new Fichinter($this->db);
+ $this->from = MAIN_DB_PREFIX.$object->table_element." as c";
+ $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl";
+ $this->field = '0';
+ $this->field_line = '0';
+ //$this->where.= " AND c.fk_statut > 0"; // Not draft and not cancelled
+ }
+ if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
+ $this->where .= ($this->where ? ' AND ' : '')."c.entity IN (".getEntity('fichinter').')';
- if ($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->socid)
+ {
+ $this->where .= " AND c.fk_soc = ".$this->socid;
+ }
+ if ($this->userid > 0) $this->where .= ' AND c.fk_user_author = '.$this->userid;
+ }
- /**
- * Return intervention number by month for a year
- *
- * @param int $year Year to scan
- * @param int $format 0=Label of abscissa is a translated text, 1=Label of abscissa is month number, 2=Label of abscissa is first letter of month
- * @return array Array with number by month
- */
- public function getNbByMonth($year, $format = 0)
- {
- global $user;
+ /**
+ * Return intervention number by month for a year
+ *
+ * @param int $year Year to scan
+ * @param int $format 0=Label of abscissa is a translated text, 1=Label of abscissa is month number, 2=Label of abscissa is first letter of month
+ * @return array Array with number by month
+ */
+ public function getNbByMonth($year, $format = 0)
+ {
+ global $user;
- $sql = "SELECT date_format(c.date_valid,'%m') as dm, COUNT(*) as nb";
- $sql .= " FROM ".$this->from;
- if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
- $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'";
- $sql .= " AND ".$this->where;
- $sql .= " GROUP BY dm";
- $sql .= $this->db->order('dm', 'DESC');
+ $sql = "SELECT date_format(c.date_valid,'%m') as dm, COUNT(*) as nb";
+ $sql .= " FROM ".$this->from;
+ if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+ $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'";
+ $sql .= " AND ".$this->where;
+ $sql .= " GROUP BY dm";
+ $sql .= $this->db->order('dm', 'DESC');
- $res = $this->_getNbByMonth($year, $sql, $format);
- return $res;
- }
+ $res = $this->_getNbByMonth($year, $sql, $format);
+ return $res;
+ }
- /**
- * Return interventions number per year
- *
- * @return array Array with number by year
- *
- */
- public function getNbByYear()
- {
- global $user;
+ /**
+ * Return interventions number per year
+ *
+ * @return array Array with number by year
+ *
+ */
+ public function getNbByYear()
+ {
+ global $user;
- $sql = "SELECT date_format(c.date_valid,'%Y') as dm, COUNT(*) as nb, 0";
- $sql .= " FROM ".$this->from;
- if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
- $sql .= " WHERE ".$this->where;
- $sql .= " GROUP BY dm";
- $sql .= $this->db->order('dm', 'DESC');
+ $sql = "SELECT date_format(c.date_valid,'%Y') as dm, COUNT(*) as nb, 0";
+ $sql .= " FROM ".$this->from;
+ if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+ $sql .= " WHERE ".$this->where;
+ $sql .= " GROUP BY dm";
+ $sql .= $this->db->order('dm', 'DESC');
- return $this->_getNbByYear($sql);
- }
+ return $this->_getNbByYear($sql);
+ }
- /**
- * Return the intervention amount by month for a year
- *
- * @param int $year Year to scan
- * @param int $format 0=Label of abscissa is a translated text, 1=Label of abscissa is month number, 2=Label of abscissa is first letter of month
- * @return array Array with amount by month
- */
- public function getAmountByMonth($year, $format = 0)
- {
- global $user;
+ /**
+ * Return the intervention amount by month for a year
+ *
+ * @param int $year Year to scan
+ * @param int $format 0=Label of abscissa is a translated text, 1=Label of abscissa is month number, 2=Label of abscissa is first letter of month
+ * @return array Array with amount by month
+ */
+ public function getAmountByMonth($year, $format = 0)
+ {
+ global $user;
- $sql = "SELECT date_format(c.date_valid,'%m') as dm, 0";
- $sql .= " FROM ".$this->from;
- if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
- $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'";
- $sql .= " AND ".$this->where;
- $sql .= " GROUP BY dm";
- $sql .= $this->db->order('dm', 'DESC');
+ $sql = "SELECT date_format(c.date_valid,'%m') as dm, 0";
+ $sql .= " FROM ".$this->from;
+ if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+ $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'";
+ $sql .= " AND ".$this->where;
+ $sql .= " GROUP BY dm";
+ $sql .= $this->db->order('dm', 'DESC');
- $res = $this->_getAmountByMonth($year, $sql, $format);
- return $res;
- }
+ $res = $this->_getAmountByMonth($year, $sql, $format);
+ return $res;
+ }
- /**
- * Return the intervention amount average by month for a year
- *
- * @param int $year year for stats
- * @return array array with number by month
- */
- public function getAverageByMonth($year)
- {
- global $user;
+ /**
+ * Return the intervention amount average by month for a year
+ *
+ * @param int $year year for stats
+ * @return array array with number by month
+ */
+ public function getAverageByMonth($year)
+ {
+ global $user;
- $sql = "SELECT date_format(c.date_valid,'%m') as dm, 0";
- $sql .= " FROM ".$this->from;
- if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
- $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'";
- $sql .= " AND ".$this->where;
- $sql .= " GROUP BY dm";
- $sql .= $this->db->order('dm', 'DESC');
+ $sql = "SELECT date_format(c.date_valid,'%m') as dm, 0";
+ $sql .= " FROM ".$this->from;
+ if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+ $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'";
+ $sql .= " AND ".$this->where;
+ $sql .= " GROUP BY dm";
+ $sql .= $this->db->order('dm', 'DESC');
- return $this->_getAverageByMonth($year, $sql);
- }
+ return $this->_getAverageByMonth($year, $sql);
+ }
- /**
- * Return nb, total and average
- *
- * @return array Array of values
- */
- public function getAllByYear()
- {
- global $user;
+ /**
+ * Return nb, total and average
+ *
+ * @return array Array of values
+ */
+ public function getAllByYear()
+ {
+ global $user;
- $sql = "SELECT date_format(c.date_valid,'%Y') as year, COUNT(*) as nb, 0 as total, 0 as avg";
- $sql .= " FROM ".$this->from;
- if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
- $sql .= " WHERE ".$this->where;
- $sql .= " GROUP BY year";
- $sql .= $this->db->order('year', 'DESC');
+ $sql = "SELECT date_format(c.date_valid,'%Y') as year, COUNT(*) as nb, 0 as total, 0 as avg";
+ $sql .= " FROM ".$this->from;
+ if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+ $sql .= " WHERE ".$this->where;
+ $sql .= " GROUP BY year";
+ $sql .= $this->db->order('year', 'DESC');
- return $this->_getAllByYear($sql);
- }
+ return $this->_getAllByYear($sql);
+ }
- /**
- * Return nb, amount of predefined product for year
- *
- * @param int $year Year to scan
- * @param int $limit Limit
- * @return array Array of values
- */
- public function getAllByProduct($year, $limit = 0)
- {
- global $user;
+ /**
+ * Return nb, amount of predefined product for year
+ *
+ * @param int $year Year to scan
+ * @param int $limit Limit
+ * @return array Array of values
+ */
+ public function getAllByProduct($year, $limit = 0)
+ {
+ global $user;
- $sql = "SELECT product.ref, COUNT(product.ref) as nb, 0 as total, 0 as avg";
- $sql .= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product";
- //if (!$user->rights->societe->client->voir && !$user->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
- $sql .= " WHERE ".$this->where;
- $sql .= " AND c.rowid = tl.fk_fichinter AND tl.fk_product = product.rowid";
- $sql .= " AND c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year, 1, false))."' AND '".$this->db->idate(dol_get_last_day($year, 12, false))."'";
- $sql .= " GROUP BY product.ref";
- $sql .= $this->db->order('nb', 'DESC');
- //$sql.= $this->db->plimit(20);
+ $sql = "SELECT product.ref, COUNT(product.ref) as nb, 0 as total, 0 as avg";
+ $sql .= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product";
+ //if (!$user->rights->societe->client->voir && !$user->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+ $sql .= " WHERE ".$this->where;
+ $sql .= " AND c.rowid = tl.fk_fichinter AND tl.fk_product = product.rowid";
+ $sql .= " AND c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year, 1, false))."' AND '".$this->db->idate(dol_get_last_day($year, 12, false))."'";
+ $sql .= " GROUP BY product.ref";
+ $sql .= $this->db->order('nb', 'DESC');
+ //$sql.= $this->db->plimit(20);
- return $this->_getAllByProduct($sql, $limit);
- }
+ return $this->_getAllByProduct($sql, $limit);
+ }
}
diff --git a/htdocs/fichinter/contact.php b/htdocs/fichinter/contact.php
index 8dd498d5242..9b617d06f1b 100644
--- a/htdocs/fichinter/contact.php
+++ b/htdocs/fichinter/contact.php
@@ -46,8 +46,8 @@ $object = new Fichinter($db);
$result = $object->fetch($id, $ref);
if (!$result)
{
- print 'Record not found';
- exit;
+ print 'Record not found';
+ exit;
}
/*
@@ -56,11 +56,11 @@ if (!$result)
if ($action == 'addcontact' && $user->rights->ficheinter->creer)
{
- if ($result > 0 && $id > 0)
- {
- $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int'));
+ if ($result > 0 && $id > 0)
+ {
+ $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int'));
$result = $object->add_contact($contactid, GETPOST('type', 'int'), GETPOST('source', 'alpha'));
- }
+ }
if ($result >= 0)
{
@@ -81,7 +81,7 @@ if ($action == 'addcontact' && $user->rights->ficheinter->creer)
// Toggle the status of a contact
elseif ($action == 'swapstatut' && $user->rights->ficheinter->creer)
{
- $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
+ $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
}
// Deletes a contact
@@ -134,42 +134,42 @@ if ($id > 0 || !empty($ref))
// Project
if (!empty($conf->projet->enabled))
{
- $langs->load("projects");
- $morehtmlref .= ' '.$langs->trans('Project').' ';
- if ($user->rights->ficheinter->creer)
- {
- if ($action != 'classify') {
- //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : ';
- $morehtmlref .= ' : ';
- }
- if ($action == 'classify') {
- //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
- $morehtmlref .= '';
- } else {
- $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
- }
- } else {
- if (!empty($object->fk_project)) {
- $proj = new Project($db);
- $proj->fetch($object->fk_project);
- $morehtmlref .= '';
- $morehtmlref .= $proj->ref;
- $morehtmlref .= ' ';
- } else {
- $morehtmlref .= '';
- }
- }
+ $langs->load("projects");
+ $morehtmlref .= ' '.$langs->trans('Project').' ';
+ if ($user->rights->ficheinter->creer)
+ {
+ if ($action != 'classify') {
+ //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : ';
+ $morehtmlref .= ' : ';
+ }
+ if ($action == 'classify') {
+ //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+ $morehtmlref .= '';
+ } else {
+ $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+ }
+ } else {
+ if (!empty($object->fk_project)) {
+ $proj = new Project($db);
+ $proj->fetch($object->fk_project);
+ $morehtmlref .= '';
+ $morehtmlref .= $proj->ref;
+ $morehtmlref .= ' ';
+ } else {
+ $morehtmlref .= '';
+ }
+ }
}
$morehtmlref .= ' ';
- dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1);
+ dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1);
- dol_fiche_end();
+ print dol_get_fiche_end();
print '
';
@@ -180,8 +180,8 @@ if ($id > 0 || !empty($ref))
$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
foreach ($dirtpls as $reldir)
{
- $res = @include dol_buildpath($reldir.'/contacts.tpl.php');
- if ($res) break;
+ $res = @include dol_buildpath($reldir.'/contacts.tpl.php');
+ if ($res) break;
}
}
diff --git a/htdocs/fichinter/document.php b/htdocs/fichinter/document.php
index e28345534d7..1b9326468f4 100644
--- a/htdocs/fichinter/document.php
+++ b/htdocs/fichinter/document.php
@@ -117,59 +117,59 @@ if ($object->id)
// Project
if (!empty($conf->projet->enabled))
{
- $langs->load("projects");
- $morehtmlref .= '
'.$langs->trans('Project').' ';
- if ($user->rights->commande->creer)
- {
- if ($action != 'classify') {
- //$morehtmlref.='
' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : ';
- $morehtmlref .= ' : ';
- }
- if ($action == 'classify') {
- //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
- $morehtmlref .= '
';
- } else {
- $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
- }
- } else {
- if (!empty($object->fk_project)) {
- $proj = new Project($db);
- $proj->fetch($object->fk_project);
- $morehtmlref .= '
';
- $morehtmlref .= $proj->ref;
- $morehtmlref .= ' ';
- } else {
- $morehtmlref .= '';
- }
- }
+ $langs->load("projects");
+ $morehtmlref .= '
'.$langs->trans('Project').' ';
+ if ($user->rights->commande->creer)
+ {
+ if ($action != 'classify') {
+ //$morehtmlref.='
' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : ';
+ $morehtmlref .= ' : ';
+ }
+ if ($action == 'classify') {
+ //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+ $morehtmlref .= '
';
+ } else {
+ $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+ }
+ } else {
+ if (!empty($object->fk_project)) {
+ $proj = new Project($db);
+ $proj->fetch($object->fk_project);
+ $morehtmlref .= '
';
+ $morehtmlref .= $proj->ref;
+ $morehtmlref .= ' ';
+ } else {
+ $morehtmlref .= '';
+ }
+ }
}
$morehtmlref .= '
';
- dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+ dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
- print '
';
- print '
';
+ print '
';
+ print '
';
- print '
';
- print ''.$langs->trans("NbOfAttachedFiles").' '.count($filearray).' ';
- print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.dol_print_size($totalsize, 1, 1).' ';
- print '
';
+ print '
';
+ print ''.$langs->trans("NbOfAttachedFiles").' '.count($filearray).' ';
+ print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.dol_print_size($totalsize, 1, 1).' ';
+ print '
';
- print '
';
+ print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
- $modulepart = 'ficheinter';
- $permission = $user->rights->ficheinter->creer;
- $permtoedit = $user->rights->ficheinter->creer;
- $param = '&id='.$object->id;
- include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
+ $modulepart = 'ficheinter';
+ $permission = $user->rights->ficheinter->creer;
+ $permtoedit = $user->rights->ficheinter->creer;
+ $param = '&id='.$object->id;
+ include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
} else {
print $langs->trans("ErrorUnknown");
}
diff --git a/htdocs/fichinter/index.php b/htdocs/fichinter/index.php
index ccadf89f1e4..3ea69f8d185 100644
--- a/htdocs/fichinter/index.php
+++ b/htdocs/fichinter/index.php
@@ -68,16 +68,16 @@ print '
';
if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo
{
- // Search ficheinter
- $var = false;
- print '
\n";
+ // Search ficheinter
+ $var = false;
+ print '
\n";
}
@@ -97,90 +97,90 @@ $sql .= " GROUP BY f.fk_statut";
$resql = $db->query($sql);
if ($resql)
{
- $num = $db->num_rows($resql);
- $i = 0;
+ $num = $db->num_rows($resql);
+ $i = 0;
- $total = 0;
- $totalinprocess = 0;
- $dataseries = array();
- $vals = array();
- $bool = false;
- // -1=Canceled, 0=Draft, 1=Validated, 2=Accepted/On process, 3=Closed (Sent/Received, billed or not)
- while ($i < $num)
- {
- $row = $db->fetch_row($resql);
- if ($row)
- {
- //if ($row[1]!=-1 && ($row[1]!=3 || $row[2]!=1))
- {
- $bool = (!empty($row[2]) ?true:false);
- if (!isset($vals[$row[1].$bool])) $vals[$row[1].$bool] = 0;
- $vals[$row[1].$bool] += $row[0];
- $totalinprocess += $row[0];
- }
- $total += $row[0];
- }
- $i++;
- }
- $db->free($resql);
+ $total = 0;
+ $totalinprocess = 0;
+ $dataseries = array();
+ $vals = array();
+ $bool = false;
+ // -1=Canceled, 0=Draft, 1=Validated, 2=Accepted/On process, 3=Closed (Sent/Received, billed or not)
+ while ($i < $num)
+ {
+ $row = $db->fetch_row($resql);
+ if ($row)
+ {
+ //if ($row[1]!=-1 && ($row[1]!=3 || $row[2]!=1))
+ {
+ $bool = (!empty($row[2]) ?true:false);
+ if (!isset($vals[$row[1].$bool])) $vals[$row[1].$bool] = 0;
+ $vals[$row[1].$bool] += $row[0];
+ $totalinprocess += $row[0];
+ }
+ $total += $row[0];
+ }
+ $i++;
+ }
+ $db->free($resql);
- include_once DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php';
+ include_once DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php';
- print '
';
- print '
';
- print ''.$langs->trans("Statistics").' - '.$langs->trans("Interventions").' '."\n";
- $listofstatus = array(0, 1, 3);
- $bool = false;
- foreach ($listofstatus as $status)
- {
- $dataseries[] = array($fichinterstatic->LibStatut($status, $bool, 1), (isset($vals[$status.$bool]) ? (int) $vals[$status.$bool] : 0));
- if ($status == 3 && !$bool) $bool = true;
- else $bool = false;
+ print '';
+ print '
';
+ print ''.$langs->trans("Statistics").' - '.$langs->trans("Interventions").' '."\n";
+ $listofstatus = array(0, 1, 3);
+ $bool = false;
+ foreach ($listofstatus as $status)
+ {
+ $dataseries[] = array($fichinterstatic->LibStatut($status, $bool, 1), (isset($vals[$status.$bool]) ? (int) $vals[$status.$bool] : 0));
+ if ($status == 3 && !$bool) $bool = true;
+ else $bool = false;
- if ($status == Fichinter::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0;
- if ($status == Fichinter::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus1;
- if ($status == Fichinter::STATUS_BILLED) $colorseries[$status] = $badgeStatus4;
- if ($status == Fichinter::STATUS_CLOSED) $colorseries[$status] = $badgeStatus6;
- }
- if ($conf->use_javascript_ajax)
- {
- print '';
+ if ($status == Fichinter::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0;
+ if ($status == Fichinter::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus1;
+ if ($status == Fichinter::STATUS_BILLED) $colorseries[$status] = $badgeStatus4;
+ if ($status == Fichinter::STATUS_CLOSED) $colorseries[$status] = $badgeStatus6;
+ }
+ if ($conf->use_javascript_ajax)
+ {
+ print ' ';
- include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
- $dolgraph = new DolGraph();
- $dolgraph->SetData($dataseries);
- $dolgraph->SetDataColor(array_values($colorseries));
- $dolgraph->setShowLegend(2);
- $dolgraph->setShowPercent(1);
- $dolgraph->SetType(array('pie'));
- $dolgraph->setHeight('200');
- $dolgraph->draw('idgraphstatus');
- print $dolgraph->show($total ? 0 : 1);
+ include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
+ $dolgraph = new DolGraph();
+ $dolgraph->SetData($dataseries);
+ $dolgraph->SetDataColor(array_values($colorseries));
+ $dolgraph->setShowLegend(2);
+ $dolgraph->setShowPercent(1);
+ $dolgraph->SetType(array('pie'));
+ $dolgraph->setHeight('200');
+ $dolgraph->draw('idgraphstatus');
+ print $dolgraph->show($total ? 0 : 1);
- print ' ';
- }
- $bool = false;
- foreach ($listofstatus as $status)
- {
- if (!$conf->use_javascript_ajax)
- {
- print '';
- print ''.$fichinterstatic->LibStatut($status, $bool, 0).' ';
- print ''.(isset($vals[$status.$bool]) ? $vals[$status.$bool] : 0).' ';
- print $fichinterstatic->LibStatut($status, $bool, 3);
- print ' ';
- print ' ';
- print " \n";
- if ($status == 3 && !$bool) $bool = true;
- else $bool = false;
- }
- }
- //if ($totalinprocess != $total)
- //print ''.$langs->trans("Total").' ('.$langs->trans("CustomersOrdersRunning").') '.$totalinprocess.' ';
- print ''.$langs->trans("Total").' '.$total.' ';
- print "
";
+ print '';
+ }
+ $bool = false;
+ foreach ($listofstatus as $status)
+ {
+ if (!$conf->use_javascript_ajax)
+ {
+ print '';
+ print ''.$fichinterstatic->LibStatut($status, $bool, 0).' ';
+ print ''.(isset($vals[$status.$bool]) ? $vals[$status.$bool] : 0).' ';
+ print $fichinterstatic->LibStatut($status, $bool, 3);
+ print ' ';
+ print ' ';
+ print " \n";
+ if ($status == 3 && !$bool) $bool = true;
+ else $bool = false;
+ }
+ }
+ //if ($totalinprocess != $total)
+ //print ''.$langs->trans("Total").' ('.$langs->trans("CustomersOrdersRunning").') '.$totalinprocess.' ';
+ print ''.$langs->trans("Total").' '.$total.' ';
+ print "
";
} else {
- dol_print_error($db);
+ dol_print_error($db);
}
@@ -202,7 +202,7 @@ if (!empty($conf->ficheinter->enabled))
$resql = $db->query($sql);
if ($resql)
{
- print '
';
+ print '
';
print '
';
print '';
print ''.$langs->trans("DraftFichinter").' ';
@@ -251,7 +251,7 @@ $sql .= $db->plimit($max, 0);
$resql = $db->query($sql);
if ($resql)
{
- print '';
+ print '
';
print '
';
print '';
print ''.$langs->trans("LastModifiedInterventions", $max).' ';
@@ -321,7 +321,7 @@ if (!empty($conf->ficheinter->enabled))
{
$num = $db->num_rows($resql);
- print '';
+ print '
';
print '
';
print '';
print ''.$langs->trans("FichinterToProcess").' '.$num.' ';
diff --git a/htdocs/fichinter/info.php b/htdocs/fichinter/info.php
index 320a29f4171..a53c69b77bd 100644
--- a/htdocs/fichinter/info.php
+++ b/htdocs/fichinter/info.php
@@ -124,7 +124,7 @@ print '
';
print '
';
-dol_fiche_end();
+print dol_get_fiche_end();
llxFooter();
$db->close();
diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php
index f6b95678f9d..bdf60e121e7 100644
--- a/htdocs/fichinter/list.php
+++ b/htdocs/fichinter/list.php
@@ -180,10 +180,10 @@ $formfile = new FormFile($db);
$objectstatic = new Fichinter($db);
$companystatic = new Societe($db);
if (!empty($conf->projet->enabled)) {
- $projetstatic = new Project($db);
+ $projetstatic = new Project($db);
}
if (!empty($conf->contrat->enabled)) {
- $contratstatic = new Contrat($db);
+ $contratstatic = new Contrat($db);
}
$title = $langs->trans("ListOfInterventions");
@@ -195,11 +195,11 @@ $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfi
$atleastonefieldinlines = 0;
foreach ($arrayfields as $tmpkey => $tmpval)
{
- if (preg_match('/^fd\./', $tmpkey) && !empty($arrayfields[$tmpkey]['checked']))
- {
- $atleastonefieldinlines++;
- break;
- }
+ if (preg_match('/^fd\./', $tmpkey) && !empty($arrayfields[$tmpkey]['checked']))
+ {
+ $atleastonefieldinlines++;
+ break;
+ }
}
$sql = "SELECT";
@@ -207,10 +207,10 @@ $sql .= " f.ref, f.rowid, f.fk_statut as status, f.description, f.datec as date_
if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) $sql .= " fd.rowid as lineid, fd.description as descriptiondetail, fd.date as dp, fd.duree,";
$sql .= " s.nom as name, s.rowid as socid, s.client, s.fournisseur, s.email, s.status as thirdpartystatus";
if (!empty($conf->projet->enabled)) {
- $sql .= ", pr.rowid as projet_id, pr.ref as projet_ref, pr.title as projet_title";
+ $sql .= ", pr.rowid as projet_id, pr.ref as projet_ref, pr.title as projet_title";
}
if (!empty($conf->contrat->enabled)) {
- $sql .= ", c.rowid as contrat_id, c.ref as contrat_ref, c.ref_customer as contrat_ref_supplier, c.ref_supplier as contrat_ref_supplier";
+ $sql .= ", c.rowid as contrat_id, c.ref as contrat_ref, c.ref_customer as contrat_ref_supplier, c.ref_supplier as contrat_ref_supplier";
}
// Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) {
@@ -222,10 +222,10 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // N
$sql .= $hookmanager->resPrint;
$sql .= " FROM ".MAIN_DB_PREFIX."fichinter as f";
if (!empty($conf->projet->enabled)) {
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr on f.fk_projet = pr.rowid";
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr on f.fk_projet = pr.rowid";
}
if (!empty($conf->contrat->enabled)) {
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contrat as c on f.fk_contrat = c.rowid";
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contrat as c on f.fk_contrat = c.rowid";
}
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 (f.rowid = ef.fk_object)";
if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."fichinterdet as fd ON fd.fk_fichinter = f.rowid";
@@ -240,10 +240,10 @@ if ($search_company) {
$sql .= natural_search('s.nom', $search_company);
}
if ($search_projet_ref) {
- $sql .= natural_search('pr.ref', $search_projet_ref);
+ $sql .= natural_search('pr.ref', $search_projet_ref);
}
if ($search_contrat_ref) {
- $sql .= natural_search('c.ref', $search_contrat_ref);
+ $sql .= natural_search('c.ref', $search_contrat_ref);
}
if ($search_desc) {
if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) $sql .= natural_search(array('f.description', 'fd.description'), $search_desc);
@@ -315,7 +315,7 @@ if ($resql)
$arrayofmassactions = array(
'generate_doc'=>$langs->trans("ReGeneratePDF"),
'builddoc'=>$langs->trans("PDFMerge"),
- //'presend'=>$langs->trans("SendByMail"),
+ //'presend'=>$langs->trans("SendByMail"),
);
if ($user->rights->ficheinter->supprimer) $arrayofmassactions['predelete'] = '
'.$langs->trans("Delete");
if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
@@ -383,18 +383,18 @@ if ($resql)
print '
';
print '';
}
- if (!empty($arrayfields['pr.ref']['checked']))
- {
- print '
';
- print ' ';
- print ' ';
- }
- if (!empty($arrayfields['c.ref']['checked']))
- {
- print '
';
- print ' ';
- print ' ';
- }
+ if (!empty($arrayfields['pr.ref']['checked']))
+ {
+ print '
';
+ print ' ';
+ print ' ';
+ }
+ if (!empty($arrayfields['c.ref']['checked']))
+ {
+ print '
';
+ print ' ';
+ print ' ';
+ }
if (!empty($arrayfields['f.description']['checked']))
{
print '
';
@@ -442,18 +442,18 @@ if ($resql)
print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 1);
print ' ';
}
- // Fields of detail line
+ // Fields of detail line
if (!empty($arrayfields['fd.description']['checked']))
{
- print '
';
+ print '
';
}
if (!empty($arrayfields['fd.date']['checked']))
{
- print '
';
+ print '
';
}
if (!empty($arrayfields['fd.duree']['checked']))
{
- print '
';
+ print '
';
}
print '
';
$searchpicto = $form->showFilterButtons();
@@ -550,31 +550,31 @@ if ($resql)
print ' ';
if (!$i) $totalarray['nbfield']++;
}
- if (!empty($arrayfields['pr.ref']['checked']))
- {
- print '
';
- $projetstatic->id = $obj->projet_id;
- $projetstatic->ref = $obj->projet_ref;
- $projetstatic->title = $obj->projet_title;
- if ($projetstatic->id > 0) {
- print $projetstatic->getNomUrl(1, '');
- }
- print ' ';
- if (!$i) $totalarray['nbfield']++;
- }
- if (!empty($arrayfields['c.ref']['checked']))
- {
- print '
';
- $contratstatic->id = $obj->contrat_id;
- $contratstatic->ref = $obj->contrat_ref;
- $contratstatic->ref_customer = $obj->contrat_ref_customer;
- $contratstatic->ref_supplier = $obj->contrat_ref_supplier;
- if ($contratstatic->id > 0) {
- print $contratstatic->getNomUrl(1, '');
- print ' ';
- }
- if (!$i) $totalarray['nbfield']++;
- }
+ if (!empty($arrayfields['pr.ref']['checked']))
+ {
+ print '
';
+ $projetstatic->id = $obj->projet_id;
+ $projetstatic->ref = $obj->projet_ref;
+ $projetstatic->title = $obj->projet_title;
+ if ($projetstatic->id > 0) {
+ print $projetstatic->getNomUrl(1, '');
+ }
+ print ' ';
+ if (!$i) $totalarray['nbfield']++;
+ }
+ if (!empty($arrayfields['c.ref']['checked']))
+ {
+ print '
';
+ $contratstatic->id = $obj->contrat_id;
+ $contratstatic->ref = $obj->contrat_ref;
+ $contratstatic->ref_customer = $obj->contrat_ref_customer;
+ $contratstatic->ref_supplier = $obj->contrat_ref_supplier;
+ if ($contratstatic->id > 0) {
+ print $contratstatic->getNomUrl(1, '');
+ print ' ';
+ }
+ if (!$i) $totalarray['nbfield']++;
+ }
if (!empty($arrayfields['f.description']['checked']))
{
print '
'.dol_trunc(dolGetFirstLineOfText($obj->description), 48).' ';
@@ -628,20 +628,20 @@ if ($resql)
// Fields of detail of line
if (!empty($arrayfields['fd.description']['checked']))
{
- print '
'.dolGetFirstLineOfText($obj->descriptiondetail).' ';
- if (!$i) $totalarray['nbfield']++;
+ print '
'.dolGetFirstLineOfText($obj->descriptiondetail).' ';
+ if (!$i) $totalarray['nbfield']++;
}
if (!empty($arrayfields['fd.date']['checked']))
{
- print '
'.dol_print_date($db->jdate($obj->dp), 'dayhour')." \n";
- if (!$i) $totalarray['nbfield']++;
+ print '
'.dol_print_date($db->jdate($obj->dp), 'dayhour')." \n";
+ if (!$i) $totalarray['nbfield']++;
}
if (!empty($arrayfields['fd.duree']['checked']))
{
- print '
'.convertSecondToTime($obj->duree, 'allhourmin').' ';
- if (!$i) $totalarray['nbfield']++;
- if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'fd.duree';
- $totalarray['val']['fd.duree'] += $obj->duree;
+ print '
'.convertSecondToTime($obj->duree, 'allhourmin').' ';
+ if (!$i) $totalarray['nbfield']++;
+ if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'fd.duree';
+ $totalarray['val']['fd.duree'] += $obj->duree;
}
// Action column
print '
';
diff --git a/htdocs/fichinter/note.php b/htdocs/fichinter/note.php
index fd18040d037..dddbe79e33e 100644
--- a/htdocs/fichinter/note.php
+++ b/htdocs/fichinter/note.php
@@ -82,40 +82,40 @@ if ($id > 0 || !empty($ref))
// Project
if (!empty($conf->projet->enabled))
{
- $langs->load("projects");
- $morehtmlref .= ' '.$langs->trans('Project').' ';
- if ($user->rights->commande->creer)
- {
- if ($action != 'classify') {
- //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : ';
- $morehtmlref .= ' : ';
- }
- if ($action == 'classify') {
- //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
- $morehtmlref .= '';
- } else {
- $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
- }
- } else {
- if (!empty($object->fk_project)) {
- $proj = new Project($db);
- $proj->fetch($object->fk_project);
- $morehtmlref .= '';
- $morehtmlref .= $proj->ref;
- $morehtmlref .= ' ';
- } else {
- $morehtmlref .= '';
- }
- }
+ $langs->load("projects");
+ $morehtmlref .= ' '.$langs->trans('Project').' ';
+ if ($user->rights->commande->creer)
+ {
+ if ($action != 'classify') {
+ //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : ';
+ $morehtmlref .= ' : ';
+ }
+ if ($action == 'classify') {
+ //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+ $morehtmlref .= '';
+ } else {
+ $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+ }
+ } else {
+ if (!empty($object->fk_project)) {
+ $proj = new Project($db);
+ $proj->fetch($object->fk_project);
+ $morehtmlref .= '';
+ $morehtmlref .= $proj->ref;
+ $morehtmlref .= ' ';
+ } else {
+ $morehtmlref .= '';
+ }
+ }
}
$morehtmlref .= '';
- dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+ dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
print '';
print '
';
@@ -125,7 +125,7 @@ if ($id > 0 || !empty($ref))
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
}
llxFooter();
diff --git a/htdocs/fichinter/stats/index.php b/htdocs/fichinter/stats/index.php
index 45d4c2c2c7d..093e0e4e73d 100644
--- a/htdocs/fichinter/stats/index.php
+++ b/htdocs/fichinter/stats/index.php
@@ -37,8 +37,8 @@ $socid = GETPOST('socid', 'int');
// Security check
if ($user->socid > 0)
{
- $action = '';
- $socid = $user->socid;
+ $action = '';
+ $socid = $user->socid;
}
$nowyear = strftime("%Y", dol_now());
@@ -79,36 +79,36 @@ $data = $stats->getNbByMonthWithPrevYear($endyear, $startyear);
if (!$user->rights->societe->client->voir || $user->socid)
{
- $filenamenb = $dir.'/interventionsnbinyear-'.$user->id.'-'.$year.'.png';
- $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsnbinyear-'.$user->id.'-'.$year.'.png';
+ $filenamenb = $dir.'/interventionsnbinyear-'.$user->id.'-'.$year.'.png';
+ $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsnbinyear-'.$user->id.'-'.$year.'.png';
} else {
- $filenamenb = $dir.'/interventionsnbinyear-'.$year.'.png';
- $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsnbinyear-'.$year.'.png';
+ $filenamenb = $dir.'/interventionsnbinyear-'.$year.'.png';
+ $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsnbinyear-'.$year.'.png';
}
$px1 = new DolGraph();
$mesg = $px1->isGraphKo();
if (!$mesg)
{
- $px1->SetData($data);
- $i = $startyear; $legend = array();
- while ($i <= $endyear)
- {
- $legend[] = $i;
- $i++;
- }
- $px1->SetLegend($legend);
- $px1->SetMaxValue($px1->GetCeilMaxValue());
- $px1->SetMinValue(min(0, $px1->GetFloorMinValue()));
- $px1->SetWidth($WIDTH);
- $px1->SetHeight($HEIGHT);
- $px1->SetYLabel($langs->trans("NbOfIntervention"));
- $px1->SetShading(3);
- $px1->SetHorizTickIncrement(1);
- $px1->mode = 'depth';
- $px1->SetTitle($langs->trans("NumberOfInterventionsByMonth"));
+ $px1->SetData($data);
+ $i = $startyear; $legend = array();
+ while ($i <= $endyear)
+ {
+ $legend[] = $i;
+ $i++;
+ }
+ $px1->SetLegend($legend);
+ $px1->SetMaxValue($px1->GetCeilMaxValue());
+ $px1->SetMinValue(min(0, $px1->GetFloorMinValue()));
+ $px1->SetWidth($WIDTH);
+ $px1->SetHeight($HEIGHT);
+ $px1->SetYLabel($langs->trans("NbOfIntervention"));
+ $px1->SetShading(3);
+ $px1->SetHorizTickIncrement(1);
+ $px1->mode = 'depth';
+ $px1->SetTitle($langs->trans("NumberOfInterventionsByMonth"));
- $px1->draw($filenamenb, $fileurlnb);
+ $px1->draw($filenamenb, $fileurlnb);
}
// Build graphic amount of object
@@ -117,36 +117,36 @@ $data = $stats->getAmountByMonthWithPrevYear($endyear, $startyear);
if (!$user->rights->societe->client->voir || $user->socid)
{
- $filenameamount = $dir.'/interventionsamountinyear-'.$user->id.'-'.$year.'.png';
- $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsamountinyear-'.$user->id.'-'.$year.'.png';
+ $filenameamount = $dir.'/interventionsamountinyear-'.$user->id.'-'.$year.'.png';
+ $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsamountinyear-'.$user->id.'-'.$year.'.png';
} else {
- $filenameamount = $dir.'/interventionsamountinyear-'.$year.'.png';
- $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsamountinyear-'.$year.'.png';
+ $filenameamount = $dir.'/interventionsamountinyear-'.$year.'.png';
+ $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsamountinyear-'.$year.'.png';
}
$px2 = new DolGraph();
$mesg = $px2->isGraphKo();
if (!$mesg)
{
- $px2->SetData($data);
- $i = $startyear; $legend = array();
- while ($i <= $endyear)
- {
- $legend[] = $i;
- $i++;
- }
- $px2->SetLegend($legend);
- $px2->SetMaxValue($px2->GetCeilMaxValue());
- $px2->SetMinValue(min(0, $px2->GetFloorMinValue()));
- $px2->SetWidth($WIDTH);
- $px2->SetHeight($HEIGHT);
- $px2->SetYLabel($langs->trans("AmountOfinterventions"));
- $px2->SetShading(3);
- $px2->SetHorizTickIncrement(1);
- $px2->mode = 'depth';
- $px2->SetTitle($langs->trans("AmountOfinterventionsByMonthHT"));
+ $px2->SetData($data);
+ $i = $startyear; $legend = array();
+ while ($i <= $endyear)
+ {
+ $legend[] = $i;
+ $i++;
+ }
+ $px2->SetLegend($legend);
+ $px2->SetMaxValue($px2->GetCeilMaxValue());
+ $px2->SetMinValue(min(0, $px2->GetFloorMinValue()));
+ $px2->SetWidth($WIDTH);
+ $px2->SetHeight($HEIGHT);
+ $px2->SetYLabel($langs->trans("AmountOfinterventions"));
+ $px2->SetShading(3);
+ $px2->SetHorizTickIncrement(1);
+ $px2->mode = 'depth';
+ $px2->SetTitle($langs->trans("AmountOfinterventionsByMonthHT"));
- $px2->draw($filenameamount, $fileurlamount);
+ $px2->draw($filenameamount, $fileurlamount);
}
@@ -154,36 +154,36 @@ $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear);
if (!$user->rights->societe->client->voir || $user->socid)
{
- $filename_avg = $dir.'/interventionsaverage-'.$user->id.'-'.$year.'.png';
- $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsaverage-'.$user->id.'-'.$year.'.png';
+ $filename_avg = $dir.'/interventionsaverage-'.$user->id.'-'.$year.'.png';
+ $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsaverage-'.$user->id.'-'.$year.'.png';
} else {
- $filename_avg = $dir.'/interventionsaverage-'.$year.'.png';
- $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsaverage-'.$year.'.png';
+ $filename_avg = $dir.'/interventionsaverage-'.$year.'.png';
+ $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsaverage-'.$year.'.png';
}
$px3 = new DolGraph();
$mesg = $px3->isGraphKo();
if (!$mesg)
{
- $px3->SetData($data);
- $i = $startyear; $legend = array();
- while ($i <= $endyear)
- {
- $legend[] = $i;
- $i++;
- }
- $px3->SetLegend($legend);
- $px3->SetYLabel($langs->trans("AmountAverage"));
- $px3->SetMaxValue($px3->GetCeilMaxValue());
- $px3->SetMinValue($px3->GetFloorMinValue());
- $px3->SetWidth($WIDTH);
- $px3->SetHeight($HEIGHT);
- $px3->SetShading(3);
- $px3->SetHorizTickIncrement(1);
- $px3->mode = 'depth';
- $px3->SetTitle($langs->trans("AmountAverage"));
+ $px3->SetData($data);
+ $i = $startyear; $legend = array();
+ while ($i <= $endyear)
+ {
+ $legend[] = $i;
+ $i++;
+ }
+ $px3->SetLegend($legend);
+ $px3->SetYLabel($langs->trans("AmountAverage"));
+ $px3->SetMaxValue($px3->GetCeilMaxValue());
+ $px3->SetMinValue($px3->GetFloorMinValue());
+ $px3->SetWidth($WIDTH);
+ $px3->SetHeight($HEIGHT);
+ $px3->SetShading(3);
+ $px3->SetHorizTickIncrement(1);
+ $px3->mode = 'depth';
+ $px3->SetTitle($langs->trans("AmountAverage"));
- $px3->draw($filename_avg, $fileurl_avg);
+ $px3->draw($filename_avg, $fileurl_avg);
}
@@ -226,7 +226,7 @@ print '';
print '
'.$langs->trans("Filter").' ';
// Company
print '
'.$langs->trans("ThirdParty").' ';
- $filter = 's.client IN (1,2,3)';
+ $filter = 's.client IN (1,2,3)';
print $form->select_company($socid, 'socid', $filter, 1, 0, 0, array(), 0, '', 'style="width: 95%"');
print ' ';
// User
@@ -270,7 +270,7 @@ foreach ($data as $val)
$year = $val['year'];
while (!empty($year) && $oldyear > $year + 1)
{
- // If we have empty year
+ // If we have empty year
$oldyear--;
print '
';
@@ -308,8 +308,8 @@ print '';
// Show graphs
print '
';
if ($mesg) { print $mesg; } else {
- print $px1->show();
- /*print " \n";
+ print $px1->show();
+ /*print " \n";
print $px2->show();
print " \n";
print $px3->show();*/
@@ -320,7 +320,7 @@ print '
';
print '
';
print '
';
-dol_fiche_end();
+print dol_get_fiche_end();
llxFooter();
diff --git a/htdocs/fichinter/tpl/linkedobjectblock.tpl.php b/htdocs/fichinter/tpl/linkedobjectblock.tpl.php
index b9a4399200d..b483e877e5e 100644
--- a/htdocs/fichinter/tpl/linkedobjectblock.tpl.php
+++ b/htdocs/fichinter/tpl/linkedobjectblock.tpl.php
@@ -38,10 +38,10 @@ $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1)
$ilink = 0;
foreach ($linkedObjectBlock as $key => $objectlink)
{
- $ilink++;
+ $ilink++;
- $trclass = 'oddeven';
- if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total';
+ $trclass = 'oddeven';
+ if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total';
?>
trans("Intervention"); ?>
diff --git a/htdocs/filefunc.inc.php b/htdocs/filefunc.inc.php
index 45dfd4b8760..1942ecd35a7 100644
--- a/htdocs/filefunc.inc.php
+++ b/htdocs/filefunc.inc.php
@@ -75,34 +75,34 @@ $result = @include_once $conffile; // Keep @ because with some error reporting t
if (!$result && !empty($_SERVER["GATEWAY_INTERFACE"])) // If install not done and we are in a web session
{
- if (!empty($_SERVER["CONTEXT_PREFIX"])) // CONTEXT_PREFIX and CONTEXT_DOCUMENT_ROOT are not defined on all apache versions
- {
- $path = $_SERVER["CONTEXT_PREFIX"]; // example '/dolibarr/' when using an apache alias.
- if (!preg_match('/\/$/', $path)) $path .= '/';
- }
- elseif (preg_match('/index\.php/', $_SERVER['PHP_SELF']))
- {
- // When we ask index.php, we MUST BE SURE that $path is '' at the end. This is required to make install process
- // when using apache alias like '/dolibarr/' that point to htdocs.
- // Note: If calling page was an index.php not into htdocs (ie comm/index.php, ...), then this redirect will fails,
- // but we don't want to change this because when URL is correct, we must be sure the redirect to install/index.php will be correct.
- $path = '';
- } else {
- // If what we look is not index.php, we can try to guess location of root. May not work all the time.
- // There is no real solution, because the only way to know the apache url relative path is to have it into conf file.
- // If it fails to find correct $path, then only solution is to ask user to enter the correct URL to index.php or install/index.php
- $TDir = explode('/', $_SERVER['PHP_SELF']);
- $path = '';
- $i = count($TDir);
- while ($i--)
- {
- if (empty($TDir[$i]) || $TDir[$i] == 'htdocs') break;
- if ($TDir[$i] == 'dolibarr') break;
- if (substr($TDir[$i], -4, 4) == '.php') continue;
+ if (!empty($_SERVER["CONTEXT_PREFIX"])) // CONTEXT_PREFIX and CONTEXT_DOCUMENT_ROOT are not defined on all apache versions
+ {
+ $path = $_SERVER["CONTEXT_PREFIX"]; // example '/dolibarr/' when using an apache alias.
+ if (!preg_match('/\/$/', $path)) $path .= '/';
+ }
+ elseif (preg_match('/index\.php/', $_SERVER['PHP_SELF']))
+ {
+ // When we ask index.php, we MUST BE SURE that $path is '' at the end. This is required to make install process
+ // when using apache alias like '/dolibarr/' that point to htdocs.
+ // Note: If calling page was an index.php not into htdocs (ie comm/index.php, ...), then this redirect will fails,
+ // but we don't want to change this because when URL is correct, we must be sure the redirect to install/index.php will be correct.
+ $path = '';
+ } else {
+ // If what we look is not index.php, we can try to guess location of root. May not work all the time.
+ // There is no real solution, because the only way to know the apache url relative path is to have it into conf file.
+ // If it fails to find correct $path, then only solution is to ask user to enter the correct URL to index.php or install/index.php
+ $TDir = explode('/', $_SERVER['PHP_SELF']);
+ $path = '';
+ $i = count($TDir);
+ while ($i--)
+ {
+ if (empty($TDir[$i]) || $TDir[$i] == 'htdocs') break;
+ if ($TDir[$i] == 'dolibarr') break;
+ if (substr($TDir[$i], -4, 4) == '.php') continue;
- $path .= '../';
- }
- }
+ $path .= '../';
+ }
+ }
header("Location: ".$path."install/index.php");
exit;
@@ -149,24 +149,24 @@ if (empty($dolibarr_strict_mode)) $dolibarr_strict_mode = 0; // For debug in php
if (!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck))
{
if (!empty($_SERVER['REQUEST_METHOD']) && !in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) && !empty($_SERVER['HTTP_HOST']))
- {
- $csrfattack = false;
- if (empty($_SERVER['HTTP_REFERER'])) $csrfattack = true; // An evil browser was used
- else {
- $tmpa = parse_url($_SERVER['HTTP_HOST']);
- $tmpb = parse_url($_SERVER['HTTP_REFERER']);
- if ((empty($tmpa['host']) ? $tmpa['path'] : $tmpa['host']) != (empty($tmpb['host']) ? $tmpb['path'] : $tmpb['host'])) $csrfattack = true;
- }
- if ($csrfattack)
- {
- //print 'NOCSRFCHECK='.defined('NOCSRFCHECK').' REQUEST_METHOD='.$_SERVER['REQUEST_METHOD'].' HTTP_HOST='.$_SERVER['HTTP_HOST'].' HTTP_REFERER='.$_SERVER['HTTP_REFERER'];
- // Note: We can't use dol_escape_htmltag here to escape output because lib functions.lib.ph is not yet loaded.
- print "Access refused by CSRF protection in main.inc.php. Referer of form (".htmlentities($_SERVER['HTTP_REFERER'], ENT_COMPAT, 'UTF-8').") is outside the server that serve this page (with method = ".htmlentities($_SERVER['REQUEST_METHOD'], ENT_COMPAT, 'UTF-8').").\n";
- print "If you access your server behind a proxy using url rewriting, you might check that all HTTP headers are propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file to remove this security check).\n";
- die;
- }
- }
- // Another test is done later on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on.
+ {
+ $csrfattack = false;
+ if (empty($_SERVER['HTTP_REFERER'])) $csrfattack = true; // An evil browser was used
+ else {
+ $tmpa = parse_url($_SERVER['HTTP_HOST']);
+ $tmpb = parse_url($_SERVER['HTTP_REFERER']);
+ if ((empty($tmpa['host']) ? $tmpa['path'] : $tmpa['host']) != (empty($tmpb['host']) ? $tmpb['path'] : $tmpb['host'])) $csrfattack = true;
+ }
+ if ($csrfattack)
+ {
+ //print 'NOCSRFCHECK='.defined('NOCSRFCHECK').' REQUEST_METHOD='.$_SERVER['REQUEST_METHOD'].' HTTP_HOST='.$_SERVER['HTTP_HOST'].' HTTP_REFERER='.$_SERVER['HTTP_REFERER'];
+ // Note: We can't use dol_escape_htmltag here to escape output because lib functions.lib.ph is not yet loaded.
+ print "Access refused by CSRF protection in main.inc.php. Referer of form (".htmlentities($_SERVER['HTTP_REFERER'], ENT_COMPAT, 'UTF-8').") is outside the server that serve this page (with method = ".htmlentities($_SERVER['REQUEST_METHOD'], ENT_COMPAT, 'UTF-8').").\n";
+ print "If you access your server behind a proxy using url rewriting, you might check that all HTTP headers are propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file to remove this security check).\n";
+ die;
+ }
+ }
+ // Another test is done later on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on.
}
if (empty($dolibarr_main_db_host))
{
@@ -197,27 +197,27 @@ $tmp = '';
$found = 0;
$real_dolibarr_main_document_root = str_replace('\\', '/', realpath($dolibarr_main_document_root)); // A) Value found into config file, to say where are store htdocs files. Ex: C:/xxx/dolibarr, C:/xxx/dolibarr/htdocs
if (!empty($_SERVER["DOCUMENT_ROOT"])) {
- $pathroot = $_SERVER["DOCUMENT_ROOT"]; // B) Value reported by web server setup (not defined on CLI mode), to say where is root of web server instance. Ex: C:/xxx/dolibarr, C:/xxx/dolibarr/htdocs
+ $pathroot = $_SERVER["DOCUMENT_ROOT"]; // B) Value reported by web server setup (not defined on CLI mode), to say where is root of web server instance. Ex: C:/xxx/dolibarr, C:/xxx/dolibarr/htdocs
} else {
- $pathroot = 'NOTDEFINED';
+ $pathroot = 'NOTDEFINED';
}
$paths = explode('/', str_replace('\\', '/', $_SERVER["SCRIPT_NAME"])); // C) Value reported by web server, to say full path on filesystem of a file. Ex: /dolibarr/htdocs/admin/system/phpinfo.php
// Try to detect if $_SERVER["DOCUMENT_ROOT"]+start of $_SERVER["SCRIPT_NAME"] is $dolibarr_main_document_root. If yes, relative url to add before dol files is this start part.
$concatpath = '';
foreach ($paths as $tmppath) // We check to find (B+start of C)=A
{
- if (empty($tmppath)) continue;
- $concatpath .= '/'.$tmppath;
- //if ($tmppath) $concatpath.='/'.$tmppath;
- //print $_SERVER["SCRIPT_NAME"].'-'.$pathroot.'-'.$concatpath.'-'.$real_dolibarr_main_document_root.'-'.realpath($pathroot.$concatpath).' ';
- if ($real_dolibarr_main_document_root == @realpath($pathroot.$concatpath)) // @ avoid warning when safe_mode is on.
- {
- //print "Found relative url = ".$concatpath;
- $tmp3 = $concatpath;
- $found = 1;
- break;
- }
- //else print "Not found yet for concatpath=".$concatpath." \n";
+ if (empty($tmppath)) continue;
+ $concatpath .= '/'.$tmppath;
+ //if ($tmppath) $concatpath.='/'.$tmppath;
+ //print $_SERVER["SCRIPT_NAME"].'-'.$pathroot.'-'.$concatpath.'-'.$real_dolibarr_main_document_root.'-'.realpath($pathroot.$concatpath).' ';
+ if ($real_dolibarr_main_document_root == @realpath($pathroot.$concatpath)) // @ avoid warning when safe_mode is on.
+ {
+ //print "Found relative url = ".$concatpath;
+ $tmp3 = $concatpath;
+ $found = 1;
+ break;
+ }
+ //else print "Not found yet for concatpath=".$concatpath." \n";
}
//print "found=".$found." dolibarr_main_url_root=".$dolibarr_main_url_root."\n";
if (!$found) $tmp = $dolibarr_main_url_root; // If autodetect fails (Ie: when using apache alias that point outside default DOCUMENT_ROOT).
diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php
index e6a1a6a5a8c..85ab93d17ec 100644
--- a/htdocs/fourn/card.php
+++ b/htdocs/fourn/card.php
@@ -85,8 +85,8 @@ if (empty($reshook))
{
$result = $object->fetch($id);
$object->code_compta_fournisseur = $_POST["supplieraccountancycode"];
- $result = $object->update($object->id, $user, 1, 0, 1);
- if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
+ $result = $object->update($object->id, $user, 1, 0, 1);
+ if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
}
// terms of the settlement
if ($action == 'setconditions' && $user->rights->societe->creer)
@@ -113,23 +113,23 @@ if (empty($reshook))
}
if ($action == 'update_extras') {
- $object->fetch($id);
+ $object->fetch($id);
- $object->oldcopy = dol_clone($object);
+ $object->oldcopy = dol_clone($object);
- // Fill array 'array_options' with data from update form
- $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
+ // Fill array 'array_options' with data from update form
+ $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
- if ($ret < 0) $error++;
+ if ($ret < 0) $error++;
- if (!$error)
- {
- $result = $object->insertExtraFields('COMPANY_MODIFY');
- if ($result < 0) $error++;
- }
+ if (!$error)
+ {
+ $result = $object->insertExtraFields('COMPANY_MODIFY');
+ if ($result < 0) $error++;
+ }
- if ($error) $action = 'edit_extras';
- }
+ if ($error) $action = 'edit_extras';
+ }
}
@@ -167,31 +167,31 @@ if ($object->id > 0)
print '';
- print '
';
+ print '
';
print '
';
- if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field
- {
- print ''.$langs->trans('Prefix').' '.$object->prefix_comm.' ';
- }
+ if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field
+ {
+ print ''.$langs->trans('Prefix').' '.$object->prefix_comm.' ';
+ }
if ($object->fournisseur)
{
print '';
- print ''.$langs->trans("SupplierCode").' ';
- print $object->code_fournisseur;
- if ($object->check_codefournisseur() <> 0) print ' ('.$langs->trans("WrongSupplierCode").') ';
- print ' ';
- print ' ';
+ print ''.$langs->trans("SupplierCode").' ';
+ print $object->code_fournisseur;
+ if ($object->check_codefournisseur() <> 0) print ' ('.$langs->trans("WrongSupplierCode").') ';
+ print ' ';
+ print '';
$langs->load('compta');
- print '';
- print '';
- print $form->editfieldkey("SupplierAccountancyCode", 'supplieraccountancycode', $object->code_compta_fournisseur, $object, $user->rights->societe->creer);
- print ' ';
- print $form->editfieldval("SupplierAccountancyCode", 'supplieraccountancycode', $object->code_compta_fournisseur, $object, $user->rights->societe->creer);
- print ' ';
- print ' ';
+ print '';
+ print '';
+ print $form->editfieldkey("SupplierAccountancyCode", 'supplieraccountancycode', $object->code_compta_fournisseur, $object, $user->rights->societe->creer);
+ print ' ';
+ print $form->editfieldval("SupplierAccountancyCode", 'supplieraccountancycode', $object->code_compta_fournisseur, $object, $user->rights->societe->creer);
+ print ' ';
+ print ' ';
}
// Assujetti a TVA ou pas
@@ -217,10 +217,10 @@ if ($object->id > 0)
print '';
}
- // TVA Intra
- print ''.$langs->trans('VATIntra').' ';
- print $object->tva_intra;
- print ' ';
+ // TVA Intra
+ print ''.$langs->trans('VATIntra').' ';
+ print $object->tva_intra;
+ print ' ';
// Default terms of the settlement
$langs->load('bills');
@@ -306,11 +306,11 @@ if ($object->id > 0)
// Categories
if (!empty($conf->categorie->enabled))
{
- $langs->load("categories");
- print ''.$langs->trans("SuppliersCategoriesShort").' ';
- print '';
- print $form->showCategories($object->id, Categorie::TYPE_SUPPLIER, 1);
- print " ";
+ $langs->load("categories");
+ print ''.$langs->trans("SuppliersCategoriesShort").' ';
+ print '';
+ print $form->showCategories($object->id, Categorie::TYPE_SUPPLIER, 1);
+ print " ";
}
// Other attributes
@@ -318,24 +318,24 @@ if ($object->id > 0)
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
// Module Adherent
- if (!empty($conf->adherent->enabled))
- {
- $langs->load("members");
- $langs->load("users");
- print ''.$langs->trans("LinkedToDolibarrMember").' ';
- print '';
- $adh = new Adherent($db);
- $result = $adh->fetch('', '', $object->id);
- if ($result > 0)
- {
- $adh->ref = $adh->getFullName($langs);
- print $adh->getNomUrl(1);
- } else {
- print $langs->trans("ThirdpartyNotLinkedToMember");
- }
- print ' ';
- print " \n";
- }
+ if (!empty($conf->adherent->enabled))
+ {
+ $langs->load("members");
+ $langs->load("users");
+ print ''.$langs->trans("LinkedToDolibarrMember").' ';
+ print '';
+ $adh = new Adherent($db);
+ $result = $adh->fetch('', '', $object->id);
+ if ($result > 0)
+ {
+ $adh->ref = $adh->getFullName($langs);
+ print $adh->getNomUrl(1);
+ } else {
+ print $langs->trans("ThirdpartyNotLinkedToMember");
+ }
+ print ' ';
+ print " \n";
+ }
print '
';
@@ -356,67 +356,67 @@ if ($object->id > 0)
if ($conf->supplier_proposal->enabled)
{
- // Box proposals
- $tmp = $object->getOutstandingProposals('supplier');
- $outstandingOpened = $tmp['opened'];
- $outstandingTotal = $tmp['total_ht'];
- $outstandingTotalIncTax = $tmp['total_ttc'];
- $text = $langs->trans("OverAllSupplierProposals");
- $link = DOL_URL_ROOT.'/supplier_proposal/list.php?socid='.$object->id;
- $icon = 'bill';
- if ($link) $boxstat .= '
';
- $boxstat .= '';
- $boxstat .= ''.img_object("", $icon).' '.$text.' ';
- $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).' ';
- $boxstat .= '
';
- if ($link) $boxstat .= ' ';
+ // Box proposals
+ $tmp = $object->getOutstandingProposals('supplier');
+ $outstandingOpened = $tmp['opened'];
+ $outstandingTotal = $tmp['total_ht'];
+ $outstandingTotalIncTax = $tmp['total_ttc'];
+ $text = $langs->trans("OverAllSupplierProposals");
+ $link = DOL_URL_ROOT.'/supplier_proposal/list.php?socid='.$object->id;
+ $icon = 'bill';
+ if ($link) $boxstat .= '
';
+ $boxstat .= '';
+ $boxstat .= ''.img_object("", $icon).' '.$text.' ';
+ $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).' ';
+ $boxstat .= '
';
+ if ($link) $boxstat .= ' ';
}
if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))
{
- // Box proposals
- $tmp = $object->getOutstandingOrders('supplier');
- $outstandingOpened = $tmp['opened'];
- $outstandingTotal = $tmp['total_ht'];
- $outstandingTotalIncTax = $tmp['total_ttc'];
- $text = $langs->trans("OverAllOrders");
- $link = DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->id;
- $icon = 'bill';
- if ($link) $boxstat .= '
';
- $boxstat .= '';
- $boxstat .= ''.img_object("", $icon).' '.$text.' ';
- $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).' ';
- $boxstat .= '
';
- if ($link) $boxstat .= ' ';
+ // Box proposals
+ $tmp = $object->getOutstandingOrders('supplier');
+ $outstandingOpened = $tmp['opened'];
+ $outstandingTotal = $tmp['total_ht'];
+ $outstandingTotalIncTax = $tmp['total_ttc'];
+ $text = $langs->trans("OverAllOrders");
+ $link = DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->id;
+ $icon = 'bill';
+ if ($link) $boxstat .= '
';
+ $boxstat .= '';
+ $boxstat .= ''.img_object("", $icon).' '.$text.' ';
+ $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).' ';
+ $boxstat .= '
';
+ if ($link) $boxstat .= ' ';
}
if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))
{
- $tmp = $object->getOutstandingBills('supplier');
- $outstandingOpened = $tmp['opened'];
- $outstandingTotal = $tmp['total_ht'];
- $outstandingTotalIncTax = $tmp['total_ttc'];
+ $tmp = $object->getOutstandingBills('supplier');
+ $outstandingOpened = $tmp['opened'];
+ $outstandingTotal = $tmp['total_ht'];
+ $outstandingTotalIncTax = $tmp['total_ttc'];
- $text = $langs->trans("OverAllInvoices");
- $link = DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->id;
- $icon = 'bill';
- if ($link) $boxstat .= '
';
- $boxstat .= '';
- $boxstat .= ''.img_object("", $icon).' '.$text.' ';
- $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).' ';
- $boxstat .= '
';
- if ($link) $boxstat .= ' ';
+ $text = $langs->trans("OverAllInvoices");
+ $link = DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->id;
+ $icon = 'bill';
+ if ($link) $boxstat .= '
';
+ $boxstat .= '';
+ $boxstat .= ''.img_object("", $icon).' '.$text.' ';
+ $boxstat .= ''.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).' ';
+ $boxstat .= '
';
+ if ($link) $boxstat .= ' ';
- // Box outstanding bill
- $text = $langs->trans("CurrentOutstandingBill");
- $link = DOL_URL_ROOT.'/fourn/recap-fourn.php?socid='.$object->id;
- $icon = 'bill';
- if ($link) $boxstat .= '
';
- $boxstat .= '';
- $boxstat .= ''.img_object("", $icon).' '.$text.' ';
- $boxstat .= ''.price($outstandingOpened, 1, $langs, 1, -1, -1, $conf->currency).$warn.' ';
- $boxstat .= '
';
- if ($link) $boxstat .= ' ';
+ // Box outstanding bill
+ $text = $langs->trans("CurrentOutstandingBill");
+ $link = DOL_URL_ROOT.'/fourn/recap-fourn.php?socid='.$object->id;
+ $icon = 'bill';
+ if ($link) $boxstat .= '
';
+ $boxstat .= '';
+ $boxstat .= ''.img_object("", $icon).' '.$text.' ';
+ $boxstat .= ''.price($outstandingOpened, 1, $langs, 1, -1, -1, $conf->currency).$warn.' ';
+ $boxstat .= '
';
+ if ($link) $boxstat .= ' ';
$tmp = $object->getOutstandingBills('supplier', 1);
$outstandingOpenedLate = $tmp['opened'];
@@ -425,9 +425,9 @@ if ($object->id > 0)
$link = DOL_URL_ROOT.'/fourn/recap-fourn.php?socid='.$object->id;
$icon = 'bill';
if ($link) $boxstat .= '
';
- $boxstat .= '';
- $boxstat .= '
' . img_object("", $icon) . ' ' . $text . ' ';
- $boxstat .= '
'.price($outstandingOpenedLate, 1, $langs, 1, -1, -1, $conf->currency) . $warn . ' ';
+ $boxstat .= '
';
+ $boxstat .= ''.img_object("", $icon).' '.$text.' ';
+ $boxstat .= ''.price($outstandingOpenedLate, 1, $langs, 1, -1, -1, $conf->currency).$warn.' ';
$boxstat .= '
';
if ($link) $boxstat .= '';
}
@@ -470,15 +470,15 @@ if ($object->id > 0)
$sql .= $db->plimit($MAXLIST);
$query = $db->query($sql);
- if (!$query) dol_print_error($db);
+ if (!$query) dol_print_error($db);
- $num = $db->num_rows($query);
+ $num = $db->num_rows($query);
- print '
';
- print '';
- print ''.$langs->trans("ProductsAndServices").' ';
- print ''.$langs->trans("AllProductReferencesOfSupplier").''.$object->nbOfProductRefs().' ';
- print ' ';
+ print '';
+ print '';
+ print ''.$langs->trans("ProductsAndServices").' ';
+ print ''.$langs->trans("AllProductReferencesOfSupplier").''.$object->nbOfProductRefs().' ';
+ print ' ';
$return = array();
if ($num > 0)
@@ -508,12 +508,12 @@ if ($object->id > 0)
//print (isset($objp->unitprice) ? price($objp->unitprice) : '');
if (isset($objp->price))
{
- print price($objp->price);
- if ($objp->quantity > 1)
- {
- print ' / ';
- print $objp->quantity;
- }
+ print price($objp->price);
+ if ($objp->quantity > 1)
+ {
+ print ' / ';
+ print $objp->quantity;
+ }
}
print '';
print '';
@@ -531,63 +531,63 @@ if ($object->id > 0)
if ($user->rights->supplier_proposal->lire)
{
- $sql = "SELECT p.rowid, p.ref, p.date_valid as dc, p.fk_statut, p.total_ht, p.tva as total_tva, p.total as total_ttc";
- $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p ";
- $sql .= " WHERE p.fk_soc =".$object->id;
- $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
- $sql .= " ORDER BY p.date_valid DESC";
- $sql .= " ".$db->plimit($MAXLIST);
+ $sql = "SELECT p.rowid, p.ref, p.date_valid as dc, p.fk_statut, p.total_ht, p.tva as total_tva, p.total as total_ttc";
+ $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p ";
+ $sql .= " WHERE p.fk_soc =".$object->id;
+ $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
+ $sql .= " ORDER BY p.date_valid DESC";
+ $sql .= " ".$db->plimit($MAXLIST);
- $resql = $db->query($sql);
- if ($resql)
- {
- $i = 0;
- $num = $db->num_rows($resql);
+ $resql = $db->query($sql);
+ if ($resql)
+ {
+ $i = 0;
+ $num = $db->num_rows($resql);
- if ($num > 0)
- {
- print '';
+ if ($num > 0)
+ {
+ print '';
- print '';
- print '';
- print '';
- print ' ';
- }
+ print '';
+ print '';
+ print '';
+ print ' ';
+ }
- while ($i < $num && $i <= $MAXLIST)
- {
- $obj = $db->fetch_object($resql);
+ while ($i < $num && $i <= $MAXLIST)
+ {
+ $obj = $db->fetch_object($resql);
- print '';
- print '';
- $proposalstatic->id = $obj->rowid;
- $proposalstatic->ref = $obj->ref;
- $proposalstatic->total_ht = $obj->total_ht;
- $proposalstatic->total_tva = $obj->total_tva;
- $proposalstatic->total_ttc = $obj->total_ttc;
- print $proposalstatic->getNomUrl(1);
- print ' ';
- print '';
- if ($obj->dc)
- {
- print dol_print_date($db->jdate($obj->dc), 'day');
- } else {
- print "-";
- }
- print ' ';
- print ''.$proposalstatic->LibStatut($obj->fk_statut, 5).' ';
- print ' ';
- $i++;
- }
- $db->free($resql);
+ print '';
+ print '';
+ $proposalstatic->id = $obj->rowid;
+ $proposalstatic->ref = $obj->ref;
+ $proposalstatic->total_ht = $obj->total_ht;
+ $proposalstatic->total_tva = $obj->total_tva;
+ $proposalstatic->total_ttc = $obj->total_ttc;
+ print $proposalstatic->getNomUrl(1);
+ print ' ';
+ print '';
+ if ($obj->dc)
+ {
+ print dol_print_date($db->jdate($obj->dc), 'day');
+ } else {
+ print "-";
+ }
+ print ' ';
+ print ''.$proposalstatic->LibStatut($obj->fk_statut, 5).' ';
+ print ' ';
+ $i++;
+ }
+ $db->free($resql);
- if ($num > 0) print "
";
- } else {
- dol_print_error($db);
- }
+ if ($num > 0) print "
";
+ } else {
+ dol_print_error($db);
+ }
}
/*
@@ -651,15 +651,15 @@ if ($object->id > 0)
if ($num > 0)
{
- print '';
+ print '';
- print '';
- print '';
- print '';
- print ' ';
+ print '';
+ print '';
+ print '';
+ print ' ';
}
while ($i < $num && $i < $MAXLIST)
@@ -667,14 +667,14 @@ if ($object->id > 0)
$obj = $db->fetch_object($resql);
print '';
- print '';
- $orderstatic->id = $obj->rowid;
- $orderstatic->ref = $obj->ref;
- $orderstatic->total_ht = $obj->total_ht;
- $orderstatic->total_tva = $obj->total_tva;
- $orderstatic->total_ttc = $obj->total_ttc;
- print $orderstatic->getNomUrl(1);
- print ' ';
+ print '';
+ $orderstatic->id = $obj->rowid;
+ $orderstatic->ref = $obj->ref;
+ $orderstatic->total_ht = $obj->total_ht;
+ $orderstatic->total_tva = $obj->total_tva;
+ $orderstatic->total_ttc = $obj->total_ttc;
+ print $orderstatic->getNomUrl(1);
+ print ' ';
print '';
if ($obj->dc)
{
@@ -720,14 +720,14 @@ if ($object->id > 0)
$num = $db->num_rows($resql);
if ($num > 0)
{
- print '';
+ print '';
- print '';
- print '';
- print '';
- print ' ';
+ print '';
+ print '';
+ print '';
+ print ' ';
}
while ($i < min($num, $MAXLIST))
@@ -743,8 +743,8 @@ if ($object->id > 0)
$facturestatic->libelle = $obj->label; // deprecated
$facturestatic->label = $obj->label;
$facturestatic->total_ht = $obj->total_ht;
- $facturestatic->total_tva = $obj->total_tva;
- $facturestatic->total_ttc = $obj->total_ttc;
+ $facturestatic->total_tva = $obj->total_tva;
+ $facturestatic->total_ttc = $obj->total_ttc;
print $facturestatic->getNomUrl(1);
print $obj->ref_supplier ? ' - '.$obj->ref_supplier : '';
print ($obj->label ? ' - ' : '').dol_trunc($obj->label, 14);
@@ -767,7 +767,7 @@ if ($object->id > 0)
print '';
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
/*
@@ -780,29 +780,29 @@ if ($object->id > 0)
// modified by hook
if (empty($reshook))
{
- if ($object->status != 1)
- {
- print '';
- }
+ if ($object->status != 1)
+ {
+ print '';
+ }
if ($conf->supplier_proposal->enabled && $user->rights->supplier_proposal->creer)
{
$langs->load("supplier_proposal");
- if ($object->status == 1) {
- print ''.$langs->trans("AddSupplierProposal").' ';
- } else {
- print ''.$langs->trans("AddSupplierProposal").' ';
- }
+ if ($object->status == 1) {
+ print ''.$langs->trans("AddSupplierProposal").' ';
+ } else {
+ print ''.$langs->trans("AddSupplierProposal").' ';
+ }
}
- if ($user->rights->fournisseur->commande->creer)
+ if ($user->rights->fournisseur->commande->creer)
{
$langs->load("orders");
- if ($object->status == 1) {
- print ''.$langs->trans("AddOrder").' ';
- } else {
- print ''.$langs->trans("AddOrder").' ';
- }
+ if ($object->status == 1) {
+ print ''.$langs->trans("AddOrder").' ';
+ } else {
+ print ''.$langs->trans("AddOrder").' ';
+ }
}
if ($user->rights->fournisseur->facture->creer)
@@ -821,23 +821,23 @@ if ($object->id > 0)
if ($user->rights->fournisseur->facture->creer)
{
$langs->load("bills");
- if ($object->status == 1) {
- print ''.$langs->trans("AddBill").' ';
- } else {
- print ''.$langs->trans("AddBill").' ';
- }
+ if ($object->status == 1) {
+ print ''.$langs->trans("AddBill").' ';
+ } else {
+ print ''.$langs->trans("AddBill").' ';
+ }
}
- // Add action
- if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1)
- {
- if ($user->rights->agenda->myactions->create)
- {
- print ''.$langs->trans("AddAction").' ';
- } else {
- print ''.$langs->trans("AddAction").' ';
- }
- }
+ // Add action
+ if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1)
+ {
+ if ($user->rights->agenda->myactions->create)
+ {
+ print ''.$langs->trans("AddAction").' ';
+ } else {
+ print ''.$langs->trans("AddAction").' ';
+ }
+ }
}
print '';
@@ -845,20 +845,20 @@ if ($object->id > 0)
if (!empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD))
{
- print ' ';
- // List of contacts
- show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id);
+ print ' ';
+ // List of contacts
+ show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id);
}
if (!empty($conf->global->MAIN_REPEATTASKONEACHTAB))
{
- print load_fiche_titre($langs->trans("ActionsOnCompany"), '', '');
+ print load_fiche_titre($langs->trans("ActionsOnCompany"), '', '');
- // List of todo actions
- show_actions_todo($conf, $langs, $db, $object);
+ // List of todo actions
+ show_actions_todo($conf, $langs, $db, $object);
- // List of done actions
- show_actions_done($conf, $langs, $db, $object);
+ // List of done actions
+ show_actions_done($conf, $langs, $db, $object);
}
} else {
dol_print_error($db);
diff --git a/htdocs/fourn/class/api_supplier_invoices.class.php b/htdocs/fourn/class/api_supplier_invoices.class.php
index 8c3ca0108e3..247434be7a8 100644
--- a/htdocs/fourn/class/api_supplier_invoices.class.php
+++ b/htdocs/fourn/class/api_supplier_invoices.class.php
@@ -677,8 +677,8 @@ class SupplierInvoices extends DolibarrApi
/**
* Clean sensible object datas
*
- * @param Object $object Object to clean
- * @return array Array of cleaned object properties
+ * @param Object $object Object to clean
+ * @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
diff --git a/htdocs/fourn/class/api_supplier_orders.class.php b/htdocs/fourn/class/api_supplier_orders.class.php
index 0fd06790011..254e577f2f2 100644
--- a/htdocs/fourn/class/api_supplier_orders.class.php
+++ b/htdocs/fourn/class/api_supplier_orders.class.php
@@ -108,18 +108,18 @@ class SupplierOrders extends DolibarrApi
// If the internal user must only see his customers, force searching by him
$search_sale = 0;
- if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id;
+ if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
$sql = "SELECT t.rowid";
- if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
+ if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
$sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as t";
- if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
+ if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
if (!empty($product_ids)) $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product
$sql .= ' WHERE t.entity IN ('.getEntity('supplier_order').')';
- if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
+ if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
if (!empty($product_ids)) $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$product_ids.")";
if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
@@ -339,8 +339,8 @@ class SupplierOrders extends DolibarrApi
/**
* Clean sensible object datas
*
- * @param Object $object Object to clean
- * @return array Array of cleaned object properties
+ * @param Object $object Object to clean
+ * @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
diff --git a/htdocs/fourn/class/fournisseur.class.php b/htdocs/fourn/class/fournisseur.class.php
index e9ba334313c..4ca073a38c7 100644
--- a/htdocs/fourn/class/fournisseur.class.php
+++ b/htdocs/fourn/class/fournisseur.class.php
@@ -100,7 +100,7 @@ class Fournisseur extends Societe
}
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Load statistics indicators
*
@@ -108,7 +108,7 @@ class Fournisseur extends Societe
*/
public function load_state_board()
{
- // phpcs:enable
+ // phpcs:enable
global $conf, $user;
$this->nb = array();
@@ -132,7 +132,7 @@ class Fournisseur extends Societe
{
$this->nb["suppliers"] = $obj->nb;
}
- $this->db->free($resql);
+ $this->db->free($resql);
return 1;
} else {
dol_print_error($this->db);
@@ -141,7 +141,7 @@ class Fournisseur extends Societe
}
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Create a supplier category
*
@@ -151,7 +151,7 @@ class Fournisseur extends Societe
*/
public function CreateCategory($user, $name)
{
- // phpcs:enable
+ // phpcs:enable
$sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie (label,visible,type)";
$sql .= " VALUES ";
$sql .= " ('".$this->db->escape($name)."',1,1)";
@@ -169,7 +169,7 @@ class Fournisseur extends Societe
}
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Return the suppliers list
*
@@ -177,7 +177,7 @@ class Fournisseur extends Societe
*/
public function ListArray()
{
- // phpcs:enable
+ // phpcs:enable
global $conf;
global $user;
diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php
index 383e5ba4d07..9b927360025 100644
--- a/htdocs/fourn/class/fournisseur.commande.class.php
+++ b/htdocs/fourn/class/fournisseur.commande.class.php
@@ -388,7 +388,7 @@ class CommandeFournisseur extends CommonOrder
$this->note_private = $obj->note_private;
$this->note_public = $obj->note_public;
$this->model_pdf = $obj->model_pdf;
- $this->modelpdf = $obj->model_pdf; // deprecated
+ $this->modelpdf = $obj->model_pdf; // deprecated
//Incoterms
$this->fk_incoterms = $obj->fk_incoterms;
@@ -763,17 +763,25 @@ class CommandeFournisseur extends CommonOrder
global $langs, $conf, $user;
$result = '';
- $label = ''.$langs->trans("PurchaseOrder").' ';
- if (!empty($this->ref))
- $label .= ''.$langs->trans('Ref').': '.$this->ref;
- if (!empty($this->ref_supplier))
- $label .= ''.$langs->trans('RefSupplier').': '.$this->ref_supplier;
- if (!empty($this->total_ht))
- $label .= ''.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
- if (!empty($this->total_tva))
- $label .= ''.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
- if (!empty($this->total_ttc))
- $label .= ''.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
+
+ $label = '';
+
+ if ($user->rights->fournisseur->commande->lire) {
+ $label = ''.$langs->trans("SupplierOrder").' ';
+ if (isset($this->statut)) {
+ $label .= ' '.$this->getLibStatut(5);
+ }
+ if (!empty($this->ref))
+ $label .= ''.$langs->trans('Ref').': '.$this->ref;
+ if (!empty($this->ref_supplier))
+ $label .= ''.$langs->trans('RefSupplier').': '.$this->ref_supplier;
+ if (!empty($this->total_ht))
+ $label .= ''.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
+ if (!empty($this->total_tva))
+ $label .= ''.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
+ if (!empty($this->total_ttc))
+ $label .= ''.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
+ }
$picto = 'order';
$url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id;
@@ -2020,8 +2028,8 @@ class CommandeFournisseur extends CommonOrder
if (!$error)
{
- // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
- $this->deleteEcmFiles();
+ // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
+ $this->deleteEcmFiles();
// We remove directory
$ref = dol_sanitizeFileName($this->ref);
@@ -2210,9 +2218,9 @@ class CommandeFournisseur extends CommonOrder
// TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty).
- if (empty($error))
- {
- $this->db->begin();
+ if (empty($error))
+ {
+ $this->db->begin();
$sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
$sql .= " SET fk_statut = ".$statut;
@@ -2228,10 +2236,10 @@ class CommandeFournisseur extends CommonOrder
$this->statut = $statut;
$this->actionmsg2 = $comment;
- // Call trigger
- $result_trigger = $this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user);
- if ($result_trigger < 0) $error++;
- // End call triggers
+ // Call trigger
+ $result_trigger = $this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user);
+ if ($result_trigger < 0) $error++;
+ // End call triggers
if (empty($error))
{
diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php
index d3780d412ea..1bf32782bdb 100644
--- a/htdocs/fourn/class/fournisseur.facture.class.php
+++ b/htdocs/fourn/class/fournisseur.facture.class.php
@@ -2219,37 +2219,37 @@ class FactureFournisseur extends CommonInvoice
if ($user->socid) $sql .= ' AND ff.fk_soc = '.$user->socid;
if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND ff.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $langs->load("bills");
- $now = dol_now();
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $langs->load("bills");
+ $now = dol_now();
- $response = new WorkboardResponse();
- $response->warning_delay = $conf->facture->fournisseur->warning_delay / 60 / 60 / 24;
- $response->label = $langs->trans("SupplierBillsToPay");
- $response->labelShort = $langs->trans("StatusToPay");
+ $response = new WorkboardResponse();
+ $response->warning_delay = $conf->facture->fournisseur->warning_delay / 60 / 60 / 24;
+ $response->label = $langs->trans("SupplierBillsToPay");
+ $response->labelShort = $langs->trans("StatusToPay");
- $response->url = DOL_URL_ROOT.'/fourn/facture/list.php?search_status=1&mainmenu=billing&leftmenu=suppliers_bills';
- $response->img = img_object($langs->trans("Bills"), "bill");
+ $response->url = DOL_URL_ROOT.'/fourn/facture/list.php?search_status=1&mainmenu=billing&leftmenu=suppliers_bills';
+ $response->img = img_object($langs->trans("Bills"), "bill");
- $facturestatic = new FactureFournisseur($this->db);
+ $facturestatic = new FactureFournisseur($this->db);
- while ($obj = $this->db->fetch_object($resql))
- {
- $response->nbtodo++;
+ while ($obj = $this->db->fetch_object($resql))
+ {
+ $response->nbtodo++;
- $facturestatic->date_echeance = $this->db->jdate($obj->datefin);
- $facturestatic->statut = $obj->fk_statut;
+ $facturestatic->date_echeance = $this->db->jdate($obj->datefin);
+ $facturestatic->statut = $obj->fk_statut;
- if ($facturestatic->hasDelay()) {
- $response->nbtodolate++;
+ if ($facturestatic->hasDelay()) {
+ $response->nbtodolate++;
$response->url_late = DOL_URL_ROOT.'/fourn/facture/list.php?option=late&mainmenu=billing&leftmenu=suppliers_bills';
- }
- }
- $this->db->free($resql);
- return $response;
- } else {
+ }
+ }
+ $this->db->free($resql);
+ return $response;
+ } else {
dol_print_error($this->db);
$this->error = $this->db->error();
return -1;
@@ -2295,10 +2295,10 @@ class FactureFournisseur extends CommonInvoice
if ($this->type == self::TYPE_CREDIT_NOTE) $picto .= 'a'; // Credit note
if ($this->type == self::TYPE_DEPOSIT) $picto .= 'd'; // Deposit invoice
- $label = img_picto('', $this->picto).' '.$langs->trans("SupplierInvoice").' ';
- if ($this->type == self::TYPE_REPLACEMENT) $label = ''.$langs->transnoentitiesnoconv("InvoiceReplace").' ';
- elseif ($this->type == self::TYPE_CREDIT_NOTE) $label = ''.$langs->transnoentitiesnoconv("CreditNote").' ';
- elseif ($this->type == self::TYPE_DEPOSIT) $label = ''.$langs->transnoentitiesnoconv("Deposit").' ';
+ $label = img_picto('', $this->picto).' '.$langs->trans("SupplierInvoice").' ';
+ if ($this->type == self::TYPE_REPLACEMENT) $label = ''.$langs->transnoentitiesnoconv("InvoiceReplace").' ';
+ elseif ($this->type == self::TYPE_CREDIT_NOTE) $label = ''.$langs->transnoentitiesnoconv("CreditNote").' ';
+ elseif ($this->type == self::TYPE_DEPOSIT) $label = ''.$langs->transnoentitiesnoconv("Deposit").' ';
if (!empty($this->ref))
$label .= ''.$langs->trans('Ref').': '.$this->ref;
if (!empty($this->ref_supplier))
diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php
index ad7c9a1f238..264e015298d 100644
--- a/htdocs/fourn/class/fournisseur.product.class.php
+++ b/htdocs/fourn/class/fournisseur.product.class.php
@@ -39,238 +39,238 @@ require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.
*/
class ProductFournisseur extends Product
{
- /**
- * @var DoliDB Database handler.
- */
- public $db;
+ /**
+ * @var DoliDB Database handler.
+ */
+ public $db;
- /**
- * @var string Error code (or message)
- */
- public $error = '';
+ /**
+ * @var string Error code (or message)
+ */
+ public $error = '';
- public $product_fourn_price_id; // id of ligne product-supplier
+ public $product_fourn_price_id; // id of ligne product-supplier
- /**
- * @var int ID
- */
- public $id;
+ /**
+ * @var int ID
+ */
+ public $id;
- /**
- * @deprecated
- * @see $ref_supplier
- */
- public $fourn_ref;
- public $delivery_time_days;
- public $ref_supplier; // ref supplier (can be set by get_buyprice)
- public $desc_supplier;
- public $vatrate_supplier; // default vat rate for this supplier/qty/product (can be set by get_buyprice)
+ /**
+ * @deprecated
+ * @see $ref_supplier
+ */
+ public $fourn_ref;
+ public $delivery_time_days;
+ public $ref_supplier; // ref supplier (can be set by get_buyprice)
+ public $desc_supplier;
+ public $vatrate_supplier; // default vat rate for this supplier/qty/product (can be set by get_buyprice)
- public $fourn_id; //supplier id
- public $fourn_qty; // quantity for price (can be set by get_buyprice)
- public $fourn_pu; // unit price for quantity (can be set by get_buyprice)
+ public $fourn_id; //supplier id
+ public $fourn_qty; // quantity for price (can be set by get_buyprice)
+ public $fourn_pu; // unit price for quantity (can be set by get_buyprice)
- public $fourn_price; // price for quantity
- public $fourn_remise_percent; // discount for quantity (percent)
- public $fourn_remise; // discount for quantity (amount)
- public $product_fourn_id; // product-supplier id
+ public $fourn_price; // price for quantity
+ public $fourn_remise_percent; // discount for quantity (percent)
+ public $fourn_remise; // discount for quantity (amount)
+ public $product_fourn_id; // product-supplier id
- /**
- * @var int ID user_id - user who created/updated supplier price
- */
- public $user_id;
+ /**
+ * @var int ID user_id - user who created/updated supplier price
+ */
+ public $user_id;
- /**
- * @var int ID availability delay - visible/used if option FOURN_PRODUCT_AVAILABILITY is on (duplicate information compared to delivery delay)
- */
- public $fk_availability;
+ /**
+ * @var int ID availability delay - visible/used if option FOURN_PRODUCT_AVAILABILITY is on (duplicate information compared to delivery delay)
+ */
+ public $fk_availability;
- public $fourn_unitprice;
- public $fourn_tva_tx;
- public $fourn_tva_npr;
+ public $fourn_unitprice;
+ public $fourn_tva_tx;
+ public $fourn_tva_npr;
- /**
- * @var int ID
- */
- public $fk_supplier_price_expression;
+ /**
+ * @var int ID
+ */
+ public $fk_supplier_price_expression;
- public $supplier_reputation; // reputation of supplier
- public $reputations = array(); // list of available supplier reputations
+ public $supplier_reputation; // reputation of supplier
+ public $reputations = array(); // list of available supplier reputations
- // Multicurreny
- public $fourn_multicurrency_id;
- public $fourn_multicurrency_code;
- public $fourn_multicurrency_tx;
- public $fourn_multicurrency_price;
- public $fourn_multicurrency_unitprice;
+ // Multicurreny
+ public $fourn_multicurrency_id;
+ public $fourn_multicurrency_code;
+ public $fourn_multicurrency_tx;
+ public $fourn_multicurrency_price;
+ public $fourn_multicurrency_unitprice;
- /**
- * Constructor
- *
- * @param DoliDB $db Database handler
- */
- public function __construct($db)
- {
- global $langs;
+ /**
+ * Constructor
+ *
+ * @param DoliDB $db Database handler
+ */
+ public function __construct($db)
+ {
+ global $langs;
- $this->db = $db;
- $langs->load("suppliers");
- $this->reputations = array('-1'=>'', 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
- }
+ $this->db = $db;
+ $langs->load("suppliers");
+ $this->reputations = array('-1'=>'', 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Remove all prices for this couple supplier-product
- *
- * @param int $id_fourn Supplier Id
- * @return int < 0 if error, > 0 if ok
- */
- public function remove_fournisseur($id_fourn)
- {
- // phpcs:enable
- $ok = 1;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Remove all prices for this couple supplier-product
+ *
+ * @param int $id_fourn Supplier Id
+ * @return int < 0 if error, > 0 if ok
+ */
+ public function remove_fournisseur($id_fourn)
+ {
+ // phpcs:enable
+ $ok = 1;
- $this->db->begin();
+ $this->db->begin();
- $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
- $sql .= " WHERE fk_product = ".$this->id." AND fk_soc = ".$id_fourn;
+ $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
+ $sql .= " WHERE fk_product = ".$this->id." AND fk_soc = ".$id_fourn;
- dol_syslog(get_class($this)."::remove_fournisseur", LOG_DEBUG);
- $resql2 = $this->db->query($sql);
- if (!$resql2)
- {
- $this->error = $this->db->lasterror();
- $ok = 0;
- }
+ dol_syslog(get_class($this)."::remove_fournisseur", LOG_DEBUG);
+ $resql2 = $this->db->query($sql);
+ if (!$resql2)
+ {
+ $this->error = $this->db->lasterror();
+ $ok = 0;
+ }
- if ($ok)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- }
+ if ($ok)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Remove a price for a couple supplier-product
- *
- * @param int $rowid Line id of price
- * @return int <0 if KO, >0 if OK
- */
- public function remove_product_fournisseur_price($rowid)
- {
- // phpcs:enable
- global $conf, $user;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Remove a price for a couple supplier-product
+ *
+ * @param int $rowid Line id of price
+ * @return int <0 if KO, >0 if OK
+ */
+ public function remove_product_fournisseur_price($rowid)
+ {
+ // phpcs:enable
+ global $conf, $user;
- $error = 0;
+ $error = 0;
- $this->db->begin();
+ $this->db->begin();
- // Call trigger
- $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_DELETE', $user);
- if ($result < 0) $error++;
- // End call triggers
+ // Call trigger
+ $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_DELETE', $user);
+ if ($result < 0) $error++;
+ // End call triggers
- if (empty($error))
- {
- $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
- $sql .= " WHERE rowid = ".$rowid;
+ if (empty($error))
+ {
+ $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
+ $sql .= " WHERE rowid = ".$rowid;
- dol_syslog(get_class($this)."::remove_product_fournisseur_price", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if (!$resql)
- {
- $this->error = $this->db->lasterror();
- $error++;
- }
- }
+ dol_syslog(get_class($this)."::remove_product_fournisseur_price", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql)
+ {
+ $this->error = $this->db->lasterror();
+ $error++;
+ }
+ }
- if (empty($error)) {
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- }
+ if (empty($error)) {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Modify the purchase price for a supplier
- *
- * @param float $qty Min quantity for which price is valid
- * @param float $buyprice Purchase price for the quantity min
- * @param User $user Object user user made changes
- * @param string $price_base_type HT or TTC
- * @param Societe $fourn Supplier
- * @param int $availability Product availability
- * @param string $ref_fourn Supplier ref
- * @param float $tva_tx New VAT Rate (For example 8.5. Should not be a string)
- * @param string $charges costs affering to product
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Modify the purchase price for a supplier
+ *
+ * @param float $qty Min quantity for which price is valid
+ * @param float $buyprice Purchase price for the quantity min
+ * @param User $user Object user user made changes
+ * @param string $price_base_type HT or TTC
+ * @param Societe $fourn Supplier
+ * @param int $availability Product availability
+ * @param string $ref_fourn Supplier ref
+ * @param float $tva_tx New VAT Rate (For example 8.5. Should not be a string)
+ * @param string $charges costs affering to product
* @param float $remise_percent Discount regarding qty (percent)
* @param float $remise Discount regarding qty (amount)
* @param int $newnpr Set NPR or not
* @param int $delivery_time_days Delay in days for delivery (max). May be '' if not defined.
* @param string $supplier_reputation Reputation with this product to the defined supplier (empty, FAVORITE, DONOTORDER)
- * @param array $localtaxes_array Array with localtaxes info array('0'=>type1,'1'=>rate1,'2'=>type2,'3'=>rate2) (loaded by getLocalTaxesFromRate(vatrate, 0, ...) function).
- * @param string $newdefaultvatcode Default vat code
- * @param float $multicurrency_buyprice Purchase price for the quantity min in currency
- * @param string $multicurrency_price_base_type HT or TTC in currency
- * @param float $multicurrency_tx Rate currency
- * @param string $multicurrency_code Currency code
- * @param string $desc_fourn Custom description for product_fourn_price
- * @param string $barcode Barcode
- * @param int $fk_barcode_type Barcode type
- * @return int <0 if KO, >=0 if OK
- */
- public function update_buyprice($qty, $buyprice, $user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges = 0, $remise_percent = 0, $remise = 0, $newnpr = 0, $delivery_time_days = 0, $supplier_reputation = '', $localtaxes_array = array(), $newdefaultvatcode = '', $multicurrency_buyprice = 0, $multicurrency_price_base_type = 'HT', $multicurrency_tx = 1, $multicurrency_code = '', $desc_fourn = '', $barcode = '', $fk_barcode_type = '')
- {
- // phpcs:enable
- global $conf, $langs;
- //global $mysoc;
+ * @param array $localtaxes_array Array with localtaxes info array('0'=>type1,'1'=>rate1,'2'=>type2,'3'=>rate2) (loaded by getLocalTaxesFromRate(vatrate, 0, ...) function).
+ * @param string $newdefaultvatcode Default vat code
+ * @param float $multicurrency_buyprice Purchase price for the quantity min in currency
+ * @param string $multicurrency_price_base_type HT or TTC in currency
+ * @param float $multicurrency_tx Rate currency
+ * @param string $multicurrency_code Currency code
+ * @param string $desc_fourn Custom description for product_fourn_price
+ * @param string $barcode Barcode
+ * @param int $fk_barcode_type Barcode type
+ * @return int <0 if KO, >=0 if OK
+ */
+ public function update_buyprice($qty, $buyprice, $user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges = 0, $remise_percent = 0, $remise = 0, $newnpr = 0, $delivery_time_days = 0, $supplier_reputation = '', $localtaxes_array = array(), $newdefaultvatcode = '', $multicurrency_buyprice = 0, $multicurrency_price_base_type = 'HT', $multicurrency_tx = 1, $multicurrency_code = '', $desc_fourn = '', $barcode = '', $fk_barcode_type = '')
+ {
+ // phpcs:enable
+ global $conf, $langs;
+ //global $mysoc;
- // Clean parameter
- if (empty($qty)) $qty = 0;
- if (empty($buyprice)) $buyprice = 0;
- if (empty($charges)) $charges = 0;
- if (empty($availability)) $availability = 0;
- if (empty($remise_percent)) $remise_percent = 0;
- if (empty($supplier_reputation) || $supplier_reputation == -1) $supplier_reputation = '';
- if ($delivery_time_days != '' && !is_numeric($delivery_time_days)) $delivery_time_days = '';
- if ($price_base_type == 'TTC')
- {
- $ttx = $tva_tx;
- $buyprice = $buyprice / (1 + ($ttx / 100));
- }
+ // Clean parameter
+ if (empty($qty)) $qty = 0;
+ if (empty($buyprice)) $buyprice = 0;
+ if (empty($charges)) $charges = 0;
+ if (empty($availability)) $availability = 0;
+ if (empty($remise_percent)) $remise_percent = 0;
+ if (empty($supplier_reputation) || $supplier_reputation == -1) $supplier_reputation = '';
+ if ($delivery_time_days != '' && !is_numeric($delivery_time_days)) $delivery_time_days = '';
+ if ($price_base_type == 'TTC')
+ {
+ $ttx = $tva_tx;
+ $buyprice = $buyprice / (1 + ($ttx / 100));
+ }
// Multicurrency
- if ($conf->multicurrency->enabled) {
- if (empty($multicurrency_tx)) $multicurrency_tx = 1;
- if (empty($multicurrency_buyprice)) $multicurrency_buyprice = 0;
+ if ($conf->multicurrency->enabled) {
+ if (empty($multicurrency_tx)) $multicurrency_tx = 1;
+ if (empty($multicurrency_buyprice)) $multicurrency_buyprice = 0;
- if (empty($multicurrency_buyprice)) $multicurrency_buyprice = 0;
- if ($multicurrency_price_base_type == 'TTC')
- {
- $ttx = $tva_tx;
- $multicurrency_buyprice = $multicurrency_buyprice / (1 + ($ttx / 100));
- }
- $multicurrency_buyprice = price2num($multicurrency_buyprice, 'MU');
- $multicurrency_unitBuyPrice = price2num($multicurrency_buyprice / $qty, 'MU');
+ if (empty($multicurrency_buyprice)) $multicurrency_buyprice = 0;
+ if ($multicurrency_price_base_type == 'TTC')
+ {
+ $ttx = $tva_tx;
+ $multicurrency_buyprice = $multicurrency_buyprice / (1 + ($ttx / 100));
+ }
+ $multicurrency_buyprice = price2num($multicurrency_buyprice, 'MU');
+ $multicurrency_unitBuyPrice = price2num($multicurrency_buyprice / $qty, 'MU');
- $buyprice = $multicurrency_buyprice / $multicurrency_tx;
- $fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $multicurrency_code);
- }
+ $buyprice = $multicurrency_buyprice / $multicurrency_tx;
+ $fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $multicurrency_code);
+ }
- $buyprice = price2num($buyprice, 'MU');
+ $buyprice = price2num($buyprice, 'MU');
$charges = price2num($charges, 'MU');
- $qty = price2num($qty, 'MS');
+ $qty = price2num($qty, 'MS');
$unitBuyPrice = price2num($buyprice / $qty, 'MU');
$packaging = price2num((($this->packaging < $qty) ? $qty : $this->packaging), 'MS');
@@ -300,50 +300,50 @@ class ProductFournisseur extends Product
{
}
- $this->db->begin();
+ $this->db->begin();
- if ($this->product_fourn_price_id > 0)
- {
- // check if price already logged, if not first log current price
- $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id);
- if (is_array($logPrices) && count($logPrices) == 0)
- {
- $currentPfp = new self($this->db);
- $result = $currentPfp->fetch_product_fournisseur_price($this->product_fourn_price_id);
- if ($result > 0 && $currentPfp->fourn_price != 0)
- {
- $currentPfpUser = new User($this->db);
- $result = $currentPfpUser->fetch($currentPfp->user_id);
- if ($result > 0) {
- $currentPfp->logPrice(
- $currentPfpUser,
- $currentPfp->date_creation,
- $currentPfp->fourn_price,
- $currentPfp->fourn_qty,
- $currentPfp->fourn_multicurrency_price,
- $currentPfp->fourn_multicurrency_unitprice,
- $currentPfp->fourn_multicurrency_tx,
- $currentPfp->fourn_multicurrency_id,
- $currentPfp->fourn_multicurrency_code
- );
- }
- }
- }
- $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price";
+ if ($this->product_fourn_price_id > 0)
+ {
+ // check if price already logged, if not first log current price
+ $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id);
+ if (is_array($logPrices) && count($logPrices) == 0)
+ {
+ $currentPfp = new self($this->db);
+ $result = $currentPfp->fetch_product_fournisseur_price($this->product_fourn_price_id);
+ if ($result > 0 && $currentPfp->fourn_price != 0)
+ {
+ $currentPfpUser = new User($this->db);
+ $result = $currentPfpUser->fetch($currentPfp->user_id);
+ if ($result > 0) {
+ $currentPfp->logPrice(
+ $currentPfpUser,
+ $currentPfp->date_creation,
+ $currentPfp->fourn_price,
+ $currentPfp->fourn_qty,
+ $currentPfp->fourn_multicurrency_price,
+ $currentPfp->fourn_multicurrency_unitprice,
+ $currentPfp->fourn_multicurrency_tx,
+ $currentPfp->fourn_multicurrency_id,
+ $currentPfp->fourn_multicurrency_code
+ );
+ }
+ }
+ }
+ $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price";
$sql .= " SET fk_user = ".$user->id." ,";
- $sql .= " ref_fourn = '".$this->db->escape($ref_fourn)."',";
- $sql .= " desc_fourn = '".$this->db->escape($desc_fourn)."',";
+ $sql .= " ref_fourn = '".$this->db->escape($ref_fourn)."',";
+ $sql .= " desc_fourn = '".$this->db->escape($desc_fourn)."',";
$sql .= " price = ".$buyprice.",";
$sql .= " quantity = ".$qty.",";
$sql .= " remise_percent = ".$remise_percent.",";
$sql .= " remise = ".$remise.",";
$sql .= " unitprice = ".$unitBuyPrice.",";
$sql .= " fk_availability = ".$availability.",";
- $sql .= " multicurrency_price = ".(isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').",";
- $sql .= " multicurrency_unitprice = ".(isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').",";
- $sql .= " multicurrency_tx = ".(isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').",";
- $sql .= " fk_multicurrency = ".(isset($fk_multicurrency) ? "'".$this->db->escape($fk_multicurrency)."'" : 'null').",";
- $sql .= " multicurrency_code = ".(isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').",";
+ $sql .= " multicurrency_price = ".(isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').",";
+ $sql .= " multicurrency_unitprice = ".(isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').",";
+ $sql .= " multicurrency_tx = ".(isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').",";
+ $sql .= " fk_multicurrency = ".(isset($fk_multicurrency) ? "'".$this->db->escape($fk_multicurrency)."'" : 'null').",";
+ $sql .= " multicurrency_code = ".(isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').",";
$sql .= " entity = ".$conf->entity.",";
$sql .= " tva_tx = ".price2num($tva_tx).",";
// TODO Add localtax1 and localtax2
@@ -356,8 +356,8 @@ class ProductFournisseur extends Product
$sql .= " charges = ".$charges.","; // deprecated
$sql .= " delivery_time_days = ".($delivery_time_days != '' ? $delivery_time_days : 'null').",";
$sql .= " supplier_reputation = ".(empty($supplier_reputation) ? 'NULL' : "'".$this->db->escape($supplier_reputation)."'").",";
- $sql .= " barcode = ".(empty($barcode) ? 'NULL' : "'".$this->db->escape($barcode)."'").",";
- $sql .= " fk_barcode_type = ".(empty($fk_barcode_type) ? 'NULL' : "'".$this->db->escape($fk_barcode_type)."'");
+ $sql .= " barcode = ".(empty($barcode) ? 'NULL' : "'".$this->db->escape($barcode)."'").",";
+ $sql .= " fk_barcode_type = ".(empty($fk_barcode_type) ? 'NULL' : "'".$this->db->escape($fk_barcode_type)."'");
if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", packaging = ".(empty($packaging) ? 1 : $packaging);
$sql .= " WHERE rowid = ".$this->product_fourn_price_id;
// TODO Add price_base_type and price_ttc
@@ -366,17 +366,17 @@ class ProductFournisseur extends Product
$resql = $this->db->query($sql);
if ($resql)
{
- // Call trigger
- $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_UPDATE', $user);
- if ($result < 0) $error++;
- // End call triggers
- if (!$error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG))
- {
- $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, $multicurrency_unitBuyPrice, $multicurrency_tx, $fk_multicurrency, $multicurrency_code);
- if ($result < 0) {
- $error++;
- }
- }
+ // Call trigger
+ $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_UPDATE', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ if (!$error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG))
+ {
+ $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, $multicurrency_unitBuyPrice, $multicurrency_tx, $fk_multicurrency, $multicurrency_code);
+ if ($result < 0) {
+ $error++;
+ }
+ }
if (empty($error))
{
$this->db->commit();
@@ -390,727 +390,727 @@ class ProductFournisseur extends Product
$this->db->rollback();
return -2;
}
- } else {
- dol_syslog(get_class($this).'::update_buyprice without knowing id of line, so we delete from company, quantity and supplier_ref and insert again', LOG_DEBUG);
+ } else {
+ dol_syslog(get_class($this).'::update_buyprice without knowing id of line, so we delete from company, quantity and supplier_ref and insert again', LOG_DEBUG);
- // Delete price for this quantity
- $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
- $sql .= " WHERE fk_soc = ".$fourn->id." AND ref_fourn = '".$this->db->escape($ref_fourn)."' AND quantity = ".$qty." AND entity = ".$conf->entity;
- $resql = $this->db->query($sql);
- if ($resql) {
- // Add price for this quantity to supplier
- $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price(";
- $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,";
- $sql .= "datec, fk_product, fk_soc, ref_fourn, desc_fourn, fk_user, price, quantity, remise_percent, remise, unitprice, tva_tx, charges, fk_availability, default_vat_code, info_bits, entity, delivery_time_days, supplier_reputation, barcode, fk_barcode_type)";
+ // Delete price for this quantity
+ $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
+ $sql .= " WHERE fk_soc = ".$fourn->id." AND ref_fourn = '".$this->db->escape($ref_fourn)."' AND quantity = ".$qty." AND entity = ".$conf->entity;
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ // Add price for this quantity to supplier
+ $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price(";
+ $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,";
+ $sql .= "datec, fk_product, fk_soc, ref_fourn, desc_fourn, fk_user, price, quantity, remise_percent, remise, unitprice, tva_tx, charges, fk_availability, default_vat_code, info_bits, entity, delivery_time_days, supplier_reputation, barcode, fk_barcode_type)";
if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", packaging";
- $sql .= " values(";
- $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').",";
- $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').",";
- $sql .= (isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').",";
- $sql .= (isset($fk_multicurrency) ? "'".$this->db->escape($fk_multicurrency)."'" : 'null').",";
- $sql .= (isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').",";
- $sql .= " '".$this->db->idate($now)."',";
- $sql .= " ".$this->id.",";
- $sql .= " ".$fourn->id.",";
- $sql .= " '".$this->db->escape($ref_fourn)."',";
- $sql .= " '".$this->db->escape($desc_fourn)."',";
- $sql .= " ".$user->id.",";
- $sql .= " ".$buyprice.",";
- $sql .= " ".$qty.",";
- $sql .= " ".$remise_percent.",";
- $sql .= " ".$remise.",";
- $sql .= " ".$unitBuyPrice.",";
- $sql .= " ".$tva_tx.",";
- $sql .= " ".$charges.",";
- $sql .= " ".$availability.",";
- $sql .= " ".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
- $sql .= " ".$newnpr.",";
- $sql .= $conf->entity.",";
- $sql .= ($delivery_time_days != '' ? $delivery_time_days : 'null').",";
- $sql .= (empty($supplier_reputation) ? 'NULL' : "'".$this->db->escape($supplier_reputation)."'").",";
- $sql .= (empty($barcode) ? 'NULL' : "'".$this->db->escape($barcode)."'").",";
- $sql .= (empty($fk_barcode_type) ? 'NULL' : "'".$this->db->escape($fk_barcode_type)."'");
+ $sql .= " values(";
+ $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').",";
+ $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').",";
+ $sql .= (isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').",";
+ $sql .= (isset($fk_multicurrency) ? "'".$this->db->escape($fk_multicurrency)."'" : 'null').",";
+ $sql .= (isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').",";
+ $sql .= " '".$this->db->idate($now)."',";
+ $sql .= " ".$this->id.",";
+ $sql .= " ".$fourn->id.",";
+ $sql .= " '".$this->db->escape($ref_fourn)."',";
+ $sql .= " '".$this->db->escape($desc_fourn)."',";
+ $sql .= " ".$user->id.",";
+ $sql .= " ".$buyprice.",";
+ $sql .= " ".$qty.",";
+ $sql .= " ".$remise_percent.",";
+ $sql .= " ".$remise.",";
+ $sql .= " ".$unitBuyPrice.",";
+ $sql .= " ".$tva_tx.",";
+ $sql .= " ".$charges.",";
+ $sql .= " ".$availability.",";
+ $sql .= " ".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
+ $sql .= " ".$newnpr.",";
+ $sql .= $conf->entity.",";
+ $sql .= ($delivery_time_days != '' ? $delivery_time_days : 'null').",";
+ $sql .= (empty($supplier_reputation) ? 'NULL' : "'".$this->db->escape($supplier_reputation)."'").",";
+ $sql .= (empty($barcode) ? 'NULL' : "'".$this->db->escape($barcode)."'").",";
+ $sql .= (empty($fk_barcode_type) ? 'NULL' : "'".$this->db->escape($fk_barcode_type)."'");
if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", ".(empty($this->packaging) ? 1 : $this->db->escape($this->packaging));
- $sql .= ")";
+ $sql .= ")";
$this->product_fourn_price_id = 0;
- $resql = $this->db->query($sql);
- if ($resql) {
- $this->product_fourn_price_id = $this->db->last_insert_id(MAIN_DB_PREFIX."product_fournisseur_price");
- } else {
- $error++;
- }
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $this->product_fourn_price_id = $this->db->last_insert_id(MAIN_DB_PREFIX."product_fournisseur_price");
+ } else {
+ $error++;
+ }
- if (!$error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG)) {
- // Add record into log table
+ if (!$error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG)) {
+ // Add record into log table
// $this->product_fourn_price_id must be set
- $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, $multicurrency_unitBuyPrice, $multicurrency_tx, $fk_multicurrency, $multicurrency_code);
- if ($result < 0) {
- $error++;
- }
- }
+ $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, $multicurrency_unitBuyPrice, $multicurrency_tx, $fk_multicurrency, $multicurrency_code);
+ if ($result < 0) {
+ $error++;
+ }
+ }
- if (!$error) {
- // Call trigger
- $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_CREATE', $user);
- if ($result < 0)
- $error++;
- // End call triggers
+ if (!$error) {
+ // Call trigger
+ $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_CREATE', $user);
+ if ($result < 0)
+ $error++;
+ // End call triggers
- if (empty($error)) {
- $this->db->commit();
- return $this->product_fourn_price_id;
- } else {
- $this->db->rollback();
- return -1;
- }
- } else {
- $this->error = $this->db->lasterror()." sql=".$sql;
- $this->db->rollback();
- return -2;
- }
- } else {
- $this->error = $this->db->lasterror()." sql=".$sql;
- $this->db->rollback();
- return -1;
- }
- }
- }
+ if (empty($error)) {
+ $this->db->commit();
+ return $this->product_fourn_price_id;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ $this->error = $this->db->lasterror()." sql=".$sql;
+ $this->db->rollback();
+ return -2;
+ }
+ } else {
+ $this->error = $this->db->lasterror()." sql=".$sql;
+ $this->db->rollback();
+ return -1;
+ }
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Loads the price information of a provider
- *
- * @param int $rowid Line id
- * @param int $ignore_expression Ignores the math expression for calculating price and uses the db value instead
- * @return int < 0 if KO, 0 if OK but not found, > 0 if OK
- */
- public function fetch_product_fournisseur_price($rowid, $ignore_expression = 0)
- {
- // phpcs:enable
- global $conf;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Loads the price information of a provider
+ *
+ * @param int $rowid Line id
+ * @param int $ignore_expression Ignores the math expression for calculating price and uses the db value instead
+ * @return int < 0 if KO, 0 if OK but not found, > 0 if OK
+ */
+ public function fetch_product_fournisseur_price($rowid, $ignore_expression = 0)
+ {
+ // phpcs:enable
+ global $conf;
- $sql = "SELECT pfp.rowid, pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.default_vat_code, pfp.info_bits as fourn_tva_npr, pfp.fk_availability,";
- $sql .= " pfp.fk_soc, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product, pfp.charges, pfp.fk_supplier_price_expression, pfp.delivery_time_days,";
- $sql .= " pfp.supplier_reputation, pfp.fk_user, pfp.datec,";
- $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
- $sql .= " pfp.barcode, pfp.fk_barcode_type";
+ $sql = "SELECT pfp.rowid, pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.default_vat_code, pfp.info_bits as fourn_tva_npr, pfp.fk_availability,";
+ $sql .= " pfp.fk_soc, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product, pfp.charges, pfp.fk_supplier_price_expression, pfp.delivery_time_days,";
+ $sql .= " pfp.supplier_reputation, pfp.fk_user, pfp.datec,";
+ $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
+ $sql .= " pfp.barcode, pfp.fk_barcode_type";
if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", pfp.packaging";
- $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
- $sql .= " WHERE pfp.rowid = ".(int) $rowid;
+ $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
+ $sql .= " WHERE pfp.rowid = ".(int) $rowid;
- dol_syslog(get_class($this)."::fetch_product_fournisseur_price", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $obj = $this->db->fetch_object($resql);
- if ($obj)
- {
- $this->product_fourn_price_id = $rowid;
- $this->id = $obj->fk_product;
- $this->fk_product = $obj->fk_product;
- $this->product_id = $obj->fk_product; // deprecated
- $this->fourn_id = $obj->fk_soc;
- $this->fourn_ref = $obj->ref_fourn; // deprecated
- $this->ref_supplier = $obj->ref_fourn;
- $this->desc_supplier = $obj->desc_fourn;
- $this->fourn_price = $obj->price;
- $this->fourn_charges = $obj->charges; // deprecated
- $this->fourn_qty = $obj->quantity;
- $this->fourn_remise_percent = $obj->remise_percent;
- $this->fourn_remise = $obj->remise;
- $this->fourn_unitprice = $obj->unitprice;
- $this->fourn_tva_tx = $obj->tva_tx;
- $this->fourn_tva_npr = $obj->fourn_tva_npr;
- // Add also localtaxes
- $this->fk_availability = $obj->fk_availability;
+ dol_syslog(get_class($this)."::fetch_product_fournisseur_price", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $obj = $this->db->fetch_object($resql);
+ if ($obj)
+ {
+ $this->product_fourn_price_id = $rowid;
+ $this->id = $obj->fk_product;
+ $this->fk_product = $obj->fk_product;
+ $this->product_id = $obj->fk_product; // deprecated
+ $this->fourn_id = $obj->fk_soc;
+ $this->fourn_ref = $obj->ref_fourn; // deprecated
+ $this->ref_supplier = $obj->ref_fourn;
+ $this->desc_supplier = $obj->desc_fourn;
+ $this->fourn_price = $obj->price;
+ $this->fourn_charges = $obj->charges; // deprecated
+ $this->fourn_qty = $obj->quantity;
+ $this->fourn_remise_percent = $obj->remise_percent;
+ $this->fourn_remise = $obj->remise;
+ $this->fourn_unitprice = $obj->unitprice;
+ $this->fourn_tva_tx = $obj->tva_tx;
+ $this->fourn_tva_npr = $obj->fourn_tva_npr;
+ // Add also localtaxes
+ $this->fk_availability = $obj->fk_availability;
$this->delivery_time_days = $obj->delivery_time_days;
- $this->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
- $this->supplier_reputation = $obj->supplier_reputation;
- $this->default_vat_code = $obj->default_vat_code;
- $this->user_id = $obj->fk_user;
- $this->date_creation = $this->db->jdate($obj->datec);
- $this->fourn_multicurrency_price = $obj->multicurrency_price;
- $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
- $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
- $this->fourn_multicurrency_id = $obj->fk_multicurrency;
- $this->fourn_multicurrency_code = $obj->multicurrency_code;
- if ($conf->barcode->enabled) {
- $this->fourn_barcode = $obj->barcode;
- $this->fourn_fk_barcode_type = $obj->fk_barcode_type;
- }
+ $this->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
+ $this->supplier_reputation = $obj->supplier_reputation;
+ $this->default_vat_code = $obj->default_vat_code;
+ $this->user_id = $obj->fk_user;
+ $this->date_creation = $this->db->jdate($obj->datec);
+ $this->fourn_multicurrency_price = $obj->multicurrency_price;
+ $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
+ $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
+ $this->fourn_multicurrency_id = $obj->fk_multicurrency;
+ $this->fourn_multicurrency_code = $obj->multicurrency_code;
+ if ($conf->barcode->enabled) {
+ $this->fourn_barcode = $obj->barcode;
+ $this->fourn_fk_barcode_type = $obj->fk_barcode_type;
+ }
if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
$this->packaging = $obj->packaging;
if ($this->packaging < $this->fourn_qty) $this->packaging = $this->fourn_qty;
}
- if (empty($ignore_expression) && !empty($this->fk_supplier_price_expression))
- {
- $priceparser = new PriceParser($this->db);
- $price_result = $priceparser->parseProductSupplier($this);
- if ($price_result >= 0) {
- $this->fourn_price = $price_result;
- //recalculation of unitprice, as probably the price changed...
- if ($this->fourn_qty != 0)
- {
- $this->fourn_unitprice = price2num($this->fourn_price / $this->fourn_qty, 'MU');
- } else {
- $this->fourn_unitprice = "";
- }
- }
- }
+ if (empty($ignore_expression) && !empty($this->fk_supplier_price_expression))
+ {
+ $priceparser = new PriceParser($this->db);
+ $price_result = $priceparser->parseProductSupplier($this);
+ if ($price_result >= 0) {
+ $this->fourn_price = $price_result;
+ //recalculation of unitprice, as probably the price changed...
+ if ($this->fourn_qty != 0)
+ {
+ $this->fourn_unitprice = price2num($this->fourn_price / $this->fourn_qty, 'MU');
+ } else {
+ $this->fourn_unitprice = "";
+ }
+ }
+ }
- return 1;
- } else {
- return 0;
- }
- } else {
- $this->error = $this->db->error();
- return -1;
- }
- }
+ return 1;
+ } else {
+ return 0;
+ }
+ } else {
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * List all supplier prices of a product
- *
- * @param int $prodid Id of product
- * @param string $sortfield Sort field
- * @param string $sortorder Sort order
- * @param int $limit Limit
- * @param int $offset Offset
- * @return array Array of Products with new properties to define supplier price
- */
- public function list_product_fournisseur_price($prodid, $sortfield = '', $sortorder = '', $limit = 0, $offset = 0)
- {
- // phpcs:enable
- global $conf;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * List all supplier prices of a product
+ *
+ * @param int $prodid Id of product
+ * @param string $sortfield Sort field
+ * @param string $sortorder Sort order
+ * @param int $limit Limit
+ * @param int $offset Offset
+ * @return array Array of Products with new properties to define supplier price
+ */
+ public function list_product_fournisseur_price($prodid, $sortfield = '', $sortorder = '', $limit = 0, $offset = 0)
+ {
+ // phpcs:enable
+ global $conf;
- $sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id,";
- $sql .= " pfp.rowid as product_fourn_pri_id, pfp.entity, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product as product_fourn_id, pfp.fk_supplier_price_expression,";
- $sql .= " pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.fk_availability, pfp.charges, pfp.info_bits, pfp.delivery_time_days, pfp.supplier_reputation,";
- $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code, pfp.datec, pfp.tms,";
- $sql .= " pfp.barcode, pfp.fk_barcode_type";
+ $sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id,";
+ $sql .= " pfp.rowid as product_fourn_pri_id, pfp.entity, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product as product_fourn_id, pfp.fk_supplier_price_expression,";
+ $sql .= " pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.fk_availability, pfp.charges, pfp.info_bits, pfp.delivery_time_days, pfp.supplier_reputation,";
+ $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code, pfp.datec, pfp.tms,";
+ $sql .= " pfp.barcode, pfp.fk_barcode_type";
if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", pfp.packaging";
$sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp, ".MAIN_DB_PREFIX."societe as s";
- $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
- $sql .= " AND pfp.fk_soc = s.rowid";
- $sql .= " AND s.status=1"; // only enabled company selected
- $sql .= " AND pfp.fk_product = ".$prodid;
- if (empty($sortfield)) $sql .= " ORDER BY s.nom, pfp.quantity, pfp.price";
- else $sql .= $this->db->order($sortfield, $sortorder);
- $sql .= $this->db->plimit($limit, $offset);
- dol_syslog(get_class($this)."::list_product_fournisseur_price", LOG_DEBUG);
+ $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
+ $sql .= " AND pfp.fk_soc = s.rowid";
+ $sql .= " AND s.status=1"; // only enabled company selected
+ $sql .= " AND pfp.fk_product = ".$prodid;
+ if (empty($sortfield)) $sql .= " ORDER BY s.nom, pfp.quantity, pfp.price";
+ else $sql .= $this->db->order($sortfield, $sortorder);
+ $sql .= $this->db->plimit($limit, $offset);
+ dol_syslog(get_class($this)."::list_product_fournisseur_price", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $retarray = array();
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $retarray = array();
- while ($record = $this->db->fetch_array($resql))
- {
- //define base attribute
- $prodfourn = new ProductFournisseur($this->db);
+ while ($record = $this->db->fetch_array($resql))
+ {
+ //define base attribute
+ $prodfourn = new ProductFournisseur($this->db);
- $prodfourn->product_fourn_price_id = $record["product_fourn_pri_id"];
- $prodfourn->product_fourn_id = $record["product_fourn_id"];
- $prodfourn->product_fourn_entity = $record["entity"];
- $prodfourn->fourn_ref = $record["ref_fourn"];
- $prodfourn->ref_supplier = $record["ref_fourn"];
- $prodfourn->desc_supplier = $record["desc_fourn"];
- $prodfourn->fourn_price = $record["price"];
- $prodfourn->fourn_qty = $record["quantity"];
+ $prodfourn->product_fourn_price_id = $record["product_fourn_pri_id"];
+ $prodfourn->product_fourn_id = $record["product_fourn_id"];
+ $prodfourn->product_fourn_entity = $record["entity"];
+ $prodfourn->fourn_ref = $record["ref_fourn"];
+ $prodfourn->ref_supplier = $record["ref_fourn"];
+ $prodfourn->desc_supplier = $record["desc_fourn"];
+ $prodfourn->fourn_price = $record["price"];
+ $prodfourn->fourn_qty = $record["quantity"];
$prodfourn->fourn_remise_percent = $record["remise_percent"];
$prodfourn->fourn_remise = $record["remise"];
$prodfourn->fourn_unitprice = $record["unitprice"];
- $prodfourn->fourn_charges = $record["charges"]; // deprecated
- $prodfourn->fourn_tva_tx = $record["tva_tx"];
- $prodfourn->fourn_id = $record["fourn_id"];
- $prodfourn->fourn_name = $record["supplier_name"];
- $prodfourn->fk_availability = $record["fk_availability"];
- $prodfourn->delivery_time_days = $record["delivery_time_days"];
- $prodfourn->id = $prodid;
- $prodfourn->fourn_tva_npr = $record["info_bits"];
- $prodfourn->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
+ $prodfourn->fourn_charges = $record["charges"]; // deprecated
+ $prodfourn->fourn_tva_tx = $record["tva_tx"];
+ $prodfourn->fourn_id = $record["fourn_id"];
+ $prodfourn->fourn_name = $record["supplier_name"];
+ $prodfourn->fk_availability = $record["fk_availability"];
+ $prodfourn->delivery_time_days = $record["delivery_time_days"];
+ $prodfourn->id = $prodid;
+ $prodfourn->fourn_tva_npr = $record["info_bits"];
+ $prodfourn->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
$prodfourn->supplier_reputation = $record["supplier_reputation"];
$prodfourn->fourn_date_creation = $this->db->jdate($record['datec']);
$prodfourn->fourn_date_modification = $this->db->jdate($record['tms']);
- $prodfourn->fourn_multicurrency_price = $record["multicurrency_price"];
- $prodfourn->fourn_multicurrency_unitprice = $record["multicurrency_unitprice"];
- $prodfourn->fourn_multicurrency_tx = $record["multicurrency_tx"];
- $prodfourn->fourn_multicurrency_id = $record["fk_multicurrency"];
- $prodfourn->fourn_multicurrency_code = $record["multicurrency_code"];
+ $prodfourn->fourn_multicurrency_price = $record["multicurrency_price"];
+ $prodfourn->fourn_multicurrency_unitprice = $record["multicurrency_unitprice"];
+ $prodfourn->fourn_multicurrency_tx = $record["multicurrency_tx"];
+ $prodfourn->fourn_multicurrency_id = $record["fk_multicurrency"];
+ $prodfourn->fourn_multicurrency_code = $record["multicurrency_code"];
if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
$prodfourn->packaging = $record["packaging"];
if ($prodfourn->packaging < $prodfourn->fourn_qty) $prodfourn->packaging = $prodfourn->fourn_qty;
}
- if ($conf->barcode->enabled) {
- $prodfourn->barcode = $record["barcode"];
- $prodfourn->fk_barcode_type = $record["fk_barcode_type"];
- }
+ if ($conf->barcode->enabled) {
+ $prodfourn->barcode = $record["barcode"];
+ $prodfourn->fk_barcode_type = $record["fk_barcode_type"];
+ }
- if (!empty($conf->dynamicprices->enabled) && !empty($prodfourn->fk_supplier_price_expression)) {
- $priceparser = new PriceParser($this->db);
- $price_result = $priceparser->parseProductSupplier($prodfourn);
- if ($price_result >= 0) {
- $prodfourn->fourn_price = $price_result;
- $prodfourn->fourn_unitprice = null; //force recalculation of unitprice, as probably the price changed...
- }
- }
+ if (!empty($conf->dynamicprices->enabled) && !empty($prodfourn->fk_supplier_price_expression)) {
+ $priceparser = new PriceParser($this->db);
+ $price_result = $priceparser->parseProductSupplier($prodfourn);
+ if ($price_result >= 0) {
+ $prodfourn->fourn_price = $price_result;
+ $prodfourn->fourn_unitprice = null; //force recalculation of unitprice, as probably the price changed...
+ }
+ }
- if (!isset($prodfourn->fourn_unitprice))
- {
- if ($prodfourn->fourn_qty != 0)
- {
- $prodfourn->fourn_unitprice = price2num($prodfourn->fourn_price / $prodfourn->fourn_qty, 'MU');
- } else {
- $prodfourn->fourn_unitprice = "";
- }
- }
+ if (!isset($prodfourn->fourn_unitprice))
+ {
+ if ($prodfourn->fourn_qty != 0)
+ {
+ $prodfourn->fourn_unitprice = price2num($prodfourn->fourn_price / $prodfourn->fourn_qty, 'MU');
+ } else {
+ $prodfourn->fourn_unitprice = "";
+ }
+ }
- $retarray[] = $prodfourn;
- }
+ $retarray[] = $prodfourn;
+ }
- $this->db->free($resql);
- return $retarray;
- } else {
- $this->error = $this->db->error();
- return -1;
- }
- }
+ $this->db->free($resql);
+ return $retarray;
+ } else {
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Load properties for minimum price
- *
- * @param int $prodid Product id
- * @param int $qty Minimum quantity
- * @param int $socid get min price for specific supplier
- * @return int <0 if KO, 0=Not found of no product id provided, >0 if OK
- */
- public function find_min_price_product_fournisseur($prodid, $qty = 0, $socid = 0)
- {
- // phpcs:enable
- global $conf;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Load properties for minimum price
+ *
+ * @param int $prodid Product id
+ * @param int $qty Minimum quantity
+ * @param int $socid get min price for specific supplier
+ * @return int <0 if KO, 0=Not found of no product id provided, >0 if OK
+ */
+ public function find_min_price_product_fournisseur($prodid, $qty = 0, $socid = 0)
+ {
+ // phpcs:enable
+ global $conf;
- if (empty($prodid))
- {
- dol_syslog("Warning function find_min_price_product_fournisseur were called with prodid empty. May be a bug.", LOG_WARNING);
- return 0;
- }
+ if (empty($prodid))
+ {
+ dol_syslog("Warning function find_min_price_product_fournisseur were called with prodid empty. May be a bug.", LOG_WARNING);
+ return 0;
+ }
- $this->product_fourn_price_id = '';
- $this->product_fourn_id = '';
- $this->fourn_ref = '';
- $this->fourn_price = '';
- $this->fourn_qty = '';
- $this->fourn_remise_percent = '';
- $this->fourn_remise = '';
- $this->fourn_unitprice = '';
- $this->fourn_id = '';
- $this->fourn_name = '';
+ $this->product_fourn_price_id = '';
+ $this->product_fourn_id = '';
+ $this->fourn_ref = '';
+ $this->fourn_price = '';
+ $this->fourn_qty = '';
+ $this->fourn_remise_percent = '';
+ $this->fourn_remise = '';
+ $this->fourn_unitprice = '';
+ $this->fourn_id = '';
+ $this->fourn_name = '';
$this->delivery_time_days = '';
- $this->id = '';
+ $this->id = '';
- $this->fourn_multicurrency_price = '';
- $this->fourn_multicurrency_unitprice = '';
- $this->fourn_multicurrency_tx = '';
- $this->fourn_multicurrency_id = '';
- $this->fourn_multicurrency_code = '';
+ $this->fourn_multicurrency_price = '';
+ $this->fourn_multicurrency_unitprice = '';
+ $this->fourn_multicurrency_tx = '';
+ $this->fourn_multicurrency_id = '';
+ $this->fourn_multicurrency_code = '';
- $sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id,";
- $sql .= " pfp.rowid as product_fourn_price_id, pfp.ref_fourn,";
- $sql .= " pfp.price, pfp.quantity, pfp.unitprice, pfp.tva_tx, pfp.charges,";
- $sql .= " pfp.remise, pfp.remise_percent, pfp.fk_supplier_price_expression, pfp.delivery_time_days";
- $sql .= " ,pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code";
- $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
- $sql .= " WHERE s.entity IN (".getEntity('societe').")";
- $sql .= " AND pfp.entity = ".$conf->entity; // only current entity
- $sql .= " AND pfp.fk_product = ".$prodid;
- $sql .= " AND pfp.fk_soc = s.rowid";
- $sql .= " AND s.status = 1"; // only enabled society
- if ($qty > 0) $sql .= " AND pfp.quantity <= ".$qty;
+ $sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id,";
+ $sql .= " pfp.rowid as product_fourn_price_id, pfp.ref_fourn,";
+ $sql .= " pfp.price, pfp.quantity, pfp.unitprice, pfp.tva_tx, pfp.charges,";
+ $sql .= " pfp.remise, pfp.remise_percent, pfp.fk_supplier_price_expression, pfp.delivery_time_days";
+ $sql .= " ,pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code";
+ $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
+ $sql .= " WHERE s.entity IN (".getEntity('societe').")";
+ $sql .= " AND pfp.entity = ".$conf->entity; // only current entity
+ $sql .= " AND pfp.fk_product = ".$prodid;
+ $sql .= " AND pfp.fk_soc = s.rowid";
+ $sql .= " AND s.status = 1"; // only enabled society
+ if ($qty > 0) $sql .= " AND pfp.quantity <= ".$qty;
if ($socid > 0) $sql .= ' AND pfp.fk_soc = '.$socid;
- dol_syslog(get_class($this)."::find_min_price_product_fournisseur", LOG_DEBUG);
+ dol_syslog(get_class($this)."::find_min_price_product_fournisseur", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $record_array = array();
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $record_array = array();
- //Store each record to array for later search of min
- while ($record = $this->db->fetch_array($resql))
- {
- $record_array[] = $record;
- }
+ //Store each record to array for later search of min
+ while ($record = $this->db->fetch_array($resql))
+ {
+ $record_array[] = $record;
+ }
- if (count($record_array) == 0)
- {
- $this->db->free($resql);
- return 0;
- } else {
- $min = -1;
- foreach ($record_array as $record)
- {
- $fourn_price = $record["price"];
- // discount calculated buy price
- $fourn_unitprice = $record["unitprice"] * (1 - $record["remise_percent"] / 100) - $record["remise"];
- if (!empty($conf->dynamicprices->enabled) && !empty($record["fk_supplier_price_expression"])) {
- $prod_supplier = new ProductFournisseur($this->db);
- $prod_supplier->product_fourn_price_id = $record["product_fourn_price_id"];
- $prod_supplier->id = $prodid;
- $prod_supplier->fourn_qty = $record["quantity"];
- $prod_supplier->fourn_tva_tx = $record["tva_tx"];
- $prod_supplier->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
- $priceparser = new PriceParser($this->db);
- $price_result = $priceparser->parseProductSupplier($prod_supplier);
- if ($price_result >= 0) {
- $fourn_price = price2num($price_result, 'MU');
- if ($record["quantity"] != 0)
- {
- $fourn_unitprice = price2num($fourn_price / $record["quantity"], 'MU');
- } else {
- $fourn_unitprice = $fourn_price;
- }
- }
- }
- if ($fourn_unitprice < $min || $min == -1)
- {
- $this->product_fourn_price_id = $record["product_fourn_price_id"];
- $this->ref_supplier = $record["ref_fourn"];
- $this->ref_fourn = $record["ref_fourn"]; // deprecated
- $this->fourn_ref = $record["ref_fourn"]; // deprecated
- $this->fourn_price = $fourn_price;
- $this->fourn_qty = $record["quantity"];
- $this->fourn_remise_percent = $record["remise_percent"];
- $this->fourn_remise = $record["remise"];
- $this->fourn_unitprice = $record["unitprice"];
- $this->fourn_charges = $record["charges"]; // deprecated
- $this->fourn_tva_tx = $record["tva_tx"];
- $this->fourn_id = $record["fourn_id"];
- $this->fourn_name = $record["supplier_name"];
+ if (count($record_array) == 0)
+ {
+ $this->db->free($resql);
+ return 0;
+ } else {
+ $min = -1;
+ foreach ($record_array as $record)
+ {
+ $fourn_price = $record["price"];
+ // discount calculated buy price
+ $fourn_unitprice = $record["unitprice"] * (1 - $record["remise_percent"] / 100) - $record["remise"];
+ if (!empty($conf->dynamicprices->enabled) && !empty($record["fk_supplier_price_expression"])) {
+ $prod_supplier = new ProductFournisseur($this->db);
+ $prod_supplier->product_fourn_price_id = $record["product_fourn_price_id"];
+ $prod_supplier->id = $prodid;
+ $prod_supplier->fourn_qty = $record["quantity"];
+ $prod_supplier->fourn_tva_tx = $record["tva_tx"];
+ $prod_supplier->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
+ $priceparser = new PriceParser($this->db);
+ $price_result = $priceparser->parseProductSupplier($prod_supplier);
+ if ($price_result >= 0) {
+ $fourn_price = price2num($price_result, 'MU');
+ if ($record["quantity"] != 0)
+ {
+ $fourn_unitprice = price2num($fourn_price / $record["quantity"], 'MU');
+ } else {
+ $fourn_unitprice = $fourn_price;
+ }
+ }
+ }
+ if ($fourn_unitprice < $min || $min == -1)
+ {
+ $this->product_fourn_price_id = $record["product_fourn_price_id"];
+ $this->ref_supplier = $record["ref_fourn"];
+ $this->ref_fourn = $record["ref_fourn"]; // deprecated
+ $this->fourn_ref = $record["ref_fourn"]; // deprecated
+ $this->fourn_price = $fourn_price;
+ $this->fourn_qty = $record["quantity"];
+ $this->fourn_remise_percent = $record["remise_percent"];
+ $this->fourn_remise = $record["remise"];
+ $this->fourn_unitprice = $record["unitprice"];
+ $this->fourn_charges = $record["charges"]; // deprecated
+ $this->fourn_tva_tx = $record["tva_tx"];
+ $this->fourn_id = $record["fourn_id"];
+ $this->fourn_name = $record["supplier_name"];
$this->delivery_time_days = $record["delivery_time_days"];
- $this->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
- $this->id = $prodid;
- $this->fourn_multicurrency_price = $record["multicurrency_price"];
- $this->fourn_multicurrency_unitprice = $record["multicurrency_unitprice"];
- $this->fourn_multicurrency_tx = $record["multicurrency_tx"];
- $this->fourn_multicurrency_id = $record["fk_multicurrency"];
- $this->fourn_multicurrency_code = $record["multicurrency_code"];
- $min = $fourn_unitprice;
- }
- }
- }
+ $this->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
+ $this->id = $prodid;
+ $this->fourn_multicurrency_price = $record["multicurrency_price"];
+ $this->fourn_multicurrency_unitprice = $record["multicurrency_unitprice"];
+ $this->fourn_multicurrency_tx = $record["multicurrency_tx"];
+ $this->fourn_multicurrency_id = $record["fk_multicurrency"];
+ $this->fourn_multicurrency_code = $record["multicurrency_code"];
+ $min = $fourn_unitprice;
+ }
+ }
+ }
- $this->db->free($resql);
- return 1;
- } else {
- $this->error = $this->db->error();
- return -1;
- }
- }
+ $this->db->free($resql);
+ return 1;
+ } else {
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
- /**
- * Sets the supplier price expression
- *
- * @param int $expression_id Expression
- * @return int <0 if KO, >0 if OK
- */
- public function setSupplierPriceExpression($expression_id)
- {
- global $conf;
+ /**
+ * Sets the supplier price expression
+ *
+ * @param int $expression_id Expression
+ * @return int <0 if KO, >0 if OK
+ */
+ public function setSupplierPriceExpression($expression_id)
+ {
+ global $conf;
- // Clean parameters
- $this->db->begin();
- $expression_id = $expression_id != 0 ? $expression_id : 'NULL';
+ // Clean parameters
+ $this->db->begin();
+ $expression_id = $expression_id != 0 ? $expression_id : 'NULL';
- $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price";
- $sql .= " SET fk_supplier_price_expression = ".$expression_id;
- $sql .= " WHERE rowid = ".$this->product_fourn_price_id;
+ $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price";
+ $sql .= " SET fk_supplier_price_expression = ".$expression_id;
+ $sql .= " WHERE rowid = ".$this->product_fourn_price_id;
- dol_syslog(get_class($this)."::setSupplierPriceExpression", LOG_DEBUG);
+ dol_syslog(get_class($this)."::setSupplierPriceExpression", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->error = $this->db->error()." sql=".$sql;
- $this->db->rollback();
- return -1;
- }
- }
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->error = $this->db->error()." sql=".$sql;
+ $this->db->rollback();
+ return -1;
+ }
+ }
- /**
- * Display supplier of product
- *
- * @param int $withpicto Add picto
- * @param string $option Target of link ('', 'customer', 'prospect', 'supplier')
- * @param int $maxlen Max length of name
- * @param integer $notooltip 1=Disable tooltip
- * @return string String with supplier price
+ /**
+ * Display supplier of product
+ *
+ * @param int $withpicto Add picto
+ * @param string $option Target of link ('', 'customer', 'prospect', 'supplier')
+ * @param int $maxlen Max length of name
+ * @param integer $notooltip 1=Disable tooltip
+ * @return string String with supplier price
* TODO Remove this method. Use getNomUrl directly.
- */
- public function getSocNomUrl($withpicto = 0, $option = 'supplier', $maxlen = 0, $notooltip = 0)
- {
- $thirdparty = new Fournisseur($this->db);
- $thirdparty->fetch($this->fourn_id);
+ */
+ public function getSocNomUrl($withpicto = 0, $option = 'supplier', $maxlen = 0, $notooltip = 0)
+ {
+ $thirdparty = new Fournisseur($this->db);
+ $thirdparty->fetch($this->fourn_id);
- return $thirdparty->getNomUrl($withpicto, $option, $maxlen, $notooltip);
- }
+ return $thirdparty->getNomUrl($withpicto, $option, $maxlen, $notooltip);
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Display price of product
- *
- * @param int $showunitprice Show "Unit price" into output string
- * @param int $showsuptitle Show "Supplier" into output string
- * @param int $maxlen Max length of name
- * @param integer $notooltip 1=Disable tooltip
- * @param array $productFournList list of ProductFournisseur objects
- * to display in table format.
- * @return string String with supplier price
- */
- public function display_price_product_fournisseur($showunitprice = 1, $showsuptitle = 1, $maxlen = 0, $notooltip = 0, $productFournList = array())
- {
- // phpcs:enable
- global $langs;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Display price of product
+ *
+ * @param int $showunitprice Show "Unit price" into output string
+ * @param int $showsuptitle Show "Supplier" into output string
+ * @param int $maxlen Max length of name
+ * @param integer $notooltip 1=Disable tooltip
+ * @param array $productFournList list of ProductFournisseur objects
+ * to display in table format.
+ * @return string String with supplier price
+ */
+ public function display_price_product_fournisseur($showunitprice = 1, $showsuptitle = 1, $maxlen = 0, $notooltip = 0, $productFournList = array())
+ {
+ // phpcs:enable
+ global $langs;
- $out = '';
- $langs->load("suppliers");
- if (count($productFournList) > 0) {
- $out .= '';
- $out .= ''.($showunitprice ? $langs->trans("Price").' '.$langs->trans("HT") : '').' ';
- $out .= ''.($showunitprice ? $langs->trans("QtyMin") : '').' ';
- $out .= ''.$langs->trans("Supplier").' ';
- $out .= ''.$langs->trans("SupplierRef").' ';
- foreach ($productFournList as $productFourn) {
- $out .= ''.($showunitprice ?price($productFourn->fourn_unitprice * (1 - $productFourn->fourn_remise_percent / 100) - $productFourn->fourn_remise) : '').' ';
- $out .= ''.($showunitprice ? $productFourn->fourn_qty : '').' ';
- $out .= ''.$productFourn->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).' ';
- $out .= ''.$productFourn->fourn_ref.' ';
- }
- $out .= '
';
- } else {
- $out = ($showunitprice ?price($this->fourn_unitprice * (1 - $this->fourn_remise_percent / 100) + $this->fourn_remise).' '.$langs->trans("HT").' (' : '').($showsuptitle ? $langs->trans("Supplier").': ' : '').$this->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).' / '.$langs->trans("SupplierRef").': '.$this->fourn_ref.($showunitprice ? ')' : '');
- }
- return $out;
- }
+ $out = '';
+ $langs->load("suppliers");
+ if (count($productFournList) > 0) {
+ $out .= '';
+ $out .= ''.($showunitprice ? $langs->trans("Price").' '.$langs->trans("HT") : '').' ';
+ $out .= ''.($showunitprice ? $langs->trans("QtyMin") : '').' ';
+ $out .= ''.$langs->trans("Supplier").' ';
+ $out .= ''.$langs->trans("SupplierRef").' ';
+ foreach ($productFournList as $productFourn) {
+ $out .= ''.($showunitprice ?price($productFourn->fourn_unitprice * (1 - $productFourn->fourn_remise_percent / 100) - $productFourn->fourn_remise) : '').' ';
+ $out .= ''.($showunitprice ? $productFourn->fourn_qty : '').' ';
+ $out .= ''.$productFourn->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).' ';
+ $out .= ''.$productFourn->fourn_ref.' ';
+ }
+ $out .= '
';
+ } else {
+ $out = ($showunitprice ?price($this->fourn_unitprice * (1 - $this->fourn_remise_percent / 100) + $this->fourn_remise).' '.$langs->trans("HT").' (' : '').($showsuptitle ? $langs->trans("Supplier").': ' : '').$this->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).' / '.$langs->trans("SupplierRef").': '.$this->fourn_ref.($showunitprice ? ')' : '');
+ }
+ return $out;
+ }
- /**
- * Function used to replace a thirdparty id with another one.
- *
- * @param DoliDB $db Database handler
- * @param int $origin_id Old thirdparty id
- * @param int $dest_id New thirdparty id
- * @return bool
- */
- public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
- {
- $tables = array(
- 'product_fournisseur_price'
- );
+ /**
+ * Function used to replace a thirdparty id with another one.
+ *
+ * @param DoliDB $db Database handler
+ * @param int $origin_id Old thirdparty id
+ * @param int $dest_id New thirdparty id
+ * @return bool
+ */
+ public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+ {
+ $tables = array(
+ 'product_fournisseur_price'
+ );
- return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
- }
+ return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+ }
- /**
- * List supplier prices log of a supplier price
- *
- * @param int $product_fourn_price_id Id of supplier price
- * @param string $sortfield Sort field
- * @param string $sortorder Sort order
- * @param int $limit Limit
- * @param int $offset Offset
- * @return array Array of Log prices
- */
- public function listProductFournisseurPriceLog($product_fourn_price_id, $sortfield = '', $sortorder = '', $limit = 0, $offset = 0)
- {
- $sql = "SELECT";
- $sql .= " pfpl.rowid, pfp.ref_fourn as supplier_ref, pfpl.datec, u.lastname,";
- $sql .= " pfpl.price, pfpl.quantity";
- $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price_log as pfpl";
- $sql .= ", ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
- $sql .= ", ".MAIN_DB_PREFIX."user as u";
- $sql .= " WHERE pfp.entity IN (".getEntity('productprice').")";
- $sql .= " AND pfpl.fk_user = u.rowid";
- $sql .= " AND pfp.rowid = pfpl.fk_product_fournisseur";
- $sql .= " AND pfpl.fk_product_fournisseur = ".$product_fourn_price_id;
- if (empty($sortfield)) $sql .= " ORDER BY pfpl.datec";
- else $sql .= $this->db->order($sortfield, $sortorder);
- $sql .= $this->db->plimit($limit, $offset);
- dol_syslog(get_class($this)."::list_product_fournisseur_price_log", LOG_DEBUG);
+ /**
+ * List supplier prices log of a supplier price
+ *
+ * @param int $product_fourn_price_id Id of supplier price
+ * @param string $sortfield Sort field
+ * @param string $sortorder Sort order
+ * @param int $limit Limit
+ * @param int $offset Offset
+ * @return array Array of Log prices
+ */
+ public function listProductFournisseurPriceLog($product_fourn_price_id, $sortfield = '', $sortorder = '', $limit = 0, $offset = 0)
+ {
+ $sql = "SELECT";
+ $sql .= " pfpl.rowid, pfp.ref_fourn as supplier_ref, pfpl.datec, u.lastname,";
+ $sql .= " pfpl.price, pfpl.quantity";
+ $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price_log as pfpl";
+ $sql .= ", ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
+ $sql .= ", ".MAIN_DB_PREFIX."user as u";
+ $sql .= " WHERE pfp.entity IN (".getEntity('productprice').")";
+ $sql .= " AND pfpl.fk_user = u.rowid";
+ $sql .= " AND pfp.rowid = pfpl.fk_product_fournisseur";
+ $sql .= " AND pfpl.fk_product_fournisseur = ".$product_fourn_price_id;
+ if (empty($sortfield)) $sql .= " ORDER BY pfpl.datec";
+ else $sql .= $this->db->order($sortfield, $sortorder);
+ $sql .= $this->db->plimit($limit, $offset);
+ dol_syslog(get_class($this)."::list_product_fournisseur_price_log", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $retarray = array();
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $retarray = array();
- while ($obj = $this->db->fetch_object($resql))
- {
- $tmparray = array();
- $tmparray['rowid'] = $obj->rowid;
- $tmparray['supplier_ref'] = $obj->supplier_ref;
- $tmparray['datec'] = $this->db->jdate($obj->datec);
- $tmparray['lastname'] = $obj->lastname;
- $tmparray['price'] = $obj->price;
- $tmparray['quantity'] = $obj->quantity;
+ while ($obj = $this->db->fetch_object($resql))
+ {
+ $tmparray = array();
+ $tmparray['rowid'] = $obj->rowid;
+ $tmparray['supplier_ref'] = $obj->supplier_ref;
+ $tmparray['datec'] = $this->db->jdate($obj->datec);
+ $tmparray['lastname'] = $obj->lastname;
+ $tmparray['price'] = $obj->price;
+ $tmparray['quantity'] = $obj->quantity;
- $retarray[] = $tmparray;
- }
+ $retarray[] = $tmparray;
+ }
- $this->db->free($resql);
- return $retarray;
- } else {
- $this->error = $this->db->error();
- return -1;
- }
- }
+ $this->db->free($resql);
+ return $retarray;
+ } else {
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
- /**
- * Display log price of product supplier price
- *
- * @param array $productFournLogList list of ProductFournisseur price log objects
- * to display in table format.
- * @return string HTML String with supplier price
- */
- public function displayPriceProductFournisseurLog($productFournLogList = array())
- {
- global $langs;
+ /**
+ * Display log price of product supplier price
+ *
+ * @param array $productFournLogList list of ProductFournisseur price log objects
+ * to display in table format.
+ * @return string HTML String with supplier price
+ */
+ public function displayPriceProductFournisseurLog($productFournLogList = array())
+ {
+ global $langs;
- $out = '';
- $langs->load("suppliers");
- if (count($productFournLogList) > 0) {
- $out .= '';
- $out .= ''.$langs->trans("Date").' ';
- $out .= ''.$langs->trans("Price").' ';
- //$out .= ''.$langs->trans("QtyMin").' ';
- $out .= ''.$langs->trans("User").' ';
- foreach ($productFournLogList as $productFournLog) {
- $out .= ''.dol_print_date($productFournLog['datec'], 'dayhour', 'tzuser').' ';
- $out .= ''.price($productFournLog['price']).' ';
- //$out.= ''.$productFournLog['quantity'].' ';
- $out .= ''.$productFournLog['lastname'].' ';
- }
- $out .= '
';
- }
- return $out;
- }
+ $out = '';
+ $langs->load("suppliers");
+ if (count($productFournLogList) > 0) {
+ $out .= '';
+ $out .= ''.$langs->trans("Date").' ';
+ $out .= ''.$langs->trans("Price").' ';
+ //$out .= ''.$langs->trans("QtyMin").' ';
+ $out .= ''.$langs->trans("User").' ';
+ foreach ($productFournLogList as $productFournLog) {
+ $out .= ''.dol_print_date($productFournLog['datec'], 'dayhour', 'tzuser').' ';
+ $out .= ''.price($productFournLog['price']).' ';
+ //$out.= ''.$productFournLog['quantity'].' ';
+ $out .= ''.$productFournLog['lastname'].' ';
+ }
+ $out .= '
';
+ }
+ return $out;
+ }
- /**
- * Return a link to the object card (with optionaly the picto).
- * Used getNomUrl of ProductFournisseur if a specific supplier ref is loaded. Otherwise use Product->getNomUrl().
- *
- * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
- * @param string $option On what the link point to ('nolink', ...)
- * @param int $notooltip 1=Disable tooltip
- * @param string $morecss Add more css on link
- * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
- * @return string String with URL
- */
- public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
- {
- global $db, $conf, $langs;
+ /**
+ * Return a link to the object card (with optionaly the picto).
+ * Used getNomUrl of ProductFournisseur if a specific supplier ref is loaded. Otherwise use Product->getNomUrl().
+ *
+ * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+ * @param string $option On what the link point to ('nolink', ...)
+ * @param int $notooltip 1=Disable tooltip
+ * @param string $morecss Add more css on link
+ * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @return string String with URL
+ */
+ public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+ {
+ global $db, $conf, $langs;
- 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 = '';
- $label = ''.$langs->trans("SupplierRef").' ';
- $label .= ' ';
- $label .= ''.$langs->trans('Product').': '.$this->ref;
- $label .= ''.$langs->trans('RefSupplier').': '.$this->ref_supplier;
+ $label = ''.$langs->trans("SupplierRef").' ';
+ $label .= ' ';
+ $label .= ''.$langs->trans('Product').': '.$this->ref;
+ $label .= ''.$langs->trans('RefSupplier').': '.$this->ref_supplier;
- $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id, 'pfpl.datec', 'DESC'); // set sort order here
- if (is_array($logPrices) && count($logPrices) > 0) {
- $label .= ' ';
- $label .= ''.$langs->trans("History").' ';
- $label .= $this->displayPriceProductFournisseurLog($logPrices);
- }
+ $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id, 'pfpl.datec', 'DESC'); // set sort order here
+ if (is_array($logPrices) && count($logPrices) > 0) {
+ $label .= ' ';
+ $label .= ''.$langs->trans("History").' ';
+ $label .= $this->displayPriceProductFournisseurLog($logPrices);
+ }
- $url = dol_buildpath('/product/fournisseurs.php', 1).'?id='.$this->id.'&action=add_price&socid='.$this->fourn_id.'&rowid='.$this->product_fourn_price_id;
+ $url = dol_buildpath('/product/fournisseurs.php', 1).'?id='.$this->id.'&action=add_price&socid='.$this->fourn_id.'&rowid='.$this->product_fourn_price_id;
- if ($option != 'nolink')
- {
- // Add param to save lastsearch_values or not
- $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 ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
- }
+ if ($option != 'nolink')
+ {
+ // Add param to save lastsearch_values or not
+ $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 ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
+ }
- $linkclose = '';
- if (empty($notooltip))
- {
- if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
- {
- $label = $langs->trans("SupplierRef");
- $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
- }
- $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
- $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
- } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+ $linkclose = '';
+ if (empty($notooltip))
+ {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
+ {
+ $label = $langs->trans("SupplierRef");
+ $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+ }
+ $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+ $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
+ } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
- $linkstart = '';
- $linkend = ' ';
+ $linkstart = '';
+ $linkend = ' ';
- $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 != 2) $result .= $this->ref.($this->ref_supplier ? ' ('.$this->ref_supplier.')' : '');
- $result .= $linkend;
- //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
+ $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 != 2) $result .= $this->ref.($this->ref_supplier ? ' ('.$this->ref_supplier.')' : '');
+ $result .= $linkend;
+ //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
- return $result;
- }
+ return $result;
+ }
- /**
- * Private function to log price history
- *
- * @param User $user Object user who adds/changes price
- * @param integer $datec date create
- * @param float $buyprice price for qty
- * @param float $qty qty for price
- * @param float $multicurrency_buyprice Purchase price for the quantity min in currency
- * @param float $multicurrency_unitBuyPrice Unit Purchase price in currency
- * @param float $multicurrency_tx Rate currency
- * @param int $fk_multicurrency key multi currency
- * @param string $multicurrency_code Currency code
- *
- * @return int < 0 NOK > 0 OK
- */
- private function logPrice($user, $datec, $buyprice, $qty, $multicurrency_buyprice = null, $multicurrency_unitBuyPrice = null, $multicurrency_tx = null, $fk_multicurrency = null, $multicurrency_code = null)
- {
- // Add record into log table
- $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price_log(";
- $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,";
- $sql .= "datec, fk_product_fournisseur,fk_user,price,quantity)";
- $sql .= "values(";
- $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').",";
- $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').",";
- $sql .= (isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').",";
- $sql .= (isset($fk_multicurrency) ? "'".$this->db->escape($fk_multicurrency)."'" : 'null').",";
- $sql .= (isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').",";
- $sql .= "'".$this->db->idate($datec)."',";
- $sql .= " ".$this->product_fourn_price_id.",";
- $sql .= " ".$user->id.",";
- $sql .= " ".price2num($buyprice).",";
- $sql .= " ".$qty;
- $sql .= ")";
+ /**
+ * Private function to log price history
+ *
+ * @param User $user Object user who adds/changes price
+ * @param integer $datec date create
+ * @param float $buyprice price for qty
+ * @param float $qty qty for price
+ * @param float $multicurrency_buyprice Purchase price for the quantity min in currency
+ * @param float $multicurrency_unitBuyPrice Unit Purchase price in currency
+ * @param float $multicurrency_tx Rate currency
+ * @param int $fk_multicurrency key multi currency
+ * @param string $multicurrency_code Currency code
+ *
+ * @return int < 0 NOK > 0 OK
+ */
+ private function logPrice($user, $datec, $buyprice, $qty, $multicurrency_buyprice = null, $multicurrency_unitBuyPrice = null, $multicurrency_tx = null, $fk_multicurrency = null, $multicurrency_code = null)
+ {
+ // Add record into log table
+ $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price_log(";
+ $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,";
+ $sql .= "datec, fk_product_fournisseur,fk_user,price,quantity)";
+ $sql .= "values(";
+ $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').",";
+ $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').",";
+ $sql .= (isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').",";
+ $sql .= (isset($fk_multicurrency) ? "'".$this->db->escape($fk_multicurrency)."'" : 'null').",";
+ $sql .= (isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').",";
+ $sql .= "'".$this->db->idate($datec)."',";
+ $sql .= " ".$this->product_fourn_price_id.",";
+ $sql .= " ".$user->id.",";
+ $sql .= " ".price2num($buyprice).",";
+ $sql .= " ".$qty;
+ $sql .= ")";
- $resql = $this->db->query($sql);
- if (!$resql) {
- return -1;
- } else {
- return 1;
- }
- }
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ return -1;
+ } else {
+ return 1;
+ }
+ }
}
diff --git a/htdocs/fourn/class/paiementfourn.class.php b/htdocs/fourn/class/paiementfourn.class.php
index 67133ed97b2..8689801e543 100644
--- a/htdocs/fourn/class/paiementfourn.class.php
+++ b/htdocs/fourn/class/paiementfourn.class.php
@@ -123,7 +123,7 @@ class PaiementFourn extends Paiement
$this->bank_account = $obj->fk_account;
$this->fk_account = $obj->fk_account;
$this->bank_line = $obj->fk_bank;
- $this->montant = $obj->amount; // deprecated
+ $this->montant = $obj->amount; // deprecated
$this->amount = $obj->amount;
$this->multicurrency_amount = $obj->multicurrency_amount;
$this->note = $obj->note;
@@ -176,7 +176,7 @@ class PaiementFourn extends Paiement
foreach ($amounts as $key => $value)
{
- $value_converted = Multicurrency::getAmountConversionFromInvoiceRate($key, $value? $value : 0, $way, 'facture_fourn');
+ $value_converted = Multicurrency::getAmountConversionFromInvoiceRate($key, $value ? $value : 0, $way, 'facture_fourn');
$totalamount_converted += $value_converted;
$amounts_to_update[$key] = price2num($value_converted, 'MT');
@@ -191,7 +191,7 @@ class PaiementFourn extends Paiement
if ($totalamount <> 0) // On accepte les montants negatifs
{
- $ref = $this->getNextNumRef(is_object($thirdparty) ? $thirdparty : '');
+ $ref = $this->getNextNumRef(is_object($thirdparty) ? $thirdparty : '');
$now = dol_now();
if ($way == 'dolibarr')
@@ -247,8 +247,8 @@ class PaiementFourn extends Paiement
// Regenerate documents of invoices
if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
{
- $newlang = '';
- $outputlangs = $langs;
+ $newlang = '';
+ $outputlangs = $langs;
if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $invoice->thirdparty->default_lang;
if (!empty($newlang)) {
$outputlangs = new Translate("", $conf);
@@ -491,7 +491,7 @@ class PaiementFourn extends Paiement
return $this->LibStatut($this->statut, $mode);
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Renvoi le libelle d'un statut donne
*
@@ -501,7 +501,7 @@ class PaiementFourn extends Paiement
*/
public function LibStatut($status, $mode = 0)
{
- // phpcs:enable
+ // phpcs:enable
global $langs;
$langs->load('compta');
@@ -550,7 +550,7 @@ class PaiementFourn extends Paiement
* @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
* @param string $option Sur quoi pointe le lien
* @param string $mode 'withlistofinvoices'=Include list of invoices into tooltip
- * @param int $notooltip 1=Disable tooltip
+ * @param int $notooltip 1=Disable tooltip
* @return string Chaine avec URL
*/
public function getNomUrl($withpicto = 0, $option = '', $mode = 'withlistofinvoices', $notooltip = 0)
@@ -695,7 +695,7 @@ class PaiementFourn extends Paiement
* @param int $hidedetails Hide details of lines
* @param int $hidedesc Hide description
* @param int $hideref Hide ref
- * @param null|array $moreparams Array to provide more information
+ * @param null|array $moreparams Array to provide more information
* @return int <0 if KO, 0 if nothing done, >0 if OK
*/
public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
@@ -753,7 +753,7 @@ class PaiementFourn extends Paiement
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Load the third party of object, from id into this->thirdparty
*
@@ -762,7 +762,7 @@ class PaiementFourn extends Paiement
*/
public function fetch_thirdparty($force_thirdparty_id = 0)
{
- // phpcs:enable
+ // phpcs:enable
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
if (empty($force_thirdparty_id))
diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php
index 524d67e55b9..b5a0111e4f4 100644
--- a/htdocs/fourn/commande/card.php
+++ b/htdocs/fourn/commande/card.php
@@ -110,7 +110,7 @@ if ($id > 0 || !empty($ref))
}
// Common permissions
-$usercanread = $user->rights->fournisseur->commande->lire;
+$usercanread = $user->rights->fournisseur->commande->lire;
$usercancreate = $user->rights->fournisseur->commande->creer;
$usercandelete = $user->rights->fournisseur->commande->supprimer;
@@ -119,14 +119,14 @@ $usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($u
// Additional area permissions
$usercanapprove = $user->rights->fournisseur->commande->approuver;
-$usercanapprovesecond = $user->rights->fournisseur->commande->approve2;
-$usercanorder = $user->rights->fournisseur->commande->commander;
+$usercanapprovesecond = $user->rights->fournisseur->commande->approve2;
+$usercanorder = $user->rights->fournisseur->commande->commander;
$usercanreceived = $user->rights->fournisseur->commande->receptionner;
// Permissions for includes
$permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
-$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
-$permissiontoedit = $usercancreate; // Used by the include of actions_lineupdown.inc.php
+$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
+$permissiontoedit = $usercancreate; // Used by the include of actions_lineupdown.inc.php
$permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php
@@ -872,7 +872,7 @@ if (empty($reshook))
$action = 'confirm_approve'; // can make standard or first level approval also if permission is set
}
- if (! $error) {
+ if (!$error) {
$db->commit();
} else {
$db->rollback();
@@ -1059,7 +1059,7 @@ if (empty($reshook))
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Delivery")), null, 'errors');
}
- if (! $error) {
+ if (!$error) {
$db->commit();
} else {
$db->rollback();
@@ -1684,8 +1684,8 @@ if ($action == 'create')
// Incoterms
if (!empty($conf->incoterm->enabled))
{
- $fkincoterms = (!empty($object->fk_incoterms) ? $object->fk_incoterms : ($socid > 0 ? $societe->fk_incoterms : ''));
- $locincoterms = (!empty($object->location_incoterms) ? $object->location_incoterms : ($socid > 0 ? $societe->location_incoterms : ''));
+ $fkincoterms = (!empty($object->fk_incoterms) ? $object->fk_incoterms : ($socid > 0 ? $societe->fk_incoterms : ''));
+ $locincoterms = (!empty($object->location_incoterms) ? $object->location_incoterms : ($socid > 0 ? $societe->location_incoterms : ''));
print '';
print ''.$form->textwithpicto($langs->trans("IncotermLabel"), $object->label_incoterms, 1).' ';
print '';
@@ -1765,7 +1765,7 @@ if ($action == 'create')
// Bouton "Create Draft"
print "
\n";
- dol_fiche_end();
+ print dol_get_fiche_end();
print '';
print ' ';
@@ -2339,7 +2339,7 @@ if ($action == 'create')
print '
';
print '';
- dol_fiche_end();
+ print dol_get_fiche_end();
/**
* Boutons actions
diff --git a/htdocs/fourn/commande/contact.php b/htdocs/fourn/commande/contact.php
index 45178a656ba..08a40ad52b8 100644
--- a/htdocs/fourn/commande/contact.php
+++ b/htdocs/fourn/commande/contact.php
@@ -55,11 +55,11 @@ if ($action == 'addcontact' && $user->rights->fournisseur->commande->creer)
{
$result = $object->fetch($id);
- if ($result > 0 && $id > 0)
- {
- $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
+ if ($result > 0 && $id > 0)
+ {
+ $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
$result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]);
- }
+ }
if ($result >= 0)
{
@@ -81,7 +81,7 @@ elseif ($action == 'swapstatut' && $user->rights->fournisseur->commande->creer)
{
if ($object->fetch($id))
{
- $result = $object->swapContactStatus(GETPOST('ligne'));
+ $result = $object->swapContactStatus(GETPOST('ligne'));
} else {
dol_print_error($db);
}
@@ -146,43 +146,43 @@ if ($id > 0 || !empty($ref))
// Project
if (!empty($conf->projet->enabled))
{
- $langs->load("projects");
- $morehtmlref .= ' '.$langs->trans('Project').' ';
- if ($user->rights->fournisseur->commande->creer)
- {
- if ($action != 'classify') {
- //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : ';
+ $langs->load("projects");
+ $morehtmlref .= ' '.$langs->trans('Project').' ';
+ if ($user->rights->fournisseur->commande->creer)
+ {
+ if ($action != 'classify') {
+ //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : ';
$morehtmlref .= ' : ';
- }
- if ($action == 'classify') {
- //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
- $morehtmlref .= '';
- } else {
- $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
- }
- } else {
- if (!empty($object->fk_project)) {
- $proj = new Project($db);
- $proj->fetch($object->fk_project);
- $morehtmlref .= '';
- $morehtmlref .= $proj->ref;
- $morehtmlref .= ' ';
- } else {
- $morehtmlref .= '';
- }
- }
+ }
+ if ($action == 'classify') {
+ //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+ $morehtmlref .= '';
+ } else {
+ $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+ }
+ } else {
+ if (!empty($object->fk_project)) {
+ $proj = new Project($db);
+ $proj->fetch($object->fk_project);
+ $morehtmlref .= '';
+ $morehtmlref .= $proj->ref;
+ $morehtmlref .= ' ';
+ } else {
+ $morehtmlref .= '';
+ }
+ }
}
$morehtmlref .= '';
dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1);
- dol_fiche_end();
+ print dol_get_fiche_end();
// Contacts lines
include DOL_DOCUMENT_ROOT.'/core/tpl/contacts.tpl.php';
diff --git a/htdocs/fourn/commande/dispatch.php b/htdocs/fourn/commande/dispatch.php
index 6f6678b57de..a924ca03270 100644
--- a/htdocs/fourn/commande/dispatch.php
+++ b/htdocs/fourn/commande/dispatch.php
@@ -38,7 +38,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
-require_once DOL_DOCUMENT_ROOT . '/product/stock/class/mouvementstock.class.php';
+require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
if (!empty($conf->projet->enabled))
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
@@ -276,7 +276,7 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner)
$sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price";
$sql .= " SET unitprice='".GETPOST($pu)."'";
$sql .= ", price=".GETPOST($pu)."*quantity";
- $sql .= ", remise_percent='".(!empty($dto)?$dto:0)."'";
+ $sql .= ", remise_percent='".(!empty($dto) ? $dto : 0)."'";
$sql .= " WHERE fk_soc=".$object->socid;
$sql .= " AND fk_product=".GETPOST($prod, 'int');
@@ -348,7 +348,7 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner)
$sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price";
$sql .= " SET unitprice='".GETPOST($pu)."'";
$sql .= ", price=".GETPOST($pu)."*quantity";
- $sql .= ", remise_percent='".(!empty($dto)?$dto:0)."'";
+ $sql .= ", remise_percent='".(!empty($dto) ? $dto : 0)."'";
$sql .= " WHERE fk_soc=".$object->socid;
$sql .= " AND fk_product=".GETPOST($prod, 'int');
@@ -419,16 +419,16 @@ if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->fourn
}
else {
// If module stock is enabled and the stock increase is done on purchase order dispatching
- if ($entrepot > 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER))
+ if ($entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER))
{
$mouv = new MouvementStock($db);
if ($product > 0)
{
$mouv->origin = &$object;
- $result=$mouv->livraison($user, $product, $entrepot, $qty, $price, $comment, '', $eatby, $sellby, $batch);
+ $result = $mouv->livraison($user, $product, $entrepot, $qty, $price, $comment, '', $eatby, $sellby, $batch);
if ($result < 0)
{
- $errors=$mouv->errors;
+ $errors = $mouv->errors;
$error++;
}
}
@@ -470,28 +470,28 @@ if ($action == 'updateline' && $user->rights->fournisseur->commande->receptionne
if ($result < 0)
{
$error++;
- $errors=$supplierorderdispatch->errors;
+ $errors = $supplierorderdispatch->errors;
}
else {
// If module stock is enabled and the stock increase is done on purchase order dispatching
- if ($entrepot > 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER))
+ if ($entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER))
{
$mouv = new MouvementStock($db);
if ($product > 0)
{
$mouv->origin = &$object;
- $result=$mouv->livraison($user, $product, $entrepot, $qty, $price, $comment, '', $eatby, $sellby, $batch);
+ $result = $mouv->livraison($user, $product, $entrepot, $qty, $price, $comment, '', $eatby, $sellby, $batch);
if ($result < 0)
{
- $errors=$mouv->errors;
+ $errors = $mouv->errors;
$error++;
}
else {
$mouv->origin = &$object;
- $result=$mouv->reception($user, $product, $supplierorderdispatch->fk_entrepot, $supplierorderdispatch->qty, $price, $comment, $eatby, $sellby, $batch);
+ $result = $mouv->reception($user, $product, $supplierorderdispatch->fk_entrepot, $supplierorderdispatch->qty, $price, $comment, $eatby, $sellby, $batch);
if ($result < 0)
{
- $errors=$mouv->errors;
+ $errors = $mouv->errors;
$error++;
}
}
@@ -534,20 +534,20 @@ if ($id > 0 || !empty($ref)) {
$title = $langs->trans("SupplierOrder");
print dol_get_fiche_head($head, 'dispatch', $title, -1, 'order');
- $formconfirm='';
+ $formconfirm = '';
// Confirmation to delete line
if ($action == 'ask_deleteline')
{
- $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
+ $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
}
// Call Hook formConfirm
$parameters = array('lineid' => $lineid);
// Note that $action and $object may be modified by hook
$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action);
- if (empty($reshook)) $formconfirm.=$hookmanager->resPrint;
- elseif ($reshook > 0) $formconfirm=$hookmanager->resPrint;
+ if (empty($reshook)) $formconfirm .= $hookmanager->resPrint;
+ elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint;
// Print form confirm
print $formconfirm;
@@ -652,7 +652,7 @@ if ($id > 0 || !empty($ref)) {
$formproduct = new FormProduct($db);
$formproduct->loadWarehouses();
$entrepot = new Entrepot($db);
- $listwarehouses=$entrepot->list_array(1);
+ $listwarehouses = $entrepot->list_array(1);
if (empty($conf->reception->enabled))print '';
}
- dol_fiche_end();
+ print dol_get_fiche_end();
// traitement entrepot par défaut
print ''."\n";
- }
+ print ' '."\n";
+ }
- print '';
- }
- } else dol_print_error($db);
+ print '';
+ }
+ } else dol_print_error($db);
}
// End of page
diff --git a/htdocs/fourn/facture/rapport.php b/htdocs/fourn/facture/rapport.php
index 1c068e19b7d..9ae7970d7db 100644
--- a/htdocs/fourn/facture/rapport.php
+++ b/htdocs/fourn/facture/rapport.php
@@ -40,8 +40,8 @@ $action = GETPOST('action', 'aZ09');
$socid = 0;
if ($user->socid > 0)
{
- $action = '';
- $socid = $user->socid;
+ $action = '';
+ $socid = $user->socid;
}
$dir = $conf->fournisseur->facture->dir_output.'/payments';
@@ -57,27 +57,27 @@ if (!$year) { $year = date("Y"); }
if ($action == 'builddoc')
{
- $rap = new pdf_paiement_fourn($db);
+ $rap = new pdf_paiement_fourn($db);
- $outputlangs = $langs;
- if (GETPOST('lang_id', 'aZ09'))
- {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang(GETPOST('lang_id', 'aZ09'));
- }
+ $outputlangs = $langs;
+ if (GETPOST('lang_id', 'aZ09'))
+ {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang(GETPOST('lang_id', 'aZ09'));
+ }
- // We save charset_output to restore it because write_file can change it if needed for
- // output format that does not support UTF8.
- $sav_charset_output = $outputlangs->charset_output;
- if ($rap->write_file($dir, GETPOST("remonth", 'int'), GETPOST("reyear", 'int'), $outputlangs) > 0)
- {
- $outputlangs->charset_output = $sav_charset_output;
- } else {
- $outputlangs->charset_output = $sav_charset_output;
- dol_print_error($db, $obj->error);
- }
+ // We save charset_output to restore it because write_file can change it if needed for
+ // output format that does not support UTF8.
+ $sav_charset_output = $outputlangs->charset_output;
+ if ($rap->write_file($dir, GETPOST("remonth", 'int'), GETPOST("reyear", 'int'), $outputlangs) > 0)
+ {
+ $outputlangs->charset_output = $sav_charset_output;
+ } else {
+ $outputlangs->charset_output = $sav_charset_output;
+ dol_print_error($db, $obj->error);
+ }
- $year = GETPOST("reyear", 'int');
+ $year = GETPOST("reyear", 'int');
}
@@ -116,58 +116,58 @@ $linkforyear = array();
$found = 0;
if (is_dir($dir))
{
- $handle = opendir($dir);
- if (is_resource($handle))
- {
- while (($file = readdir($handle)) !== false)
- {
- if (is_dir($dir.'/'.$file) && !preg_match('/^\./', $file) && is_numeric($file))
- {
- $found = 1;
- $linkforyear[] = $file;
- }
- }
- }
+ $handle = opendir($dir);
+ if (is_resource($handle))
+ {
+ while (($file = readdir($handle)) !== false)
+ {
+ if (is_dir($dir.'/'.$file) && !preg_match('/^\./', $file) && is_numeric($file))
+ {
+ $found = 1;
+ $linkforyear[] = $file;
+ }
+ }
+ }
}
asort($linkforyear);
foreach ($linkforyear as $cursoryear)
{
- print ''.$cursoryear.' ';
+ print ''.$cursoryear.' ';
}
if ($year)
{
- if (is_dir($dir.'/'.$year))
- {
- $handle = opendir($dir.'/'.$year);
+ if (is_dir($dir.'/'.$year))
+ {
+ $handle = opendir($dir.'/'.$year);
- if ($found) print ' ';
- print ' ';
- print '';
- print '';
- print ''.$langs->trans("Reporting").' ';
- print ''.$langs->trans("Size").' ';
- print ''.$langs->trans("Date").' ';
- print ' ';
+ if ($found) print ' ';
+ print ' ';
+ print '';
+ print '';
+ print ''.$langs->trans("Reporting").' ';
+ print ''.$langs->trans("Size").' ';
+ print ''.$langs->trans("Date").' ';
+ print ' ';
- if (is_resource($handle))
- {
- while (($file = readdir($handle)) !== false)
- {
- if (preg_match('/^supplier_payment/i', $file))
- {
- $tfile = $dir.'/'.$year.'/'.$file;
- $relativepath = $year.'/'.$file;
- print ''.img_pdf().' '.$file.' '.$formfile->showPreview($file, 'facture_fournisseur', 'payments/'.$relativepath, 0).' ';
- print ''.dol_print_size(dol_filesize($tfile)).' ';
- print ''.dol_print_date(dol_filemtime($tfile), "dayhour").' ';
- }
- }
- closedir($handle);
- }
+ if (is_resource($handle))
+ {
+ while (($file = readdir($handle)) !== false)
+ {
+ if (preg_match('/^supplier_payment/i', $file))
+ {
+ $tfile = $dir.'/'.$year.'/'.$file;
+ $relativepath = $year.'/'.$file;
+ print ''.img_pdf().' '.$file.' '.$formfile->showPreview($file, 'facture_fournisseur', 'payments/'.$relativepath, 0).' ';
+ print ''.dol_print_size(dol_filesize($tfile)).' ';
+ print ''.dol_print_date(dol_filemtime($tfile), "dayhour").' ';
+ }
+ }
+ closedir($handle);
+ }
- print '
';
- }
+ print '
';
+ }
}
// End of page
diff --git a/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php b/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php
index 0826a4ab200..4456d27c539 100644
--- a/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php
+++ b/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php
@@ -40,29 +40,29 @@ $langs->load("bills");
$total = 0; $ilink = 0;
foreach ($linkedObjectBlock as $key => $objectlink)
{
- $ilink++;
+ $ilink++;
- $trclass = 'oddeven';
- if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total';
- ?>
+ $trclass = 'oddeven';
+ if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total';
+ ?>
trans("SupplierInvoice"); ?>
trans("ShowBill"), "bill").' '.$objectlink->ref; ?>
ref_supplier; ?>
date, 'day'); ?>
rights->fournisseur->facture->lire) {
- $sign = 1;
- if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $sign = -1;
- if ($objectlink->statut != 3)
- {
+ if ($user->rights->fournisseur->facture->lire) {
+ $sign = 1;
+ if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $sign = -1;
+ if ($objectlink->statut != 3)
+ {
// If not abandonned
- $total = $total + $sign * $objectlink->total_ht;
- echo price($objectlink->total_ht);
- } else {
- echo ''.price($objectlink->total_ht).' ';
- }
- } ?>
+ $total = $total + $sign * $objectlink->total_ht;
+ echo price($objectlink->total_ht);
+ } else {
+ echo ''.price($objectlink->total_ht).' ';
+ }
+ } ?>
getLibStatut(3); ?>
id.'&action=dellink&dellinkid='.$key; ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
@@ -70,7 +70,7 @@ foreach ($linkedObjectBlock as $key => $objectlink)
}
if (count($linkedObjectBlock) > 1)
{
- ?>
+ ?>
trans("Total"); ?>
diff --git a/htdocs/fourn/paiement/card.php b/htdocs/fourn/paiement/card.php
index cfd65a631da..80f6d2eed5e 100644
--- a/htdocs/fourn/paiement/card.php
+++ b/htdocs/fourn/paiement/card.php
@@ -292,7 +292,7 @@ if ($result > 0)
$facturestatic->total_tva = $objp->total_tva;
$facturestatic->total_ttc = $objp->total_ttc;
$facturestatic->statut = $objp->status;
- $facturestatic->alreadypaid = -1; // unknown
+ $facturestatic->alreadypaid = -1; // unknown
print ' ';
// Ref
@@ -396,7 +396,7 @@ if ($result > 0)
print $langs->trans("ErrorRecordNotFound");
}
-dol_fiche_end();
+print dol_get_fiche_end();
// End of page
llxFooter();
diff --git a/htdocs/fourn/paiement/info.php b/htdocs/fourn/paiement/info.php
index 1ca4c113612..97ac2343c23 100644
--- a/htdocs/fourn/paiement/info.php
+++ b/htdocs/fourn/paiement/info.php
@@ -49,7 +49,7 @@ print dol_get_fiche_head($head, 'info', $langs->trans("SupplierPayment"), 0, 'pa
dol_banner_tab($object, 'id', $linkback, -1, 'rowid', 'ref');
-dol_fiche_end();
+print dol_get_fiche_end();
print '';
dol_print_object_info($object);
diff --git a/htdocs/fourn/paiement/list.php b/htdocs/fourn/paiement/list.php
index 0310a75fe57..3fca286eff0 100644
--- a/htdocs/fourn/paiement/list.php
+++ b/htdocs/fourn/paiement/list.php
@@ -56,29 +56,29 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
// Load translation files required by the page
$langs->loadLangs(array('companies', 'bills', 'banks', 'compta'));
-$action = GETPOST('action', 'alpha');
+$action = GETPOST('action', 'alpha');
$massaction = GETPOST('massaction', 'alpha');
-$optioncss = GETPOST('optioncss', 'alpha');
+$optioncss = GETPOST('optioncss', 'alpha');
$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'vendorpaymentlist';
-$socid = GETPOST('socid', 'int');
+$socid = GETPOST('socid', 'int');
$search_ref = GETPOST('search_ref', 'alpha');
$search_day = GETPOST('search_day', 'int');
-$search_month = GETPOST('search_month', 'int');
+$search_month = GETPOST('search_month', 'int');
$search_year = GETPOST('search_year', 'int');
-$search_company = GETPOST('search_company', 'alpha');
+$search_company = GETPOST('search_company', 'alpha');
$search_payment_type = GETPOST('search_payment_type');
-$search_cheque_num = GETPOST('search_cheque_num', 'alpha');
+$search_cheque_num = GETPOST('search_cheque_num', 'alpha');
$search_bank_account = GETPOST('search_bank_account', 'int');
-$search_amount = GETPOST('search_amount', 'alpha'); // alpha because we must be able to search on '< x'
+$search_amount = GETPOST('search_amount', 'alpha'); // alpha because we must be able to search on '< x'
-$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
+$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', '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;
$pageprev = $page - 1;
$pagenext = $page + 1;
@@ -86,7 +86,7 @@ $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC";
if (!$sortfield) $sortfield = "p.datep";
-$search_all = trim(GETPOSTISSET("search_all") ? GETPOSTISSET("search_all", 'alpha') : GETPOST('sall'));
+$search_all = trim(GETPOSTISSET("search_all") ? GETPOST("search_all", 'alpha') : GETPOST('sall'));
// List of fields to search into when doing a "search in all"
$fieldstosearchall = array(
diff --git a/htdocs/fourn/product/list.php b/htdocs/fourn/product/list.php
index e3d2b5b91d2..04310945cf7 100644
--- a/htdocs/fourn/product/list.php
+++ b/htdocs/fourn/product/list.php
@@ -81,22 +81,22 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
if (empty($reshook))
{
- // Selection of new fields
- include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
+ // Selection of new fields
+ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
- // 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
- {
- $sref = '';
- $sRefSupplier = '';
- $snom = '';
- $search_field1 = '';
- $search_field2 = '';
- $search_date_creation = '';
- $search_date_update = '';
- $toselect = '';
- $search_array_options = array();
- }
+ // 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
+ {
+ $sref = '';
+ $sRefSupplier = '';
+ $snom = '';
+ $search_field1 = '';
+ $search_field2 = '';
+ $search_date_creation = '';
+ $search_date_update = '';
+ $toselect = '';
+ $search_array_options = array();
+ }
}
/*
@@ -119,8 +119,8 @@ if ($fourn_id)
$arrayofmassactions = array(
'generate_doc'=>$langs->trans("ReGeneratePDF"),
- 'builddoc'=>$langs->trans("PDFMerge"),
- 'presend'=>$langs->trans("SendByMail"),
+ 'builddoc'=>$langs->trans("PDFMerge"),
+ 'presend'=>$langs->trans("SendByMail"),
);
if ($user->rights->mymodule->supprimer) $arrayofmassactions['predelete'] = ' '.$langs->trans("Delete");
if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
@@ -177,13 +177,13 @@ $sql .= $db->order($sortfield, $sortorder);
$nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
- $result = $db->query($sql);
- $nbtotalofrecords = $db->num_rows($result);
- if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
- {
- $page = 0;
- $offset = 0;
- }
+ $result = $db->query($sql);
+ $nbtotalofrecords = $db->num_rows($result);
+ if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ {
+ $page = 0;
+ $offset = 0;
+ }
}
$sql .= $db->plimit($limit + 1, $offset);
@@ -224,12 +224,12 @@ if ($resql)
}
print '';
- if ($optioncss != '') print ' ';
+ if ($optioncss != '') print ' ';
print ' ';
if ($fourn_id > 0) print ' ';
print ' ';
print ' ';
- print ' ';
+ print ' ';
print ' ';
$topicmail = "Information";
@@ -255,11 +255,11 @@ if ($resql)
print ' ';
print ' ';
print ' ';
- // add filters from hooks
- $parameters = array();
- $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action);
- if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
- print $hookmanager->resPrint;
+ // add filters from hooks
+ $parameters = array();
+ $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action);
+ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+ print $hookmanager->resPrint;
print '';
$searchpicto = $form->showFilterButtons();
print $searchpicto;
@@ -276,10 +276,10 @@ if ($resql)
print_liste_field_titre("QtyMin", $_SERVER["PHP_SELF"], "ppf.quantity", $param, "", '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("UnitPrice", $_SERVER["PHP_SELF"], "ppf.unitprice", $param, "", '', $sortfield, $sortorder, 'right ');
// add header cells from hooks
- $parameters = array();
- $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action);
- if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
- print $hookmanager->resPrint;
+ $parameters = array();
+ $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action);
+ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+ print $hookmanager->resPrint;
print_liste_field_titre('', $_SERVER["PHP_SELF"]);
print " \n";
@@ -318,10 +318,10 @@ if ($resql)
print ''.(isset($objp->unitprice) ? price($objp->unitprice) : '').' ';
// add additional columns from hooks
- $parameters = array();
- $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $objp, $action);
- if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
- print $hookmanager->resPrint;
+ $parameters = array();
+ $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $objp, $action);
+ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+ print $hookmanager->resPrint;
print ' ';
diff --git a/htdocs/fourn/recap-fourn.php b/htdocs/fourn/recap-fourn.php
index e75151fb54a..736a7bf4f90 100644
--- a/htdocs/fourn/recap-fourn.php
+++ b/htdocs/fourn/recap-fourn.php
@@ -34,8 +34,8 @@ $langs->loadLangs(array('bills', 'companies'));
$socid = GETPOST("socid", 'int');
if ($user->socid > 0)
{
- $action = '';
- $socid = $user->socid;
+ $action = '';
+ $socid = $user->socid;
}
@@ -53,138 +53,138 @@ llxHeader();
if ($socid > 0)
{
- $societe = new Societe($db);
- $societe->fetch($socid);
+ $societe = new Societe($db);
+ $societe->fetch($socid);
- /*
+ /*
* Affichage onglets
*/
- $head = societe_prepare_head($societe);
+ $head = societe_prepare_head($societe);
- print dol_get_fiche_head($head, 'supplier', $langs->trans("ThirdParty"), 0, 'company');
+ print dol_get_fiche_head($head, 'supplier', $langs->trans("ThirdParty"), 0, 'company');
dol_banner_tab($societe, 'socid', '', ($user->socid ? 0 : 1), 'rowid', 'nom');
- dol_fiche_end();
+ print dol_get_fiche_end();
- if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->facture->lire)
- {
- // Invoice list
- print load_fiche_titre($langs->trans("SupplierPreview"));
+ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->facture->lire)
+ {
+ // Invoice list
+ print load_fiche_titre($langs->trans("SupplierPreview"));
- print '';
+ print '';
- $sql = "SELECT s.nom, s.rowid as socid, f.ref_supplier, f.datef as df,";
- $sql .= " f.paye as paye, f.fk_statut as statut, f.rowid as facid,";
- $sql .= " u.login, u.rowid as userid";
- $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_fourn as f,".MAIN_DB_PREFIX."user as u";
- $sql .= " WHERE f.fk_soc = s.rowid AND s.rowid = ".$societe->id;
- $sql .= " AND f.entity IN (".getEntity("facture_fourn").")"; // Recognition of the entity attributed to this invoice for Multicompany
- $sql .= " AND f.fk_user_valid = u.rowid";
- $sql .= " ORDER BY f.datef DESC";
+ $sql = "SELECT s.nom, s.rowid as socid, f.ref_supplier, f.datef as df,";
+ $sql .= " f.paye as paye, f.fk_statut as statut, f.rowid as facid,";
+ $sql .= " u.login, u.rowid as userid";
+ $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_fourn as f,".MAIN_DB_PREFIX."user as u";
+ $sql .= " WHERE f.fk_soc = s.rowid AND s.rowid = ".$societe->id;
+ $sql .= " AND f.entity IN (".getEntity("facture_fourn").")"; // Recognition of the entity attributed to this invoice for Multicompany
+ $sql .= " AND f.fk_user_valid = u.rowid";
+ $sql .= " ORDER BY f.datef DESC";
- $resql = $db->query($sql);
- if ($resql)
- {
- $num = $db->num_rows($resql);
+ $resql = $db->query($sql);
+ if ($resql)
+ {
+ $num = $db->num_rows($resql);
- print '';
- print ''.$langs->trans("Date").' ';
- print ' ';
- print ''.$langs->trans("Status").' ';
- print ''.$langs->trans("Debit").' ';
- print ''.$langs->trans("Credit").' ';
- print ''.$langs->trans("Balance").' ';
- print ' ';
- print ' ';
+ print '';
+ print ''.$langs->trans("Date").' ';
+ print ' ';
+ print ''.$langs->trans("Status").' ';
+ print ''.$langs->trans("Debit").' ';
+ print ''.$langs->trans("Credit").' ';
+ print ''.$langs->trans("Balance").' ';
+ print ' ';
+ print ' ';
- if (!$num > 0)
- {
- print ''.$langs->trans("NoInvoice").' ';
- }
+ if (!$num > 0)
+ {
+ print ''.$langs->trans("NoInvoice").' ';
+ }
- $solde = 0;
+ $solde = 0;
- // Boucle sur chaque facture
- for ($i = 0; $i < $num; $i++)
- {
- $objf = $db->fetch_object($resql);
+ // Boucle sur chaque facture
+ for ($i = 0; $i < $num; $i++)
+ {
+ $objf = $db->fetch_object($resql);
- $fac = new FactureFournisseur($db);
- $ret = $fac->fetch($objf->facid);
- if ($ret < 0)
- {
- print $fac->error." ";
- continue;
- }
- $totalpaye = $fac->getSommePaiement();
+ $fac = new FactureFournisseur($db);
+ $ret = $fac->fetch($objf->facid);
+ if ($ret < 0)
+ {
+ print $fac->error." ";
+ continue;
+ }
+ $totalpaye = $fac->getSommePaiement();
- print '';
+ print ' ';
- print "".dol_print_date($fac->date)." \n";
- print "id\">".img_object($langs->trans("ShowBill"), "bill")." ".$fac->ref." \n";
+ print "".dol_print_date($fac->date)." \n";
+ print "id\">".img_object($langs->trans("ShowBill"), "bill")." ".$fac->ref." \n";
- print ''.$fac->getLibStatut(2, $totalpaye).' ';
- print ''.price($fac->total_ttc)." \n";
- $solde = $solde + $fac->total_ttc;
+ print ''.$fac->getLibStatut(2, $totalpaye).' ';
+ print ''.price($fac->total_ttc)." \n";
+ $solde = $solde + $fac->total_ttc;
- print ' ';
- print ''.price($solde)." \n";
+ print ' ';
+ print ''.price($solde)." \n";
- // Author
- print ''.img_object($langs->trans("ShowUser"), 'user').' '.$objf->login.' ';
+ // Author
+ print ''.img_object($langs->trans("ShowUser"), 'user').' '.$objf->login.' ';
- print " \n";
+ print "\n";
- // Payments
- $sql = "SELECT p.rowid, p.datep as dp, pf.amount, p.statut,";
- $sql .= " p.fk_user_author, u.login, u.rowid as userid";
- $sql .= " FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf,";
- $sql .= " ".MAIN_DB_PREFIX."paiementfourn as p";
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON p.fk_user_author = u.rowid";
- $sql .= " WHERE pf.fk_paiementfourn = p.rowid";
- $sql .= " AND pf.fk_facturefourn = ".$fac->id;
+ // Payments
+ $sql = "SELECT p.rowid, p.datep as dp, pf.amount, p.statut,";
+ $sql .= " p.fk_user_author, u.login, u.rowid as userid";
+ $sql .= " FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf,";
+ $sql .= " ".MAIN_DB_PREFIX."paiementfourn as p";
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON p.fk_user_author = u.rowid";
+ $sql .= " WHERE pf.fk_paiementfourn = p.rowid";
+ $sql .= " AND pf.fk_facturefourn = ".$fac->id;
- $resqlp = $db->query($sql);
- if ($resqlp)
- {
- $nump = $db->num_rows($resqlp);
- $j = 0;
+ $resqlp = $db->query($sql);
+ if ($resqlp)
+ {
+ $nump = $db->num_rows($resqlp);
+ $j = 0;
- while ($j < $nump)
- {
- $objp = $db->fetch_object($resqlp);
- //
- print '';
- print ''.dol_print_date($db->jdate($objp->dp))." \n";
- print '';
- print ' '; // Decalage
- print ''.img_object($langs->trans("ShowPayment"), "payment").' '.$langs->trans("Payment").' '.$objp->rowid.' ';
- print " \n";
- print " \n";
- print ''.price($objp->amount).' ';
- $solde = $solde - $objp->amount;
- print ''.price($solde)." \n";
+ while ($j < $nump)
+ {
+ $objp = $db->fetch_object($resqlp);
+ //
+ print ' ';
+ print ''.dol_print_date($db->jdate($objp->dp))." \n";
+ print '';
+ print ' '; // Decalage
+ print ''.img_object($langs->trans("ShowPayment"), "payment").' '.$langs->trans("Payment").' '.$objp->rowid.' ';
+ print " \n";
+ print " \n";
+ print ''.price($objp->amount).' ';
+ $solde = $solde - $objp->amount;
+ print ''.price($solde)." \n";
- // Auteur
- print ''.img_object($langs->trans("ShowUser"), 'user').' '.$objp->login.' ';
+ // Auteur
+ print ''.img_object($langs->trans("ShowUser"), 'user').' '.$objp->login.' ';
- print ' ';
+ print '';
- $j++;
- }
+ $j++;
+ }
- $db->free($resqlp);
- } else {
- dol_print_error($db);
- }
- }
- } else {
- dol_print_error($db);
- }
+ $db->free($resqlp);
+ } else {
+ dol_print_error($db);
+ }
+ }
+ } else {
+ dol_print_error($db);
+ }
- print "
";
- }
+ print "
";
+ }
} else {
- dol_print_error($db);
+ dol_print_error($db);
}
// End of page
diff --git a/htdocs/ftp/admin/ftpclient.php b/htdocs/ftp/admin/ftpclient.php
index 70a96546fc2..6a51d6d0a88 100644
--- a/htdocs/ftp/admin/ftpclient.php
+++ b/htdocs/ftp/admin/ftpclient.php
@@ -114,16 +114,16 @@ if (GETPOST('delete', 'alpha'))
if ($result4) $result5 = dolibarr_del_const($db, "FTP_NAME_".$entry, $conf->entity);
if ($result4) $result6 = dolibarr_del_const($db, "FTP_PASSIVE_".$entry, $conf->entity);
- if ($result1 && $result2 && $result3 && $result4 && $result5 && $result6)
- {
- $db->commit();
- header("Location: ".$_SERVER["PHP_SELF"]);
- exit;
- } else {
- $db->rollback();
- dol_print_error($db);
- }
- }
+ if ($result1 && $result2 && $result3 && $result4 && $result5 && $result6)
+ {
+ $db->commit();
+ header("Location: ".$_SERVER["PHP_SELF"]);
+ exit;
+ } else {
+ $db->rollback();
+ dol_print_error($db);
+ }
+ }
}
diff --git a/htdocs/ftp/index.php b/htdocs/ftp/index.php
index 7c0eab0f352..51a8028e1f3 100644
--- a/htdocs/ftp/index.php
+++ b/htdocs/ftp/index.php
@@ -108,7 +108,7 @@ if (GETPOST("sendit") && !empty($conf->global->MAIN_UPLOAD_DOC))
{
setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
} elseif (preg_match('/ErrorFileIsInfectedWithAVirus/', $resupload)) {
- // Files infected by a virus
+ // Files infected by a virus
setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
} else // Known error
{
@@ -158,10 +158,10 @@ if ($action == 'confirm_deletefile' && GETPOST('confirm') == 'yes')
$newsection = $section;
if (!empty($conf->global->FTP_CONNECT_WITH_SFTP))
{
- $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169
+ $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169
}
- $langs->load("other");
+ $langs->load("other");
// Remote file
$filename = $file;
@@ -210,14 +210,14 @@ if (GETPOST("const", 'array') && GETPOST("delete") && GETPOST("delete") == $lang
{
if ($const["check"]) // Is checkbox checked
{
- $langs->load("other");
+ $langs->load("other");
// Remote file
$file = $const["file"];
$newsection = $const["section"];
if (!empty($conf->global->FTP_CONNECT_WITH_SFTP))
{
- $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169
+ $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169
}
$remotefile = $newsection.(preg_match('@[\\\/]$@', $newsection) ? '' : '/').$file;
$newremotefileiso = utf8_decode($remotefile);
@@ -265,7 +265,7 @@ if ($action == 'confirm_deletesection' && $confirm == 'yes')
$newsection = $section;
if (!empty($conf->global->FTP_CONNECT_WITH_SFTP))
{
- $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169
+ $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169
}
// Remote file
@@ -314,7 +314,7 @@ if ($action == 'download')
$newsection = $section;
if (!empty($conf->global->FTP_CONNECT_WITH_SFTP))
{
- $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169
+ $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169
}
// Remote file
@@ -323,7 +323,7 @@ if ($action == 'download')
$newremotefileiso = utf8_decode($remotefile);
if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) {
- $result = fopen('ssh2.sftp://' . intval($conn_id) . $newremotefileiso, 'r');
+ $result = fopen('ssh2.sftp://'.intval($conn_id).$newremotefileiso, 'r');
} else {
$result = ftp_get($conn_id, $localfile, $newremotefileiso, FTP_BINARY);
}
@@ -415,7 +415,7 @@ if (!function_exists('ftp_connect'))
{
print $langs->trans("FTPFeatureNotSupportedByYourPHP");
} else {
- if (!empty($ftp_server))
+ if (!empty($ftp_server))
{
// Confirm remove file
if ($action == 'delete')
@@ -432,9 +432,9 @@ if (!function_exists('ftp_connect'))
print $langs->trans("Server").': '.$ftp_server.' ';
print $langs->trans("Port").': '.$ftp_port.' '.($ftp_passive ? "(Passive)" : "(Active)").' ';
print $langs->trans("User").': '.$ftp_user.' ';
- print $langs->trans("FTPs (FTP over SSH)").': '.yn($conf->global->FTP_CONNECT_WITH_SSL).' ';
- print $langs->trans("SFTP (FTP as a subsytem of SSH)").': '.yn($conf->global->FTP_CONNECT_WITH_SFTP).' ';
- print $langs->trans("Directory").': ';
+ print $langs->trans("FTPs (FTP over SSH)").': '.yn($conf->global->FTP_CONNECT_WITH_SSL).' ';
+ print $langs->trans("SFTP (FTP as a subsytem of SSH)").': '.yn($conf->global->FTP_CONNECT_WITH_SFTP).' ';
+ print $langs->trans("Directory").': ';
$sectionarray = preg_split('|[\/]|', $section);
// For /
$newsection = '/';
@@ -461,7 +461,7 @@ if (!function_exists('ftp_connect'))
print " \n";
print '';
- print ' ';
+ print ' ';
print ' ';
@@ -496,7 +496,7 @@ if (!function_exists('ftp_connect'))
//$type = ftp_systype($conn_id);
$newsection = $section;
- $newsectioniso = utf8_decode($section);
+ $newsectioniso = utf8_decode($section);
//$newsection='/home';
// List content of directory ($newsection = '/', '/home', ...)
@@ -504,23 +504,23 @@ if (!function_exists('ftp_connect'))
{
if ($newsection == '/') {
//$newsection = '/./';
- $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169
+ $newsection = ssh2_sftp_realpath($conn_id, ".").'/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169
}
- //$newsection='/';
- //$dirHandle = opendir("ssh2.sftp://$conn_id".$newsection);
+ //$newsection='/';
+ //$dirHandle = opendir("ssh2.sftp://$conn_id".$newsection);
//$dirHandle = opendir("ssh2.sftp://".intval($conn_id).ssh2_sftp_realpath($conn_id, ".").'/./');
- $contents = scandir('ssh2.sftp://'.intval($conn_id).$newsection);
- $buff = array();
- foreach ($contents as $i => $key)
- {
- $buff[$i] = "---------- - root root 1234 Aug 01 2000 ".$key;
- }
- } else {
- $buff = ftp_rawlist($conn_id, $newsectioniso);
- $contents = ftp_nlist($conn_id, $newsectioniso); // Sometimes rawlist fails but never nlist
- //var_dump($contents);
- //var_dump($buff);
- }
+ $contents = scandir('ssh2.sftp://'.intval($conn_id).$newsection);
+ $buff = array();
+ foreach ($contents as $i => $key)
+ {
+ $buff[$i] = "---------- - root root 1234 Aug 01 2000 ".$key;
+ }
+ } else {
+ $buff = ftp_rawlist($conn_id, $newsectioniso);
+ $contents = ftp_nlist($conn_id, $newsectioniso); // Sometimes rawlist fails but never nlist
+ //var_dump($contents);
+ //var_dump($buff);
+ }
$nboflines = count($contents);
$rawlisthasfailed = false;
@@ -626,8 +626,8 @@ if (!function_exists('ftp_connect'))
if (!$ok)
{
- print $mesg.' '."\n";
- setEventMessages($mesg, null, 'errors');
+ print $mesg.' '."\n";
+ setEventMessages($mesg, null, 'errors');
}
@@ -661,12 +661,12 @@ if (!function_exists('ftp_connect'))
}
$i++;
}
- if (!$foundsetup)
- {
- print $langs->trans("SetupOfFTPClientModuleNotComplete");
- } else {
- print $langs->trans("ChooseAFTPEntryIntoMenu");
- }
+ if (!$foundsetup)
+ {
+ print $langs->trans("SetupOfFTPClientModuleNotComplete");
+ } else {
+ print $langs->trans("ChooseAFTPEntryIntoMenu");
+ }
}
}
@@ -675,14 +675,14 @@ print ' ';
// Close FTP connection
if ($conn_id)
{
- if (!empty($conf->global->FTP_CONNECT_WITH_SFTP))
- {
- } elseif (!empty($conf->global->FTP_CONNECT_WITH_SSL))
- {
- ftp_close($conn_id);
- } else {
- ftp_close($conn_id);
- }
+ if (!empty($conf->global->FTP_CONNECT_WITH_SFTP))
+ {
+ } elseif (!empty($conf->global->FTP_CONNECT_WITH_SSL))
+ {
+ ftp_close($conn_id);
+ } else {
+ ftp_close($conn_id);
+ }
}
// End of page
@@ -707,7 +707,7 @@ function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $sect
global $langs, $conf;
$ok = 1;
- $conn_id = null;
+ $conn_id = null;
if (!is_numeric($ftp_port))
{
@@ -719,14 +719,14 @@ function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $sect
{
$connecttimeout = (empty($conf->global->FTP_CONNECT_TIMEOUT) ? 40 : $conf->global->FTP_CONNECT_TIMEOUT);
if (!empty($conf->global->FTP_CONNECT_WITH_SFTP)) {
- dol_syslog('Try to connect with ssh2_ftp');
- $tmp_conn_id = ssh2_connect($ftp_server, $ftp_port);
+ dol_syslog('Try to connect with ssh2_ftp');
+ $tmp_conn_id = ssh2_connect($ftp_server, $ftp_port);
} elseif (!empty($conf->global->FTP_CONNECT_WITH_SSL)) {
- dol_syslog('Try to connect with ftp_ssl_connect');
- $conn_id = ftp_ssl_connect($ftp_server, $ftp_port, $connecttimeout);
+ dol_syslog('Try to connect with ftp_ssl_connect');
+ $conn_id = ftp_ssl_connect($ftp_server, $ftp_port, $connecttimeout);
} else {
- dol_syslog('Try to connect with ftp_connect');
- $conn_id = ftp_connect($ftp_server, $ftp_port, $connecttimeout);
+ dol_syslog('Try to connect with ftp_connect');
+ $conn_id = ftp_connect($ftp_server, $ftp_port, $connecttimeout);
}
if ($conn_id || $tmp_conn_id)
{
@@ -735,46 +735,46 @@ function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $sect
if (!empty($conf->global->FTP_CONNECT_WITH_SFTP))
{
dol_syslog('Try to authenticate with ssh2_auth_password');
- if (ssh2_auth_password($tmp_conn_id, $ftp_user, $ftp_password))
- {
- // Turn on passive mode transfers (must be after a successful login
- //if ($ftp_passive) ftp_pasv($conn_id, true);
+ if (ssh2_auth_password($tmp_conn_id, $ftp_user, $ftp_password))
+ {
+ // Turn on passive mode transfers (must be after a successful login
+ //if ($ftp_passive) ftp_pasv($conn_id, true);
- // Change the dir
- $newsectioniso = utf8_decode($section);
- //ftp_chdir($conn_id, $newsectioniso);
- $conn_id = ssh2_sftp($tmp_conn_id);
- if (!$conn_id)
- {
- dol_syslog('Failed to connect to SFTP after sssh authentication', LOG_DEBUG);
- $mesg = $langs->transnoentitiesnoconv("FailedToConnectToSFTPAfterSSHAuthentication");
- $ok = 0;
- $error++;
- }
- } else {
- dol_syslog('Failed to connect to FTP with login '.$ftp_user, LOG_DEBUG);
- $mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
- $ok = 0;
- $error++;
- }
+ // Change the dir
+ $newsectioniso = utf8_decode($section);
+ //ftp_chdir($conn_id, $newsectioniso);
+ $conn_id = ssh2_sftp($tmp_conn_id);
+ if (!$conn_id)
+ {
+ dol_syslog('Failed to connect to SFTP after sssh authentication', LOG_DEBUG);
+ $mesg = $langs->transnoentitiesnoconv("FailedToConnectToSFTPAfterSSHAuthentication");
+ $ok = 0;
+ $error++;
+ }
+ } else {
+ dol_syslog('Failed to connect to FTP with login '.$ftp_user, LOG_DEBUG);
+ $mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
+ $ok = 0;
+ $error++;
+ }
} else {
- if (ftp_login($conn_id, $ftp_user, $ftp_password))
- {
- // Turn on passive mode transfers (must be after a successful login
- if ($ftp_passive) ftp_pasv($conn_id, true);
+ if (ftp_login($conn_id, $ftp_user, $ftp_password))
+ {
+ // Turn on passive mode transfers (must be after a successful login
+ if ($ftp_passive) ftp_pasv($conn_id, true);
- // Change the dir
- $newsectioniso = utf8_decode($section);
- ftp_chdir($conn_id, $newsectioniso);
- } else {
- $mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
- $ok = 0;
- $error++;
- }
+ // Change the dir
+ $newsectioniso = utf8_decode($section);
+ ftp_chdir($conn_id, $newsectioniso);
+ } else {
+ $mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
+ $ok = 0;
+ $error++;
+ }
}
}
} else {
- dol_syslog('FailedToConnectToFTPServer '.$ftp_server.' '.$ftp_port, LOG_ERR);
+ dol_syslog('FailedToConnectToFTPServer '.$ftp_server.' '.$ftp_port, LOG_ERR);
$mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServer", $ftp_server, $ftp_port);
$ok = 0;
}
diff --git a/htdocs/holiday/card.php b/htdocs/holiday/card.php
index 1aac890c458..5cd43424760 100644
--- a/htdocs/holiday/card.php
+++ b/htdocs/holiday/card.php
@@ -153,7 +153,7 @@ if (empty($reshook))
setEventMessages($langs->trans("NotEnoughPermission"), null, 'errors');
} else {
if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance)) {
- if (! in_array($fuserid, $childids)) {
+ if (!in_array($fuserid, $childids)) {
$error++;
setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
$action = 'create';
@@ -204,7 +204,7 @@ if (empty($reshook))
$nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday);
if ($nbopenedday < 0.5)
{
- setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); // No working day
+ setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); // No working day
$error++;
$action = 'create';
}
@@ -979,7 +979,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add')
print $langs->trans('SoldeCPUser', round($nb_holiday, 5)).' ';
print $out;
- dol_fiche_end();
+ print dol_get_fiche_end();
} elseif (!is_numeric($conf->global->HOLIDAY_HIDE_BALANCE))
{
print $langs->trans($conf->global->HOLIDAY_HIDE_BALANCE).' ';
@@ -1094,7 +1094,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add')
print '';
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
print '';
print '
';
@@ -1394,7 +1394,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add')
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
// Confirmation messages
diff --git a/htdocs/holiday/class/holiday.class.php b/htdocs/holiday/class/holiday.class.php
index b702bbf5353..a0f640f0cd3 100644
--- a/htdocs/holiday/class/holiday.class.php
+++ b/htdocs/holiday/class/holiday.class.php
@@ -85,36 +85,36 @@ class Holiday extends CommonObject
public $statut = ''; // 1=draft, 2=validated, 3=approved
/**
- * @var int ID
- */
+ * @var int ID
+ */
public $fk_validator;
public $date_valid = '';
/**
- * @var int ID
- */
+ * @var int ID
+ */
public $fk_user_valid;
public $date_refuse = '';
/**
- * @var int ID
- */
+ * @var int ID
+ */
public $fk_user_refuse;
public $date_cancel = '';
/**
- * @var int ID
- */
+ * @var int ID
+ */
public $fk_user_cancel;
public $detail_refuse = '';
/**
- * @var int ID
- */
+ * @var int ID
+ */
public $fk_type;
public $holiday = array();
@@ -1178,11 +1178,11 @@ class Holiday extends CommonObject
$result = '';
- $label = img_picto('', $this->picto).'
'.$langs->trans("Holiday").' ';
- $label .= '
'.$langs->trans('Ref').': '.$this->ref;
+ $label = img_picto('', $this->picto).'
'.$langs->trans("Holiday").' ';
if (isset($this->statut)) {
- $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5);
+ $label .= ' '.$this->getLibStatut(5);
}
+ $label .= '
'.$langs->trans('Ref').': '.$this->ref;
$url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id;
@@ -1217,7 +1217,7 @@ class Holiday extends CommonObject
return $this->LibStatut($this->statut, $mode, $this->date_debut);
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Returns the label of a status
*
@@ -1263,8 +1263,8 @@ class Holiday extends CommonObject
* @param string $htmlname Name of HTML select field
* @return string Show select of status
*/
- public function selectStatutCP($selected = '', $htmlname = 'select_statut')
- {
+ public function selectStatutCP($selected = '', $htmlname = 'select_statut')
+ {
global $langs;
@@ -1298,8 +1298,8 @@ class Holiday extends CommonObject
* @param string $value vrai si mise à jour OK sinon faux
* @return boolean ok or ko
*/
- public function updateConfCP($name, $value)
- {
+ public function updateConfCP($name, $value)
+ {
$sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
$sql .= " value = '".$this->db->escape($value)."'";
@@ -1493,8 +1493,8 @@ class Holiday extends CommonObject
* @param string $name name du paramètre de configuration
* @return string retourne checked si > 0
*/
- public function getCheckOption($name)
- {
+ public function getCheckOption($name)
+ {
$sql = "SELECT value";
$sql .= " FROM ".MAIN_DB_PREFIX."holiday_config";
@@ -1553,8 +1553,8 @@ class Holiday extends CommonObject
* @param int $user_id ID de l'utilisateur à supprimer
* @return boolean Vrai si pas d'erreur, faut si Erreur
*/
- public function deleteCPuser($user_id)
- {
+ public function deleteCPuser($user_id)
+ {
$sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday_users";
$sql .= " WHERE fk_user = ".((int) $user_id);
@@ -1800,7 +1800,7 @@ class Holiday extends CommonObject
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Return list of people with permission to validate leave requests.
* Search for permission "approve leave requests"
@@ -1809,7 +1809,7 @@ class Holiday extends CommonObject
*/
public function fetch_users_approver_holiday()
{
- // phpcs:enable
+ // phpcs:enable
$users_validator = array();
$sql = "SELECT DISTINCT ur.fk_user";
@@ -1862,8 +1862,8 @@ class Holiday extends CommonObject
*
* @return int retourne le nombre d'utilisateur
*/
- public function countActiveUsersWithoutCP()
- {
+ public function countActiveUsersWithoutCP()
+ {
$sql = "SELECT count(u.rowid) as compteur";
$sql .= " FROM ".MAIN_DB_PREFIX."user as u LEFT OUTER JOIN ".MAIN_DB_PREFIX."holiday_users hu ON (hu.fk_user=u.rowid)";
@@ -2097,95 +2097,95 @@ class Holiday extends CommonObject
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
- * Load this->nb for dashboard
- *
- * @return int <0 if KO, >0 if OK
- */
- public function load_state_board()
- {
- // phpcs:enable
+ * Load this->nb for dashboard
+ *
+ * @return int <0 if KO, >0 if OK
+ */
+ public function load_state_board()
+ {
+ // phpcs:enable
global $user;
- $this->nb = array();
+ $this->nb = array();
- $sql = "SELECT count(h.rowid) as nb";
- $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
- $sql .= " WHERE h.statut > 1";
- $sql .= " AND h.entity IN (".getEntity('holiday').")";
+ $sql = "SELECT count(h.rowid) as nb";
+ $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
+ $sql .= " WHERE h.statut > 1";
+ $sql .= " AND h.entity IN (".getEntity('holiday').")";
if (empty($user->rights->expensereport->read_all))
{
$userchildids = $user->getAllChildIds(1);
- $sql.= " AND (h.fk_user IN (".join(',', $userchildids).")";
- $sql.= " OR h.fk_validator IN (".join(',', $userchildids)."))";
+ $sql .= " AND (h.fk_user IN (".join(',', $userchildids).")";
+ $sql .= " OR h.fk_validator IN (".join(',', $userchildids)."))";
}
- $resql = $this->db->query($sql);
- if ($resql) {
- while ($obj = $this->db->fetch_object($resql)) {
- $this->nb["holidays"] = $obj->nb;
- }
- $this->db->free($resql);
- return 1;
- } else {
- dol_print_error($this->db);
- $this->error = $this->db->error();
- return -1;
- }
- }
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ while ($obj = $this->db->fetch_object($resql)) {
+ $this->nb["holidays"] = $obj->nb;
+ }
+ $this->db->free($resql);
+ return 1;
+ } else {
+ dol_print_error($this->db);
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
- *
- * @param User $user Objet user
- * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
- */
- public function load_board($user)
- {
- // phpcs:enable
- global $conf, $langs;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
+ *
+ * @param User $user Objet user
+ * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
+ */
+ public function load_board($user)
+ {
+ // phpcs:enable
+ 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();
- $sql = "SELECT h.rowid, h.date_debut";
- $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
- $sql .= " WHERE h.statut = 2";
- $sql .= " AND h.entity IN (".getEntity('holiday').")";
+ $sql = "SELECT h.rowid, h.date_debut";
+ $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
+ $sql .= " WHERE h.statut = 2";
+ $sql .= " AND h.entity IN (".getEntity('holiday').")";
if (empty($user->rights->expensereport->read_all))
{
$userchildids = $user->getAllChildIds(1);
- $sql.= " AND (h.fk_user IN (".join(',', $userchildids).")";
- $sql.= " OR h.fk_validator IN (".join(',', $userchildids)."))";
+ $sql .= " AND (h.fk_user IN (".join(',', $userchildids).")";
+ $sql .= " OR h.fk_validator IN (".join(',', $userchildids)."))";
}
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $langs->load("members");
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $langs->load("members");
- $response = new WorkboardResponse();
- $response->warning_delay = $conf->holiday->approve->warning_delay / 60 / 60 / 24;
- $response->label = $langs->trans("HolidaysToApprove");
- $response->labelShort = $langs->trans("ToApprove");
- $response->url = DOL_URL_ROOT.'/holiday/list.php?search_statut=2&mainmenu=hrm&leftmenu=holiday';
- $response->img = img_object('', "holiday");
+ $response = new WorkboardResponse();
+ $response->warning_delay = $conf->holiday->approve->warning_delay / 60 / 60 / 24;
+ $response->label = $langs->trans("HolidaysToApprove");
+ $response->labelShort = $langs->trans("ToApprove");
+ $response->url = DOL_URL_ROOT.'/holiday/list.php?search_statut=2&mainmenu=hrm&leftmenu=holiday';
+ $response->img = img_object('', "holiday");
- while ($obj = $this->db->fetch_object($resql))
- {
- $response->nbtodo++;
+ while ($obj = $this->db->fetch_object($resql))
+ {
+ $response->nbtodo++;
- if ($this->db->jdate($obj->date_debut) < ($now - $conf->holiday->approve->warning_delay)) {
- $response->nbtodolate++;
- }
- }
+ if ($this->db->jdate($obj->date_debut) < ($now - $conf->holiday->approve->warning_delay)) {
+ $response->nbtodolate++;
+ }
+ }
- return $response;
- } else {
- dol_print_error($this->db);
- $this->error = $this->db->error();
- return -1;
- }
- }
+ return $response;
+ } else {
+ dol_print_error($this->db);
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
}
diff --git a/htdocs/holiday/common.inc.php b/htdocs/holiday/common.inc.php
index 5fbab2c2700..f8a09e85ad5 100644
--- a/htdocs/holiday/common.inc.php
+++ b/htdocs/holiday/common.inc.php
@@ -33,10 +33,10 @@ $langs->loadLangs(array('user', 'other', 'holiday'));
if (empty($conf->holiday->enabled))
{
- llxHeader('', $langs->trans('CPTitreMenu'));
- print '
';
- print ''.$langs->trans('NotActiveModCP').' ';
- print '
';
- llxFooter();
- exit();
+ llxHeader('', $langs->trans('CPTitreMenu'));
+ print '
';
+ print ''.$langs->trans('NotActiveModCP').' ';
+ print '
';
+ llxFooter();
+ exit();
}
diff --git a/htdocs/holiday/define_holiday.php b/htdocs/holiday/define_holiday.php
index af646984045..47f6eeda550 100644
--- a/htdocs/holiday/define_holiday.php
+++ b/htdocs/holiday/define_holiday.php
@@ -79,20 +79,20 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
if (empty($reshook))
{
- // Selection of new fields
- include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
+ // Selection of new fields
+ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
- // 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
- {
- $search_name = '';
- $search_supervisor = '';
- $toselect = '';
- $search_array_options = array();
- }
+ // 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
+ {
+ $search_name = '';
+ $search_supervisor = '';
+ $toselect = '';
+ $search_array_options = array();
+ }
- // Mass actions
- /*
+ // Mass actions
+ /*
$objectclass='Skeleton';
$objectlabel='Skeleton';
$permissiontoread = $user->rights->skeleton->read;
@@ -101,52 +101,52 @@ if (empty($reshook))
include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
*/
- // Si il y a une action de mise à jour
- if ($action == 'update' && isset($_POST['update_cp']))
- {
- $error = 0;
+ // Si il y a une action de mise à jour
+ if ($action == 'update' && isset($_POST['update_cp']))
+ {
+ $error = 0;
- $typeleaves = $holiday->getTypes(1, 1);
+ $typeleaves = $holiday->getTypes(1, 1);
- $userID = array_keys($_POST['update_cp']);
- $userID = $userID[0];
+ $userID = array_keys($_POST['update_cp']);
+ $userID = $userID[0];
- foreach ($typeleaves as $key => $val)
- {
- $userValue = $_POST['nb_holiday_'.$val['rowid']];
- $userValue = $userValue[$userID];
+ foreach ($typeleaves as $key => $val)
+ {
+ $userValue = $_POST['nb_holiday_'.$val['rowid']];
+ $userValue = $userValue[$userID];
- if (!empty($userValue) || (string) $userValue == '0')
- {
- $userValue = price2num($userValue, 5);
- } else {
- $userValue = '';
- }
+ if (!empty($userValue) || (string) $userValue == '0')
+ {
+ $userValue = price2num($userValue, 5);
+ } else {
+ $userValue = '';
+ }
- //If the user set a comment, we add it to the log comment
- $comment = ((isset($_POST['note_holiday'][$userID]) && !empty($_POST['note_holiday'][$userID])) ? ' ('.$_POST['note_holiday'][$userID].')' : '');
+ //If the user set a comment, we add it to the log comment
+ $comment = ((isset($_POST['note_holiday'][$userID]) && !empty($_POST['note_holiday'][$userID])) ? ' ('.$_POST['note_holiday'][$userID].')' : '');
- //print 'holiday: '.$val['rowid'].'-'.$userValue;
- if ($userValue != '')
- {
- // We add the modification to the log (must be before update of sold because we read current value of sold)
- $result = $holiday->addLogCP($user->id, $userID, $langs->transnoentitiesnoconv('ManualUpdate').$comment, $userValue, $val['rowid']);
- if ($result < 0)
- {
- setEventMessages($holiday->error, $holiday->errors, 'errors');
- $error++;
- }
+ //print 'holiday: '.$val['rowid'].'-'.$userValue;
+ if ($userValue != '')
+ {
+ // We add the modification to the log (must be before update of sold because we read current value of sold)
+ $result = $holiday->addLogCP($user->id, $userID, $langs->transnoentitiesnoconv('ManualUpdate').$comment, $userValue, $val['rowid']);
+ if ($result < 0)
+ {
+ setEventMessages($holiday->error, $holiday->errors, 'errors');
+ $error++;
+ }
- // Update of the days of the employee
- $result = $holiday->updateSoldeCP($userID, $userValue, $val['rowid']);
- if ($result < 0)
- {
- setEventMessages($holiday->error, $holiday->errors, 'errors');
- $error++;
- }
+ // Update of the days of the employee
+ $result = $holiday->updateSoldeCP($userID, $userValue, $val['rowid']);
+ if ($result < 0)
+ {
+ setEventMessages($holiday->error, $holiday->errors, 'errors');
+ $error++;
+ }
- // If it first update of balance, we set date to avoid to have sold incremented by new month
- /*
+ // If it first update of balance, we set date to avoid to have sold incremented by new month
+ /*
$now=dol_now();
$sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
$sql.= " value = '".dol_print_date($now,'%Y%m%d%H%M%S')."'";
@@ -154,11 +154,11 @@ if (empty($reshook))
dol_syslog('define_holiday update lastUpdate entry', LOG_DEBUG);
$result = $db->query($sql);
*/
- }
- }
+ }
+ }
- if (!$error) setEventMessages('UpdateConfCPOK', '', 'mesgs');
- }
+ if (!$error) setEventMessages('UpdateConfCPOK', '', 'mesgs');
+ }
}
@@ -194,10 +194,10 @@ print load_fiche_titre($langs->trans('MenuConfCP'), '', 'title_hrm.png');
print '
'.$langs->trans('LastUpdateCP').': '."\n";
$lastUpdate = $holiday->getConfCP('lastUpdate');
if ($lastUpdate) {
- print ''.dol_print_date($db->jdate($lastUpdate), 'dayhour').' ';
- print ' '.$langs->trans("MonthOfLastMonthlyUpdate").': '.$langs->trans('Month'.substr($lastUpdate, 4, 2)).' '.substr($lastUpdate, 0, 4).' '."\n";
+ print ''.dol_print_date($db->jdate($lastUpdate), 'dayhour').' ';
+ print ' '.$langs->trans("MonthOfLastMonthlyUpdate").': '.$langs->trans('Month'.substr($lastUpdate, 4, 2)).' '.substr($lastUpdate, 0, 4).' '."\n";
} else {
- print $langs->trans('None');
+ print $langs->trans('None');
}
print "
\n";
@@ -220,7 +220,7 @@ $filters .= ' AND employee = 1'; // Only employee users are visible
$listUsers = $holiday->fetchUsers(false, true, $filters);
if (is_numeric($listUsers) && $listUsers < 0)
{
- setEventMessages($holiday->error, $holiday->errors, 'errors');
+ setEventMessages($holiday->error, $holiday->errors, 'errors');
}
$i = 0;
@@ -228,137 +228,137 @@ $i = 0;
if (count($typeleaves) == 0)
{
- //print '
';
- print $langs->trans("NoLeaveWithCounterDefined")." \n";
- print $langs->trans("GoIntoDictionaryHolidayTypes");
- //print '
';
+ //print '
';
+ print $langs->trans("NoLeaveWithCounterDefined")." \n";
+ print $langs->trans("GoIntoDictionaryHolidayTypes");
+ //print '
';
} else {
- $canedit = 0;
- if (!empty($user->rights->holiday->define_holiday)) $canedit = 1;
+ $canedit = 0;
+ if (!empty($user->rights->holiday->define_holiday)) $canedit = 1;
- $moreforfilter = '';
+ $moreforfilter = '';
- print '
';
- print '
'."\n";
+ print '';
+ print '
'."\n";
- print '';
+ print ' ';
- // User
- print ' ';
+ // User
+ print ' ';
- // Supervisor
- print '';
- print $form->select_dolusers($search_supervisor, 'search_supervisor', 1, null, 0, null, null, 0, 0, 0, '', 0, '', 'maxwidth200');
- print ' ';
+ // Supervisor
+ print '';
+ print $form->select_dolusers($search_supervisor, 'search_supervisor', 1, null, 0, null, null, 0, 0, 0, '', 0, '', 'maxwidth200');
+ print ' ';
- // Type of leave request
- if (count($typeleaves))
- {
- foreach ($typeleaves as $key => $val)
- {
- print ' ';
- }
- } else {
- print ' ';
- }
- print ' ';
+ // Type of leave request
+ if (count($typeleaves))
+ {
+ foreach ($typeleaves as $key => $val)
+ {
+ print ' ';
+ }
+ } else {
+ print ' ';
+ }
+ print ' ';
- // Action column
- print '';
- $searchpicto = $form->showFilterButtons();
- print $searchpicto;
- print ' ';
+ // Action column
+ print '';
+ $searchpicto = $form->showFilterButtons();
+ print $searchpicto;
+ print ' ';
- print ' ';
+ print '';
- print '';
- print_liste_field_titre('Employee', $_SERVER["PHP_SELF"]);
- print_liste_field_titre('Supervisor', $_SERVER["PHP_SELF"]);
- if (count($typeleaves))
- {
- foreach ($typeleaves as $key => $val)
- {
- $labeltype = ($langs->trans($val['code']) != $val['code']) ? $langs->trans($val['code']) : $langs->trans($val['label']);
- print_liste_field_titre($labeltype, $_SERVER["PHP_SELF"], '', '', '', '', '', '', 'center ');
- }
- } else {
- print_liste_field_titre('NoLeaveWithCounterDefined', $_SERVER["PHP_SELF"], '', '', '', '');
- }
- print_liste_field_titre((empty($user->rights->holiday->define_holiday) ? '' : 'Note'), $_SERVER["PHP_SELF"]);
- print_liste_field_titre('');
- print ' ';
+ print '';
+ print_liste_field_titre('Employee', $_SERVER["PHP_SELF"]);
+ print_liste_field_titre('Supervisor', $_SERVER["PHP_SELF"]);
+ if (count($typeleaves))
+ {
+ foreach ($typeleaves as $key => $val)
+ {
+ $labeltype = ($langs->trans($val['code']) != $val['code']) ? $langs->trans($val['code']) : $langs->trans($val['label']);
+ print_liste_field_titre($labeltype, $_SERVER["PHP_SELF"], '', '', '', '', '', '', 'center ');
+ }
+ } else {
+ print_liste_field_titre('NoLeaveWithCounterDefined', $_SERVER["PHP_SELF"], '', '', '', '');
+ }
+ print_liste_field_titre((empty($user->rights->holiday->define_holiday) ? '' : 'Note'), $_SERVER["PHP_SELF"]);
+ print_liste_field_titre('');
+ print ' ';
- $usersupervisor = new User($db);
+ $usersupervisor = new User($db);
- foreach ($listUsers as $users)
- {
- // If user has not permission to edit/read all, we must see only subordinates
- if (empty($user->rights->holiday->read_all))
- {
- if (($users['rowid'] != $user->id) && (!in_array($users['rowid'], $userchilds))) continue; // This user is not into hierarchy of current user, we hide it.
- }
+ foreach ($listUsers as $users)
+ {
+ // If user has not permission to edit/read all, we must see only subordinates
+ if (empty($user->rights->holiday->read_all))
+ {
+ if (($users['rowid'] != $user->id) && (!in_array($users['rowid'], $userchilds))) continue; // This user is not into hierarchy of current user, we hide it.
+ }
- $userstatic->id = $users['rowid'];
- $userstatic->lastname = $users['lastname'];
- $userstatic->firstname = $users['firstname'];
- $userstatic->gender = $users['gender'];
- $userstatic->photo = $users['photo'];
- $userstatic->statut = $users['status'];
- $userstatic->employee = $users['employee'];
- $userstatic->fk_user = $users['fk_user'];
+ $userstatic->id = $users['rowid'];
+ $userstatic->lastname = $users['lastname'];
+ $userstatic->firstname = $users['firstname'];
+ $userstatic->gender = $users['gender'];
+ $userstatic->photo = $users['photo'];
+ $userstatic->statut = $users['status'];
+ $userstatic->employee = $users['employee'];
+ $userstatic->fk_user = $users['fk_user'];
- if ($userstatic->fk_user > 0) $usersupervisor->fetch($userstatic->fk_user);
+ if ($userstatic->fk_user > 0) $usersupervisor->fetch($userstatic->fk_user);
- print '';
+ print ' ';
- // User
- print '';
- print $userstatic->getNomUrl(-1);
- print ' ';
+ // User
+ print '';
+ print $userstatic->getNomUrl(-1);
+ print ' ';
- // Supervisor
- print '';
- if ($userstatic->fk_user > 0) print $usersupervisor->getNomUrl(-1);
- print ' ';
+ // Supervisor
+ print '';
+ if ($userstatic->fk_user > 0) print $usersupervisor->getNomUrl(-1);
+ print ' ';
- // Amount for each type
- if (count($typeleaves))
- {
- foreach ($typeleaves as $key => $val)
- {
- $nbtoshow = '';
- if ($holiday->getCPforUser($users['rowid'], $val['rowid']) != '') $nbtoshow = price2num($holiday->getCPforUser($users['rowid'], $val['rowid']), 5);
+ // Amount for each type
+ if (count($typeleaves))
+ {
+ foreach ($typeleaves as $key => $val)
+ {
+ $nbtoshow = '';
+ if ($holiday->getCPforUser($users['rowid'], $val['rowid']) != '') $nbtoshow = price2num($holiday->getCPforUser($users['rowid'], $val['rowid']), 5);
- //var_dump($users['rowid'].' - '.$val['rowid']);
- print '';
- if ($canedit) print ' ';
- else print $nbtoshow;
- //print ' '.$langs->trans('days');
- print ' '."\n";
- }
- } else {
- print ' ';
- }
+ //var_dump($users['rowid'].' - '.$val['rowid']);
+ print '';
+ if ($canedit) print ' ';
+ else print $nbtoshow;
+ //print ' '.$langs->trans('days');
+ print ' '."\n";
+ }
+ } else {
+ print ' ';
+ }
- // Note
- print '';
- if ($canedit) print ' ';
- print ' ';
+ // Note
+ print '';
+ if ($canedit) print ' ';
+ print ' ';
- // Button modify
- print '';
- if (!empty($user->rights->holiday->define_holiday)) // Allowed to set the balance of any user
- {
- print ' ';
- }
- print ' '."\n";
- print ' ';
+ // Button modify
+ print '';
+ if (!empty($user->rights->holiday->define_holiday)) // Allowed to set the balance of any user
+ {
+ print ' ';
+ }
+ print ' '."\n";
+ print '';
- $i++;
- }
+ $i++;
+ }
- print '
';
- print '
';
+ print '
';
+ print '
';
}
print '';
diff --git a/htdocs/holiday/document.php b/htdocs/holiday/document.php
index c37f403be4d..192c7d24e33 100644
--- a/htdocs/holiday/document.php
+++ b/htdocs/holiday/document.php
@@ -119,114 +119,114 @@ if ($object->id)
print '
';
- print '';
- print ''.$langs->trans("User").' ';
+ print ' ';
+ print ''.$langs->trans("User").' ';
print '';
print $userRequest->getNomUrl(-1, 'leave');
print ' ';
- // Type
- print '';
- print ''.$langs->trans("Type").' ';
- print '';
- $typeleaves = $object->getTypes(1, -1);
- $labeltoshow = (($typeleaves[$object->fk_type]['code'] && $langs->trans($typeleaves[$object->fk_type]['code']) != $typeleaves[$object->fk_type]['code']) ? $langs->trans($typeleaves[$object->fk_type]['code']) : $typeleaves[$object->fk_type]['label']);
- print empty($labeltoshow) ? $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type) : $labeltoshow;
- print ' ';
- print ' ';
+ // Type
+ print '';
+ print ''.$langs->trans("Type").' ';
+ print '';
+ $typeleaves = $object->getTypes(1, -1);
+ $labeltoshow = (($typeleaves[$object->fk_type]['code'] && $langs->trans($typeleaves[$object->fk_type]['code']) != $typeleaves[$object->fk_type]['code']) ? $langs->trans($typeleaves[$object->fk_type]['code']) : $typeleaves[$object->fk_type]['label']);
+ print empty($labeltoshow) ? $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type) : $labeltoshow;
+ print ' ';
+ print ' ';
- $starthalfday = ($object->halfday == -1 || $object->halfday == 2) ? 'afternoon' : 'morning';
- $endhalfday = ($object->halfday == 1 || $object->halfday == 2) ? 'morning' : 'afternoon';
+ $starthalfday = ($object->halfday == -1 || $object->halfday == 2) ? 'afternoon' : 'morning';
+ $endhalfday = ($object->halfday == 1 || $object->halfday == 2) ? 'morning' : 'afternoon';
- if (!$edit)
- {
- print '';
- print '';
- print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday"));
- print ' ';
- print ''.dol_print_date($object->date_debut, 'day');
- print ' ';
- print ''.$langs->trans($listhalfday[$starthalfday]).' ';
- print ' ';
- print ' ';
- } else {
- print '';
- print '';
- print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday"));
- print ' ';
- print '';
- print $form->selectDate($object->date_debut, 'date_debut_');
- print ' ';
+ if (!$edit)
+ {
+ print ' ';
+ print '';
+ print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday"));
+ print ' ';
+ print ''.dol_print_date($object->date_debut, 'day');
+ print ' ';
+ print ''.$langs->trans($listhalfday[$starthalfday]).' ';
+ print ' ';
+ print ' ';
+ } else {
+ print '';
+ print '';
+ print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday"));
+ print ' ';
+ print '';
+ print $form->selectDate($object->date_debut, 'date_debut_');
+ print ' ';
print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday') ?GETPOST('starthalfday') : $starthalfday));
- print ' ';
- print ' ';
- }
+ print '';
+ print '';
+ }
- if (!$edit)
- {
- print '';
- print '';
- print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday"));
- print ' ';
- print ''.dol_print_date($object->date_fin, 'day');
- print ' ';
- print ''.$langs->trans($listhalfday[$endhalfday]).' ';
- print ' ';
- print ' ';
- } else {
- print '';
- print '';
- print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday"));
- print ' ';
- print '';
- print $form->selectDate($object->date_fin, 'date_fin_');
- print ' ';
- print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday') ?GETPOST('endhalfday') : $endhalfday));
- print ' ';
- print ' ';
- }
+ if (!$edit)
+ {
+ print '';
+ print '';
+ print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday"));
+ print ' ';
+ print ''.dol_print_date($object->date_fin, 'day');
+ print ' ';
+ print ''.$langs->trans($listhalfday[$endhalfday]).' ';
+ print ' ';
+ print ' ';
+ } else {
+ print '';
+ print '';
+ print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday"));
+ print ' ';
+ print '';
+ print $form->selectDate($object->date_fin, 'date_fin_');
+ print ' ';
+ print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday') ?GETPOST('endhalfday') : $endhalfday));
+ print ' ';
+ print ' ';
+ }
- // Nb days consumed
- print '';
- print '';
- $htmlhelp = $langs->trans('NbUseDaysCPHelp');
- $includesaturday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY : 1);
- $includesunday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY : 1);
- if ($includesaturday) $htmlhelp .= ' '.$langs->trans("DayIsANonWorkingDay", $langs->trans("Saturday"));
- if ($includesunday) $htmlhelp .= ' '.$langs->trans("DayIsANonWorkingDay", $langs->trans("Sunday"));
- print $form->textwithpicto($langs->trans('NbUseDaysCP'), $htmlhelp);
- print ' ';
- print ''.num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday).' ';
- print ' ';
+ // Nb days consumed
+ print '';
+ print '';
+ $htmlhelp = $langs->trans('NbUseDaysCPHelp');
+ $includesaturday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY : 1);
+ $includesunday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY : 1);
+ if ($includesaturday) $htmlhelp .= ' '.$langs->trans("DayIsANonWorkingDay", $langs->trans("Saturday"));
+ if ($includesunday) $htmlhelp .= ' '.$langs->trans("DayIsANonWorkingDay", $langs->trans("Sunday"));
+ print $form->textwithpicto($langs->trans('NbUseDaysCP'), $htmlhelp);
+ print ' ';
+ print ''.num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday).' ';
+ print ' ';
- if ($object->statut == 5)
- {
- print '';
- print ''.$langs->trans('DetailRefusCP').' ';
- print ''.$object->detail_refuse.' ';
- print ' ';
- }
+ if ($object->statut == 5)
+ {
+ print '';
+ print ''.$langs->trans('DetailRefusCP').' ';
+ print ''.$object->detail_refuse.' ';
+ print ' ';
+ }
- // Description
- if (!$edit)
- {
- print '';
- print ''.$langs->trans('DescCP').' ';
- print ''.nl2br($object->description).' ';
- print ' ';
- } else {
- print '';
- print ''.$langs->trans('DescCP').' ';
- print ''.$object->description.' ';
- print ' ';
- }
+ // Description
+ if (!$edit)
+ {
+ print '';
+ print ''.$langs->trans('DescCP').' ';
+ print ''.nl2br($object->description).' ';
+ print ' ';
+ } else {
+ print '';
+ print ''.$langs->trans('DescCP').' ';
+ print ''.$object->description.' ';
+ print ' ';
+ }
- print ''.$langs->trans("NbOfAttachedFiles").' '.count($filearray).' ';
- print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.dol_print_size($totalsize, 1, 1).' ';
+ print ''.$langs->trans("NbOfAttachedFiles").' '.count($filearray).' ';
+ print ''.$langs->trans("TotalSizeOfAttachedFiles").' '.dol_print_size($totalsize, 1, 1).' ';
- print '';
- print '
'."\n";
- /*
+ print '';
+ print '
'."\n";
+ /*
print '';
print '';
print '
';
@@ -288,19 +288,19 @@ if ($object->id)
print '
';
print '
'; */
- print '';
+ print '';
- print '
';
+ print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
- $modulepart = 'holiday';
- $permission = $user->rights->holiday->write;
- $permtoedit = $user->rights->holiday->write;
- $param = '&id='.$object->id;
- include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
+ $modulepart = 'holiday';
+ $permission = $user->rights->holiday->write;
+ $permtoedit = $user->rights->holiday->write;
+ $param = '&id='.$object->id;
+ include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
} else {
print $langs->trans("ErrorUnknown");
}
diff --git a/htdocs/holiday/list.php b/htdocs/holiday/list.php
index 78e838ae058..f16375209e1 100644
--- a/htdocs/holiday/list.php
+++ b/htdocs/holiday/list.php
@@ -68,14 +68,14 @@ $result = restrictedArea($user, 'holiday', '', '');
// If we are on the view of a specific user
if ($id > 0)
{
- $canread = 0;
- if ($id == $user->id) $canread = 1;
- if (!empty($user->rights->holiday->read_all)) $canread = 1;
- if (!empty($user->rights->holiday->read) && in_array($id, $childids)) $canread = 1;
- if (!$canread)
- {
- accessforbidden();
- }
+ $canread = 0;
+ if ($id == $user->id) $canread = 1;
+ if (!empty($user->rights->holiday->read_all)) $canread = 1;
+ if (!empty($user->rights->holiday->read) && in_array($id, $childids)) $canread = 1;
+ if (!$canread)
+ {
+ accessforbidden();
+ }
}
$diroutputmassaction = $conf->holiday->dir_output.'/temp/massgeneration/'.$user->id;
@@ -122,9 +122,9 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
// List of fields to search into when doing a "search in all"
$fieldstosearchall = array(
'cp.ref'=>'Ref',
- 'cp.description'=>'Description',
- 'uu.lastname'=>'EmployeeLastname',
- 'uu.firstname'=>'EmployeeFirstname',
+ 'cp.description'=>'Description',
+ 'uu.lastname'=>'EmployeeLastname',
+ 'uu.firstname'=>'EmployeeFirstname',
'uu.login'=>'Login'
);
@@ -176,7 +176,7 @@ if (empty($reshook))
$search_ref = "";
$search_month_create = "";
$search_year_create = "";
- $search_month_start = "";
+ $search_month_start = "";
$search_year_start = "";
$search_month_end = "";
$search_year_end = "";
@@ -404,18 +404,18 @@ if ($resql)
print dol_get_fiche_head($head, 'paidholidays', $title, -1, 'user');
- dol_banner_tab($fuser, 'id', $linkback, $user->rights->user->user->lire || $user->admin);
+ dol_banner_tab($fuser, 'id', $linkback, $user->rights->user->user->lire || $user->admin);
if (empty($conf->global->HOLIDAY_HIDE_BALANCE))
{
- print '
';
+ print '
';
- print ' ';
+ print ' ';
- showMyBalance($object, $user_id);
+ showMyBalance($object, $user_id);
}
- dol_fiche_end();
+ print dol_get_fiche_end();
// Buttons for actions
@@ -445,8 +445,8 @@ if ($resql)
if ($sall)
{
- foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
- print ''.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
';
+ foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
+ print ''.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
';
}
$moreforfilter = '';
@@ -509,16 +509,16 @@ if ($resql)
{
if ($user->rights->holiday->read_all)
{
- print ' ';
- $validator = new UserGroup($db);
- $excludefilter = $user->admin ? '' : 'u.rowid <> '.$user->id;
- $valideurobjects = $validator->listUsersForGroup($excludefilter);
- $valideurarray = array();
- foreach ($valideurobjects as $val) $valideurarray[$val->id] = $val->id;
- print $form->select_dolusers($search_valideur, "search_valideur", 1, "", 0, $valideurarray, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth150');
- print ' ';
+ print '';
+ $validator = new UserGroup($db);
+ $excludefilter = $user->admin ? '' : 'u.rowid <> '.$user->id;
+ $valideurobjects = $validator->listUsersForGroup($excludefilter);
+ $valideurarray = array();
+ foreach ($valideurobjects as $val) $valideurarray[$val->id] = $val->id;
+ print $form->select_dolusers($search_valideur, "search_valideur", 1, "", 0, $valideurarray, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth150');
+ print ' ';
} else {
- print ' ';
+ print ' ';
}
}
@@ -637,9 +637,9 @@ if ($resql)
$result = 0;
} elseif ($num > 0 && !empty($mysoc->country_id))
{
- // Lines
- $userstatic = new User($db);
- $approbatorstatic = new User($db);
+ // Lines
+ $userstatic = new User($db);
+ $approbatorstatic = new User($db);
$typeleaves = $object->getTypes(1, -1);
@@ -756,14 +756,14 @@ if ($resql)
if (!$i) $totalarray['nbfield']++;
}
- // Action column
- print '';
+ // Action column
+ print ' ';
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;
print ' ';
- }
+ }
print ' ';
if (!$i) $totalarray['nbfield']++;
diff --git a/htdocs/holiday/month_report.php b/htdocs/holiday/month_report.php
index 7e7e7ed29f9..5108c97f54a 100644
--- a/htdocs/holiday/month_report.php
+++ b/htdocs/holiday/month_report.php
@@ -57,8 +57,8 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_
$sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'alpha');
-if (! $sortfield) $sortfield = "cp.rowid";
-if (! $sortorder) $sortorder = "ASC";
+if (!$sortfield) $sortfield = "cp.rowid";
+if (!$sortorder) $sortorder = "ASC";
$hookmanager->initHooks(array('leavemovementlist'));
@@ -78,42 +78,42 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
if (empty($reshook))
{
- // Selection of new fields
- include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
+ // Selection of new fields
+ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
- // 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
- {
- $search_ref = '';
- $search_employee = '';
- $search_type = '';
- $search_description = '';
- $toselect = '';
- $search_array_options = array();
- }
+ // 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
+ {
+ $search_ref = '';
+ $search_employee = '';
+ $search_type = '';
+ $search_description = '';
+ $toselect = '';
+ $search_array_options = array();
+ }
- 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'))
- {
- $massaction = '';
- }
+ 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'))
+ {
+ $massaction = '';
+ }
}
$arrayfields = array(
- 'cp.ref'=>array('label'=>$langs->trans('Ref'), 'checked'=>1),
- 'cp.fk_user'=>array('label'=>$langs->trans('Employee'), 'checked'=>1),
- 'ct.label'=>array('label'=>$langs->trans('Type'), 'checked'=>1),
- 'cp.date_debut'=>array('label'=>$langs->trans('DateDebCP'), 'checked'=>1),
- 'cp.date_fin'=>array('label'=>$langs->trans('DateFinCP'), 'checked'=>1),
- 'used_days'=>array('label'=>$langs->trans('NbUseDaysCPShort'), 'checked'=>1),
- 'date_start_month'=>array('label'=>$langs->trans('DateStartInMonth'), 'checked'=>1),
- 'date_end_month'=>array('label'=>$langs->trans('DateEndInMonth'), 'checked'=>1),
- 'used_days_month'=>array('label'=>$langs->trans('NbUseDaysCPShortInMonth'), 'checked'=>1),
- 'cp.description'=>array('label'=>$langs->trans('DescCP'), 'checked'=>1),
+ 'cp.ref'=>array('label'=>$langs->trans('Ref'), 'checked'=>1),
+ 'cp.fk_user'=>array('label'=>$langs->trans('Employee'), 'checked'=>1),
+ 'ct.label'=>array('label'=>$langs->trans('Type'), 'checked'=>1),
+ 'cp.date_debut'=>array('label'=>$langs->trans('DateDebCP'), 'checked'=>1),
+ 'cp.date_fin'=>array('label'=>$langs->trans('DateFinCP'), 'checked'=>1),
+ 'used_days'=>array('label'=>$langs->trans('NbUseDaysCPShort'), 'checked'=>1),
+ 'date_start_month'=>array('label'=>$langs->trans('DateStartInMonth'), 'checked'=>1),
+ 'date_end_month'=>array('label'=>$langs->trans('DateEndInMonth'), 'checked'=>1),
+ 'used_days_month'=>array('label'=>$langs->trans('NbUseDaysCPShortInMonth'), 'checked'=>1),
+ 'cp.description'=>array('label'=>$langs->trans('DescCP'), 'checked'=>1),
);
@@ -134,19 +134,19 @@ $search_year = GETPOST("reyear", 'int') ?GETPOST("reyear", 'int') : date("Y", ti
$year_month = sprintf("%04d", $search_year).'-'.sprintf("%02d", $search_month);
$sql = "SELECT cp.rowid, cp.ref, cp.fk_user, cp.date_debut, cp.date_fin, ct.label, cp.description, cp.halfday";
-$sql.= " FROM ".MAIN_DB_PREFIX."holiday cp";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user u ON cp.fk_user = u.rowid";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_holiday_types ct ON cp.fk_type = ct.rowid";
-$sql.= " WHERE cp.rowid > 0";
-$sql.= " AND cp.statut = 3"; // 3 = Approved
-$sql.= " AND (date_format(cp.date_debut, '%Y-%m') = '".$db->escape($year_month)."' OR date_format(cp.date_fin, '%Y-%m') = '".$db->escape($year_month)."')";
+$sql .= " FROM ".MAIN_DB_PREFIX."holiday cp";
+$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user u ON cp.fk_user = u.rowid";
+$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_holiday_types ct ON cp.fk_type = ct.rowid";
+$sql .= " WHERE cp.rowid > 0";
+$sql .= " AND cp.statut = 3"; // 3 = Approved
+$sql .= " AND (date_format(cp.date_debut, '%Y-%m') = '".$db->escape($year_month)."' OR date_format(cp.date_fin, '%Y-%m') = '".$db->escape($year_month)."')";
if (!empty($search_ref)) $sql .= natural_search('cp.ref', $search_ref);
if (!empty($search_employee)) $sql .= " AND cp.fk_user = '".$db->escape($search_employee)."'";
if (!empty($search_type)) $sql .= ' AND cp.fk_type IN ('.$db->escape($search_type).')';
-if (!empty($search_description)) $sql.= natural_search('cp.description', $search_description);
+if (!empty($search_description)) $sql .= natural_search('cp.description', $search_description);
-$sql.= $db->order($sortfield, $sortorder);
+$sql .= $db->order($sortfield, $sortorder);
$resql = $db->query($sql);
if (empty($resql))
@@ -158,7 +158,7 @@ if (empty($resql))
$num = $db->num_rows($resql);
$param = '';
-if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.= '&contextpage='.urlencode($contextpage);
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
if (!empty($search_ref)) $param .= '&search_ref='.urlencode($search_ref);
if (!empty($search_employee)) $param .= '&search_employee='.urlencode($search_employee);
@@ -190,7 +190,7 @@ $moreforfilter = '';
$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
$selectedfields = '';
$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
-$selectedfields.= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
+$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
print '';
print '
';
@@ -199,31 +199,31 @@ print '';
// Filter: Ref
if (!empty($arrayfields['cp.ref']['checked'])) {
- print '';
- print ' ';
- print ' ';
+ print '';
+ print ' ';
+ print ' ';
}
// Filter: Employee
if (!empty($arrayfields['cp.fk_user']['checked'])) {
- print '';
- print $form->select_dolusers($search_employee, "search_employee", 1, null, 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200');
- print ' ';
+ print '';
+ print $form->select_dolusers($search_employee, "search_employee", 1, null, 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200');
+ print ' ';
}
// Filter: Type
if (!empty($arrayfields['ct.label']['checked'])) {
- $typeleaves = $holidaystatic->getTypes(1, -1);
- $arraytypeleaves = array();
- foreach ($typeleaves as $key => $val)
- {
- $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']);
- $arraytypeleaves[$val['rowid']] = $labeltoshow;
- }
+ $typeleaves = $holidaystatic->getTypes(1, -1);
+ $arraytypeleaves = array();
+ foreach ($typeleaves as $key => $val)
+ {
+ $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']);
+ $arraytypeleaves[$val['rowid']] = $labeltoshow;
+ }
- print '';
- print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1, 0, 0, '', 0, 0, 0, '', '', 1);
- print ' ';
+ print '';
+ print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1, 0, 0, '', 0, 0, 0, '', '', 1);
+ print ' ';
}
if (!empty($arrayfields['cp.date_debut']['checked'])) print ' ';
@@ -235,9 +235,9 @@ if (!empty($arrayfields['used_days_month']['checked'])) print '';
- print ' ';
- print ' ';
+ print '';
+ print ' ';
+ print ' ';
}
// Action column
@@ -263,93 +263,93 @@ print ' ';
if ($num == 0)
{
- print ''.$langs->trans('None').' ';
+ print ''.$langs->trans('None').' ';
}
else {
- while ($obj = $db->fetch_object($resql))
- {
- $user = new User($db);
- $user->fetch($obj->fk_user);
+ while ($obj = $db->fetch_object($resql))
+ {
+ $user = new User($db);
+ $user->fetch($obj->fk_user);
- $date_start = $db->jdate($obj->date_debut, true);
- $date_end = $db->jdate($obj->date_fin, true);
+ $date_start = $db->jdate($obj->date_debut, true);
+ $date_end = $db->jdate($obj->date_fin, true);
- $tmpstart = dol_getdate($date_start);
- $tmpend = dol_getdate($date_end);
+ $tmpstart = dol_getdate($date_start);
+ $tmpend = dol_getdate($date_end);
- $starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning';
- $endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon';
+ $starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning';
+ $endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon';
- $halfdayinmonth = $obj->halfday;
- $starthalfdayinmonth = $starthalfday;
- $endhalfdayinmonth = $endhalfday;
+ $halfdayinmonth = $obj->halfday;
+ $starthalfdayinmonth = $starthalfday;
+ $endhalfdayinmonth = $endhalfday;
- //0:Full days, 2:Start afternoon end morning, -1:Start afternoon end afternoon, 1:Start morning end morning
+ //0:Full days, 2:Start afternoon end morning, -1:Start afternoon end afternoon, 1:Start morning end morning
- // Set date_start_gmt and date_end_gmt that are date to show for the selected month
- $date_start_inmonth = $db->jdate($obj->date_debut, true);
- $date_end_inmonth = $db->jdate($obj->date_fin, true);
- if ($tmpstart['year'] < $search_year || $tmpstart['mon'] < $search_month)
- {
- $date_start_inmonth = dol_get_first_day($search_year, $search_month, true);
- $starthalfdayinmonth = 'morning';
- if ($halfdayinmonth == 2) $halfdayinmonth = 1;
- if ($halfdayinmonth == -1) $halfdayinmonth = 0;
- }
- if ($tmpend['year'] > $search_year || $tmpend['mon'] > $search_month)
- {
- $date_end_inmonth = dol_get_last_day($search_year, $search_month, true) - ((24 * 3600) - 1);
- $endhalfdayinmonth = 'afternoon';
- if ($halfdayinmonth == 2) $halfdayinmonth = -1;
- if ($halfdayinmonth == 1) $halfdayinmonth = 0;
- }
+ // Set date_start_gmt and date_end_gmt that are date to show for the selected month
+ $date_start_inmonth = $db->jdate($obj->date_debut, true);
+ $date_end_inmonth = $db->jdate($obj->date_fin, true);
+ if ($tmpstart['year'] < $search_year || $tmpstart['mon'] < $search_month)
+ {
+ $date_start_inmonth = dol_get_first_day($search_year, $search_month, true);
+ $starthalfdayinmonth = 'morning';
+ if ($halfdayinmonth == 2) $halfdayinmonth = 1;
+ if ($halfdayinmonth == -1) $halfdayinmonth = 0;
+ }
+ if ($tmpend['year'] > $search_year || $tmpend['mon'] > $search_month)
+ {
+ $date_end_inmonth = dol_get_last_day($search_year, $search_month, true) - ((24 * 3600) - 1);
+ $endhalfdayinmonth = 'afternoon';
+ if ($halfdayinmonth == 2) $halfdayinmonth = -1;
+ if ($halfdayinmonth == 1) $halfdayinmonth = 0;
+ }
- // Leave request
- $holidaystatic->id = $obj->rowid;
- $holidaystatic->ref = $obj->ref;
+ // Leave request
+ $holidaystatic->id = $obj->rowid;
+ $holidaystatic->ref = $obj->ref;
- print '';
+ print ' ';
- if (!empty($arrayfields['cp.ref']['checked'])) print ''.$holidaystatic->getNomUrl(1, 1).' ';
- if (!empty($arrayfields['cp.fk_user']['checked'])) print ''.$user->getFullName($langs).' ';
- if (!empty($arrayfields['ct.label']['checked'])) print ''.$obj->label.' ';
+ if (!empty($arrayfields['cp.ref']['checked'])) print ''.$holidaystatic->getNomUrl(1, 1).' ';
+ if (!empty($arrayfields['cp.fk_user']['checked'])) print ''.$user->getFullName($langs).' ';
+ if (!empty($arrayfields['ct.label']['checked'])) print ''.$obj->label.' ';
- if (!empty($arrayfields['cp.date_debut']['checked']))
- {
- print ''.dol_print_date($db->jdate($obj->date_debut), 'day');
- print ' ('.$langs->trans($listhalfday[$starthalfday]).') ';
- print ' ';
- }
+ if (!empty($arrayfields['cp.date_debut']['checked']))
+ {
+ print ''.dol_print_date($db->jdate($obj->date_debut), 'day');
+ print ' ('.$langs->trans($listhalfday[$starthalfday]).') ';
+ print ' ';
+ }
- if (!empty($arrayfields['cp.date_fin']['checked']))
- {
- print ''.dol_print_date($db->jdate($obj->date_fin), 'day');
- print ' ('.$langs->trans($listhalfday[$endhalfday]).') ';
- print ' ';
- }
+ if (!empty($arrayfields['cp.date_fin']['checked']))
+ {
+ print ''.dol_print_date($db->jdate($obj->date_fin), 'day');
+ print ' ('.$langs->trans($listhalfday[$endhalfday]).') ';
+ print ' ';
+ }
- if (!empty($arrayfields['used_days']['checked'])) print ''.num_open_day($date_start, $date_end, 0, 1, $obj->halfday).' ';
+ if (!empty($arrayfields['used_days']['checked'])) print ''.num_open_day($date_start, $date_end, 0, 1, $obj->halfday).' ';
- if (!empty($arrayfields['date_start_month']['checked']))
- {
- print ''.dol_print_date($date_start_inmonth, 'day');
- print ' ('.$langs->trans($listhalfday[$starthalfdayinmonth]).') ';
- print ' ';
- }
+ if (!empty($arrayfields['date_start_month']['checked']))
+ {
+ print ''.dol_print_date($date_start_inmonth, 'day');
+ print ' ('.$langs->trans($listhalfday[$starthalfdayinmonth]).') ';
+ print ' ';
+ }
- if (!empty($arrayfields['date_end_month']['checked']))
- {
- print ''.dol_print_date($date_end_inmonth, 'day');
- print ' ('.$langs->trans($listhalfday[$endhalfdayinmonth]).') ';
- print ' ';
- }
+ if (!empty($arrayfields['date_end_month']['checked']))
+ {
+ print ''.dol_print_date($date_end_inmonth, 'day');
+ print ' ('.$langs->trans($listhalfday[$endhalfdayinmonth]).') ';
+ print ' ';
+ }
- if (!empty($arrayfields['used_days_month']['checked'])) print ''.num_open_day($date_start_inmonth, $date_end_inmonth, 0, 1, $halfdayinmonth).' ';
- if (!empty($arrayfields['cp.description']['checked'])) print ''.dol_escape_htmltag(dolGetFirstLineOfText($obj->description)).' ';
+ if (!empty($arrayfields['used_days_month']['checked'])) print ''.num_open_day($date_start_inmonth, $date_end_inmonth, 0, 1, $halfdayinmonth).' ';
+ if (!empty($arrayfields['cp.description']['checked'])) print ''.dol_escape_htmltag(dolGetFirstLineOfText($obj->description)).' ';
- print ' ';
- print ' ';
- }
+ print ' ';
+ print '';
+ }
}
print '
';
print '
';
diff --git a/htdocs/holiday/view_log.php b/htdocs/holiday/view_log.php
index 7043f436e87..669bb9aa32f 100644
--- a/htdocs/holiday/view_log.php
+++ b/htdocs/holiday/view_log.php
@@ -36,15 +36,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
require_once DOL_DOCUMENT_ROOT.'/holiday/common.inc.php';
-$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
-$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
-$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ?
-$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation
-$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button
-$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
-$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'myobjectlist'; // To manage different context of search
-$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
-$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
+$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
+$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
+$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ?
+$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation
+$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button
+$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
+$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'myobjectlist'; // To manage different context of search
+$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
+$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
$search_id = GETPOST('search_id', 'alphanohtml');
$search_month = GETPOST('search_month', 'int');
@@ -65,8 +65,8 @@ if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST(
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
-if (! $sortfield) $sortfield="cpl.rowid";
-if (! $sortorder) $sortorder="DESC";
+if (!$sortfield) $sortfield = "cpl.rowid";
+if (!$sortorder) $sortorder = "DESC";
// Si l'utilisateur n'a pas le droit de lire cette page
if (!$user->rights->holiday->read_all) accessforbidden();
@@ -174,13 +174,13 @@ if (!empty($search_year) && $search_year > 0) {
$sqlwhere .= "AND date_action BETWEEN '".$db->idate($from_date)."' AND '".$db->idate($to_date)."'";
}
-if (!empty($search_id) && $search_id > 0) $sqlwhere.= natural_search('rowid', $search_id, 1);
-if (!empty($search_validator) && $search_validator > 0) $sqlwhere.= natural_search('fk_user_action', $search_validator, 1);
-if (!empty($search_employee) && $search_employee > 0) $sqlwhere.= natural_search('fk_user_update', $search_employee, 1);
-if (!empty($search_description)) $sqlwhere.= natural_search('type_action', $search_description);
-if (!empty($search_type) && $search_type > 0) $sqlwhere.= natural_search('fk_type', $search_type, 1);
-if (!empty($search_prev_solde)) $sqlwhere.= natural_search('prev_solde', $search_prev_solde, 1);
-if (!empty($search_new_solde)) $sqlwhere.= natural_search('new_solde', $search_new_solde, 1);
+if (!empty($search_id) && $search_id > 0) $sqlwhere .= natural_search('rowid', $search_id, 1);
+if (!empty($search_validator) && $search_validator > 0) $sqlwhere .= natural_search('fk_user_action', $search_validator, 1);
+if (!empty($search_employee) && $search_employee > 0) $sqlwhere .= natural_search('fk_user_update', $search_employee, 1);
+if (!empty($search_description)) $sqlwhere .= natural_search('type_action', $search_description);
+if (!empty($search_type) && $search_type > 0) $sqlwhere .= natural_search('fk_type', $search_type, 1);
+if (!empty($search_prev_solde)) $sqlwhere .= natural_search('prev_solde', $search_prev_solde, 1);
+if (!empty($search_new_solde)) $sqlwhere .= natural_search('new_solde', $search_new_solde, 1);
$sqlorder = $db->order($sortfield, $sortorder);
@@ -248,8 +248,8 @@ $moreforfilter = '';
$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
$selectedfields = '';
-$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
-$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
+$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
+$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
print '';
print '
';
@@ -358,13 +358,13 @@ while ($i < min($num, $limit))
//TODO: $obj = $db->fetch_object($resql);
$obj = next($object->logs);
- $holidaylogstatic->id = $obj['rowid'];
- $holidaylogstatic->date = $obj['date_action'];
+ $holidaylogstatic->id = $obj['rowid'];
+ $holidaylogstatic->date = $obj['date_action'];
$holidaylogstatic->validator = $obj['fk_user_action'];
$holidaylogstatic->employee = $obj['fk_user_update'];
$holidaylogstatic->description = $obj['type_action'];
- $holidaylogstatic->type = $obj['fk_type'];
- $holidaylogstatic->balance_previous = $obj['prev_solde'];
+ $holidaylogstatic->type = $obj['fk_type'];
+ $holidaylogstatic->balance_previous = $obj['prev_solde'];
$holidaylogstatic->balance_new = $obj['new_solde'];
print '';
diff --git a/htdocs/hrm/admin/admin_establishment.php b/htdocs/hrm/admin/admin_establishment.php
index b169354bef7..a777ada50f9 100644
--- a/htdocs/hrm/admin/admin_establishment.php
+++ b/htdocs/hrm/admin/admin_establishment.php
@@ -131,7 +131,7 @@ if ($result)
dol_print_error($db);
}
-dol_fiche_end();
+print dol_get_fiche_end();
// Buttons
print '';
diff --git a/htdocs/hrm/admin/admin_hrm.php b/htdocs/hrm/admin/admin_hrm.php
index f51bb373f62..4648c2d690a 100644
--- a/htdocs/hrm/admin/admin_hrm.php
+++ b/htdocs/hrm/admin/admin_hrm.php
@@ -104,7 +104,7 @@ foreach ($list as $key) {
print "
\n";
-dol_fiche_end();
+print dol_get_fiche_end();
print '
';
diff --git a/htdocs/hrm/class/establishment.class.php b/htdocs/hrm/class/establishment.class.php
index d2b53337abe..02083ccd819 100644
--- a/htdocs/hrm/class/establishment.class.php
+++ b/htdocs/hrm/class/establishment.class.php
@@ -1,6 +1,6 @@
- * Copyright (C) 2018 Frédéric France
+ * Copyright (C) 2018-2020 Frédéric France
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -75,6 +75,9 @@ class Establishment extends CommonObject
*/
public $rowid;
+ /**
+ * @var string Label
+ */
public $label;
/**
@@ -82,9 +85,21 @@ class Establishment extends CommonObject
*/
public $address;
+ /**
+ * @var string Zip
+ */
public $zip;
+
+ /**
+ * @var string Town
+ */
public $town;
+ /**
+ * @var int country id
+ */
+ public $country_id;
+
/**
* @var int Status 0=open, 1=closed
*/
@@ -95,8 +110,20 @@ class Establishment extends CommonObject
*/
public $entity;
- public $country_id;
+ /**
+ * @var int user mod id
+ */
+ public $fk_user_mod;
+ /**
+ * @var int user author id
+ */
+ public $fk_user_author;
+
+ /**
+ * @var int date create
+ */
+ public $datec;
const STATUS_OPEN = 1;
const STATUS_CLOSED = 0;
@@ -148,6 +175,7 @@ class Establishment extends CommonObject
$now = dol_now();
// Clean parameters
+ $this->label = trim($this->label);
$this->address = trim($this->address);
$this->zip = trim($this->zip);
$this->town = trim($this->town);
@@ -189,10 +217,6 @@ class Establishment extends CommonObject
$this->errors[] = "Error ".$this->db->lasterror();
}
- if (!$error) {
- $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."establishment");
- }
-
// Commit or rollback
if ($error) {
foreach ($this->errors as $errmsg) {
diff --git a/htdocs/hrm/establishment/card.php b/htdocs/hrm/establishment/card.php
index 11dba56a5d7..20d61334579 100644
--- a/htdocs/hrm/establishment/card.php
+++ b/htdocs/hrm/establishment/card.php
@@ -241,7 +241,7 @@ if ($action == 'create')
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
print '';
print ' ';
@@ -324,7 +324,7 @@ if (($id || $ref) && $action == 'edit')
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
print '';
print '
';
@@ -418,7 +418,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
/*
* Barre d'actions
diff --git a/htdocs/hrm/establishment/info.php b/htdocs/hrm/establishment/info.php
index bb4d04d7d00..3185f897958 100644
--- a/htdocs/hrm/establishment/info.php
+++ b/htdocs/hrm/establishment/info.php
@@ -175,7 +175,7 @@ if ($object->id > 0)
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
}
diff --git a/htdocs/imports/class/import.class.php b/htdocs/imports/class/import.class.php
index 3684d4d2d7e..19b71cb8cd3 100644
--- a/htdocs/imports/class/import.class.php
+++ b/htdocs/imports/class/import.class.php
@@ -28,21 +28,21 @@
*/
class Import
{
- public $array_import_module;
- public $array_import_perms;
- public $array_import_icon;
- public $array_import_code;
- public $array_import_label;
- public $array_import_tables;
- public $array_import_tables_creator;
- public $array_import_fields;
- public $array_import_fieldshidden;
- public $array_import_entities;
- public $array_import_regex;
- public $array_import_updatekeys;
- public $array_import_examplevalues;
- public $array_import_convertvalue;
- public $array_import_run_sql_after;
+ public $array_import_module;
+ public $array_import_perms;
+ public $array_import_icon;
+ public $array_import_code;
+ public $array_import_label;
+ public $array_import_tables;
+ public $array_import_tables_creator;
+ public $array_import_fields;
+ public $array_import_fieldshidden;
+ public $array_import_entities;
+ public $array_import_regex;
+ public $array_import_updatekeys;
+ public $array_import_examplevalues;
+ public $array_import_convertvalue;
+ public $array_import_run_sql_after;
/**
* @var string Error code (or message)
@@ -55,40 +55,40 @@ class Import
public $errors = array();
- /**
- * Constructor
- *
- * @param DoliDB $db Database handler
- */
- public function __construct($db)
- {
- $this->db = $db;
- }
+ /**
+ * Constructor
+ *
+ * @param DoliDB $db Database handler
+ */
+ public function __construct($db)
+ {
+ $this->db = $db;
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Load description int this->array_import_module, this->array_import_fields, ... of an importable dataset
*
* @param User $user Object user making import
* @param string $filter Load a particular dataset only. Index will start to 0.
- * @return int <0 if KO, >0 if OK
+ * @return int <0 if KO, >0 if OK
*/
- public function load_arrays($user, $filter = '')
+ public function load_arrays($user, $filter = '')
{
- // phpcs:enable
+ // phpcs:enable
global $langs, $conf;
dol_syslog(get_class($this)."::load_arrays user=".$user->id." filter=".$filter);
- $i = 0;
+ $i = 0;
- require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
- $modulesdir = dolGetModulesDirs();
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+ $modulesdir = dolGetModulesDirs();
- // Load list of modules
- foreach ($modulesdir as $dir)
- {
+ // Load list of modules
+ foreach ($modulesdir as $dir)
+ {
$handle = @opendir(dol_osencode($dir));
if (!is_resource($handle)) continue;
@@ -181,14 +181,14 @@ class Import
}
}
}
- closedir($handle);
+ closedir($handle);
}
return 1;
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Build an import example file.
* Arrays this->array_export_xxx are already loaded for required datatoexport
@@ -199,9 +199,9 @@ class Import
* @param string $datatoimport Dataset to import
* @return string <0 if KO, >0 if OK
*/
- public function build_example_file($model, $headerlinefields, $contentlinevalues, $datatoimport)
+ public function build_example_file($model, $headerlinefields, $contentlinevalues, $datatoimport)
{
- // phpcs:enable
+ // phpcs:enable
global $conf, $langs;
$indice = 0;
@@ -239,7 +239,7 @@ class Import
* @param User $user Object user that save
* @return int <0 if KO, >0 if OK
*/
- public function create($user)
+ public function create($user)
{
global $conf;
@@ -277,7 +277,7 @@ class Import
* @param int $id Id of profil to load
* @return int <0 if KO, >0 if OK
*/
- public function fetch($id)
+ public function fetch($id)
{
$sql = 'SELECT em.rowid, em.field, em.label, em.type';
$sql .= ' FROM '.MAIN_DB_PREFIX.'import_model as em';
@@ -313,7 +313,7 @@ class Import
* @param int $notrigger 0=launch triggers after, 1=disable triggers
* @return int <0 if KO, >0 if OK
*/
- public function delete($user, $notrigger = 0)
+ public function delete($user, $notrigger = 0)
{
global $conf, $langs;
$error = 0;
diff --git a/htdocs/imports/emptyexample.php b/htdocs/imports/emptyexample.php
index 9c5d8c12a0d..7e7cec1707e 100644
--- a/htdocs/imports/emptyexample.php
+++ b/htdocs/imports/emptyexample.php
@@ -21,7 +21,7 @@
* \brief Show example of import file
*/
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
/**
@@ -32,7 +32,7 @@ if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not rol
*/
function llxHeader()
{
- print 'Build an import example file ';
+ print 'Build an import example file ';
}
/**
@@ -43,7 +43,7 @@ function llxHeader()
*/
function llxFooter()
{
- print '';
+ print '';
}
require '../main.inc.php';
diff --git a/htdocs/imports/import.php b/htdocs/imports/import.php
index 0ef716b0c50..e9ee3d0bece 100644
--- a/htdocs/imports/import.php
+++ b/htdocs/imports/import.php
@@ -328,7 +328,7 @@ if ($step == 1 || !$datatoimport)
llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones');
- $head = import_prepare_head($param, 1);
+ $head = import_prepare_head($param, 1);
print dol_get_fiche_head($head, 'step1', $langs->trans("NewImport"), -1);
@@ -358,7 +358,7 @@ if ($step == 1 || !$datatoimport)
print '';
print img_object($objimport->array_import_module[$key]['module']->getName(), $objimport->array_import_icon[$key]).' ';
print $objimport->array_import_label[$key];
- print ' ';
+ print ' ';
if ($objimport->array_import_perms[$key])
{
print ''.img_picto($langs->trans("NewImport"), 'next', 'class="fa-15x"').' ';
@@ -371,9 +371,9 @@ if ($step == 1 || !$datatoimport)
print ' '.$langs->trans("NoImportableData").' ';
}
print '
';
- print '';
+ print '';
- dol_fiche_end();
+ print dol_get_fiche_end();
}
@@ -388,7 +388,7 @@ if ($step == 2 && $datatoimport)
llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones');
- $head = import_prepare_head($param, 2);
+ $head = import_prepare_head($param, 2);
print dol_get_fiche_head($head, 'step2', $langs->trans("NewImport"), -2);
@@ -417,7 +417,7 @@ if ($step == 2 && $datatoimport)
print '';
- dol_fiche_end();
+ print dol_get_fiche_end();
print '';
@@ -440,8 +440,8 @@ if ($step == 2 && $datatoimport)
{
print '';
print ''.img_picto_common($key, $objmodelimport->getPictoForKey($key)).' ';
- $text = $objmodelimport->getDriverDescForKey($key);
- print ''.$form->textwithpicto($objmodelimport->getDriverLabelForKey($key), $text).' ';
+ $text = $objmodelimport->getDriverDescForKey($key);
+ print ''.$form->textwithpicto($objmodelimport->getDriverLabelForKey($key), $text).' ';
print ''.$langs->trans("DownloadEmptyExample").' ';
// Action button
print '';
@@ -470,7 +470,7 @@ if ($step == 3 && $datatoimport)
llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones');
- $head = import_prepare_head($param, 3);
+ $head = import_prepare_head($param, 3);
print dol_get_fiche_head($head, 'step3', $langs->trans("NewImport"), -2);
@@ -517,16 +517,16 @@ if ($step == 3 && $datatoimport)
// Source file format
print ' '.$langs->trans("SourceFileFormat").' ';
print '';
- $text = $objmodelimport->getDriverDescForKey($format);
- print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
- print ' '.$langs->trans("DownloadEmptyExample").' ';
+ $text = $objmodelimport->getDriverDescForKey($format);
+ print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
+ print ''.$langs->trans("DownloadEmptyExample").' ';
print ' ';
print '
';
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
if ($format == 'xlsx' && !class_exists('XMLWriter')) {
@@ -535,7 +535,7 @@ if ($step == 3 && $datatoimport)
}
- print ' ';
+ print ' ';
print '';
print ' ';
@@ -596,11 +596,11 @@ if ($step == 3 && $datatoimport)
}
}
- $langs->load('other');
- $out .= ' ';
- $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
+ $langs->load('other');
+ $out .= ' ';
+ $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
} else {
- $out .= ' ('.$langs->trans("UploadDisabled").')';
+ $out .= ' ('.$langs->trans("UploadDisabled").')';
}
print $out;
print '';
@@ -616,7 +616,7 @@ if ($step == 3 && $datatoimport)
$i = 0;
foreach ($filearray as $key => $val)
{
- $file = $val['name'];
+ $file = $val['name'];
// readdir return value in ISO and we want UTF8 in memory
if (!utf8_check($file)) $file = utf8_encode($file);
@@ -630,9 +630,9 @@ if ($step == 3 && $datatoimport)
print '';
print ''.img_mime($file).' ';
print '';
- print '';
- print $file;
- print ' ';
+ print '';
+ print $file;
+ print ' ';
print ' ';
// Affiche taille fichier
print ''.dol_print_size(dol_filesize($dir.'/'.$file)).' ';
@@ -670,19 +670,19 @@ if ($step == 4 && $datatoimport)
$obj = new $classname($db, $datatoimport);
if ($model == 'csv')
{
- $obj->separator = $separator;
- $obj->enclosure = $enclosure;
+ $obj->separator = $separator;
+ $obj->enclosure = $enclosure;
+ }
+ if ($model == 'xlsx') {
+ if (!preg_match('/\.xlsx$/i', $filetoimport))
+ {
+ $langs->load("errors");
+ $param = '&datatoimport='.$datatoimport.'&format='.$format;
+ setEventMessages($langs->trans("ErrorFileMustHaveFormat", $model), null, 'errors');
+ header("Location: ".$_SERVER["PHP_SELF"].'?step=3'.$param.'&filetoimport='.urlencode($relativepath));
+ exit;
+ }
}
- if ($model == 'xlsx') {
- if (!preg_match('/\.xlsx$/i', $filetoimport))
- {
- $langs->load("errors");
- $param = '&datatoimport='.$datatoimport.'&format='.$format;
- setEventMessages($langs->trans("ErrorFileMustHaveFormat", $model), null, 'errors');
- header("Location: ".$_SERVER["PHP_SELF"].'?step=3'.$param.'&filetoimport='.urlencode($relativepath));
- exit;
- }
- }
if (GETPOST('update')) {
$array_match_file_to_database = array();
@@ -761,7 +761,7 @@ if ($step == 4 && $datatoimport)
llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones');
- $head = import_prepare_head($param, 4);
+ $head = import_prepare_head($param, 4);
print dol_get_fiche_head($head, 'step4', $langs->trans("NewImport"), -2);
@@ -799,12 +799,12 @@ if ($step == 4 && $datatoimport)
// Source file format
print ' '.$langs->trans("SourceFileFormat").' ';
print '';
- $text = $objmodelimport->getDriverDescForKey($format);
- print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
+ $text = $objmodelimport->getDriverDescForKey($format);
+ print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
print ' ';
// Separator and enclosure
- if ($model == 'csv') {
+ if ($model == 'csv') {
print ''.$langs->trans("CsvOptions").' ';
print '';
print '';
@@ -822,50 +822,50 @@ if ($step == 4 && $datatoimport)
print ' ';
print ' ';
print ' ';
- }
+ }
// File to import
print ''.$langs->trans("FileToImport").' ';
print '';
$modulepart = 'import';
$relativepath = GETPOST('filetoimport');
- print '';
- print $filetoimport;
- print ' ';
+ print '';
+ print $filetoimport;
+ print ' ';
print ' ';
print '
';
print '
';
- dol_fiche_end();
+ print dol_get_fiche_end();
print '
'."\n";
- // List of source fields
- print ''."\n";
- print '
';
- print ' ';
- print ' ';
- print ' ';
- print ' ';
- print ' ';
- print ' ';
- print ' ';
- print ' ';
- print ' ';
- print ' ';
+ // List of source fields
+ print ''."\n";
+ print ' ';
+ print ' ';
+ print ' ';
+ print ' ';
+ print ' ';
+ print ' ';
+ print ' ';
+ print ' ';
+ print ' ';
+ print ' ';
+ print ' ';
- print '';
- print ''.$langs->trans("SelectImportFields", img_picto('', 'grip_title', '', false, 0, 0, '', '', 0)).' ';
- $htmlother->select_import_model($importmodelid, 'importmodelid', $datatoimport, 1);
- print ' ';
- print '
';
- print ' ';
+ print '
';
+ print ''.$langs->trans("SelectImportFields", img_picto('', 'grip_title', '', false, 0, 0, '', '', 0)).' ';
+ $htmlother->select_import_model($importmodelid, 'importmodelid', $datatoimport, 1);
+ print ' ';
+ print '
';
+ print '';
// Title of array with fields
- print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
- print '
';
+ print ''; // You can use div-table-responsive-no-min if you dont need reserved height for your table
+ print '
';
print '';
print ''.$langs->trans("FieldsInSourceFile").' ';
print ''.$langs->trans("FieldsInTargetDatabase").' ';
@@ -978,11 +978,11 @@ if ($step == 4 && $datatoimport)
// Example
if (empty($objimport->array_import_convertvalue[0][$code])) // If source file does not need convertion
{
- if ($example) $htmltext .= $langs->trans("SourceExample").': '.$example.' ';
+ if ($example) $htmltext .= $langs->trans("SourceExample").': '.$example.' ';
} else {
- if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromref') $htmltext .= $langs->trans("SourceExample").': '.$langs->transnoentitiesnoconv("ExampleAnyRefFoundIntoElement", $entitylang).($example ? ' ('.$langs->transnoentitiesnoconv("Example").': '.$example.')' : '').' ';
- elseif ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromcodeid') $htmltext .= $langs->trans("SourceExample").': '.$langs->trans("ExampleAnyCodeOrIdFoundIntoDictionary", $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$code]['dict'])).($example ? ' ('.$langs->transnoentitiesnoconv("Example").': '.$example.')' : '').' ';
- elseif ($example) $htmltext .= $langs->trans("SourceExample").': '.$example.' ';
+ if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromref') $htmltext .= $langs->trans("SourceExample").': '.$langs->transnoentitiesnoconv("ExampleAnyRefFoundIntoElement", $entitylang).($example ? ' ('.$langs->transnoentitiesnoconv("Example").': '.$example.')' : '').' ';
+ elseif ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromcodeid') $htmltext .= $langs->trans("SourceExample").': '.$langs->trans("ExampleAnyCodeOrIdFoundIntoDictionary", $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$code]['dict'])).($example ? ' ('.$langs->transnoentitiesnoconv("Example").': '.$example.')' : '').' ';
+ elseif ($example) $htmltext .= $langs->trans("SourceExample").': '.$example.' ';
}
// Format control rule
if (!empty($objimport->array_import_regex[0][$code]))
@@ -1055,13 +1055,13 @@ if ($step == 4 && $datatoimport)
print ' ';
print '
';
- print '
';
+ print '';
if ($conf->use_javascript_ajax)
{
- print ''."\n";
+ print "\n";
+ print 'function updateOrder(){'."\n";
+ print 'var left_list = cleanSerialize(jQuery("#left").sortable("serialize" ));'."\n";
+ //print 'var right_list = cleanSerialize(jQuery("#right").sortable("serialize" ));'."\n";
+ print 'var boxorder = \'A:\' + left_list;'."\n";
+ //print 'var boxorder = \'A:\' + left_list + \'-B:\' + right_list;'."\n";
+ //print 'alert(\'boxorder=\' + boxorder);';
+ //print 'var userid = \''.$user->id.'\';'."\n";
+ //print 'var datatoimport = "'.$datatoimport.'";'."\n";
+ // print 'jQuery.ajax({ url: "ajaximport.php?step=4&boxorder=" + boxorder + "&userid=" + userid + "&datatoimport=" + datatoimport,
+ // async: false
+ // });'."\n";
+ // Now reload page
+ print 'var newlocation= \''.$_SERVER["PHP_SELF"].'?step=4'.$param.'&action=saveorder&boxorder=\' + boxorder;'."\n";
+ //print 'alert(newlocation);';
+ print 'window.location.href=newlocation;'."\n";
+ print '}'."\n";
+ print ''."\n";
}
/*
@@ -1126,12 +1126,12 @@ if ($step == 4 && $datatoimport)
print ' ';
print ' ';
print ' ';
- print ' ';
+ print ' ';
print ' ';
- print ' ';
- print ' ';
- print ' ';
- print ' ';
+ print ' ';
+ print ' ';
+ print ' ';
+ print ' ';
print '';
print '';
@@ -1189,8 +1189,8 @@ if ($step == 5 && $datatoimport)
require_once $dir.$file;
$obj = new $classname($db, $datatoimport);
if ($model == 'csv') {
- $obj->separator = $separator;
- $obj->enclosure = $enclosure;
+ $obj->separator = $separator;
+ $obj->enclosure = $enclosure;
}
// Load source fields in input file
@@ -1221,13 +1221,13 @@ if ($step == 5 && $datatoimport)
llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones');
- $head = import_prepare_head($param, 5);
+ $head = import_prepare_head($param, 5);
- print '';
- print ' ';
- print ' '; // step 5
- print ' '; // step 5
+ print ' ';
+ print ' ';
+ print ' '; // step 5
+ print ' '; // step 5
print dol_get_fiche_head($head, 'step5', $langs->trans("NewImport"), -2);
@@ -1265,17 +1265,17 @@ if ($step == 5 && $datatoimport)
// Source file format
print ''.$langs->trans("SourceFileFormat").' ';
print '';
- $text = $objmodelimport->getDriverDescForKey($format);
- print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
+ $text = $objmodelimport->getDriverDescForKey($format);
+ print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
print ' ';
// Separator and enclosure
if ($model == 'csv') {
- print ''.$langs->trans("CsvOptions").' ';
- print '';
- print $langs->trans("Separator").' : '.dol_escape_htmltag($separator);
- print ' '.$langs->trans("Enclosure").' : '.dol_escape_htmltag($enclosure);
- print ' ';
+ print ''.$langs->trans("CsvOptions").' ';
+ print '';
+ print $langs->trans("Separator").' : '.dol_escape_htmltag($separator);
+ print ' '.$langs->trans("Enclosure").' : '.dol_escape_htmltag($enclosure);
+ print ' ';
}
// File to import
@@ -1283,10 +1283,10 @@ if ($step == 5 && $datatoimport)
print '';
$modulepart = 'import';
$relativepath = GETPOST('filetoimport');
- print '';
- print $filetoimport;
- print ' ';
- print ' ';
+ print '';
+ print $filetoimport;
+ print ' ';
+ print '';
// Total lines in source file
print '';
@@ -1301,22 +1301,22 @@ if ($step == 5 && $datatoimport)
print ' ';
if ($action == 'launchsimu')
{
- print ' ';
- print ' ';
+ print ' ';
+ print ' ';
} else {
- print ' ';
- print $form->textwithpicto("", $langs->trans("SetThisValueTo2ToExcludeFirstLine"));
+ print ' ';
+ print $form->textwithpicto("", $langs->trans("SetThisValueTo2ToExcludeFirstLine"));
}
print ' - ';
if ($action == 'launchsimu')
{
- print ' ';
- print ' ';
+ print ' ';
+ print ' ';
} else {
- print ' ';
- print $form->textwithpicto("", $langs->trans("KeepEmptyToGoToEndOfFile"));
+ print ' ';
+ print $form->textwithpicto("", $langs->trans("KeepEmptyToGoToEndOfFile"));
}
- if ($action == 'launchsimu') print ' '.$langs->trans("Modify").' ';
+ if ($action == 'launchsimu') print ' '.$langs->trans("Modify").' ';
print ' ';
// Keys for data UPDATE (not INSERT of new data)
@@ -1336,7 +1336,7 @@ if ($step == 5 && $datatoimport)
print ' '.$langs->trans("Modify").' ';
} else {
if (is_array($objimport->array_import_updatekeys[0]) && count($objimport->array_import_updatekeys[0]))
- { //TODO dropdown UL is created inside nested SPANS
+ { //TODO dropdown UL is created inside nested SPANS
print $form->multiselectarray('updatekeys', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0, '', 1, '80%');
print $form->textwithpicto("", $langs->trans("SelectPrimaryColumnsForUpdateAttempt"));
} else {
@@ -1421,186 +1421,186 @@ if ($step == 5 && $datatoimport)
print '
';
print '';
- dol_fiche_end();
+ print dol_get_fiche_end();
- if ($action != 'launchsimu')
- {
- // Show import id
- print '';
- print $langs->trans("NowClickToTestTheImport", $langs->transnoentitiesnoconv("RunSimulateImportFile")).' ';
- print ' ';
+ if ($action != 'launchsimu')
+ {
+ // Show import id
+ print '';
+ print $langs->trans("NowClickToTestTheImport", $langs->transnoentitiesnoconv("RunSimulateImportFile")).' ';
+ print ' ';
- // Actions
- print '';
- } else {
- // Launch import
- $arrayoferrors = array();
- $arrayofwarnings = array();
- $maxnboferrors = empty($conf->global->IMPORT_MAX_NB_OF_ERRORS) ? 50 : $conf->global->IMPORT_MAX_NB_OF_ERRORS;
- $maxnbofwarnings = empty($conf->global->IMPORT_MAX_NB_OF_WARNINGS) ? 50 : $conf->global->IMPORT_MAX_NB_OF_WARNINGS;
- $nboferrors = 0;
- $nbofwarnings = 0;
+ // Actions
+ print '';
+ } else {
+ // Launch import
+ $arrayoferrors = array();
+ $arrayofwarnings = array();
+ $maxnboferrors = empty($conf->global->IMPORT_MAX_NB_OF_ERRORS) ? 50 : $conf->global->IMPORT_MAX_NB_OF_ERRORS;
+ $maxnbofwarnings = empty($conf->global->IMPORT_MAX_NB_OF_WARNINGS) ? 50 : $conf->global->IMPORT_MAX_NB_OF_WARNINGS;
+ $nboferrors = 0;
+ $nbofwarnings = 0;
- $importid = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
+ $importid = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
- //var_dump($array_match_file_to_database);
+ //var_dump($array_match_file_to_database);
- $db->begin();
+ $db->begin();
- // Open input file
- $nbok = 0;
- $pathfile = $conf->import->dir_temp.'/'.$filetoimport;
- $result = $obj->import_open_file($pathfile, $langs);
- if ($result > 0)
- {
- global $tablewithentity_cache;
- $tablewithentity_cache = array();
- $sourcelinenb = 0; $endoffile = 0;
+ // Open input file
+ $nbok = 0;
+ $pathfile = $conf->import->dir_temp.'/'.$filetoimport;
+ $result = $obj->import_open_file($pathfile, $langs);
+ if ($result > 0)
+ {
+ global $tablewithentity_cache;
+ $tablewithentity_cache = array();
+ $sourcelinenb = 0; $endoffile = 0;
- // Loop on each input file record
- while (($sourcelinenb < $nboflines) && !$endoffile)
- {
- $sourcelinenb++;
- // Read line and store it into $arrayrecord
- //dol_syslog("line ".$sourcelinenb.' - '.$nboflines.' - '.$excludefirstline.' - '.$endatlinenb);
- $arrayrecord = $obj->import_read_record();
- if ($arrayrecord === false)
- {
+ // Loop on each input file record
+ while (($sourcelinenb < $nboflines) && !$endoffile)
+ {
+ $sourcelinenb++;
+ // Read line and store it into $arrayrecord
+ //dol_syslog("line ".$sourcelinenb.' - '.$nboflines.' - '.$excludefirstline.' - '.$endatlinenb);
+ $arrayrecord = $obj->import_read_record();
+ if ($arrayrecord === false)
+ {
$arrayofwarnings[$sourcelinenb][0] = array('lib'=>'File has '.$nboflines.' lines. However we reach end of file after record '.$sourcelinenb.'. This may occurs when some records are split onto several lines. Ensure the complete string is delimited correctly when there is a separator character in the text string.', 'type'=>'EOF_RECORD_ON_SEVERAL_LINES');
- $endoffile++;
- continue;
- }
- if ($excludefirstline && ($sourcelinenb < $excludefirstline)) continue;
- if ($endatlinenb && ($sourcelinenb > $endatlinenb)) break;
+ $endoffile++;
+ continue;
+ }
+ if ($excludefirstline && ($sourcelinenb < $excludefirstline)) continue;
+ if ($endatlinenb && ($sourcelinenb > $endatlinenb)) break;
- // Run import
- $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
+ // Run import
+ $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
- if (count($obj->errors)) $arrayoferrors[$sourcelinenb] = $obj->errors;
- if (count($obj->warnings)) $arrayofwarnings[$sourcelinenb] = $obj->warnings;
- if (!count($obj->errors) && !count($obj->warnings)) $nbok++;
- }
- // Close file
- $obj->import_close_file();
- } else {
- print $langs->trans("ErrorFailedToOpenFile", $pathfile);
- }
+ if (count($obj->errors)) $arrayoferrors[$sourcelinenb] = $obj->errors;
+ if (count($obj->warnings)) $arrayofwarnings[$sourcelinenb] = $obj->warnings;
+ if (!count($obj->errors) && !count($obj->warnings)) $nbok++;
+ }
+ // Close file
+ $obj->import_close_file();
+ } else {
+ print $langs->trans("ErrorFailedToOpenFile", $pathfile);
+ }
- $error = 0;
+ $error = 0;
- // Run the sql after import if defined
- //var_dump($objimport->array_import_run_sql_after[0]);
- if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0]))
- {
- $i = 0;
- foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport)
- {
- $i++;
- $resqlafterimport = $db->query($sqlafterimport);
- if (!$resqlafterimport)
- {
- $arrayoferrors['none'][] = array('lib'=>$langs->trans("Error running final request: ".$sqlafterimport));
- $error++;
- }
- }
- }
+ // Run the sql after import if defined
+ //var_dump($objimport->array_import_run_sql_after[0]);
+ if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0]))
+ {
+ $i = 0;
+ foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport)
+ {
+ $i++;
+ $resqlafterimport = $db->query($sqlafterimport);
+ if (!$resqlafterimport)
+ {
+ $arrayoferrors['none'][] = array('lib'=>$langs->trans("Error running final request: ".$sqlafterimport));
+ $error++;
+ }
+ }
+ }
- $db->rollback(); // We force rollback because this was just a simulation.
+ $db->rollback(); // We force rollback because this was just a simulation.
- // Show OK
- if (!count($arrayoferrors) && !count($arrayofwarnings)) {
- print ''.img_picto($langs->trans("OK"), 'tick').' '.$langs->trans("NoError").'
';
+ // Show OK
+ if (!count($arrayoferrors) && !count($arrayofwarnings)) {
+ print ''.img_picto($langs->trans("OK"), 'tick').' '.$langs->trans("NoError").'
';
print $langs->trans("NbInsert", $obj->nbinsert).' ';
print $langs->trans("NbUpdate", $obj->nbupdate).' ';
} else print $langs->trans("NbOfLinesOK", $nbok).' ';
- // Show Errors
- //var_dump($arrayoferrors);
- if (count($arrayoferrors))
- {
- print img_error().' '.$langs->trans("ErrorsOnXLines", count($arrayoferrors)).' ';
- print '';
- foreach ($arrayoferrors as $key => $val)
- {
- $nboferrors++;
- if ($nboferrors > $maxnboferrors)
- {
- print $langs->trans("TooMuchErrors", (count($arrayoferrors) - $nboferrors))." ";
- break;
- }
- print '* '.$langs->trans("Line").' '.$key.' ';
- foreach ($val as $i => $err)
- {
- print ' > '.$err['lib'].' ';
- }
- }
- print '
';
- print ' ';
- }
+ // Show Errors
+ //var_dump($arrayoferrors);
+ if (count($arrayoferrors))
+ {
+ print img_error().' '.$langs->trans("ErrorsOnXLines", count($arrayoferrors)).' ';
+ print '';
+ foreach ($arrayoferrors as $key => $val)
+ {
+ $nboferrors++;
+ if ($nboferrors > $maxnboferrors)
+ {
+ print $langs->trans("TooMuchErrors", (count($arrayoferrors) - $nboferrors))." ";
+ break;
+ }
+ print '* '.$langs->trans("Line").' '.$key.' ';
+ foreach ($val as $i => $err)
+ {
+ print ' > '.$err['lib'].' ';
+ }
+ }
+ print '
';
+ print ' ';
+ }
- // Show Warnings
- //var_dump($arrayoferrors);
- if (count($arrayofwarnings))
- {
- print img_warning().' '.$langs->trans("WarningsOnXLines", count($arrayofwarnings)).' ';
- print '';
- foreach ($arrayofwarnings as $key => $val)
- {
- $nbofwarnings++;
- if ($nbofwarnings > $maxnbofwarnings)
- {
- print $langs->trans("TooMuchWarnings", (count($arrayofwarnings) - $nbofwarnings))." ";
- break;
- }
- print ' * '.$langs->trans("Line").' '.$key.' ';
- foreach ($val as $i => $err)
- {
- print ' > '.$err['lib'].' ';
- }
- }
- print '
';
- print ' ';
- }
+ // Show Warnings
+ //var_dump($arrayoferrors);
+ if (count($arrayofwarnings))
+ {
+ print img_warning().' '.$langs->trans("WarningsOnXLines", count($arrayofwarnings)).' ';
+ print '';
+ foreach ($arrayofwarnings as $key => $val)
+ {
+ $nbofwarnings++;
+ if ($nbofwarnings > $maxnbofwarnings)
+ {
+ print $langs->trans("TooMuchWarnings", (count($arrayofwarnings) - $nbofwarnings))." ";
+ break;
+ }
+ print ' * '.$langs->trans("Line").' '.$key.' ';
+ foreach ($val as $i => $err)
+ {
+ print ' > '.$err['lib'].' ';
+ }
+ }
+ print '
';
+ print ' ';
+ }
- // Show import id
- $importid = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
+ // Show import id
+ $importid = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
- print '';
- print ''.$langs->trans("NowClickToRunTheImport", $langs->transnoentitiesnoconv("RunImportFile")).' ';
- if (empty($nboferrors)) print $langs->trans("DataLoadedWithId", $importid).' ';
- print '
';
+ print '';
+ print ''.$langs->trans("NowClickToRunTheImport", $langs->transnoentitiesnoconv("RunImportFile")).' ';
+ if (empty($nboferrors)) print $langs->trans("DataLoadedWithId", $importid).' ';
+ print '
';
- print ' ';
+ print ' ';
- // Actions
- print '';
+ }
- print '';
+ print '';
}
@@ -1619,8 +1619,8 @@ if ($step == 6 && $datatoimport)
require_once $dir.$file;
$obj = new $classname($db, $datatoimport);
if ($model == 'csv') {
- $obj->separator = $separator;
- $obj->enclosure = $enclosure;
+ $obj->separator = $separator;
+ $obj->enclosure = $enclosure;
}
// Load source fields in input file
@@ -1650,7 +1650,7 @@ if ($step == 6 && $datatoimport)
llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones');
- $head = import_prepare_head($param, 6);
+ $head = import_prepare_head($param, 6);
print dol_get_fiche_head($head, 'step6', $langs->trans("NewImport"), -1);
@@ -1688,29 +1688,29 @@ if ($step == 6 && $datatoimport)
// Source file format
print ''.$langs->trans("SourceFileFormat").' ';
print '';
- $text = $objmodelimport->getDriverDescForKey($format);
- print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
+ $text = $objmodelimport->getDriverDescForKey($format);
+ print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
print ' ';
// Separator and enclosure
if ($model == 'csv') {
- print ''.$langs->trans("CsvOptions").' ';
- print '';
- print $langs->trans("Separator").' : ';
- print htmlentities($separator);
- print ' '.$langs->trans("Enclosure").' : ';
- print htmlentities($enclosure);
- print ' ';
+ print ''.$langs->trans("CsvOptions").' ';
+ print '';
+ print $langs->trans("Separator").' : ';
+ print htmlentities($separator);
+ print ' '.$langs->trans("Enclosure").' : ';
+ print htmlentities($enclosure);
+ print ' ';
}
// File to import
print ''.$langs->trans("FileToImport").' ';
print '';
$modulepart = 'import';
- $relativepath = GETPOST('filetoimport');
- print '';
- print $filetoimport;
- print ' ';
+ $relativepath = GETPOST('filetoimport');
+ print '';
+ print $filetoimport;
+ print ' ';
print ' ';
// Nb of fields
@@ -1731,7 +1731,7 @@ if ($step == 6 && $datatoimport)
print '';
print $langs->trans("EndAtLineNb");
print ' ';
- print ' ';
+ print ' ';
print ' ';
print '
';
@@ -1824,8 +1824,8 @@ if ($step == 6 && $datatoimport)
$result = $obj->import_open_file($pathfile, $langs);
if ($result > 0)
{
- global $tablewithentity_cache;
- $tablewithentity_cache = array();
+ global $tablewithentity_cache;
+ $tablewithentity_cache = array();
$sourcelinenb = 0; $endoffile = 0;
while ($sourcelinenb < $nboflines && !$endoffile)
@@ -1856,30 +1856,30 @@ if ($step == 6 && $datatoimport)
if (count($arrayoferrors) > 0) $db->rollback(); // We force rollback because this was errors.
else {
- $error = 0;
+ $error = 0;
// Run the sql after import if defined
- //var_dump($objimport->array_import_run_sql_after[0]);
- if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0]))
- {
- $i = 0;
- foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport)
- {
- $i++;
- $resqlafterimport = $db->query($sqlafterimport);
- if (!$resqlafterimport)
- {
- $arrayoferrors['none'][] = array('lib'=>$langs->trans("Error running final request: ".$sqlafterimport));
- $error++;
- }
- }
- }
+ //var_dump($objimport->array_import_run_sql_after[0]);
+ if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0]))
+ {
+ $i = 0;
+ foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport)
+ {
+ $i++;
+ $resqlafterimport = $db->query($sqlafterimport);
+ if (!$resqlafterimport)
+ {
+ $arrayoferrors['none'][] = array('lib'=>$langs->trans("Error running final request: ".$sqlafterimport));
+ $error++;
+ }
+ }
+ }
- if (!$error) $db->commit(); // We can commit if no errors.
- else $db->rollback();
+ if (!$error) $db->commit(); // We can commit if no errors.
+ else $db->rollback();
}
- dol_fiche_end();
+ print dol_get_fiche_end();
// Show result
@@ -1918,17 +1918,17 @@ function show_elem($fieldssource, $pos, $key, $var, $nostyle = '')
$height = '24px';
- if ($key == 'none') {
- //stop multiple duplicate ids with no number
- print "\n\n\n";
- print '
'."\n";
- print '
'."\n";
- } else {
- print "\n\n\n";
- print ''."\n";
+ if ($key == 'none') {
+ //stop multiple duplicate ids with no number
+ print "\n\n\n";
+ print '
'."\n";
+ print '
'."\n";
+ } else {
+ print "\n\n\n";
+ print ''."\n";
- print '
'."\n";
- }
+ print ''."\n";
+ }
if ($pos && $pos > count($fieldssource)) // No fields
{
@@ -1962,8 +1962,8 @@ function show_elem($fieldssource, $pos, $key, $var, $nostyle = '')
$example = $fieldssource[$pos]['example1'];
if ($example)
{
- if (!utf8_check($example)) $example = utf8_encode($example);
- print ' ('.$example.' )';
+ if (!utf8_check($example)) $example = utf8_encode($example);
+ print ' ('.$example.' )';
}
print '';
print '';
diff --git a/htdocs/imports/index.php b/htdocs/imports/index.php
index bc68b53cfd0..4c556325b05 100644
--- a/htdocs/imports/index.php
+++ b/htdocs/imports/index.php
@@ -51,7 +51,7 @@ print ' ';
print '';
if (count($import->array_import_code))
{
- print dolGetButtonTitle($langs->trans('NewImport'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/imports/import.php?leftmenu=import');
+ print dolGetButtonTitle($langs->trans('NewImport'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/imports/import.php?leftmenu=import');
}
print '
';
print ' ';
diff --git a/htdocs/includes/odtphp/zip/pclzip/LICENSE b/htdocs/includes/odtphp/zip/pclzip/LICENSE
new file mode 100644
index 00000000000..dbbe3558157
--- /dev/null
+++ b/htdocs/includes/odtphp/zip/pclzip/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published
+ by the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+ .
diff --git a/htdocs/includes/odtphp/zip/pclzip/composer.json b/htdocs/includes/odtphp/zip/pclzip/composer.json
new file mode 100644
index 00000000000..fd36bfbfed3
--- /dev/null
+++ b/htdocs/includes/odtphp/zip/pclzip/composer.json
@@ -0,0 +1,20 @@
+{
+ "name": "chamilo/pclzip",
+ "type": "library",
+ "description": "A PHP library that offers compression and extraction functions for Zip formatted archives",
+ "keywords": ["php", "zip"],
+ "homepage": "https://github.com/chamilo/pclzip",
+ "license": ["LGPL-2.1"],
+ "authors": [
+ {
+ "name": "Vincent Blavet"
+ }
+ ],
+ "replace": {
+ "pclzip/pclzip": "^2.8"
+ },
+ "autoload": {
+ "classmap": ["pclzip.lib.php"]
+ }
+}
+
diff --git a/htdocs/includes/odtphp/zip/pclzip/gnu-lgpl.txt b/htdocs/includes/odtphp/zip/pclzip/gnu-lgpl.txt
index 82fc70b870e..583509c7efb 100644
--- a/htdocs/includes/odtphp/zip/pclzip/gnu-lgpl.txt
+++ b/htdocs/includes/odtphp/zip/pclzip/gnu-lgpl.txt
@@ -1,8 +1,8 @@
- GNU LESSER GENERAL PUBLIC LICENSE
- Version 2.1, February 1999
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
@@ -10,7 +10,7 @@
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
- Preamble
+ Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
@@ -55,7 +55,7 @@ modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
-
+
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
@@ -111,8 +111,8 @@ modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
-
- GNU LESSER GENERAL PUBLIC LICENSE
+
+ GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
@@ -146,7 +146,7 @@ such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
-
+
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
@@ -158,7 +158,7 @@ Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
-
+
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
@@ -216,7 +216,7 @@ instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
-
+
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
@@ -267,7 +267,7 @@ Library will still fall under Section 6.)
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
-
+
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
@@ -329,7 +329,7 @@ restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
-
+
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
@@ -370,7 +370,7 @@ subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
-
+
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
@@ -422,7 +422,7 @@ conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
-
+
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
@@ -432,7 +432,7 @@ decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
- NO WARRANTY
+ NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
@@ -455,8 +455,8 @@ FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
- END OF TERMS AND CONDITIONS
-
+ END OF TERMS AND CONDITIONS
+
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
@@ -484,7 +484,8 @@ convey the exclusion of warranty; and each file should have at least the
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
- License along with this library; If not, see .
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
diff --git a/htdocs/includes/odtphp/zip/pclzip/pclzip.lib.php b/htdocs/includes/odtphp/zip/pclzip/pclzip.lib.php
index 8cc5ca828bf..2a1a2b8d798 100644
--- a/htdocs/includes/odtphp/zip/pclzip/pclzip.lib.php
+++ b/htdocs/includes/odtphp/zip/pclzip/pclzip.lib.php
@@ -1,9 +1,10 @@
zipname = $p_zipname;
- $this->zip_fd = 0;
- $this->magic_quotes_status = -1;
-
- // ----- Return
- return;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function :
- // create($p_filelist, $p_add_dir="", $p_remove_dir="")
- // create($p_filelist, $p_option, $p_option_value, ...)
- // Description :
- // This method supports two different synopsis. The first one is historical.
- // This method creates a Zip Archive. The Zip file is created in the
- // filesystem. The files and directories indicated in $p_filelist
- // are added in the archive. See the parameters description for the
- // supported format of $p_filelist.
- // When a directory is in the list, the directory and its content is added
- // in the archive.
- // In this synopsis, the function takes an optional variable list of
- // options. See bellow the supported options.
- // Parameters :
- // $p_filelist : An array containing file or directory names, or
- // a string containing one filename or one directory name, or
- // a string containing a list of filenames and/or directory
- // names separated by spaces.
- // $p_add_dir : A path to add before the real path of the archived file,
- // in order to have it memorized in the archive.
- // $p_remove_dir : A path to remove from the real path of the file to archive,
- // in order to have a shorter path memorized in the archive.
- // When $p_add_dir and $p_remove_dir are set, $p_remove_dir
- // is removed first, before $p_add_dir is added.
- // Options :
- // PCLZIP_OPT_ADD_PATH :
- // PCLZIP_OPT_REMOVE_PATH :
- // PCLZIP_OPT_REMOVE_ALL_PATH :
- // PCLZIP_OPT_COMMENT :
- // PCLZIP_CB_PRE_ADD :
- // PCLZIP_CB_POST_ADD :
- // Return Values :
- // 0 on failure,
- // The list of the added files, with a status of the add action.
- // (see PclZip::listContent() for list entry format)
- // --------------------------------------------------------------------------------
- function create($p_filelist)
- {
- $v_result=1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Set default values
- $v_options = array();
- $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE;
-
- // ----- Look for variable options arguments
- $v_size = func_num_args();
-
- // ----- Look for arguments
- if ($v_size > 1) {
- // ----- Get the arguments
- $v_arg_list = func_get_args();
-
- // ----- Remove from the options list the first argument
- array_shift($v_arg_list);
- $v_size--;
-
- // ----- Look for first arg
- if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
-
- // ----- Parse the options
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
- array (PCLZIP_OPT_REMOVE_PATH => 'optional',
- PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
- PCLZIP_OPT_ADD_PATH => 'optional',
- PCLZIP_CB_PRE_ADD => 'optional',
- PCLZIP_CB_POST_ADD => 'optional',
- PCLZIP_OPT_NO_COMPRESSION => 'optional',
- PCLZIP_OPT_COMMENT => 'optional',
- PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
- PCLZIP_OPT_TEMP_FILE_ON => 'optional',
- PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
- //, PCLZIP_OPT_CRYPT => 'optional'
- ));
- if ($v_result != 1) {
- return 0;
- }
- }
-
- // ----- Look for 2 args
- // Here we need to support the first historic synopsis of the
- // method.
- else {
-
- // ----- Get the first argument
- $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0];
-
- // ----- Look for the optional second argument
- if ($v_size == 2) {
- $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
- }
- else if ($v_size > 2) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
- "Invalid number / type of arguments");
- return 0;
- }
- }
- }
-
- // ----- Look for default option values
- $this->privOptionDefaultThreshold($v_options);
-
- // ----- Init
- $v_string_list = array();
- $v_att_list = array();
- $v_filedescr_list = array();
- $p_result_list = array();
-
- // ----- Look if the $p_filelist is really an array
- if (is_array($p_filelist)) {
-
- // ----- Look if the first element is also an array
- // This will mean that this is a file description entry
- if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
- $v_att_list = $p_filelist;
- }
-
- // ----- The list is a list of string names
- else {
- $v_string_list = $p_filelist;
- }
- }
-
- // ----- Look if the $p_filelist is a string
- else if (is_string($p_filelist)) {
- // ----- Create a list from the string
- $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
- }
-
- // ----- Invalid variable type for $p_filelist
- else {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist");
- return 0;
- }
-
- // ----- Reformat the string list
- if (sizeof($v_string_list) != 0) {
- foreach ($v_string_list as $v_string) {
- if ($v_string != '') {
- $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
- }
- else {
- }
- }
- }
-
- // ----- For each file in the list check the attributes
- $v_supported_attributes
- = array ( PCLZIP_ATT_FILE_NAME => 'mandatory'
- ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional'
- ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional'
- ,PCLZIP_ATT_FILE_MTIME => 'optional'
- ,PCLZIP_ATT_FILE_CONTENT => 'optional'
- ,PCLZIP_ATT_FILE_COMMENT => 'optional'
- );
- foreach ($v_att_list as $v_entry) {
- $v_result = $this->privFileDescrParseAtt($v_entry,
- $v_filedescr_list[],
- $v_options,
- $v_supported_attributes);
- if ($v_result != 1) {
- return 0;
- }
- }
-
- // ----- Expand the filelist (expand directories)
- $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
- if ($v_result != 1) {
- return 0;
- }
-
- // ----- Call the create fct
- $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options);
- if ($v_result != 1) {
- return 0;
- }
-
- // ----- Return
- return $p_result_list;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function :
- // add($p_filelist, $p_add_dir="", $p_remove_dir="")
- // add($p_filelist, $p_option, $p_option_value, ...)
- // Description :
- // This method supports two synopsis. The first one is historical.
- // This methods add the list of files in an existing archive.
- // If a file with the same name already exists, it is added at the end of the
- // archive, the first one is still present.
- // If the archive does not exist, it is created.
- // Parameters :
- // $p_filelist : An array containing file or directory names, or
- // a string containing one filename or one directory name, or
- // a string containing a list of filenames and/or directory
- // names separated by spaces.
- // $p_add_dir : A path to add before the real path of the archived file,
- // in order to have it memorized in the archive.
- // $p_remove_dir : A path to remove from the real path of the file to archive,
- // in order to have a shorter path memorized in the archive.
- // When $p_add_dir and $p_remove_dir are set, $p_remove_dir
- // is removed first, before $p_add_dir is added.
- // Options :
- // PCLZIP_OPT_ADD_PATH :
- // PCLZIP_OPT_REMOVE_PATH :
- // PCLZIP_OPT_REMOVE_ALL_PATH :
- // PCLZIP_OPT_COMMENT :
- // PCLZIP_OPT_ADD_COMMENT :
- // PCLZIP_OPT_PREPEND_COMMENT :
- // PCLZIP_CB_PRE_ADD :
- // PCLZIP_CB_POST_ADD :
- // Return Values :
- // 0 on failure,
- // The list of the added files, with a status of the add action.
- // (see PclZip::listContent() for list entry format)
- // --------------------------------------------------------------------------------
- function add($p_filelist)
- {
- $v_result=1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Set default values
- $v_options = array();
- $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE;
-
- // ----- Look for variable options arguments
- $v_size = func_num_args();
-
- // ----- Look for arguments
- if ($v_size > 1) {
- // ----- Get the arguments
- $v_arg_list = func_get_args();
-
- // ----- Remove form the options list the first argument
- array_shift($v_arg_list);
- $v_size--;
-
- // ----- Look for first arg
- if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
-
- // ----- Parse the options
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
- array (PCLZIP_OPT_REMOVE_PATH => 'optional',
- PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
- PCLZIP_OPT_ADD_PATH => 'optional',
- PCLZIP_CB_PRE_ADD => 'optional',
- PCLZIP_CB_POST_ADD => 'optional',
- PCLZIP_OPT_NO_COMPRESSION => 'optional',
- PCLZIP_OPT_COMMENT => 'optional',
- PCLZIP_OPT_ADD_COMMENT => 'optional',
- PCLZIP_OPT_PREPEND_COMMENT => 'optional',
- PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
- PCLZIP_OPT_TEMP_FILE_ON => 'optional',
- PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
- //, PCLZIP_OPT_CRYPT => 'optional'
- ));
- if ($v_result != 1) {
- return 0;
- }
- }
-
- // ----- Look for 2 args
- // Here we need to support the first historic synopsis of the
- // method.
- else {
-
- // ----- Get the first argument
- $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0];
-
- // ----- Look for the optional second argument
- if ($v_size == 2) {
- $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
- }
- else if ($v_size > 2) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
-
- // ----- Return
- return 0;
- }
- }
- }
-
- // ----- Look for default option values
- $this->privOptionDefaultThreshold($v_options);
-
- // ----- Init
- $v_string_list = array();
- $v_att_list = array();
- $v_filedescr_list = array();
- $p_result_list = array();
-
- // ----- Look if the $p_filelist is really an array
- if (is_array($p_filelist)) {
-
- // ----- Look if the first element is also an array
- // This will mean that this is a file description entry
- if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
- $v_att_list = $p_filelist;
- }
-
- // ----- The list is a list of string names
- else {
- $v_string_list = $p_filelist;
- }
- }
-
- // ----- Look if the $p_filelist is a string
- else if (is_string($p_filelist)) {
- // ----- Create a list from the string
- $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
- }
-
- // ----- Invalid variable type for $p_filelist
- else {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist");
- return 0;
- }
-
- // ----- Reformat the string list
- if (sizeof($v_string_list) != 0) {
- foreach ($v_string_list as $v_string) {
- $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
- }
- }
-
- // ----- For each file in the list check the attributes
- $v_supported_attributes
- = array ( PCLZIP_ATT_FILE_NAME => 'mandatory'
- ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional'
- ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional'
- ,PCLZIP_ATT_FILE_MTIME => 'optional'
- ,PCLZIP_ATT_FILE_CONTENT => 'optional'
- ,PCLZIP_ATT_FILE_COMMENT => 'optional'
- );
- foreach ($v_att_list as $v_entry) {
- $v_result = $this->privFileDescrParseAtt($v_entry,
- $v_filedescr_list[],
- $v_options,
- $v_supported_attributes);
- if ($v_result != 1) {
- return 0;
- }
- }
-
- // ----- Expand the filelist (expand directories)
- $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
- if ($v_result != 1) {
- return 0;
- }
-
- // ----- Call the create fct
- $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options);
- if ($v_result != 1) {
- return 0;
- }
-
- // ----- Return
- return $p_result_list;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : listContent()
- // Description :
- // This public method, gives the list of the files and directories, with their
- // properties.
- // The properties of each entries in the list are (used also in other functions) :
- // filename : Name of the file. For a create or add action it is the filename
- // given by the user. For an extract function it is the filename
- // of the extracted file.
- // stored_filename : Name of the file / directory stored in the archive.
- // size : Size of the stored file.
- // compressed_size : Size of the file's data compressed in the archive
- // (without the headers overhead)
- // mtime : Last known modification date of the file (UNIX timestamp)
- // comment : Comment associated with the file
- // folder : true | false
- // index : index of the file in the archive
- // status : status of the action (depending of the action) :
- // Values are :
- // ok : OK !
- // filtered : the file / dir is not extracted (filtered by user)
- // already_a_directory : the file can not be extracted because a
- // directory with the same name already exists
- // write_protected : the file can not be extracted because a file
- // with the same name already exists and is
- // write protected
- // newer_exist : the file was not extracted because a newer file exists
- // path_creation_fail : the file is not extracted because the folder
- // does not exist and can not be created
- // write_error : the file was not extracted because there was a
- // error while writing the file
- // read_error : the file was not extracted because there was a error
- // while reading the file
- // invalid_header : the file was not extracted because of an archive
- // format error (bad file header)
- // Note that each time a method can continue operating when there
- // is an action error on a file, the error is only logged in the file status.
- // Return Values :
- // 0 on an unrecoverable failure,
- // The list of the files in the archive.
- // --------------------------------------------------------------------------------
- function listContent()
- {
- $v_result=1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Check archive
- if (!$this->privCheckFormat()) {
- return(0);
- }
-
- // ----- Call the extracting fct
- $p_list = array();
- if (($v_result = $this->privList($p_list)) != 1)
- {
- unset($p_list);
- return(0);
- }
-
- // ----- Return
- return $p_list;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function :
- // extract($p_path="./", $p_remove_path="")
- // extract([$p_option, $p_option_value, ...])
- // Description :
- // This method supports two synopsis. The first one is historical.
- // This method extract all the files / directories from the archive to the
- // folder indicated in $p_path.
- // If you want to ignore the 'root' part of path of the memorized files
- // you can indicate this in the optional $p_remove_path parameter.
- // By default, if a newer file with the same name already exists, the
- // file is not extracted.
- //
- // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions
- // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append
- // at the end of the path value of PCLZIP_OPT_PATH.
- // Parameters :
- // $p_path : Path where the files and directories are to be extracted
- // $p_remove_path : First part ('root' part) of the memorized path
- // (if any similar) to remove while extracting.
- // Options :
- // PCLZIP_OPT_PATH :
- // PCLZIP_OPT_ADD_PATH :
- // PCLZIP_OPT_REMOVE_PATH :
- // PCLZIP_OPT_REMOVE_ALL_PATH :
- // PCLZIP_CB_PRE_EXTRACT :
- // PCLZIP_CB_POST_EXTRACT :
- // Return Values :
- // 0 or a negative value on failure,
- // The list of the extracted files, with a status of the action.
- // (see PclZip::listContent() for list entry format)
- // --------------------------------------------------------------------------------
- function extract()
- {
- $v_result=1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Check archive
- if (!$this->privCheckFormat()) {
- return(0);
- }
-
- // ----- Set default values
- $v_options = array();
-// $v_path = "./";
- $v_path = '';
- $v_remove_path = "";
- $v_remove_all_path = false;
-
- // ----- Look for variable options arguments
- $v_size = func_num_args();
-
- // ----- Default values for option
- $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
-
- // ----- Look for arguments
- if ($v_size > 0) {
- // ----- Get the arguments
- $v_arg_list = func_get_args();
-
- // ----- Look for first arg
- if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
-
- // ----- Parse the options
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
- array (PCLZIP_OPT_PATH => 'optional',
- PCLZIP_OPT_REMOVE_PATH => 'optional',
- PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
- PCLZIP_OPT_ADD_PATH => 'optional',
- PCLZIP_CB_PRE_EXTRACT => 'optional',
- PCLZIP_CB_POST_EXTRACT => 'optional',
- PCLZIP_OPT_SET_CHMOD => 'optional',
- PCLZIP_OPT_BY_NAME => 'optional',
- PCLZIP_OPT_BY_EREG => 'optional',
- PCLZIP_OPT_BY_PREG => 'optional',
- PCLZIP_OPT_BY_INDEX => 'optional',
- PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
- PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional',
- PCLZIP_OPT_REPLACE_NEWER => 'optional'
- ,PCLZIP_OPT_STOP_ON_ERROR => 'optional'
- ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
- PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
- PCLZIP_OPT_TEMP_FILE_ON => 'optional',
- PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
- ));
- if ($v_result != 1) {
- return 0;
+ // ----- Tests the zlib
+ if (!function_exists('gzopen')) {
+ die('Abort ' . basename(__FILE__) . ' : Missing zlib extensions');
}
- // ----- Set the arguments
- if (isset($v_options[PCLZIP_OPT_PATH])) {
- $v_path = $v_options[PCLZIP_OPT_PATH];
- }
- if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
- $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
- }
- if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
- $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
- }
- if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
- // ----- Check for '/' in last path char
- if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
- $v_path .= '/';
- }
- $v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
- }
- }
-
- // ----- Look for 2 args
- // Here we need to support the first historic synopsis of the
- // method.
- else {
-
- // ----- Get the first argument
- $v_path = $v_arg_list[0];
-
- // ----- Look for the optional second argument
- if ($v_size == 2) {
- $v_remove_path = $v_arg_list[1];
- }
- else if ($v_size > 2) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
-
- // ----- Return
- return 0;
- }
- }
- }
-
- // ----- Look for default option values
- $this->privOptionDefaultThreshold($v_options);
-
- // ----- Trace
-
- // ----- Call the extracting fct
- $p_list = array();
- $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path,
- $v_remove_all_path, $v_options);
- if ($v_result < 1) {
- unset($p_list);
- return(0);
- }
-
- // ----- Return
- return $p_list;
- }
- // --------------------------------------------------------------------------------
-
-
- // --------------------------------------------------------------------------------
- // Function :
- // extractByIndex($p_index, $p_path="./", $p_remove_path="")
- // extractByIndex($p_index, [$p_option, $p_option_value, ...])
- // Description :
- // This method supports two synopsis. The first one is historical.
- // This method is doing a partial extract of the archive.
- // The extracted files or folders are identified by their index in the
- // archive (from 0 to n).
- // Note that if the index identify a folder, only the folder entry is
- // extracted, not all the files included in the archive.
- // Parameters :
- // $p_index : A single index (integer) or a string of indexes of files to
- // extract. The form of the string is "0,4-6,8-12" with only numbers
- // and '-' for range or ',' to separate ranges. No spaces or ';'
- // are allowed.
- // $p_path : Path where the files and directories are to be extracted
- // $p_remove_path : First part ('root' part) of the memorized path
- // (if any similar) to remove while extracting.
- // Options :
- // PCLZIP_OPT_PATH :
- // PCLZIP_OPT_ADD_PATH :
- // PCLZIP_OPT_REMOVE_PATH :
- // PCLZIP_OPT_REMOVE_ALL_PATH :
- // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and
- // not as files.
- // The resulting content is in a new field 'content' in the file
- // structure.
- // This option must be used alone (any other options are ignored).
- // PCLZIP_CB_PRE_EXTRACT :
- // PCLZIP_CB_POST_EXTRACT :
- // Return Values :
- // 0 on failure,
- // The list of the extracted files, with a status of the action.
- // (see PclZip::listContent() for list entry format)
- // --------------------------------------------------------------------------------
- //function extractByIndex($p_index, options...)
- function extractByIndex($p_index)
- {
- $v_result=1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Check archive
- if (!$this->privCheckFormat()) {
- return(0);
- }
-
- // ----- Set default values
- $v_options = array();
-// $v_path = "./";
- $v_path = '';
- $v_remove_path = "";
- $v_remove_all_path = false;
-
- // ----- Look for variable options arguments
- $v_size = func_num_args();
-
- // ----- Default values for option
- $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
-
- // ----- Look for arguments
- if ($v_size > 1) {
- // ----- Get the arguments
- $v_arg_list = func_get_args();
-
- // ----- Remove form the options list the first argument
- array_shift($v_arg_list);
- $v_size--;
-
- // ----- Look for first arg
- if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
-
- // ----- Parse the options
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
- array (PCLZIP_OPT_PATH => 'optional',
- PCLZIP_OPT_REMOVE_PATH => 'optional',
- PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
- PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
- PCLZIP_OPT_ADD_PATH => 'optional',
- PCLZIP_CB_PRE_EXTRACT => 'optional',
- PCLZIP_CB_POST_EXTRACT => 'optional',
- PCLZIP_OPT_SET_CHMOD => 'optional',
- PCLZIP_OPT_REPLACE_NEWER => 'optional'
- ,PCLZIP_OPT_STOP_ON_ERROR => 'optional'
- ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
- PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
- PCLZIP_OPT_TEMP_FILE_ON => 'optional',
- PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
- ));
- if ($v_result != 1) {
- return 0;
- }
-
- // ----- Set the arguments
- if (isset($v_options[PCLZIP_OPT_PATH])) {
- $v_path = $v_options[PCLZIP_OPT_PATH];
- }
- if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
- $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
- }
- if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
- $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
- }
- if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
- // ----- Check for '/' in last path char
- if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
- $v_path .= '/';
- }
- $v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
- }
- if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) {
- $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
- }
- else {
- }
- }
-
- // ----- Look for 2 args
- // Here we need to support the first historic synopsis of the
- // method.
- else {
-
- // ----- Get the first argument
- $v_path = $v_arg_list[0];
-
- // ----- Look for the optional second argument
- if ($v_size == 2) {
- $v_remove_path = $v_arg_list[1];
- }
- else if ($v_size > 2) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
-
- // ----- Return
- return 0;
- }
- }
- }
-
- // ----- Trace
-
- // ----- Trick
- // Here I want to reuse extractByRule(), so I need to parse the $p_index
- // with privParseOptions()
- $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index);
- $v_options_trick = array();
- $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick,
- array (PCLZIP_OPT_BY_INDEX => 'optional' ));
- if ($v_result != 1) {
- return 0;
- }
- $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX];
-
- // ----- Look for default option values
- $this->privOptionDefaultThreshold($v_options);
-
- // ----- Call the extracting fct
- if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) {
- return(0);
- }
-
- // ----- Return
- return $p_list;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function :
- // delete([$p_option, $p_option_value, ...])
- // Description :
- // This method removes files from the archive.
- // If no parameters are given, then all the archive is emptied.
- // Parameters :
- // None or optional arguments.
- // Options :
- // PCLZIP_OPT_BY_INDEX :
- // PCLZIP_OPT_BY_NAME :
- // PCLZIP_OPT_BY_EREG :
- // PCLZIP_OPT_BY_PREG :
- // Return Values :
- // 0 on failure,
- // The list of the files which are still present in the archive.
- // (see PclZip::listContent() for list entry format)
- // --------------------------------------------------------------------------------
- function delete()
- {
- $v_result=1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Check archive
- if (!$this->privCheckFormat()) {
- return(0);
- }
-
- // ----- Set default values
- $v_options = array();
-
- // ----- Look for variable options arguments
- $v_size = func_num_args();
-
- // ----- Look for arguments
- if ($v_size > 0) {
- // ----- Get the arguments
- $v_arg_list = func_get_args();
-
- // ----- Parse the options
- $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
- array (PCLZIP_OPT_BY_NAME => 'optional',
- PCLZIP_OPT_BY_EREG => 'optional',
- PCLZIP_OPT_BY_PREG => 'optional',
- PCLZIP_OPT_BY_INDEX => 'optional' ));
- if ($v_result != 1) {
- return 0;
- }
- }
-
- // ----- Magic quotes trick
- $this->privDisableMagicQuotes();
-
- // ----- Call the delete fct
- $v_list = array();
- if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) {
- $this->privSwapBackMagicQuotes();
- unset($v_list);
- return(0);
- }
-
- // ----- Magic quotes trick
- $this->privSwapBackMagicQuotes();
-
- // ----- Return
- return $v_list;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : deleteByIndex()
- // Description :
- // ***** Deprecated *****
- // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered.
- // --------------------------------------------------------------------------------
- function deleteByIndex($p_index)
- {
-
- $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index);
-
- // ----- Return
- return $p_list;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : properties()
- // Description :
- // This method gives the properties of the archive.
- // The properties are :
- // nb : Number of files in the archive
- // comment : Comment associated with the archive file
- // status : not_exist, ok
- // Parameters :
- // None
- // Return Values :
- // 0 on failure,
- // An array with the archive properties.
- // --------------------------------------------------------------------------------
- function properties()
- {
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Magic quotes trick
- $this->privDisableMagicQuotes();
-
- // ----- Check archive
- if (!$this->privCheckFormat()) {
- $this->privSwapBackMagicQuotes();
- return(0);
- }
-
- // ----- Default properties
- $v_prop = array();
- $v_prop['comment'] = '';
- $v_prop['nb'] = 0;
- $v_prop['status'] = 'not_exist';
-
- // ----- Look if file exists
- if (@is_file($this->zipname))
- {
- // ----- Open the zip file
- if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
- {
- $this->privSwapBackMagicQuotes();
-
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
+ // ----- Set the attributes
+ $this->zipname = $p_zipname;
+ $this->zip_fd = 0;
+ $this->magic_quotes_status = -1;
// ----- Return
- return 0;
- }
-
- // ----- Read the central directory informations
- $v_central_dir = array();
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
- {
- $this->privSwapBackMagicQuotes();
- return 0;
- }
-
- // ----- Close the zip file
- $this->privCloseFd();
-
- // ----- Set the user attributes
- $v_prop['comment'] = $v_central_dir['comment'];
- $v_prop['nb'] = $v_central_dir['entries'];
- $v_prop['status'] = 'ok';
+ return;
}
+ // --------------------------------------------------------------------------------
- // ----- Magic quotes trick
- $this->privSwapBackMagicQuotes();
-
- // ----- Return
- return $v_prop;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : duplicate()
- // Description :
- // This method creates an archive by copying the content of an other one. If
- // the archive already exist, it is replaced by the new one without any warning.
- // Parameters :
- // $p_archive : The filename of a valid archive, or
- // a valid PclZip object.
- // Return Values :
- // 1 on success.
- // 0 or a negative value on error (error code).
- // --------------------------------------------------------------------------------
- function duplicate($p_archive)
- {
- $v_result = 1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Look if the $p_archive is a PclZip object
- if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip'))
+ // --------------------------------------------------------------------------------
+ // Function :
+ // create($p_filelist, $p_add_dir="", $p_remove_dir="")
+ // create($p_filelist, $p_option, $p_option_value, ...)
+ // Description :
+ // This method supports two different synopsis. The first one is historical.
+ // This method creates a Zip Archive. The Zip file is created in the
+ // filesystem. The files and directories indicated in $p_filelist
+ // are added in the archive. See the parameters description for the
+ // supported format of $p_filelist.
+ // When a directory is in the list, the directory and its content is added
+ // in the archive.
+ // In this synopsis, the function takes an optional variable list of
+ // options. See bellow the supported options.
+ // Parameters :
+ // $p_filelist : An array containing file or directory names, or
+ // a string containing one filename or one directory name, or
+ // a string containing a list of filenames and/or directory
+ // names separated by spaces.
+ // $p_add_dir : A path to add before the real path of the archived file,
+ // in order to have it memorized in the archive.
+ // $p_remove_dir : A path to remove from the real path of the file to archive,
+ // in order to have a shorter path memorized in the archive.
+ // When $p_add_dir and $p_remove_dir are set, $p_remove_dir
+ // is removed first, before $p_add_dir is added.
+ // Options :
+ // PCLZIP_OPT_ADD_PATH :
+ // PCLZIP_OPT_REMOVE_PATH :
+ // PCLZIP_OPT_REMOVE_ALL_PATH :
+ // PCLZIP_OPT_COMMENT :
+ // PCLZIP_CB_PRE_ADD :
+ // PCLZIP_CB_POST_ADD :
+ // Return Values :
+ // 0 on failure,
+ // The list of the added files, with a status of the add action.
+ // (see PclZip::listContent() for list entry format)
+ // --------------------------------------------------------------------------------
+ public function create($p_filelist)
{
-
- // ----- Duplicate the archive
- $v_result = $this->privDuplicate($p_archive->zipname);
- }
-
- // ----- Look if the $p_archive is a string (so a filename)
- else if (is_string($p_archive))
- {
-
- // ----- Check that $p_archive is a valid zip file
- // TBC : Should also check the archive format
- if (!is_file($p_archive)) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'");
- $v_result = PCLZIP_ERR_MISSING_FILE;
- }
- else {
- // ----- Duplicate the archive
- $v_result = $this->privDuplicate($p_archive);
- }
- }
-
- // ----- Invalid variable
- else
- {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
- $v_result = PCLZIP_ERR_INVALID_PARAMETER;
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : merge()
- // Description :
- // This method merge the $p_archive_to_add archive at the end of the current
- // one ($this).
- // If the archive ($this) does not exist, the merge becomes a duplicate.
- // If the $p_archive_to_add archive does not exist, the merge is a success.
- // Parameters :
- // $p_archive_to_add : It can be directly the filename of a valid zip archive,
- // or a PclZip object archive.
- // Return Values :
- // 1 on success,
- // 0 or negative values on error (see below).
- // --------------------------------------------------------------------------------
- function merge($p_archive_to_add)
- {
- $v_result = 1;
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Check archive
- if (!$this->privCheckFormat()) {
- return(0);
- }
-
- // ----- Look if the $p_archive_to_add is a PclZip object
- if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip'))
- {
-
- // ----- Merge the archive
- $v_result = $this->privMerge($p_archive_to_add);
- }
-
- // ----- Look if the $p_archive_to_add is a string (so a filename)
- else if (is_string($p_archive_to_add))
- {
-
- // ----- Create a temporary archive
- $v_object_archive = new PclZip($p_archive_to_add);
-
- // ----- Merge the archive
- $v_result = $this->privMerge($v_object_archive);
- }
-
- // ----- Invalid variable
- else
- {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
- $v_result = PCLZIP_ERR_INVALID_PARAMETER;
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
-
-
- // --------------------------------------------------------------------------------
- // Function : errorCode()
- // Description :
- // Parameters :
- // --------------------------------------------------------------------------------
- function errorCode()
- {
- if (PCLZIP_ERROR_EXTERNAL == 1) {
- return(PclErrorCode());
- }
- else {
- return($this->error_code);
- }
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : errorName()
- // Description :
- // Parameters :
- // --------------------------------------------------------------------------------
- function errorName($p_with_code=false)
- {
- $v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR',
- PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL',
- PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL',
- PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER',
- PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE',
- PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG',
- PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP',
- PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE',
- PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL',
- PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION',
- PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT',
- PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL',
- PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL',
- PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM',
- PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP',
- PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE',
- PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE',
- PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION',
- PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION'
- ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE'
- ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION'
- );
-
- if (isset($v_name[$this->error_code])) {
- $v_value = $v_name[$this->error_code];
- }
- else {
- $v_value = 'NoName';
- }
-
- if ($p_with_code) {
- return($v_value.' ('.$this->error_code.')');
- }
- else {
- return($v_value);
- }
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : errorInfo()
- // Description :
- // Parameters :
- // --------------------------------------------------------------------------------
- function errorInfo($p_full=false)
- {
- if (PCLZIP_ERROR_EXTERNAL == 1) {
- return(PclErrorString());
- }
- else {
- if ($p_full) {
- return($this->errorName(true)." : ".$this->error_string);
- }
- else {
- return($this->error_string." [code ".$this->error_code."]");
- }
- }
- }
- // --------------------------------------------------------------------------------
-
-
-// --------------------------------------------------------------------------------
-// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
-// ***** *****
-// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY *****
-// --------------------------------------------------------------------------------
-
-
-
- // --------------------------------------------------------------------------------
- // Function : privCheckFormat()
- // Description :
- // This method check that the archive exists and is a valid zip archive.
- // Several level of check exists. (futur)
- // Parameters :
- // $p_level : Level of check. Default 0.
- // 0 : Check the first bytes (magic codes) (default value))
- // 1 : 0 + Check the central directory (futur)
- // 2 : 1 + Check each file header (futur)
- // Return Values :
- // true on success,
- // false on error, the error code is set.
- // --------------------------------------------------------------------------------
- function privCheckFormat($p_level=0)
- {
- $v_result = true;
-
- // ----- Reset the file system cache
- clearstatcache();
-
- // ----- Reset the error handler
- $this->privErrorReset();
-
- // ----- Look if the file exits
- if (!is_file($this->zipname)) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'");
- return(false);
- }
-
- // ----- Check that the file is readeable
- if (!is_readable($this->zipname)) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'");
- return(false);
- }
-
- // ----- Check the magic code
- // TBC
-
- // ----- Check the central header
- // TBC
-
- // ----- Check each file header
- // TBC
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privParseOptions()
- // Description :
- // This internal methods reads the variable list of arguments ($p_options_list,
- // $p_size) and generate an array with the options and values ($v_result_list).
- // $v_requested_options contains the options that can be present and those that
- // must be present.
- // $v_requested_options is an array, with the option value as key, and 'optional',
- // or 'mandatory' as value.
- // Parameters :
- // See above.
- // Return Values :
- // 1 on success.
- // 0 on failure.
- // --------------------------------------------------------------------------------
- function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false)
- {
- $v_result=1;
-
- // ----- Read the options
- $i=0;
- while ($i<$p_size) {
-
- // ----- Check if the option is supported
- if (!isset($v_requested_options[$p_options_list[$i]])) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Look for next option
- switch ($p_options_list[$i]) {
- // ----- Look for options that request a path value
- case PCLZIP_OPT_PATH :
- case PCLZIP_OPT_REMOVE_PATH :
- case PCLZIP_OPT_ADD_PATH :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE);
- $i++;
- break;
-
- case PCLZIP_OPT_TEMP_FILE_THRESHOLD :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
- return PclZip::errorCode();
- }
-
- // ----- Check for incompatible options
- if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'");
- return PclZip::errorCode();
- }
-
- // ----- Check the value
- $v_value = $p_options_list[$i+1];
- if ((!is_integer($v_value)) || ($v_value<0)) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'");
- return PclZip::errorCode();
- }
-
- // ----- Get the value (and convert it in bytes)
- $v_result_list[$p_options_list[$i]] = $v_value*1048576;
- $i++;
- break;
-
- case PCLZIP_OPT_TEMP_FILE_ON :
- // ----- Check for incompatible options
- if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'");
- return PclZip::errorCode();
- }
-
- $v_result_list[$p_options_list[$i]] = true;
- break;
-
- case PCLZIP_OPT_TEMP_FILE_OFF :
- // ----- Check for incompatible options
- if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'");
- return PclZip::errorCode();
- }
- // ----- Check for incompatible options
- if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'");
- return PclZip::errorCode();
- }
-
- $v_result_list[$p_options_list[$i]] = true;
- break;
-
- case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- if ( is_string($p_options_list[$i+1])
- && ($p_options_list[$i+1] != '')) {
- $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE);
- $i++;
- }
- else {
- }
- break;
-
- // ----- Look for options that request an array of string for value
- case PCLZIP_OPT_BY_NAME :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- if (is_string($p_options_list[$i+1])) {
- $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1];
- }
- else if (is_array($p_options_list[$i+1])) {
- $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
- }
- else {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
- $i++;
- break;
-
- // ----- Look for options that request an EREG or PREG expression
- case PCLZIP_OPT_BY_EREG :
- // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG
- // to PCLZIP_OPT_BY_PREG
- $p_options_list[$i] = PCLZIP_OPT_BY_PREG;
- case PCLZIP_OPT_BY_PREG :
- //case PCLZIP_OPT_CRYPT :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- if (is_string($p_options_list[$i+1])) {
- $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
- }
- else {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
- $i++;
- break;
-
- // ----- Look for options that takes a string
- case PCLZIP_OPT_COMMENT :
- case PCLZIP_OPT_ADD_COMMENT :
- case PCLZIP_OPT_PREPEND_COMMENT :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE,
- "Missing parameter value for option '"
- .PclZipUtilOptionText($p_options_list[$i])
- ."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- if (is_string($p_options_list[$i+1])) {
- $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
- }
- else {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE,
- "Wrong parameter value for option '"
- .PclZipUtilOptionText($p_options_list[$i])
- ."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
- $i++;
- break;
-
- // ----- Look for options that request an array of index
- case PCLZIP_OPT_BY_INDEX :
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- $v_work_list = array();
- if (is_string($p_options_list[$i+1])) {
-
- // ----- Remove spaces
- $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', '');
-
- // ----- Parse items
- $v_work_list = explode(",", $p_options_list[$i+1]);
- }
- else if (is_integer($p_options_list[$i+1])) {
- $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1];
- }
- else if (is_array($p_options_list[$i+1])) {
- $v_work_list = $p_options_list[$i+1];
- }
- else {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Reduce the index list
- // each index item in the list must be a couple with a start and
- // an end value : [0,3], [5-5], [8-10], ...
- // ----- Check the format of each item
- $v_sort_flag=false;
- $v_sort_value=0;
- for ($j=0; $j= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
- $i++;
- break;
-
- // ----- Look for options that request a call-back
- case PCLZIP_CB_PRE_EXTRACT :
- case PCLZIP_CB_POST_EXTRACT :
- case PCLZIP_CB_PRE_ADD :
- case PCLZIP_CB_POST_ADD :
- /* for futur use
- case PCLZIP_CB_PRE_DELETE :
- case PCLZIP_CB_POST_DELETE :
- case PCLZIP_CB_PRE_LIST :
- case PCLZIP_CB_POST_LIST :
- */
- // ----- Check the number of parameters
- if (($i+1) >= $p_size) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Get the value
- $v_function_name = $p_options_list[$i+1];
-
- // ----- Check that the value is a valid existing function
- if (!function_exists($v_function_name)) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Set the attribute
- $v_result_list[$p_options_list[$i]] = $v_function_name;
- $i++;
- break;
-
- default :
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
- "Unknown parameter '"
- .$p_options_list[$i]."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Next options
- $i++;
- }
-
- // ----- Look for mandatory options
- if ($v_requested_options !== false) {
- for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) {
- // ----- Look for mandatory option
- if ($v_requested_options[$key] == 'mandatory') {
- // ----- Look if present
- if (!isset($v_result_list[$key])) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")");
-
- // ----- Return
- return PclZip::errorCode();
- }
- }
- }
- }
-
- // ----- Look for default values
- if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
-
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privOptionDefaultThreshold()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privOptionDefaultThreshold(&$p_options)
- {
- $v_result=1;
-
- if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD])
- || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) {
- return $v_result;
- }
-
- // ----- Get 'memory_limit' configuration value
- $v_memory_limit = ini_get('memory_limit');
- $v_memory_limit = trim($v_memory_limit);
- $last = strtolower(substr($v_memory_limit, -1));
-
- if($last == 'g')
- //$v_memory_limit = $v_memory_limit*1024*1024*1024;
- $v_memory_limit = $v_memory_limit*1073741824;
- if($last == 'm')
- //$v_memory_limit = $v_memory_limit*1024*1024;
- $v_memory_limit = $v_memory_limit*1048576;
- if($last == 'k')
- $v_memory_limit = $v_memory_limit*1024;
-
- $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO);
-
-
- // ----- Sanity check : No threshold if value lower than 1M
- if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) {
- unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]);
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privFileDescrParseAtt()
- // Description :
- // Parameters :
- // Return Values :
- // 1 on success.
- // 0 on failure.
- // --------------------------------------------------------------------------------
- function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false)
- {
- $v_result=1;
-
- // ----- For each file in the list check the attributes
- foreach ($p_file_list as $v_key => $v_value) {
-
- // ----- Check if the option is supported
- if (!isset($v_requested_options[$v_key])) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Look for attribute
- switch ($v_key) {
- case PCLZIP_ATT_FILE_NAME :
- if (!is_string($v_value)) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
- return PclZip::errorCode();
- }
-
- $p_filedescr['filename'] = PclZipUtilPathReduction($v_value);
-
- if ($p_filedescr['filename'] == '') {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'");
- return PclZip::errorCode();
- }
-
- break;
-
- case PCLZIP_ATT_FILE_NEW_SHORT_NAME :
- if (!is_string($v_value)) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
- return PclZip::errorCode();
- }
-
- $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value);
-
- if ($p_filedescr['new_short_name'] == '') {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'");
- return PclZip::errorCode();
- }
- break;
-
- case PCLZIP_ATT_FILE_NEW_FULL_NAME :
- if (!is_string($v_value)) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
- return PclZip::errorCode();
- }
-
- $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value);
-
- if ($p_filedescr['new_full_name'] == '') {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'");
- return PclZip::errorCode();
- }
- break;
-
- // ----- Look for options that takes a string
- case PCLZIP_ATT_FILE_COMMENT :
- if (!is_string($v_value)) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
- return PclZip::errorCode();
- }
-
- $p_filedescr['comment'] = $v_value;
- break;
-
- case PCLZIP_ATT_FILE_MTIME :
- if (!is_integer($v_value)) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'");
- return PclZip::errorCode();
- }
-
- $p_filedescr['mtime'] = $v_value;
- break;
-
- case PCLZIP_ATT_FILE_CONTENT :
- $p_filedescr['content'] = $v_value;
- break;
-
- default :
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
- "Unknown parameter '".$v_key."'");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Look for mandatory options
- if ($v_requested_options !== false) {
- for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) {
- // ----- Look for mandatory option
- if ($v_requested_options[$key] == 'mandatory') {
- // ----- Look if present
- if (!isset($p_file_list[$key])) {
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")");
- return PclZip::errorCode();
- }
- }
- }
- }
-
- // end foreach
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privFileDescrExpand()
- // Description :
- // This method look for each item of the list to see if its a file, a folder
- // or a string to be added as file. For any other type of files (link, other)
- // just ignore the item.
- // Then prepare the information that will be stored for that file.
- // When its a folder, expand the folder with all the files that are in that
- // folder (recursively).
- // Parameters :
- // Return Values :
- // 1 on success.
- // 0 on failure.
- // --------------------------------------------------------------------------------
- function privFileDescrExpand(&$p_filedescr_list, &$p_options)
- {
- $v_result=1;
-
- // ----- Create a result list
- $v_result_list = array();
-
- // ----- Look each entry
- for ($i=0; $iprivCalculateStoredFilename($v_descr, $p_options);
-
- // ----- Add the descriptor in result list
- $v_result_list[sizeof($v_result_list)] = $v_descr;
-
- // ----- Look for folder
- if ($v_descr['type'] == 'folder') {
- // ----- List of items in folder
- $v_dirlist_descr = array();
- $v_dirlist_nb = 0;
- if ($v_folder_handler = @opendir($v_descr['filename'])) {
- while (($v_item_handler = @readdir($v_folder_handler)) !== false) {
-
- // ----- Skip '.' and '..'
- if (($v_item_handler == '.') || ($v_item_handler == '..')) {
- continue;
- }
-
- // ----- Compose the full filename
- $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler;
-
- // ----- Look for different stored filename
- // Because the name of the folder was changed, the name of the
- // files/sub-folders also change
- if (($v_descr['stored_filename'] != $v_descr['filename'])
- && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) {
- if ($v_descr['stored_filename'] != '') {
- $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler;
- }
- else {
- $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler;
- }
- }
-
- $v_dirlist_nb++;
- }
-
- @closedir($v_folder_handler);
- }
- else {
- // TBC : unable to open folder in read mode
- }
-
- // ----- Expand each element of the list
- if ($v_dirlist_nb != 0) {
- // ----- Expand
- if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) {
- return $v_result;
- }
-
- // ----- Concat the resulting list
- $v_result_list = array_merge($v_result_list, $v_dirlist_descr);
- }
- else {
- }
-
- // ----- Free local array
- unset($v_dirlist_descr);
- }
- }
-
- // ----- Get the result list
- $p_filedescr_list = $v_result_list;
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privCreate()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privCreate($p_filedescr_list, &$p_result_list, &$p_options)
- {
- $v_result=1;
- $v_list_detail = array();
-
- // ----- Magic quotes trick
- $this->privDisableMagicQuotes();
-
- // ----- Open the file in write mode
- if (($v_result = $this->privOpenFd('wb')) != 1)
- {
- // ----- Return
- return $v_result;
- }
-
- // ----- Add the list of files
- $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options);
-
- // ----- Close
- $this->privCloseFd();
-
- // ----- Magic quotes trick
- $this->privSwapBackMagicQuotes();
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privAdd()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privAdd($p_filedescr_list, &$p_result_list, &$p_options)
- {
- $v_result=1;
- $v_list_detail = array();
-
- // ----- Look if the archive exists or is empty
- if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0))
- {
-
- // ----- Do a create
- $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options);
-
- // ----- Return
- return $v_result;
- }
- // ----- Magic quotes trick
- $this->privDisableMagicQuotes();
-
- // ----- Open the zip file
- if (($v_result=$this->privOpenFd('rb')) != 1)
- {
- // ----- Magic quotes trick
- $this->privSwapBackMagicQuotes();
-
- // ----- Return
- return $v_result;
- }
-
- // ----- Read the central directory informations
- $v_central_dir = array();
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
- {
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
- return $v_result;
- }
-
- // ----- Go to beginning of File
- @rewind($this->zip_fd);
-
- // ----- Creates a temporay file
- $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
-
- // ----- Open the temporary file in write mode
- if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0)
- {
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
-
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Copy the files from the archive to the temporary file
- // TBC : Here I should better append the file and go back to erase the central dir
- $v_size = $v_central_dir['offset'];
- while ($v_size != 0)
- {
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = fread($this->zip_fd, $v_read_size);
- @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
- $v_size -= $v_read_size;
- }
-
- // ----- Swap the file descriptor
- // Here is a trick : I swap the temporary fd with the zip fd, in order to use
- // the following methods on the temporary fil and not the real archive
- $v_swap = $this->zip_fd;
- $this->zip_fd = $v_zip_temp_fd;
- $v_zip_temp_fd = $v_swap;
-
- // ----- Add the files
- $v_header_list = array();
- if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1)
- {
- fclose($v_zip_temp_fd);
- $this->privCloseFd();
- @unlink($v_zip_temp_name);
- $this->privSwapBackMagicQuotes();
-
- // ----- Return
- return $v_result;
- }
-
- // ----- Store the offset of the central dir
- $v_offset = @ftell($this->zip_fd);
-
- // ----- Copy the block of file headers from the old archive
- $v_size = $v_central_dir['size'];
- while ($v_size != 0)
- {
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = @fread($v_zip_temp_fd, $v_read_size);
- @fwrite($this->zip_fd, $v_buffer, $v_read_size);
- $v_size -= $v_read_size;
- }
-
- // ----- Create the Central Dir files header
- for ($i=0, $v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) {
- fclose($v_zip_temp_fd);
- $this->privCloseFd();
- @unlink($v_zip_temp_name);
- $this->privSwapBackMagicQuotes();
-
- // ----- Return
- return $v_result;
- }
- $v_count++;
- }
-
- // ----- Transform the header to a 'usable' info
- $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
- }
-
- // ----- Zip file comment
- $v_comment = $v_central_dir['comment'];
- if (isset($p_options[PCLZIP_OPT_COMMENT])) {
- $v_comment = $p_options[PCLZIP_OPT_COMMENT];
- }
- if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) {
- $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT];
- }
- if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) {
- $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment;
- }
-
- // ----- Calculate the size of the central header
- $v_size = @ftell($this->zip_fd)-$v_offset;
-
- // ----- Create the central dir footer
- if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1)
- {
- // ----- Reset the file list
- unset($v_header_list);
- $this->privSwapBackMagicQuotes();
-
- // ----- Return
- return $v_result;
- }
-
- // ----- Swap back the file descriptor
- $v_swap = $this->zip_fd;
- $this->zip_fd = $v_zip_temp_fd;
- $v_zip_temp_fd = $v_swap;
-
- // ----- Close
- $this->privCloseFd();
-
- // ----- Close the temporary file
- @fclose($v_zip_temp_fd);
-
- // ----- Magic quotes trick
- $this->privSwapBackMagicQuotes();
-
- // ----- Delete the zip file
- // TBC : I should test the result ...
- @unlink($this->zipname);
-
- // ----- Rename the temporary file
- // TBC : I should test the result ...
- //@rename($v_zip_temp_name, $this->zipname);
- PclZipUtilRename($v_zip_temp_name, $this->zipname);
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privOpenFd()
- // Description :
- // Parameters :
- // --------------------------------------------------------------------------------
- function privOpenFd($p_mode)
- {
- $v_result=1;
-
- // ----- Look if already open
- if ($this->zip_fd != 0)
- {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Open the zip file
- if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0)
- {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privCloseFd()
- // Description :
- // Parameters :
- // --------------------------------------------------------------------------------
- function privCloseFd()
- {
- $v_result=1;
-
- if ($this->zip_fd != 0)
- @fclose($this->zip_fd);
- $this->zip_fd = 0;
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privAddList()
- // Description :
- // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is
- // different from the real path of the file. This is usefull if you want to have PclTar
- // running in any directory, and memorize relative path from an other directory.
- // Parameters :
- // $p_list : An array containing the file or directory names to add in the tar
- // $p_result_list : list of added files with their properties (specially the status field)
- // $p_add_dir : Path to add in the filename path archived
- // $p_remove_dir : Path to remove in the filename path archived
- // Return Values :
- // --------------------------------------------------------------------------------
-// function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options)
- function privAddList($p_filedescr_list, &$p_result_list, &$p_options)
- {
- $v_result=1;
-
- // ----- Add the files
- $v_header_list = array();
- if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1)
- {
- // ----- Return
- return $v_result;
- }
-
- // ----- Store the offset of the central dir
- $v_offset = @ftell($this->zip_fd);
-
- // ----- Create the Central Dir files header
- for ($i=0,$v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) {
- // ----- Return
- return $v_result;
- }
- $v_count++;
- }
-
- // ----- Transform the header to a 'usable' info
- $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
- }
-
- // ----- Zip file comment
- $v_comment = '';
- if (isset($p_options[PCLZIP_OPT_COMMENT])) {
- $v_comment = $p_options[PCLZIP_OPT_COMMENT];
- }
-
- // ----- Calculate the size of the central header
- $v_size = @ftell($this->zip_fd)-$v_offset;
-
- // ----- Create the central dir footer
- if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1)
- {
- // ----- Reset the file list
- unset($v_header_list);
-
- // ----- Return
- return $v_result;
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privAddFileList()
- // Description :
- // Parameters :
- // $p_filedescr_list : An array containing the file description
- // or directory names to add in the zip
- // $p_result_list : list of added files with their properties (specially the status field)
- // Return Values :
- // --------------------------------------------------------------------------------
- function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options)
- {
- $v_result=1;
- $v_header = array();
-
- // ----- Recuperate the current number of elt in list
- $v_nb = sizeof($p_result_list);
-
- // ----- Loop on the files
- for ($j=0; ($jprivAddFile($p_filedescr_list[$j], $v_header,
- $p_options);
- if ($v_result != 1) {
- return $v_result;
- }
-
- // ----- Store the file infos
- $p_result_list[$v_nb++] = $v_header;
- }
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privAddFile()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privAddFile($p_filedescr, &$p_header, &$p_options)
- {
- $v_result=1;
-
- // ----- Working variable
- $p_filename = $p_filedescr['filename'];
-
- // TBC : Already done in the fileAtt check ... ?
- if ($p_filename == "") {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)");
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Look for a stored different filename
- /* TBC : Removed
- if (isset($p_filedescr['stored_filename'])) {
- $v_stored_filename = $p_filedescr['stored_filename'];
- }
- else {
- $v_stored_filename = $p_filedescr['stored_filename'];
- }
- */
-
- // ----- Set the file properties
- clearstatcache();
- $p_header['version'] = 20;
- $p_header['version_extracted'] = 10;
- $p_header['flag'] = 0;
- $p_header['compression'] = 0;
- $p_header['crc'] = 0;
- $p_header['compressed_size'] = 0;
- $p_header['filename_len'] = strlen($p_filename);
- $p_header['extra_len'] = 0;
- $p_header['disk'] = 0;
- $p_header['internal'] = 0;
- $p_header['offset'] = 0;
- $p_header['filename'] = $p_filename;
-// TBC : Removed $p_header['stored_filename'] = $v_stored_filename;
- $p_header['stored_filename'] = $p_filedescr['stored_filename'];
- $p_header['extra'] = '';
- $p_header['status'] = 'ok';
- $p_header['index'] = -1;
-
- // ----- Look for regular file
- if ($p_filedescr['type']=='file') {
- $p_header['external'] = 0x00000000;
- $p_header['size'] = filesize($p_filename);
- }
-
- // ----- Look for regular folder
- else if ($p_filedescr['type']=='folder') {
- $p_header['external'] = 0x00000010;
- $p_header['mtime'] = filemtime($p_filename);
- $p_header['size'] = filesize($p_filename);
- }
-
- // ----- Look for virtual file
- else if ($p_filedescr['type'] == 'virtual_file') {
- $p_header['external'] = 0x00000000;
- $p_header['size'] = strlen($p_filedescr['content']);
- }
-
-
- // ----- Look for filetime
- if (isset($p_filedescr['mtime'])) {
- $p_header['mtime'] = $p_filedescr['mtime'];
- }
- else if ($p_filedescr['type'] == 'virtual_file') {
- $p_header['mtime'] = time();
- }
- else {
- $p_header['mtime'] = filemtime($p_filename);
- }
-
- // ------ Look for file comment
- if (isset($p_filedescr['comment'])) {
- $p_header['comment_len'] = strlen($p_filedescr['comment']);
- $p_header['comment'] = $p_filedescr['comment'];
- }
- else {
- $p_header['comment_len'] = 0;
- $p_header['comment'] = '';
- }
-
- // ----- Look for pre-add callback
- if (isset($p_options[PCLZIP_CB_PRE_ADD])) {
-
- // ----- Generate a local information
- $v_local_header = array();
- $this->privConvertHeader2FileInfo($p_header, $v_local_header);
-
- // ----- Call the callback
- // Here I do not use call_user_func() because I need to send a reference to the
- // header.
-// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);');
- $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header);
- if ($v_result == 0) {
- // ----- Change the file status
- $p_header['status'] = "skipped";
$v_result = 1;
- }
- // ----- Update the informations
- // Only some fields can be modified
- if ($p_header['stored_filename'] != $v_local_header['stored_filename']) {
- $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']);
- }
- }
+ // ----- Reset the error handler
+ $this->privErrorReset();
- // ----- Look for empty stored filename
- if ($p_header['stored_filename'] == "") {
- $p_header['status'] = "filtered";
- }
-
- // ----- Check the path length
- if (strlen($p_header['stored_filename']) > 0xFF) {
- $p_header['status'] = 'filename_too_long';
- }
+ // ----- Set default values
+ $v_options = array();
+ $v_options[PCLZIP_OPT_NO_COMPRESSION] = false;
- // ----- Look if no error, or file not skipped
- if ($p_header['status'] == 'ok') {
+ // ----- Look for variable options arguments
+ $v_size = func_num_args();
- // ----- Look for a file
- if ($p_filedescr['type'] == 'file') {
- // ----- Look for using temporary file to zip
- if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF]))
- && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON])
- || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD])
- && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])) ) ) {
- $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options);
- if ($v_result < PCLZIP_ERR_NO_ERROR) {
- return $v_result;
- }
- }
-
- // ----- Use "in memory" zip algo
- else {
+ // ----- Look for arguments
+ if ($v_size > 1) {
+ // ----- Get the arguments
+ $v_arg_list = func_get_args();
- // ----- Open the source file
- if (($v_file = @fopen($p_filename, "rb")) == 0) {
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
- return PclZip::errorCode();
+ // ----- Remove from the options list the first argument
+ array_shift($v_arg_list);
+ $v_size--;
+
+ // ----- Look for first arg
+ if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
+
+ // ----- Parse the options
+ $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array(
+ PCLZIP_OPT_REMOVE_PATH => 'optional',
+ PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
+ PCLZIP_OPT_ADD_PATH => 'optional',
+ PCLZIP_CB_PRE_ADD => 'optional',
+ PCLZIP_CB_POST_ADD => 'optional',
+ PCLZIP_OPT_NO_COMPRESSION => 'optional',
+ PCLZIP_OPT_COMMENT => 'optional',
+ PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
+ PCLZIP_OPT_TEMP_FILE_ON => 'optional',
+ PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
+ //, PCLZIP_OPT_CRYPT => 'optional'
+ ));
+ if ($v_result != 1) {
+ return 0;
+ }
+
+ // ----- Look for 2 args
+ // Here we need to support the first historic synopsis of the
+ // method.
+ } else {
+
+ // ----- Get the first argument
+ $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0];
+
+ // ----- Look for the optional second argument
+ if ($v_size == 2) {
+ $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
+ } elseif ($v_size > 2) {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
+
+ return 0;
+ }
+ }
}
- // ----- Read the file content
- $v_content = @fread($v_file, $p_header['size']);
+ // ----- Look for default option values
+ $this->privOptionDefaultThreshold($v_options);
- // ----- Close the file
- @fclose($v_file);
+ // ----- Init
+ $v_string_list = array();
+ $v_att_list = array();
+ $v_filedescr_list = array();
+ $p_result_list = array();
- // ----- Calculate the CRC
- $p_header['crc'] = @crc32($v_content);
-
- // ----- Look for no compression
- if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {
- // ----- Set header parameters
- $p_header['compressed_size'] = $p_header['size'];
- $p_header['compression'] = 0;
- }
-
- // ----- Look for normal compression
- else {
- // ----- Compress the content
- $v_content = @gzdeflate($v_content);
+ // ----- Look if the $p_filelist is really an array
+ if (is_array($p_filelist)) {
- // ----- Set header parameters
- $p_header['compressed_size'] = strlen($v_content);
- $p_header['compression'] = 8;
- }
-
- // ----- Call the header generation
- if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
- @fclose($v_file);
- return $v_result;
+ // ----- Look if the first element is also an array
+ // This will mean that this is a file description entry
+ if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
+ $v_att_list = $p_filelist;
+
+ // ----- The list is a list of string names
+ } else {
+ $v_string_list = $p_filelist;
+ }
+
+ // ----- Look if the $p_filelist is a string
+ } elseif (is_string($p_filelist)) {
+ // ----- Create a list from the string
+ $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
+
+ // ----- Invalid variable type for $p_filelist
+ } else {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist");
+
+ return 0;
}
- // ----- Write the compressed (or not) content
- @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
-
+ // ----- Reformat the string list
+ if (sizeof($v_string_list) != 0) {
+ foreach ($v_string_list as $v_string) {
+ if ($v_string != '') {
+ $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
+ } else {
+ }
+ }
}
- }
-
- // ----- Look for a virtual file (a file from string)
- else if ($p_filedescr['type'] == 'virtual_file') {
-
- $v_content = $p_filedescr['content'];
-
- // ----- Calculate the CRC
- $p_header['crc'] = @crc32($v_content);
-
- // ----- Look for no compression
- if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {
- // ----- Set header parameters
- $p_header['compressed_size'] = $p_header['size'];
- $p_header['compression'] = 0;
- }
-
- // ----- Look for normal compression
- else {
- // ----- Compress the content
- $v_content = @gzdeflate($v_content);
-
- // ----- Set header parameters
- $p_header['compressed_size'] = strlen($v_content);
- $p_header['compression'] = 8;
- }
-
- // ----- Call the header generation
- if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
- @fclose($v_file);
- return $v_result;
+ // ----- For each file in the list check the attributes
+ $v_supported_attributes = array(
+ PCLZIP_ATT_FILE_NAME => 'mandatory',
+ PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional',
+ PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional',
+ PCLZIP_ATT_FILE_MTIME => 'optional',
+ PCLZIP_ATT_FILE_CONTENT => 'optional',
+ PCLZIP_ATT_FILE_COMMENT => 'optional'
+ );
+ foreach ($v_att_list as $v_entry) {
+ $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes);
+ if ($v_result != 1) {
+ return 0;
+ }
}
- // ----- Write the compressed (or not) content
- @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
- }
-
- // ----- Look for a directory
- else if ($p_filedescr['type'] == 'folder') {
- // ----- Look for directory last '/'
- if (@substr($p_header['stored_filename'], -1) != '/') {
- $p_header['stored_filename'] .= '/';
+ // ----- Expand the filelist (expand directories)
+ $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
+ if ($v_result != 1) {
+ return 0;
}
- // ----- Set the file properties
- $p_header['size'] = 0;
- //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked
- $p_header['external'] = 0x00000010; // Value for a folder : to be checked
-
- // ----- Call the header generation
- if (($v_result = $this->privWriteFileHeader($p_header)) != 1)
- {
- return $v_result;
+ // ----- Call the create fct
+ $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options);
+ if ($v_result != 1) {
+ return 0;
}
- }
- }
-
- // ----- Look for post-add callback
- if (isset($p_options[PCLZIP_CB_POST_ADD])) {
-
- // ----- Generate a local information
- $v_local_header = array();
- $this->privConvertHeader2FileInfo($p_header, $v_local_header);
-
- // ----- Call the callback
- // Here I do not use call_user_func() because I need to send a reference to the
- // header.
-// eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);');
- $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header);
- if ($v_result == 0) {
- // ----- Ignored
- $v_result = 1;
- }
-
- // ----- Update the informations
- // Nothing can be modified
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privAddFileUsingTempFile()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options)
- {
- $v_result=PCLZIP_ERR_NO_ERROR;
-
- // ----- Working variable
- $p_filename = $p_filedescr['filename'];
-
-
- // ----- Open the source file
- if (($v_file = @fopen($p_filename, "rb")) == 0) {
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
- return PclZip::errorCode();
- }
-
- // ----- Creates a compressed temporary file
- $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz';
- if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) {
- fclose($v_file);
- PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode');
- return PclZip::errorCode();
- }
-
- // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
- $v_size = filesize($p_filename);
- while ($v_size != 0) {
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = @fread($v_file, $v_read_size);
- //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
- @gzputs($v_file_compressed, $v_buffer, $v_read_size);
- $v_size -= $v_read_size;
- }
-
- // ----- Close the file
- @fclose($v_file);
- @gzclose($v_file_compressed);
-
- // ----- Check the minimum file size
- if (filesize($v_gzip_temp_name) < 18) {
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes');
- return PclZip::errorCode();
- }
-
- // ----- Extract the compressed attributes
- if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) {
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
- return PclZip::errorCode();
- }
-
- // ----- Read the gzip file header
- $v_binary_data = @fread($v_file_compressed, 10);
- $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data);
-
- // ----- Check some parameters
- $v_data_header['os'] = bin2hex($v_data_header['os']);
-
- // ----- Read the gzip file footer
- @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8);
- $v_binary_data = @fread($v_file_compressed, 8);
- $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data);
-
- // ----- Set the attributes
- $p_header['compression'] = ord($v_data_header['cm']);
- //$p_header['mtime'] = $v_data_header['mtime'];
- $p_header['crc'] = $v_data_footer['crc'];
- $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18;
-
- // ----- Close the file
- @fclose($v_file_compressed);
-
- // ----- Call the header generation
- if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
- return $v_result;
- }
-
- // ----- Add the compressed data
- if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0)
- {
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
- return PclZip::errorCode();
- }
-
- // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
- fseek($v_file_compressed, 10);
- $v_size = $p_header['compressed_size'];
- while ($v_size != 0)
- {
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = @fread($v_file_compressed, $v_read_size);
- //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
- @fwrite($this->zip_fd, $v_buffer, $v_read_size);
- $v_size -= $v_read_size;
- }
-
- // ----- Close the file
- @fclose($v_file_compressed);
-
- // ----- Unlink the temporary file
- @unlink($v_gzip_temp_name);
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privCalculateStoredFilename()
- // Description :
- // Based on file descriptor properties and global options, this method
- // calculate the filename that will be stored in the archive.
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privCalculateStoredFilename(&$p_filedescr, &$p_options)
- {
- $v_result=1;
-
- // ----- Working variables
- $p_filename = $p_filedescr['filename'];
- if (isset($p_options[PCLZIP_OPT_ADD_PATH])) {
- $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH];
- }
- else {
- $p_add_dir = '';
- }
- if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) {
- $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH];
- }
- else {
- $p_remove_dir = '';
- }
- if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
- $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH];
- }
- else {
- $p_remove_all_dir = 0;
- }
-
-
- // ----- Look for full name change
- if (isset($p_filedescr['new_full_name'])) {
- // ----- Remove drive letter if any
- $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']);
- }
-
- // ----- Look for path and/or short name change
- else {
-
- // ----- Look for short name change
- // Its when we cahnge just the filename but not the path
- if (isset($p_filedescr['new_short_name'])) {
- $v_path_info = pathinfo($p_filename);
- $v_dir = '';
- if ($v_path_info['dirname'] != '') {
- $v_dir = $v_path_info['dirname'].'/';
- }
- $v_stored_filename = $v_dir.$p_filedescr['new_short_name'];
- }
- else {
- // ----- Calculate the stored filename
- $v_stored_filename = $p_filename;
- }
-
- // ----- Look for all path to remove
- if ($p_remove_all_dir) {
- $v_stored_filename = basename($p_filename);
- }
- // ----- Look for partial path remove
- else if ($p_remove_dir != "") {
- if (substr($p_remove_dir, -1) != '/')
- $p_remove_dir .= "/";
-
- if ( (substr($p_filename, 0, 2) == "./")
- || (substr($p_remove_dir, 0, 2) == "./")) {
-
- if ( (substr($p_filename, 0, 2) == "./")
- && (substr($p_remove_dir, 0, 2) != "./")) {
- $p_remove_dir = "./".$p_remove_dir;
- }
- if ( (substr($p_filename, 0, 2) != "./")
- && (substr($p_remove_dir, 0, 2) == "./")) {
- $p_remove_dir = substr($p_remove_dir, 2);
- }
- }
-
- $v_compare = PclZipUtilPathInclusion($p_remove_dir,
- $v_stored_filename);
- if ($v_compare > 0) {
- if ($v_compare == 2) {
- $v_stored_filename = "";
- }
- else {
- $v_stored_filename = substr($v_stored_filename,
- strlen($p_remove_dir));
- }
- }
- }
-
- // ----- Remove drive letter if any
- $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename);
-
- // ----- Look for path to add
- if ($p_add_dir != "") {
- if (substr($p_add_dir, -1) == "/")
- $v_stored_filename = $p_add_dir.$v_stored_filename;
- else
- $v_stored_filename = $p_add_dir."/".$v_stored_filename;
- }
- }
-
- // ----- Filename (reduce the path of stored name)
- $v_stored_filename = PclZipUtilPathReduction($v_stored_filename);
- $p_filedescr['stored_filename'] = $v_stored_filename;
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privWriteFileHeader()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privWriteFileHeader(&$p_header)
- {
- $v_result=1;
-
- // ----- Store the offset position of the file
- $p_header['offset'] = ftell($this->zip_fd);
-
- // ----- Transform UNIX mtime to DOS format mdate/mtime
- $v_date = getdate($p_header['mtime']);
- $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
- $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
-
- // ----- Packed data
- $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50,
- $p_header['version_extracted'], $p_header['flag'],
- $p_header['compression'], $v_mtime, $v_mdate,
- $p_header['crc'], $p_header['compressed_size'],
- $p_header['size'],
- strlen($p_header['stored_filename']),
- $p_header['extra_len']);
-
- // ----- Write the first 148 bytes of the header in the archive
- fputs($this->zip_fd, $v_binary_data, 30);
-
- // ----- Write the variable fields
- if (strlen($p_header['stored_filename']) != 0)
- {
- fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
- }
- if ($p_header['extra_len'] != 0)
- {
- fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privWriteCentralFileHeader()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privWriteCentralFileHeader(&$p_header)
- {
- $v_result=1;
-
- // TBC
- //for(reset($p_header); $key = key($p_header); next($p_header)) {
- //}
-
- // ----- Transform UNIX mtime to DOS format mdate/mtime
- $v_date = getdate($p_header['mtime']);
- $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
- $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
-
-
- // ----- Packed data
- $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50,
- $p_header['version'], $p_header['version_extracted'],
- $p_header['flag'], $p_header['compression'],
- $v_mtime, $v_mdate, $p_header['crc'],
- $p_header['compressed_size'], $p_header['size'],
- strlen($p_header['stored_filename']),
- $p_header['extra_len'], $p_header['comment_len'],
- $p_header['disk'], $p_header['internal'],
- $p_header['external'], $p_header['offset']);
-
- // ----- Write the 42 bytes of the header in the zip file
- fputs($this->zip_fd, $v_binary_data, 46);
-
- // ----- Write the variable fields
- if (strlen($p_header['stored_filename']) != 0)
- {
- fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
- }
- if ($p_header['extra_len'] != 0)
- {
- fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
- }
- if ($p_header['comment_len'] != 0)
- {
- fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']);
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privWriteCentralHeader()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment)
- {
- $v_result=1;
-
- // ----- Packed data
- $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries,
- $p_nb_entries, $p_size,
- $p_offset, strlen($p_comment));
-
- // ----- Write the 22 bytes of the header in the zip file
- fputs($this->zip_fd, $v_binary_data, 22);
-
- // ----- Write the variable fields
- if (strlen($p_comment) != 0)
- {
- fputs($this->zip_fd, $p_comment, strlen($p_comment));
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privList()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privList(&$p_list)
- {
- $v_result=1;
-
- // ----- Magic quotes trick
- $this->privDisableMagicQuotes();
-
- // ----- Open the zip file
- if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
- {
- // ----- Magic quotes trick
- $this->privSwapBackMagicQuotes();
-
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Read the central directory informations
- $v_central_dir = array();
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
- {
- $this->privSwapBackMagicQuotes();
- return $v_result;
- }
-
- // ----- Go to beginning of Central Dir
- @rewind($this->zip_fd);
- if (@fseek($this->zip_fd, $v_central_dir['offset']))
- {
- $this->privSwapBackMagicQuotes();
-
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Read each entry
- for ($i=0; $i<$v_central_dir['entries']; $i++)
- {
- // ----- Read the file header
- if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1)
- {
- $this->privSwapBackMagicQuotes();
- return $v_result;
- }
- $v_header['index'] = $i;
-
- // ----- Get the only interesting attributes
- $this->privConvertHeader2FileInfo($v_header, $p_list[$i]);
- unset($v_header);
- }
-
- // ----- Close the zip file
- $this->privCloseFd();
-
- // ----- Magic quotes trick
- $this->privSwapBackMagicQuotes();
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privConvertHeader2FileInfo()
- // Description :
- // This function takes the file informations from the central directory
- // entries and extract the interesting parameters that will be given back.
- // The resulting file infos are set in the array $p_info
- // $p_info['filename'] : Filename with full path. Given by user (add),
- // extracted in the filesystem (extract).
- // $p_info['stored_filename'] : Stored filename in the archive.
- // $p_info['size'] = Size of the file.
- // $p_info['compressed_size'] = Compressed size of the file.
- // $p_info['mtime'] = Last modification date of the file.
- // $p_info['comment'] = Comment associated with the file.
- // $p_info['folder'] = true/false : indicates if the entry is a folder or not.
- // $p_info['status'] = status of the action on the file.
- // $p_info['crc'] = CRC of the file content.
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privConvertHeader2FileInfo($p_header, &$p_info)
- {
- $v_result=1;
-
- // ----- Get the interesting attributes
- $v_temp_path = PclZipUtilPathReduction($p_header['filename']);
- $p_info['filename'] = $v_temp_path;
- $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']);
- $p_info['stored_filename'] = $v_temp_path;
- $p_info['size'] = $p_header['size'];
- $p_info['compressed_size'] = $p_header['compressed_size'];
- $p_info['mtime'] = $p_header['mtime'];
- $p_info['comment'] = $p_header['comment'];
- $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010);
- $p_info['index'] = $p_header['index'];
- $p_info['status'] = $p_header['status'];
- $p_info['crc'] = $p_header['crc'];
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privExtractByRule()
- // Description :
- // Extract a file or directory depending of rules (by index, by name, ...)
- // Parameters :
- // $p_file_list : An array where will be placed the properties of each
- // extracted file
- // $p_path : Path to add while writing the extracted files
- // $p_remove_path : Path to remove (from the file memorized path) while writing the
- // extracted files. If the path does not match the file path,
- // the file is extracted with its memorized path.
- // $p_remove_path does not apply to 'list' mode.
- // $p_path and $p_remove_path are commulative.
- // Return Values :
- // 1 on success,0 or less on error (see error code list)
- // --------------------------------------------------------------------------------
- function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
- {
- $v_result=1;
-
- // ----- Magic quotes trick
- $this->privDisableMagicQuotes();
-
- // ----- Check the path
- if ( ($p_path == "")
- || ( (substr($p_path, 0, 1) != "/")
- && (substr($p_path, 0, 3) != "../")
- && (substr($p_path,1,2)!=":/")))
- $p_path = "./".$p_path;
-
- // ----- Reduce the path last (and duplicated) '/'
- if (($p_path != "./") && ($p_path != "/"))
- {
- // ----- Look for the path end '/'
- while (substr($p_path, -1) == "/")
- {
- $p_path = substr($p_path, 0, strlen($p_path)-1);
- }
- }
-
- // ----- Look for path to remove format (should end by /)
- if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/'))
- {
- $p_remove_path .= '/';
- }
- $p_remove_path_size = strlen($p_remove_path);
-
- // ----- Open the zip file
- if (($v_result = $this->privOpenFd('rb')) != 1)
- {
- $this->privSwapBackMagicQuotes();
- return $v_result;
- }
-
- // ----- Read the central directory informations
- $v_central_dir = array();
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
- {
- // ----- Close the zip file
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
-
- return $v_result;
- }
-
- // ----- Start at beginning of Central Dir
- $v_pos_entry = $v_central_dir['offset'];
-
- // ----- Read each entry
- $j_start = 0;
- for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++)
- {
-
- // ----- Read next Central dir entry
- @rewind($this->zip_fd);
- if (@fseek($this->zip_fd, $v_pos_entry))
- {
- // ----- Close the zip file
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
-
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Read the file header
- $v_header = array();
- if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1)
- {
- // ----- Close the zip file
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
-
- return $v_result;
- }
-
- // ----- Store the index
- $v_header['index'] = $i;
-
- // ----- Store the file position
- $v_pos_entry = ftell($this->zip_fd);
-
- // ----- Look for the specific extract rules
- $v_extract = false;
-
- // ----- Look for extract by name rule
- if ( (isset($p_options[PCLZIP_OPT_BY_NAME]))
- && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
-
- // ----- Look if the filename is in the list
- for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j]))
- && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
- $v_extract = true;
- }
- }
- // ----- Look for a filename
- elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
- $v_extract = true;
- }
- }
- }
-
- // ----- Look for extract by ereg rule
- // ereg() is deprecated with PHP 5.3
- /*
- else if ( (isset($p_options[PCLZIP_OPT_BY_EREG]))
- && ($p_options[PCLZIP_OPT_BY_EREG] != "")) {
-
- if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) {
- $v_extract = true;
- }
- }
- */
-
- // ----- Look for extract by preg rule
- else if ( (isset($p_options[PCLZIP_OPT_BY_PREG]))
- && ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
-
- if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) {
- $v_extract = true;
- }
- }
-
- // ----- Look for extract by index rule
- else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX]))
- && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
-
- // ----- Look if the index is in the list
- for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
- $v_extract = true;
- }
- if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
- $j_start = $j+1;
- }
-
- if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
- break;
- }
- }
- }
-
- // ----- Look for no rule, which means extract all the archive
- else {
- $v_extract = true;
- }
-
- // ----- Check compression method
- if ( ($v_extract)
- && ( ($v_header['compression'] != 8)
- && ($v_header['compression'] != 0))) {
- $v_header['status'] = 'unsupported_compression';
-
- // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
- if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
-
- $this->privSwapBackMagicQuotes();
-
- PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION,
- "Filename '".$v_header['stored_filename']."' is "
- ."compressed by an unsupported compression "
- ."method (".$v_header['compression'].") ");
-
- return PclZip::errorCode();
- }
- }
-
- // ----- Check encrypted files
- if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
- $v_header['status'] = 'unsupported_encryption';
-
- // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
- if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
-
- $this->privSwapBackMagicQuotes();
-
- PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION,
- "Unsupported encryption for "
- ." filename '".$v_header['stored_filename']
- ."'");
-
- return PclZip::errorCode();
- }
+ return $p_result_list;
}
+ // --------------------------------------------------------------------------------
- // ----- Look for real extraction
- if (($v_extract) && ($v_header['status'] != 'ok')) {
- $v_result = $this->privConvertHeader2FileInfo($v_header,
- $p_file_list[$v_nb_extracted++]);
- if ($v_result != 1) {
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
- return $v_result;
- }
-
- $v_extract = false;
- }
-
- // ----- Look for real extraction
- if ($v_extract)
- {
-
- // ----- Go to the file position
- @rewind($this->zip_fd);
- if (@fseek($this->zip_fd, $v_header['offset']))
- {
- // ----- Close the zip file
- $this->privCloseFd();
-
- $this->privSwapBackMagicQuotes();
-
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Look for extraction as string
- if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) {
-
- $v_string = '';
-
- // ----- Extracting the file
- $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options);
- if ($v_result1 < 1) {
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
- return $v_result1;
- }
-
- // ----- Get the only interesting attributes
- if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1)
- {
- // ----- Close the zip file
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
-
- return $v_result;
- }
-
- // ----- Set the file content
- $p_file_list[$v_nb_extracted]['content'] = $v_string;
-
- // ----- Next extracted file
- $v_nb_extracted++;
-
- // ----- Look for user callback abort
- if ($v_result1 == 2) {
- break;
- }
- }
- // ----- Look for extraction in standard output
- elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT]))
- && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) {
- // ----- Extracting the file in standard output
- $v_result1 = $this->privExtractFileInOutput($v_header, $p_options);
- if ($v_result1 < 1) {
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
- return $v_result1;
- }
-
- // ----- Get the only interesting attributes
- if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) {
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
- return $v_result;
- }
-
- // ----- Look for user callback abort
- if ($v_result1 == 2) {
- break;
- }
- }
- // ----- Look for normal extraction
- else {
- // ----- Extracting the file
- $v_result1 = $this->privExtractFile($v_header,
- $p_path, $p_remove_path,
- $p_remove_all_path,
- $p_options);
- if ($v_result1 < 1) {
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
- return $v_result1;
- }
-
- // ----- Get the only interesting attributes
- if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1)
- {
- // ----- Close the zip file
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
-
- return $v_result;
- }
-
- // ----- Look for user callback abort
- if ($v_result1 == 2) {
- break;
- }
- }
- }
- }
-
- // ----- Close the zip file
- $this->privCloseFd();
- $this->privSwapBackMagicQuotes();
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privExtractFile()
- // Description :
- // Parameters :
- // Return Values :
- //
- // 1 : ... ?
- // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback
- // --------------------------------------------------------------------------------
- function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
- {
- $v_result=1;
-
- // ----- Read the file header
- if (($v_result = $this->privReadFileHeader($v_header)) != 1)
+ // --------------------------------------------------------------------------------
+ // Function :
+ // add($p_filelist, $p_add_dir="", $p_remove_dir="")
+ // add($p_filelist, $p_option, $p_option_value, ...)
+ // Description :
+ // This method supports two synopsis. The first one is historical.
+ // This methods add the list of files in an existing archive.
+ // If a file with the same name already exists, it is added at the end of the
+ // archive, the first one is still present.
+ // If the archive does not exist, it is created.
+ // Parameters :
+ // $p_filelist : An array containing file or directory names, or
+ // a string containing one filename or one directory name, or
+ // a string containing a list of filenames and/or directory
+ // names separated by spaces.
+ // $p_add_dir : A path to add before the real path of the archived file,
+ // in order to have it memorized in the archive.
+ // $p_remove_dir : A path to remove from the real path of the file to archive,
+ // in order to have a shorter path memorized in the archive.
+ // When $p_add_dir and $p_remove_dir are set, $p_remove_dir
+ // is removed first, before $p_add_dir is added.
+ // Options :
+ // PCLZIP_OPT_ADD_PATH :
+ // PCLZIP_OPT_REMOVE_PATH :
+ // PCLZIP_OPT_REMOVE_ALL_PATH :
+ // PCLZIP_OPT_COMMENT :
+ // PCLZIP_OPT_ADD_COMMENT :
+ // PCLZIP_OPT_PREPEND_COMMENT :
+ // PCLZIP_CB_PRE_ADD :
+ // PCLZIP_CB_POST_ADD :
+ // Return Values :
+ // 0 on failure,
+ // The list of the added files, with a status of the add action.
+ // (see PclZip::listContent() for list entry format)
+ // --------------------------------------------------------------------------------
+ public function add($p_filelist)
{
- // ----- Return
- return $v_result;
- }
+ $v_result = 1;
+ // ----- Reset the error handler
+ $this->privErrorReset();
- // ----- Check that the file header is coherent with $p_entry info
- if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
- // TBC
- }
+ // ----- Set default values
+ $v_options = array();
+ $v_options[PCLZIP_OPT_NO_COMPRESSION] = false;
- // ----- Look for all path to remove
- if ($p_remove_all_path == true) {
- // ----- Look for folder entry that not need to be extracted
- if (($p_entry['external']&0x00000010)==0x00000010) {
+ // ----- Look for variable options arguments
+ $v_size = func_num_args();
- $p_entry['status'] = "filtered";
+ // ----- Look for arguments
+ if ($v_size > 1) {
+ // ----- Get the arguments
+ $v_arg_list = func_get_args();
- return $v_result;
+ // ----- Remove form the options list the first argument
+ array_shift($v_arg_list);
+ $v_size--;
+
+ // ----- Look for first arg
+ if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
+
+ // ----- Parse the options
+ $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array(
+ PCLZIP_OPT_REMOVE_PATH => 'optional',
+ PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
+ PCLZIP_OPT_ADD_PATH => 'optional',
+ PCLZIP_CB_PRE_ADD => 'optional',
+ PCLZIP_CB_POST_ADD => 'optional',
+ PCLZIP_OPT_NO_COMPRESSION => 'optional',
+ PCLZIP_OPT_COMMENT => 'optional',
+ PCLZIP_OPT_ADD_COMMENT => 'optional',
+ PCLZIP_OPT_PREPEND_COMMENT => 'optional',
+ PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
+ PCLZIP_OPT_TEMP_FILE_ON => 'optional',
+ PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
+ //, PCLZIP_OPT_CRYPT => 'optional'
+ ));
+ if ($v_result != 1) {
+ return 0;
+ }
+
+ // ----- Look for 2 args
+ // Here we need to support the first historic synopsis of the
+ // method.
+ } else {
+
+ // ----- Get the first argument
+ $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0];
+
+ // ----- Look for the optional second argument
+ if ($v_size == 2) {
+ $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
+ } elseif ($v_size > 2) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
+
+ // ----- Return
+ return 0;
+ }
+ }
}
- // ----- Get the basename of the path
- $p_entry['filename'] = basename($p_entry['filename']);
- }
+ // ----- Look for default option values
+ $this->privOptionDefaultThreshold($v_options);
- // ----- Look for path to remove
- else if ($p_remove_path != "")
- {
- if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2)
- {
+ // ----- Init
+ $v_string_list = array();
+ $v_att_list = array();
+ $v_filedescr_list = array();
+ $p_result_list = array();
- // ----- Change the file status
- $p_entry['status'] = "filtered";
+ // ----- Look if the $p_filelist is really an array
+ if (is_array($p_filelist)) {
+
+ // ----- Look if the first element is also an array
+ // This will mean that this is a file description entry
+ if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
+ $v_att_list = $p_filelist;
+
+ // ----- The list is a list of string names
+ } else {
+ $v_string_list = $p_filelist;
+ }
+
+ // ----- Look if the $p_filelist is a string
+ } elseif (is_string($p_filelist)) {
+ // ----- Create a list from the string
+ $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
+
+ // ----- Invalid variable type for $p_filelist
+ } else {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '" . gettype($p_filelist) . "' for p_filelist");
+
+ return 0;
+ }
+
+ // ----- Reformat the string list
+ if (sizeof($v_string_list) != 0) {
+ foreach ($v_string_list as $v_string) {
+ $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
+ }
+ }
+
+ // ----- For each file in the list check the attributes
+ $v_supported_attributes = array(
+ PCLZIP_ATT_FILE_NAME => 'mandatory',
+ PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional',
+ PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional',
+ PCLZIP_ATT_FILE_MTIME => 'optional',
+ PCLZIP_ATT_FILE_CONTENT => 'optional',
+ PCLZIP_ATT_FILE_COMMENT => 'optional'
+ );
+ foreach ($v_att_list as $v_entry) {
+ $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes);
+ if ($v_result != 1) {
+ return 0;
+ }
+ }
+
+ // ----- Expand the filelist (expand directories)
+ $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
+ if ($v_result != 1) {
+ return 0;
+ }
+
+ // ----- Call the create fct
+ $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options);
+ if ($v_result != 1) {
+ return 0;
+ }
// ----- Return
- return $v_result;
- }
-
- $p_remove_path_size = strlen($p_remove_path);
- if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path)
- {
-
- // ----- Remove the path
- $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size);
-
- }
+ return $p_result_list;
}
+ // --------------------------------------------------------------------------------
- // ----- Add the path
- if ($p_path != '') {
- $p_entry['filename'] = $p_path."/".$p_entry['filename'];
- }
-
- // ----- Check a base_dir_restriction
- if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) {
- $v_inclusion
- = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION],
- $p_entry['filename']);
- if ($v_inclusion == 0) {
-
- PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION,
- "Filename '".$p_entry['filename']."' is "
- ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION");
-
- return PclZip::errorCode();
- }
- }
-
- // ----- Look for pre-extract callback
- if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
-
- // ----- Generate a local information
- $v_local_header = array();
- $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
-
- // ----- Call the callback
- // Here I do not use call_user_func() because I need to send a reference to the
- // header.
-// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
- $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
- if ($v_result == 0) {
- // ----- Change the file status
- $p_entry['status'] = "skipped";
- $v_result = 1;
- }
-
- // ----- Look for abort result
- if ($v_result == 2) {
- // ----- This status is internal and will be changed in 'skipped'
- $p_entry['status'] = "aborted";
- $v_result = PCLZIP_ERR_USER_ABORTED;
- }
-
- // ----- Update the informations
- // Only some fields can be modified
- $p_entry['filename'] = $v_local_header['filename'];
- }
-
-
- // ----- Look if extraction should be done
- if ($p_entry['status'] == 'ok') {
-
- // ----- Look for specific actions while the file exist
- if (file_exists($p_entry['filename']))
+ // --------------------------------------------------------------------------------
+ // Function : listContent()
+ // Description :
+ // This public method, gives the list of the files and directories, with their
+ // properties.
+ // The properties of each entries in the list are (used also in other functions) :
+ // filename : Name of the file. For a create or add action it is the filename
+ // given by the user. For an extract function it is the filename
+ // of the extracted file.
+ // stored_filename : Name of the file / directory stored in the archive.
+ // size : Size of the stored file.
+ // compressed_size : Size of the file's data compressed in the archive
+ // (without the headers overhead)
+ // mtime : Last known modification date of the file (UNIX timestamp)
+ // comment : Comment associated with the file
+ // folder : true | false
+ // index : index of the file in the archive
+ // status : status of the action (depending of the action) :
+ // Values are :
+ // ok : OK !
+ // filtered : the file / dir is not extracted (filtered by user)
+ // already_a_directory : the file can not be extracted because a
+ // directory with the same name already exists
+ // write_protected : the file can not be extracted because a file
+ // with the same name already exists and is
+ // write protected
+ // newer_exist : the file was not extracted because a newer file exists
+ // path_creation_fail : the file is not extracted because the folder
+ // does not exist and can not be created
+ // write_error : the file was not extracted because there was a
+ // error while writing the file
+ // read_error : the file was not extracted because there was a error
+ // while reading the file
+ // invalid_header : the file was not extracted because of an archive
+ // format error (bad file header)
+ // Note that each time a method can continue operating when there
+ // is an action error on a file, the error is only logged in the file status.
+ // Return Values :
+ // 0 on an unrecoverable failure,
+ // The list of the files in the archive.
+ // --------------------------------------------------------------------------------
+ public function listContent()
{
-
- // ----- Look if file is a directory
- if (is_dir($p_entry['filename']))
- {
-
- // ----- Change the file status
- $p_entry['status'] = "already_a_directory";
-
- // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
- // For historical reason first PclZip implementation does not stop
- // when this kind of error occurs.
- if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
-
- PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY,
- "Filename '".$p_entry['filename']."' is "
- ."already used by an existing directory");
-
- return PclZip::errorCode();
- }
- }
- // ----- Look if file is write protected
- else if (!is_writeable($p_entry['filename']))
- {
-
- // ----- Change the file status
- $p_entry['status'] = "write_protected";
-
- // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
- // For historical reason first PclZip implementation does not stop
- // when this kind of error occurs.
- if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
-
- PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
- "Filename '".$p_entry['filename']."' exists "
- ."and is write protected");
-
- return PclZip::errorCode();
- }
- }
-
- // ----- Look if the extracted file is older
- else if (filemtime($p_entry['filename']) > $p_entry['mtime'])
- {
- // ----- Change the file status
- if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER]))
- && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) {
- }
- else {
- $p_entry['status'] = "newer_exist";
-
- // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
- // For historical reason first PclZip implementation does not stop
- // when this kind of error occurs.
- if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
-
- PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
- "Newer version of '".$p_entry['filename']."' exists "
- ."and option PCLZIP_OPT_REPLACE_NEWER is not selected");
-
- return PclZip::errorCode();
- }
- }
- }
- else {
- }
- }
-
- // ----- Check the directory availability and create it if necessary
- else {
- if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/'))
- $v_dir_to_check = $p_entry['filename'];
- else if (!strstr($p_entry['filename'], "/"))
- $v_dir_to_check = "";
- else
- $v_dir_to_check = dirname($p_entry['filename']);
-
- if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) {
-
- // ----- Change the file status
- $p_entry['status'] = "path_creation_fail";
-
- // ----- Return
- //return $v_result;
- $v_result = 1;
- }
- }
- }
-
- // ----- Look if extraction should be done
- if ($p_entry['status'] == 'ok') {
-
- // ----- Do the extraction (if not a folder)
- if (!(($p_entry['external']&0x00000010)==0x00000010))
- {
- // ----- Look for not compressed file
- if ($p_entry['compression'] == 0) {
-
- // ----- Opening destination file
- if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0)
- {
-
- // ----- Change the file status
- $p_entry['status'] = "write_error";
-
- // ----- Return
- return $v_result;
- }
-
-
- // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
- $v_size = $p_entry['compressed_size'];
- while ($v_size != 0)
- {
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = @fread($this->zip_fd, $v_read_size);
- /* Try to speed up the code
- $v_binary_data = pack('a'.$v_read_size, $v_buffer);
- @fwrite($v_dest_file, $v_binary_data, $v_read_size);
- */
- @fwrite($v_dest_file, $v_buffer, $v_read_size);
- $v_size -= $v_read_size;
- }
-
- // ----- Closing the destination file
- fclose($v_dest_file);
-
- // ----- Change the file mtime
- touch($p_entry['filename'], $p_entry['mtime']);
-
-
- }
- else {
- // ----- TBC
- // Need to be finished
- if (($p_entry['flag'] & 1) == 1) {
- PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.');
- return PclZip::errorCode();
- }
-
-
- // ----- Look for using temporary file to unzip
- if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF]))
- && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON])
- || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD])
- && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])) ) ) {
- $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options);
- if ($v_result < PCLZIP_ERR_NO_ERROR) {
- return $v_result;
- }
- }
-
- // ----- Look for extract in memory
- else {
-
-
- // ----- Read the compressed file in a buffer (one shot)
- $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
-
- // ----- Decompress the file
- $v_file_content = @gzinflate($v_buffer);
- unset($v_buffer);
- if ($v_file_content === FALSE) {
-
- // ----- Change the file status
- // TBC
- $p_entry['status'] = "error";
-
- return $v_result;
- }
-
- // ----- Opening destination file
- if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
-
- // ----- Change the file status
- $p_entry['status'] = "write_error";
-
- return $v_result;
- }
-
- // ----- Write the uncompressed data
- @fwrite($v_dest_file, $v_file_content, $p_entry['size']);
- unset($v_file_content);
-
- // ----- Closing the destination file
- @fclose($v_dest_file);
-
- }
-
- // ----- Change the file mtime
- @touch($p_entry['filename'], $p_entry['mtime']);
- }
-
- // ----- Look for chmod option
- if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) {
-
- // ----- Change the mode of the file
- @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]);
- }
-
- }
- }
-
- // ----- Change abort status
- if ($p_entry['status'] == "aborted") {
- $p_entry['status'] = "skipped";
- }
-
- // ----- Look for post-extract callback
- elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
-
- // ----- Generate a local information
- $v_local_header = array();
- $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
-
- // ----- Call the callback
- // Here I do not use call_user_func() because I need to send a reference to the
- // header.
-// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
- $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
-
- // ----- Look for abort result
- if ($v_result == 2) {
- $v_result = PCLZIP_ERR_USER_ABORTED;
- }
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privExtractFileUsingTempFile()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privExtractFileUsingTempFile(&$p_entry, &$p_options)
- {
- $v_result=1;
-
- // ----- Creates a temporary file
- $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz';
- if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) {
- fclose($v_file);
- PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode');
- return PclZip::errorCode();
- }
-
-
- // ----- Write gz file format header
- $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3));
- @fwrite($v_dest_file, $v_binary_data, 10);
-
- // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
- $v_size = $p_entry['compressed_size'];
- while ($v_size != 0)
- {
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = @fread($this->zip_fd, $v_read_size);
- //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
- @fwrite($v_dest_file, $v_buffer, $v_read_size);
- $v_size -= $v_read_size;
- }
-
- // ----- Write gz file format footer
- $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']);
- @fwrite($v_dest_file, $v_binary_data, 8);
-
- // ----- Close the temporary file
- @fclose($v_dest_file);
-
- // ----- Opening destination file
- if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
- $p_entry['status'] = "write_error";
- return $v_result;
- }
-
- // ----- Open the temporary gz file
- if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) {
- @fclose($v_dest_file);
- $p_entry['status'] = "read_error";
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
- return PclZip::errorCode();
- }
-
-
- // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
- $v_size = $p_entry['size'];
- while ($v_size != 0) {
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = @gzread($v_src_file, $v_read_size);
- //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
- @fwrite($v_dest_file, $v_buffer, $v_read_size);
- $v_size -= $v_read_size;
- }
- @fclose($v_dest_file);
- @gzclose($v_src_file);
-
- // ----- Delete the temporary file
- @unlink($v_gzip_temp_name);
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privExtractFileInOutput()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privExtractFileInOutput(&$p_entry, &$p_options)
- {
- $v_result=1;
-
- // ----- Read the file header
- if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
- return $v_result;
- }
-
-
- // ----- Check that the file header is coherent with $p_entry info
- if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
- // TBC
- }
-
- // ----- Look for pre-extract callback
- if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
-
- // ----- Generate a local information
- $v_local_header = array();
- $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
-
- // ----- Call the callback
- // Here I do not use call_user_func() because I need to send a reference to the
- // header.
-// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
- $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
- if ($v_result == 0) {
- // ----- Change the file status
- $p_entry['status'] = "skipped";
$v_result = 1;
- }
- // ----- Look for abort result
- if ($v_result == 2) {
- // ----- This status is internal and will be changed in 'skipped'
- $p_entry['status'] = "aborted";
- $v_result = PCLZIP_ERR_USER_ABORTED;
- }
+ // ----- Reset the error handler
+ $this->privErrorReset();
- // ----- Update the informations
- // Only some fields can be modified
- $p_entry['filename'] = $v_local_header['filename'];
- }
-
- // ----- Trace
-
- // ----- Look if extraction should be done
- if ($p_entry['status'] == 'ok') {
-
- // ----- Do the extraction (if not a folder)
- if (!(($p_entry['external']&0x00000010)==0x00000010)) {
- // ----- Look for not compressed file
- if ($p_entry['compressed_size'] == $p_entry['size']) {
-
- // ----- Read the file in a buffer (one shot)
- $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
-
- // ----- Send the file to the output
- echo $v_buffer;
- unset($v_buffer);
+ // ----- Check archive
+ if (!$this->privCheckFormat()) {
+ return (0);
}
- else {
- // ----- Read the compressed file in a buffer (one shot)
- $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
-
- // ----- Decompress the file
- $v_file_content = gzinflate($v_buffer);
- unset($v_buffer);
+ // ----- Call the extracting fct
+ $p_list = array();
+ if (($v_result = $this->privList($p_list)) != 1) {
+ unset($p_list);
- // ----- Send the file to the output
- echo $v_file_content;
- unset($v_file_content);
+ return (0);
}
- }
+
+ // ----- Return
+ return $p_list;
}
+ // --------------------------------------------------------------------------------
- // ----- Change abort status
- if ($p_entry['status'] == "aborted") {
- $p_entry['status'] = "skipped";
- }
-
- // ----- Look for post-extract callback
- elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
-
- // ----- Generate a local information
- $v_local_header = array();
- $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
-
- // ----- Call the callback
- // Here I do not use call_user_func() because I need to send a reference to the
- // header.
-// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
- $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
-
- // ----- Look for abort result
- if ($v_result == 2) {
- $v_result = PCLZIP_ERR_USER_ABORTED;
- }
- }
-
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privExtractFileAsString()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privExtractFileAsString(&$p_entry, &$p_string, &$p_options)
- {
- $v_result=1;
-
- // ----- Read the file header
- $v_header = array();
- if (($v_result = $this->privReadFileHeader($v_header)) != 1)
+ // --------------------------------------------------------------------------------
+ // Function :
+ // extract($p_path="./", $p_remove_path="")
+ // extract([$p_option, $p_option_value, ...])
+ // Description :
+ // This method supports two synopsis. The first one is historical.
+ // This method extract all the files / directories from the archive to the
+ // folder indicated in $p_path.
+ // If you want to ignore the 'root' part of path of the memorized files
+ // you can indicate this in the optional $p_remove_path parameter.
+ // By default, if a newer file with the same name already exists, the
+ // file is not extracted.
+ //
+ // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions
+ // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append
+ // at the end of the path value of PCLZIP_OPT_PATH.
+ // Parameters :
+ // $p_path : Path where the files and directories are to be extracted
+ // $p_remove_path : First part ('root' part) of the memorized path
+ // (if any similar) to remove while extracting.
+ // Options :
+ // PCLZIP_OPT_PATH :
+ // PCLZIP_OPT_ADD_PATH :
+ // PCLZIP_OPT_REMOVE_PATH :
+ // PCLZIP_OPT_REMOVE_ALL_PATH :
+ // PCLZIP_CB_PRE_EXTRACT :
+ // PCLZIP_CB_POST_EXTRACT :
+ // Return Values :
+ // 0 or a negative value on failure,
+ // The list of the extracted files, with a status of the action.
+ // (see PclZip::listContent() for list entry format)
+ // --------------------------------------------------------------------------------
+ public function extract()
{
- // ----- Return
- return $v_result;
- }
-
-
- // ----- Check that the file header is coherent with $p_entry info
- if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
- // TBC
- }
-
- // ----- Look for pre-extract callback
- if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
-
- // ----- Generate a local information
- $v_local_header = array();
- $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
-
- // ----- Call the callback
- // Here I do not use call_user_func() because I need to send a reference to the
- // header.
-// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
- $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
- if ($v_result == 0) {
- // ----- Change the file status
- $p_entry['status'] = "skipped";
$v_result = 1;
- }
-
- // ----- Look for abort result
- if ($v_result == 2) {
- // ----- This status is internal and will be changed in 'skipped'
- $p_entry['status'] = "aborted";
- $v_result = PCLZIP_ERR_USER_ABORTED;
- }
- // ----- Update the informations
- // Only some fields can be modified
- $p_entry['filename'] = $v_local_header['filename'];
- }
+ // ----- Reset the error handler
+ $this->privErrorReset();
-
- // ----- Look if extraction should be done
- if ($p_entry['status'] == 'ok') {
-
- // ----- Do the extraction (if not a folder)
- if (!(($p_entry['external']&0x00000010)==0x00000010)) {
- // ----- Look for not compressed file
- // if ($p_entry['compressed_size'] == $p_entry['size'])
- if ($p_entry['compression'] == 0) {
-
- // ----- Reading the file
- $p_string = @fread($this->zip_fd, $p_entry['compressed_size']);
+ // ----- Check archive
+ if (!$this->privCheckFormat()) {
+ return (0);
}
- else {
-
- // ----- Reading the file
- $v_data = @fread($this->zip_fd, $p_entry['compressed_size']);
-
- // ----- Decompress the file
- if (($p_string = @gzinflate($v_data)) === FALSE) {
- // TBC
- }
+
+ // ----- Set default values
+ $v_options = array();
+ // $v_path = "./";
+ $v_path = '';
+ $v_remove_path = "";
+ $v_remove_all_path = false;
+
+ // ----- Look for variable options arguments
+ $v_size = func_num_args();
+
+ // ----- Default values for option
+ $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false;
+
+ // ----- Look for arguments
+ if ($v_size > 0) {
+ // ----- Get the arguments
+ $v_arg_list = func_get_args();
+
+ // ----- Look for first arg
+ if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
+
+ // ----- Parse the options
+ $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array(
+ PCLZIP_OPT_PATH => 'optional',
+ PCLZIP_OPT_REMOVE_PATH => 'optional',
+ PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
+ PCLZIP_OPT_ADD_PATH => 'optional',
+ PCLZIP_CB_PRE_EXTRACT => 'optional',
+ PCLZIP_CB_POST_EXTRACT => 'optional',
+ PCLZIP_OPT_SET_CHMOD => 'optional',
+ PCLZIP_OPT_BY_NAME => 'optional',
+ PCLZIP_OPT_BY_EREG => 'optional',
+ PCLZIP_OPT_BY_PREG => 'optional',
+ PCLZIP_OPT_BY_INDEX => 'optional',
+ PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
+ PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional',
+ PCLZIP_OPT_REPLACE_NEWER => 'optional',
+ PCLZIP_OPT_STOP_ON_ERROR => 'optional',
+ PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
+ PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
+ PCLZIP_OPT_TEMP_FILE_ON => 'optional',
+ PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
+ ));
+ if ($v_result != 1) {
+ return 0;
+ }
+
+ // ----- Set the arguments
+ if (isset($v_options[PCLZIP_OPT_PATH])) {
+ $v_path = $v_options[PCLZIP_OPT_PATH];
+ }
+ if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
+ $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
+ }
+ if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
+ $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
+ }
+ if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
+ // ----- Check for '/' in last path char
+ if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
+ $v_path .= '/';
+ }
+ $v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
+ }
+
+ // ----- Look for 2 args
+ // Here we need to support the first historic synopsis of the
+ // method.
+ } else {
+
+ // ----- Get the first argument
+ $v_path = $v_arg_list[0];
+
+ // ----- Look for the optional second argument
+ if ($v_size == 2) {
+ $v_remove_path = $v_arg_list[1];
+ } elseif ($v_size > 2) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
+
+ // ----- Return
+ return 0;
+ }
+ }
}
-
+
+ // ----- Look for default option values
+ $this->privOptionDefaultThreshold($v_options);
+
// ----- Trace
- }
- else {
- // TBC : error : can not extract a folder in a string
- }
-
- }
- // ----- Change abort status
- if ($p_entry['status'] == "aborted") {
- $p_entry['status'] = "skipped";
- }
-
- // ----- Look for post-extract callback
- elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
+ // ----- Call the extracting fct
+ $p_list = array();
+ $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options);
+ if ($v_result < 1) {
+ unset($p_list);
- // ----- Generate a local information
- $v_local_header = array();
- $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
-
- // ----- Swap the content to header
- $v_local_header['content'] = $p_string;
- $p_string = '';
-
- // ----- Call the callback
- // Here I do not use call_user_func() because I need to send a reference to the
- // header.
-// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
- $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
-
- // ----- Swap back the content to header
- $p_string = $v_local_header['content'];
- unset($v_local_header['content']);
-
- // ----- Look for abort result
- if ($v_result == 2) {
- $v_result = PCLZIP_ERR_USER_ABORTED;
- }
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privReadFileHeader()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privReadFileHeader(&$p_header)
- {
- $v_result=1;
-
- // ----- Read the 4 bytes signature
- $v_binary_data = @fread($this->zip_fd, 4);
- $v_data = unpack('Vid', $v_binary_data);
-
- // ----- Check signature
- if ($v_data['id'] != 0x04034b50)
- {
-
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Read the first 42 bytes of the header
- $v_binary_data = fread($this->zip_fd, 26);
-
- // ----- Look for invalid block size
- if (strlen($v_binary_data) != 26)
- {
- $p_header['filename'] = "";
- $p_header['status'] = "invalid_header";
-
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Extract the values
- $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data);
-
- // ----- Get filename
- $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']);
-
- // ----- Get extra_fields
- if ($v_data['extra_len'] != 0) {
- $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']);
- }
- else {
- $p_header['extra'] = '';
- }
-
- // ----- Extract properties
- $p_header['version_extracted'] = $v_data['version'];
- $p_header['compression'] = $v_data['compression'];
- $p_header['size'] = $v_data['size'];
- $p_header['compressed_size'] = $v_data['compressed_size'];
- $p_header['crc'] = $v_data['crc'];
- $p_header['flag'] = $v_data['flag'];
- $p_header['filename_len'] = $v_data['filename_len'];
-
- // ----- Recuperate date in UNIX format
- $p_header['mdate'] = $v_data['mdate'];
- $p_header['mtime'] = $v_data['mtime'];
- if ($p_header['mdate'] && $p_header['mtime'])
- {
- // ----- Extract time
- $v_hour = ($p_header['mtime'] & 0xF800) >> 11;
- $v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
- $v_seconde = ($p_header['mtime'] & 0x001F)*2;
-
- // ----- Extract date
- $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
- $v_month = ($p_header['mdate'] & 0x01E0) >> 5;
- $v_day = $p_header['mdate'] & 0x001F;
-
- // ----- Get UNIX date format
- $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
-
- }
- else
- {
- $p_header['mtime'] = time();
- }
-
- // TBC
- //for(reset($v_data); $key = key($v_data); next($v_data)) {
- //}
-
- // ----- Set the stored filename
- $p_header['stored_filename'] = $p_header['filename'];
-
- // ----- Set the status field
- $p_header['status'] = "ok";
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privReadCentralFileHeader()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privReadCentralFileHeader(&$p_header)
- {
- $v_result=1;
-
- // ----- Read the 4 bytes signature
- $v_binary_data = @fread($this->zip_fd, 4);
- $v_data = unpack('Vid', $v_binary_data);
-
- // ----- Check signature
- if ($v_data['id'] != 0x02014b50)
- {
-
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Read the first 42 bytes of the header
- $v_binary_data = fread($this->zip_fd, 42);
-
- // ----- Look for invalid block size
- if (strlen($v_binary_data) != 42)
- {
- $p_header['filename'] = "";
- $p_header['status'] = "invalid_header";
-
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Extract the values
- $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data);
-
- // ----- Get filename
- if ($p_header['filename_len'] != 0)
- $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']);
- else
- $p_header['filename'] = '';
-
- // ----- Get extra
- if ($p_header['extra_len'] != 0)
- $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']);
- else
- $p_header['extra'] = '';
-
- // ----- Get comment
- if ($p_header['comment_len'] != 0)
- $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']);
- else
- $p_header['comment'] = '';
-
- // ----- Extract properties
-
- // ----- Recuperate date in UNIX format
- //if ($p_header['mdate'] && $p_header['mtime'])
- // TBC : bug : this was ignoring time with 0/0/0
- if (1)
- {
- // ----- Extract time
- $v_hour = ($p_header['mtime'] & 0xF800) >> 11;
- $v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
- $v_seconde = ($p_header['mtime'] & 0x001F)*2;
-
- // ----- Extract date
- $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
- $v_month = ($p_header['mdate'] & 0x01E0) >> 5;
- $v_day = $p_header['mdate'] & 0x001F;
-
- // ----- Get UNIX date format
- $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
-
- }
- else
- {
- $p_header['mtime'] = time();
- }
-
- // ----- Set the stored filename
- $p_header['stored_filename'] = $p_header['filename'];
-
- // ----- Set default status to ok
- $p_header['status'] = 'ok';
-
- // ----- Look if it is a directory
- if (substr($p_header['filename'], -1) == '/') {
- //$p_header['external'] = 0x41FF0010;
- $p_header['external'] = 0x00000010;
- }
-
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privCheckFileHeaders()
- // Description :
- // Parameters :
- // Return Values :
- // 1 on success,
- // 0 on error;
- // --------------------------------------------------------------------------------
- function privCheckFileHeaders(&$p_local_header, &$p_central_header)
- {
- $v_result=1;
-
- // ----- Check the static values
- // TBC
- if ($p_local_header['filename'] != $p_central_header['filename']) {
- }
- if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
- }
- if ($p_local_header['flag'] != $p_central_header['flag']) {
- }
- if ($p_local_header['compression'] != $p_central_header['compression']) {
- }
- if ($p_local_header['mtime'] != $p_central_header['mtime']) {
- }
- if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
- }
-
- // ----- Look for flag bit 3
- if (($p_local_header['flag'] & 8) == 8) {
- $p_local_header['size'] = $p_central_header['size'];
- $p_local_header['compressed_size'] = $p_central_header['compressed_size'];
- $p_local_header['crc'] = $p_central_header['crc'];
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privReadEndCentralDir()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privReadEndCentralDir(&$p_central_dir)
- {
- $v_result=1;
-
- // ----- Go to the end of the zip file
- $v_size = filesize($this->zipname);
- @fseek($this->zip_fd, $v_size);
- if (@ftell($this->zip_fd) != $v_size)
- {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\'');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- First try : look if this is an archive with no commentaries (most of the time)
- // in this case the end of central dir is at 22 bytes of the file end
- $v_found = 0;
- if ($v_size > 26) {
- @fseek($this->zip_fd, $v_size-22);
- if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22))
- {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Read for bytes
- $v_binary_data = @fread($this->zip_fd, 4);
- $v_data = @unpack('Vid', $v_binary_data);
-
- // ----- Check signature
- if ($v_data['id'] == 0x06054b50) {
- $v_found = 1;
- }
-
- $v_pos = ftell($this->zip_fd);
- }
-
- // ----- Go back to the maximum possible size of the Central Dir End Record
- if (!$v_found) {
- $v_maximum_size = 65557; // 0xFFFF + 22;
- if ($v_maximum_size > $v_size)
- $v_maximum_size = $v_size;
- @fseek($this->zip_fd, $v_size-$v_maximum_size);
- if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size))
- {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Read byte per byte in order to find the signature
- $v_pos = ftell($this->zip_fd);
- $v_bytes = 0x00000000;
- while ($v_pos < $v_size)
- {
- // ----- Read a byte
- $v_byte = @fread($this->zip_fd, 1);
-
- // ----- Add the byte
- //$v_bytes = ($v_bytes << 8) | Ord($v_byte);
- // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number
- // Otherwise on systems where we have 64bit integers the check below for the magic number will fail.
- $v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte);
-
- // ----- Compare the bytes
- if ($v_bytes == 0x504b0506)
- {
- $v_pos++;
- break;
+ return (0);
}
- $v_pos++;
- }
-
- // ----- Look if not found end of central dir
- if ($v_pos == $v_size)
- {
-
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature");
-
// ----- Return
- return PclZip::errorCode();
- }
+ return $p_list;
}
+ // --------------------------------------------------------------------------------
- // ----- Read the first 18 bytes of the header
- $v_binary_data = fread($this->zip_fd, 18);
- // ----- Look for invalid block size
- if (strlen($v_binary_data) != 18)
+ // --------------------------------------------------------------------------------
+ // Function :
+ // extractByIndex($p_index, $p_path="./", $p_remove_path="")
+ // extractByIndex($p_index, [$p_option, $p_option_value, ...])
+ // Description :
+ // This method supports two synopsis. The first one is historical.
+ // This method is doing a partial extract of the archive.
+ // The extracted files or folders are identified by their index in the
+ // archive (from 0 to n).
+ // Note that if the index identify a folder, only the folder entry is
+ // extracted, not all the files included in the archive.
+ // Parameters :
+ // $p_index : A single index (integer) or a string of indexes of files to
+ // extract. The form of the string is "0,4-6,8-12" with only numbers
+ // and '-' for range or ',' to separate ranges. No spaces or ';'
+ // are allowed.
+ // $p_path : Path where the files and directories are to be extracted
+ // $p_remove_path : First part ('root' part) of the memorized path
+ // (if any similar) to remove while extracting.
+ // Options :
+ // PCLZIP_OPT_PATH :
+ // PCLZIP_OPT_ADD_PATH :
+ // PCLZIP_OPT_REMOVE_PATH :
+ // PCLZIP_OPT_REMOVE_ALL_PATH :
+ // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and
+ // not as files.
+ // The resulting content is in a new field 'content' in the file
+ // structure.
+ // This option must be used alone (any other options are ignored).
+ // PCLZIP_CB_PRE_EXTRACT :
+ // PCLZIP_CB_POST_EXTRACT :
+ // Return Values :
+ // 0 on failure,
+ // The list of the extracted files, with a status of the action.
+ // (see PclZip::listContent() for list entry format)
+ // --------------------------------------------------------------------------------
+ //function extractByIndex($p_index, options...)
+ public function extractByIndex($p_index)
{
+ $v_result = 1;
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data));
+ // ----- Reset the error handler
+ $this->privErrorReset();
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Extract the values
- $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data);
-
- // ----- Check the global size
- if (($v_pos + $v_data['comment_size'] + 18) != $v_size) {
-
- // ----- Removed in release 2.2 see readme file
- // The check of the file size is a little too strict.
- // Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
- // While decrypted, zip has training 0 bytes
- if (0) {
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT,
- 'The central dir is not at the end of the archive.'
- .' Some trailing bytes exists after the archive.');
-
- // ----- Return
- return PclZip::errorCode();
- }
- }
-
- // ----- Get comment
- if ($v_data['comment_size'] != 0) {
- $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']);
- }
- else
- $p_central_dir['comment'] = '';
-
- $p_central_dir['entries'] = $v_data['entries'];
- $p_central_dir['disk_entries'] = $v_data['disk_entries'];
- $p_central_dir['offset'] = $v_data['offset'];
- $p_central_dir['size'] = $v_data['size'];
- $p_central_dir['disk'] = $v_data['disk'];
- $p_central_dir['disk_start'] = $v_data['disk_start'];
-
- // TBC
- //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) {
- //}
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privDeleteByRule()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privDeleteByRule(&$p_result_list, &$p_options)
- {
- $v_result=1;
- $v_list_detail = array();
-
- // ----- Open the zip file
- if (($v_result=$this->privOpenFd('rb')) != 1)
- {
- // ----- Return
- return $v_result;
- }
-
- // ----- Read the central directory informations
- $v_central_dir = array();
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
- {
- $this->privCloseFd();
- return $v_result;
- }
-
- // ----- Go to beginning of File
- @rewind($this->zip_fd);
-
- // ----- Scan all the files
- // ----- Start at beginning of Central Dir
- $v_pos_entry = $v_central_dir['offset'];
- @rewind($this->zip_fd);
- if (@fseek($this->zip_fd, $v_pos_entry))
- {
- // ----- Close the zip file
- $this->privCloseFd();
-
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Read each entry
- $v_header_list = array();
- $j_start = 0;
- for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++)
- {
-
- // ----- Read the file header
- $v_header_list[$v_nb_extracted] = array();
- if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1)
- {
- // ----- Close the zip file
- $this->privCloseFd();
-
- return $v_result;
- }
-
-
- // ----- Store the index
- $v_header_list[$v_nb_extracted]['index'] = $i;
-
- // ----- Look for the specific extract rules
- $v_found = false;
-
- // ----- Look for extract by name rule
- if ( (isset($p_options[PCLZIP_OPT_BY_NAME]))
- && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
-
- // ----- Look if the filename is in the list
- for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j]))
- && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
- $v_found = true;
- }
- elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */
- && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
- $v_found = true;
- }
- }
- // ----- Look for a filename
- elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
- $v_found = true;
- }
- }
- }
-
- // ----- Look for extract by ereg rule
- // ereg() is deprecated with PHP 5.3
- /*
- else if ( (isset($p_options[PCLZIP_OPT_BY_EREG]))
- && ($p_options[PCLZIP_OPT_BY_EREG] != "")) {
-
- if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
- $v_found = true;
- }
- }
- */
-
- // ----- Look for extract by preg rule
- else if ( (isset($p_options[PCLZIP_OPT_BY_PREG]))
- && ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
-
- if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
- $v_found = true;
- }
- }
-
- // ----- Look for extract by index rule
- else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX]))
- && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
-
- // ----- Look if the index is in the list
- for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
- $v_found = true;
- }
- if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
- $j_start = $j+1;
- }
-
- if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
- break;
- }
- }
- }
- else {
- $v_found = true;
- }
-
- // ----- Look for deletion
- if ($v_found)
- {
- unset($v_header_list[$v_nb_extracted]);
- }
- else
- {
- $v_nb_extracted++;
- }
- }
-
- // ----- Look if something need to be deleted
- if ($v_nb_extracted > 0) {
-
- // ----- Creates a temporay file
- $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
-
- // ----- Creates a temporary zip archive
- $v_temp_zip = new PclZip($v_zip_temp_name);
-
- // ----- Open the temporary zip file in write mode
- if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) {
- $this->privCloseFd();
-
- // ----- Return
- return $v_result;
+ // ----- Check archive
+ if (!$this->privCheckFormat()) {
+ return (0);
}
- // ----- Look which file need to be kept
- for ($i=0; $izip_fd);
- if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) {
- // ----- Close the zip file
- $this->privCloseFd();
- $v_temp_zip->privCloseFd();
- @unlink($v_zip_temp_name);
+ // ----- Look for variable options arguments
+ $v_size = func_num_args();
+
+ // ----- Default values for option
+ $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false;
+
+ // ----- Look for arguments
+ if ($v_size > 1) {
+ // ----- Get the arguments
+ $v_arg_list = func_get_args();
+
+ // ----- Remove form the options list the first argument
+ array_shift($v_arg_list);
+ $v_size--;
+
+ // ----- Look for first arg
+ if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
+
+ // ----- Parse the options
+ $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array(
+ PCLZIP_OPT_PATH => 'optional',
+ PCLZIP_OPT_REMOVE_PATH => 'optional',
+ PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
+ PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
+ PCLZIP_OPT_ADD_PATH => 'optional',
+ PCLZIP_CB_PRE_EXTRACT => 'optional',
+ PCLZIP_CB_POST_EXTRACT => 'optional',
+ PCLZIP_OPT_SET_CHMOD => 'optional',
+ PCLZIP_OPT_REPLACE_NEWER => 'optional',
+ PCLZIP_OPT_STOP_ON_ERROR => 'optional',
+ PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
+ PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
+ PCLZIP_OPT_TEMP_FILE_ON => 'optional',
+ PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
+ ));
+ if ($v_result != 1) {
+ return 0;
+ }
+
+ // ----- Set the arguments
+ if (isset($v_options[PCLZIP_OPT_PATH])) {
+ $v_path = $v_options[PCLZIP_OPT_PATH];
+ }
+ if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
+ $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
+ }
+ if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
+ $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
+ }
+ if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
+ // ----- Check for '/' in last path char
+ if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
+ $v_path .= '/';
+ }
+ $v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
+ }
+ if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) {
+ $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false;
+ } else {
+ }
+
+ // ----- Look for 2 args
+ // Here we need to support the first historic synopsis of the
+ // method.
+ } else {
+
+ // ----- Get the first argument
+ $v_path = $v_arg_list[0];
+
+ // ----- Look for the optional second argument
+ if ($v_size == 2) {
+ $v_remove_path = $v_arg_list[1];
+ } elseif ($v_size > 2) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
+
+ // ----- Return
+ return 0;
+ }
+ }
+ }
+
+ // ----- Trace
+
+ // ----- Trick
+ // Here I want to reuse extractByRule(), so I need to parse the $p_index
+ // with privParseOptions()
+ $v_arg_trick = array(
+ PCLZIP_OPT_BY_INDEX,
+ $p_index
+ );
+ $v_options_trick = array();
+ $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, array(
+ PCLZIP_OPT_BY_INDEX => 'optional'
+ ));
+ if ($v_result != 1) {
+ return 0;
+ }
+ $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX];
+
+ // ----- Look for default option values
+ $this->privOptionDefaultThreshold($v_options);
+
+ // ----- Call the extracting fct
+ if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) {
+ return (0);
+ }
+
+ // ----- Return
+ return $p_list;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function :
+ // delete([$p_option, $p_option_value, ...])
+ // Description :
+ // This method removes files from the archive.
+ // If no parameters are given, then all the archive is emptied.
+ // Parameters :
+ // None or optional arguments.
+ // Options :
+ // PCLZIP_OPT_BY_INDEX :
+ // PCLZIP_OPT_BY_NAME :
+ // PCLZIP_OPT_BY_EREG :
+ // PCLZIP_OPT_BY_PREG :
+ // Return Values :
+ // 0 on failure,
+ // The list of the files which are still present in the archive.
+ // (see PclZip::listContent() for list entry format)
+ // --------------------------------------------------------------------------------
+ public function delete()
+ {
+ $v_result = 1;
+
+ // ----- Reset the error handler
+ $this->privErrorReset();
+
+ // ----- Check archive
+ if (!$this->privCheckFormat()) {
+ return (0);
+ }
+
+ // ----- Set default values
+ $v_options = array();
+
+ // ----- Look for variable options arguments
+ $v_size = func_num_args();
+
+ // ----- Look for arguments
+ if ($v_size > 0) {
+ // ----- Get the arguments
+ $v_arg_list = func_get_args();
+
+ // ----- Parse the options
+ $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array(
+ PCLZIP_OPT_BY_NAME => 'optional',
+ PCLZIP_OPT_BY_EREG => 'optional',
+ PCLZIP_OPT_BY_PREG => 'optional',
+ PCLZIP_OPT_BY_INDEX => 'optional'
+ ));
+ if ($v_result != 1) {
+ return 0;
+ }
+ }
+
+ // ----- Magic quotes trick
+ $this->privDisableMagicQuotes();
+
+ // ----- Call the delete fct
+ $v_list = array();
+ if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) {
+ $this->privSwapBackMagicQuotes();
+ unset($v_list);
+
+ return (0);
+ }
+
+ // ----- Magic quotes trick
+ $this->privSwapBackMagicQuotes();
+
+ // ----- Return
+ return $v_list;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : deleteByIndex()
+ // Description :
+ // ***** Deprecated *****
+ // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered.
+ // --------------------------------------------------------------------------------
+ public function deleteByIndex($p_index)
+ {
+
+ $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index);
+
+ // ----- Return
+ return $p_list;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : properties()
+ // Description :
+ // This method gives the properties of the archive.
+ // The properties are :
+ // nb : Number of files in the archive
+ // comment : Comment associated with the archive file
+ // status : not_exist, ok
+ // Parameters :
+ // None
+ // Return Values :
+ // 0 on failure,
+ // An array with the archive properties.
+ // --------------------------------------------------------------------------------
+ public function properties()
+ {
+
+ // ----- Reset the error handler
+ $this->privErrorReset();
+
+ // ----- Magic quotes trick
+ $this->privDisableMagicQuotes();
+
+ // ----- Check archive
+ if (!$this->privCheckFormat()) {
+ $this->privSwapBackMagicQuotes();
+
+ return (0);
+ }
+
+ // ----- Default properties
+ $v_prop = array();
+ $v_prop['comment'] = '';
+ $v_prop['nb'] = 0;
+ $v_prop['status'] = 'not_exist';
+
+ // ----- Look if file exists
+ if (@is_file($this->zipname)) {
+ // ----- Open the zip file
+ if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) {
+ $this->privSwapBackMagicQuotes();
// ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \'' . $this->zipname . '\' in binary read mode');
+
+ // ----- Return
+ return 0;
+ }
+
+ // ----- Read the central directory informations
+ $v_central_dir = array();
+ if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
+ $this->privSwapBackMagicQuotes();
+
+ return 0;
+ }
+
+ // ----- Close the zip file
+ $this->privCloseFd();
+
+ // ----- Set the user attributes
+ $v_prop['comment'] = $v_central_dir['comment'];
+ $v_prop['nb'] = $v_central_dir['entries'];
+ $v_prop['status'] = 'ok';
+ }
+
+ // ----- Magic quotes trick
+ $this->privSwapBackMagicQuotes();
+
+ // ----- Return
+ return $v_prop;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : duplicate()
+ // Description :
+ // This method creates an archive by copying the content of an other one. If
+ // the archive already exist, it is replaced by the new one without any warning.
+ // Parameters :
+ // $p_archive : The filename of a valid archive, or
+ // a valid PclZip object.
+ // Return Values :
+ // 1 on success.
+ // 0 or a negative value on error (error code).
+ // --------------------------------------------------------------------------------
+ public function duplicate($p_archive)
+ {
+ $v_result = 1;
+
+ // ----- Reset the error handler
+ $this->privErrorReset();
+
+ // ----- Look if the $p_archive is a PclZip object
+ if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) {
+
+ // ----- Duplicate the archive
+ $v_result = $this->privDuplicate($p_archive->zipname);
+
+ // ----- Look if the $p_archive is a string (so a filename)
+ } elseif (is_string($p_archive)) {
+
+ // ----- Check that $p_archive is a valid zip file
+ // TBC : Should also check the archive format
+ if (!is_file($p_archive)) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '" . $p_archive . "'");
+ $v_result = PCLZIP_ERR_MISSING_FILE;
+ } else {
+ // ----- Duplicate the archive
+ $v_result = $this->privDuplicate($p_archive);
+ }
+
+ // ----- Invalid variable
+ } else {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
+ $v_result = PCLZIP_ERR_INVALID_PARAMETER;
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : merge()
+ // Description :
+ // This method merge the $p_archive_to_add archive at the end of the current
+ // one ($this).
+ // If the archive ($this) does not exist, the merge becomes a duplicate.
+ // If the $p_archive_to_add archive does not exist, the merge is a success.
+ // Parameters :
+ // $p_archive_to_add : It can be directly the filename of a valid zip archive,
+ // or a PclZip object archive.
+ // Return Values :
+ // 1 on success,
+ // 0 or negative values on error (see below).
+ // --------------------------------------------------------------------------------
+ public function merge($p_archive_to_add)
+ {
+ $v_result = 1;
+
+ // ----- Reset the error handler
+ $this->privErrorReset();
+
+ // ----- Check archive
+ if (!$this->privCheckFormat()) {
+ return (0);
+ }
+
+ // ----- Look if the $p_archive_to_add is a PclZip object
+ if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) {
+
+ // ----- Merge the archive
+ $v_result = $this->privMerge($p_archive_to_add);
+
+ // ----- Look if the $p_archive_to_add is a string (so a filename)
+ } elseif (is_string($p_archive_to_add)) {
+
+ // ----- Create a temporary archive
+ $v_object_archive = new PclZip($p_archive_to_add);
+
+ // ----- Merge the archive
+ $v_result = $this->privMerge($v_object_archive);
+
+ // ----- Invalid variable
+ } else {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
+ $v_result = PCLZIP_ERR_INVALID_PARAMETER;
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : errorCode()
+ // Description :
+ // Parameters :
+ // --------------------------------------------------------------------------------
+ public function errorCode()
+ {
+ if (PCLZIP_ERROR_EXTERNAL == 1) {
+ return (PclErrorCode());
+ } else {
+ return ($this->error_code);
+ }
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : errorName()
+ // Description :
+ // Parameters :
+ // --------------------------------------------------------------------------------
+ public function errorName($p_with_code = false)
+ {
+ $v_name = array(
+ PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR',
+ PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL',
+ PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL',
+ PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER',
+ PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE',
+ PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG',
+ PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP',
+ PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE',
+ PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL',
+ PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION',
+ PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT',
+ PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL',
+ PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL',
+ PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM',
+ PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP',
+ PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE',
+ PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE',
+ PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION',
+ PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION',
+ PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE',
+ PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION'
+ );
+
+ if (isset($v_name[$this->error_code])) {
+ $v_value = $v_name[$this->error_code];
+ } else {
+ $v_value = 'NoName';
+ }
+
+ if ($p_with_code) {
+ return ($v_value . ' (' . $this->error_code . ')');
+ } else {
+ return ($v_value);
+ }
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : errorInfo()
+ // Description :
+ // Parameters :
+ // --------------------------------------------------------------------------------
+ public function errorInfo($p_full = false)
+ {
+ if (PCLZIP_ERROR_EXTERNAL == 1) {
+ return (PclErrorString());
+ } else {
+ if ($p_full) {
+ return ($this->errorName(true) . " : " . $this->error_string);
+ } else {
+ return ($this->error_string . " [code " . $this->error_code . "]");
+ }
+ }
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
+ // ***** *****
+ // ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY *****
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privCheckFormat()
+ // Description :
+ // This method check that the archive exists and is a valid zip archive.
+ // Several level of check exists. (futur)
+ // Parameters :
+ // $p_level : Level of check. Default 0.
+ // 0 : Check the first bytes (magic codes) (default value))
+ // 1 : 0 + Check the central directory (futur)
+ // 2 : 1 + Check each file header (futur)
+ // Return Values :
+ // true on success,
+ // false on error, the error code is set.
+ // --------------------------------------------------------------------------------
+ public function privCheckFormat($p_level = 0)
+ {
+ $v_result = true;
+
+ // ----- Reset the file system cache
+ clearstatcache();
+
+ // ----- Reset the error handler
+ $this->privErrorReset();
+
+ // ----- Look if the file exits
+ if (!is_file($this->zipname)) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '" . $this->zipname . "'");
+
+ return (false);
+ }
+
+ // ----- Check that the file is readeable
+ if (!is_readable($this->zipname)) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '" . $this->zipname . "'");
+
+ return (false);
+ }
+
+ // ----- Check the magic code
+ // TBC
+
+ // ----- Check the central header
+ // TBC
+
+ // ----- Check each file header
+ // TBC
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privParseOptions()
+ // Description :
+ // This internal methods reads the variable list of arguments ($p_options_list,
+ // $p_size) and generate an array with the options and values ($v_result_list).
+ // $v_requested_options contains the options that can be present and those that
+ // must be present.
+ // $v_requested_options is an array, with the option value as key, and 'optional',
+ // or 'mandatory' as value.
+ // Parameters :
+ // See above.
+ // Return Values :
+ // 1 on success.
+ // 0 on failure.
+ // --------------------------------------------------------------------------------
+ public function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options = false)
+ {
+ $v_result = 1;
+
+ // ----- Read the options
+ $i = 0;
+ while ($i < $p_size) {
+
+ // ----- Check if the option is supported
+ if (!isset($v_requested_options[$p_options_list[$i]])) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '" . $p_options_list[$i] . "' for this method");
// ----- Return
return PclZip::errorCode();
}
- // ----- Read the file header
- $v_local_header = array();
- if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) {
- // ----- Close the zip file
- $this->privCloseFd();
- $v_temp_zip->privCloseFd();
- @unlink($v_zip_temp_name);
+ // ----- Look for next option
+ switch ($p_options_list[$i]) {
+ // ----- Look for options that request a path value
+ case PCLZIP_OPT_PATH:
+ case PCLZIP_OPT_REMOVE_PATH:
+ case PCLZIP_OPT_ADD_PATH:
+ // ----- Check the number of parameters
+ if (($i + 1) >= $p_size) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Get the value
+ $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i + 1], false);
+ $i++;
+ break;
+
+ case PCLZIP_OPT_TEMP_FILE_THRESHOLD:
+ // ----- Check the number of parameters
+ if (($i + 1) >= $p_size) {
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Check for incompatible options
+ if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '" . PclZipUtilOptionText($p_options_list[$i]) . "' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'");
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Check the value
+ $v_value = $p_options_list[$i + 1];
+ if ((!is_integer($v_value)) || ($v_value < 0)) {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Get the value (and convert it in bytes)
+ $v_result_list[$p_options_list[$i]] = $v_value * 1048576;
+ $i++;
+ break;
+
+ case PCLZIP_OPT_TEMP_FILE_ON:
+ // ----- Check for incompatible options
+ if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '" . PclZipUtilOptionText($p_options_list[$i]) . "' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'");
+
+ return PclZip::errorCode();
+ }
+
+ $v_result_list[$p_options_list[$i]] = true;
+ break;
+
+ case PCLZIP_OPT_TEMP_FILE_OFF:
+ // ----- Check for incompatible options
+ if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '" . PclZipUtilOptionText($p_options_list[$i]) . "' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'");
+
+ return PclZip::errorCode();
+ }
+ // ----- Check for incompatible options
+ if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '" . PclZipUtilOptionText($p_options_list[$i]) . "' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'");
+
+ return PclZip::errorCode();
+ }
+
+ $v_result_list[$p_options_list[$i]] = true;
+ break;
+
+ case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION:
+ // ----- Check the number of parameters
+ if (($i + 1) >= $p_size) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Get the value
+ if (is_string($p_options_list[$i + 1]) && ($p_options_list[$i + 1] != '')) {
+ $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i + 1], false);
+ $i++;
+ } else {
+ }
+ break;
+
+ // ----- Look for options that request an array of string for value
+ case PCLZIP_OPT_BY_NAME:
+ // ----- Check the number of parameters
+ if (($i + 1) >= $p_size) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Get the value
+ if (is_string($p_options_list[$i + 1])) {
+ $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i + 1];
+ } elseif (is_array($p_options_list[$i + 1])) {
+ $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1];
+ } else {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+ $i++;
+ break;
+
+ // ----- Look for options that request an EREG or PREG expression
+ case PCLZIP_OPT_BY_EREG:
+ $p_options_list[$i] = PCLZIP_OPT_BY_PREG;
+ // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG
+ // to PCLZIP_OPT_BY_PREG
+ case PCLZIP_OPT_BY_PREG:
+ //case PCLZIP_OPT_CRYPT :
+ // ----- Check the number of parameters
+ if (($i + 1) >= $p_size) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Get the value
+ if (is_string($p_options_list[$i + 1])) {
+ $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1];
+ } else {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+ $i++;
+ break;
+
+ // ----- Look for options that takes a string
+ case PCLZIP_OPT_COMMENT:
+ case PCLZIP_OPT_ADD_COMMENT:
+ case PCLZIP_OPT_PREPEND_COMMENT:
+ // ----- Check the number of parameters
+ if (($i + 1) >= $p_size) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Get the value
+ if (is_string($p_options_list[$i + 1])) {
+ $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1];
+ } else {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+ $i++;
+ break;
+
+ // ----- Look for options that request an array of index
+ case PCLZIP_OPT_BY_INDEX:
+ // ----- Check the number of parameters
+ if (($i + 1) >= $p_size) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Get the value
+ $v_work_list = array();
+ if (is_string($p_options_list[$i + 1])) {
+
+ // ----- Remove spaces
+ $p_options_list[$i + 1] = strtr($p_options_list[$i + 1], ' ', '');
+
+ // ----- Parse items
+ $v_work_list = explode(",", $p_options_list[$i + 1]);
+ } elseif (is_integer($p_options_list[$i + 1])) {
+ $v_work_list[0] = $p_options_list[$i + 1] . '-' . $p_options_list[$i + 1];
+ } elseif (is_array($p_options_list[$i + 1])) {
+ $v_work_list = $p_options_list[$i + 1];
+ } else {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Reduce the index list
+ // each index item in the list must be a couple with a start and
+ // an end value : [0,3], [5-5], [8-10], ...
+ // ----- Check the format of each item
+ $v_sort_flag = false;
+ $v_sort_value = 0;
+ for ($j = 0; $j < sizeof($v_work_list); $j++) {
+ // ----- Explode the item
+ $v_item_list = explode("-", $v_work_list[$j]);
+ $v_size_item_list = sizeof($v_item_list);
+
+ // ----- TBC : Here we might check that each item is a
+ // real integer ...
+
+ // ----- Look for single value
+ if ($v_size_item_list == 1) {
+ // ----- Set the option value
+ $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
+ $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[0];
+ } elseif ($v_size_item_list == 2) {
+ // ----- Set the option value
+ $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
+ $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[1];
+ } else {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Too many values in index range for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Look for list sort
+ if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) {
+ $v_sort_flag = true;
+
+ // ----- TBC : An automatic sort should be writen ...
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Invalid order of index range for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+ $v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start'];
+ }
+
+ // ----- Sort the items
+ if ($v_sort_flag) {
+ // TBC : To Be Completed
+ }
+
+ // ----- Next option
+ $i++;
+ break;
+
+ // ----- Look for options that request no value
+ case PCLZIP_OPT_REMOVE_ALL_PATH:
+ case PCLZIP_OPT_EXTRACT_AS_STRING:
+ case PCLZIP_OPT_NO_COMPRESSION:
+ case PCLZIP_OPT_EXTRACT_IN_OUTPUT:
+ case PCLZIP_OPT_REPLACE_NEWER:
+ case PCLZIP_OPT_STOP_ON_ERROR:
+ $v_result_list[$p_options_list[$i]] = true;
+ break;
+
+ // ----- Look for options that request an octal value
+ case PCLZIP_OPT_SET_CHMOD:
+ // ----- Check the number of parameters
+ if (($i + 1) >= $p_size) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Get the value
+ $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1];
+ $i++;
+ break;
+
+ // ----- Look for options that request a call-back
+ case PCLZIP_CB_PRE_EXTRACT:
+ case PCLZIP_CB_POST_EXTRACT:
+ case PCLZIP_CB_PRE_ADD:
+ case PCLZIP_CB_POST_ADD:
+ /* for futur use
+ case PCLZIP_CB_PRE_DELETE :
+ case PCLZIP_CB_POST_DELETE :
+ case PCLZIP_CB_PRE_LIST :
+ case PCLZIP_CB_POST_LIST :
+ */
+ // ----- Check the number of parameters
+ if (($i + 1) >= $p_size) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Get the value
+ $v_function_name = $p_options_list[$i + 1];
+
+ // ----- Check that the value is a valid existing function
+ if (!function_exists($v_function_name)) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '" . $v_function_name . "()' is not an existing function for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Set the attribute
+ $v_result_list[$p_options_list[$i]] = $v_function_name;
+ $i++;
+ break;
+
+ default:
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '" . $p_options_list[$i] . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Next options
+ $i++;
+ }
+
+ // ----- Look for mandatory options
+ if ($v_requested_options !== false) {
+ for ($key = reset($v_requested_options); $key = key($v_requested_options); $key = next($v_requested_options)) {
+ // ----- Look for mandatory option
+ if ($v_requested_options[$key] == 'mandatory') {
+ // ----- Look if present
+ if (!isset($v_result_list[$key])) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter " . PclZipUtilOptionText($key) . "(" . $key . ")");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+ }
+ }
+ }
+
+ // ----- Look for default values
+ if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
+
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privOptionDefaultThreshold()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privOptionDefaultThreshold(&$p_options)
+ {
+ $v_result = 1;
+
+ if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) {
+ return $v_result;
+ }
+
+ // ----- Get 'memory_limit' configuration value
+ $v_memory_limit = ini_get('memory_limit');
+ $v_memory_limit = trim($v_memory_limit);
+ $last = strtolower(substr($v_memory_limit, -1));
+ $v_memory_limit = preg_replace('/\s*[KkMmGg]$/', '', $v_memory_limit);
+
+ if ($last == 'g') {
+ //$v_memory_limit = $v_memory_limit*1024*1024*1024;
+ $v_memory_limit = $v_memory_limit * 1073741824;
+ }
+ if ($last == 'm') {
+ //$v_memory_limit = $v_memory_limit*1024*1024;
+ $v_memory_limit = $v_memory_limit * 1048576;
+ }
+ if ($last == 'k') {
+ $v_memory_limit = $v_memory_limit * 1024;
+ }
+
+ $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit * PCLZIP_TEMPORARY_FILE_RATIO);
+
+ // ----- Sanity check : No threshold if value lower than 1M
+ if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) {
+ unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]);
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privFileDescrParseAtt()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // 1 on success.
+ // 0 on failure.
+ // --------------------------------------------------------------------------------
+ public function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options = false)
+ {
+ $v_result = 1;
+
+ // ----- For each file in the list check the attributes
+ foreach ($p_file_list as $v_key => $v_value) {
+
+ // ----- Check if the option is supported
+ if (!isset($v_requested_options[$v_key])) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '" . $v_key . "' for this file");
// ----- Return
- return $v_result;
+ return PclZip::errorCode();
}
-
- // ----- Check that local file header is same as central file header
- if ($this->privCheckFileHeaders($v_local_header,
- $v_header_list[$i]) != 1) {
- // TBC
- }
- unset($v_local_header);
- // ----- Write the file header
- if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) {
- // ----- Close the zip file
- $this->privCloseFd();
- $v_temp_zip->privCloseFd();
- @unlink($v_zip_temp_name);
+ // ----- Look for attribute
+ switch ($v_key) {
+ case PCLZIP_ATT_FILE_NAME:
+ if (!is_string($v_value)) {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type " . gettype($v_value) . ". String expected for attribute '" . PclZipUtilOptionText($v_key) . "'");
+
+ return PclZip::errorCode();
+ }
+
+ $p_filedescr['filename'] = PclZipUtilPathReduction($v_value);
+
+ if ($p_filedescr['filename'] == '') {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '" . PclZipUtilOptionText($v_key) . "'");
+
+ return PclZip::errorCode();
+ }
+
+ break;
+
+ case PCLZIP_ATT_FILE_NEW_SHORT_NAME:
+ if (!is_string($v_value)) {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type " . gettype($v_value) . ". String expected for attribute '" . PclZipUtilOptionText($v_key) . "'");
+
+ return PclZip::errorCode();
+ }
+
+ $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value);
+
+ if ($p_filedescr['new_short_name'] == '') {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '" . PclZipUtilOptionText($v_key) . "'");
+
+ return PclZip::errorCode();
+ }
+ break;
+
+ case PCLZIP_ATT_FILE_NEW_FULL_NAME:
+ if (!is_string($v_value)) {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type " . gettype($v_value) . ". String expected for attribute '" . PclZipUtilOptionText($v_key) . "'");
+
+ return PclZip::errorCode();
+ }
+
+ $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value);
+
+ if ($p_filedescr['new_full_name'] == '') {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '" . PclZipUtilOptionText($v_key) . "'");
+
+ return PclZip::errorCode();
+ }
+ break;
+
+ // ----- Look for options that takes a string
+ case PCLZIP_ATT_FILE_COMMENT:
+ if (!is_string($v_value)) {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type " . gettype($v_value) . ". String expected for attribute '" . PclZipUtilOptionText($v_key) . "'");
+
+ return PclZip::errorCode();
+ }
+
+ $p_filedescr['comment'] = $v_value;
+ break;
+
+ case PCLZIP_ATT_FILE_MTIME:
+ if (!is_integer($v_value)) {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type " . gettype($v_value) . ". Integer expected for attribute '" . PclZipUtilOptionText($v_key) . "'");
+
+ return PclZip::errorCode();
+ }
+
+ $p_filedescr['mtime'] = $v_value;
+ break;
+
+ case PCLZIP_ATT_FILE_CONTENT:
+ $p_filedescr['content'] = $v_value;
+ break;
+
+ default:
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '" . $v_key . "'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Look for mandatory options
+ if ($v_requested_options !== false) {
+ for ($key = reset($v_requested_options); $key = key($v_requested_options); $key = next($v_requested_options)) {
+ // ----- Look for mandatory option
+ if ($v_requested_options[$key] == 'mandatory') {
+ // ----- Look if present
+ if (!isset($p_file_list[$key])) {
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter " . PclZipUtilOptionText($key) . "(" . $key . ")");
+
+ return PclZip::errorCode();
+ }
+ }
+ }
+ }
+
+ // end foreach
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privFileDescrExpand()
+ // Description :
+ // This method look for each item of the list to see if its a file, a folder
+ // or a string to be added as file. For any other type of files (link, other)
+ // just ignore the item.
+ // Then prepare the information that will be stored for that file.
+ // When its a folder, expand the folder with all the files that are in that
+ // folder (recursively).
+ // Parameters :
+ // Return Values :
+ // 1 on success.
+ // 0 on failure.
+ // --------------------------------------------------------------------------------
+ public function privFileDescrExpand(&$p_filedescr_list, &$p_options)
+ {
+ $v_result = 1;
+
+ // ----- Create a result list
+ $v_result_list = array();
+
+ // ----- Look each entry
+ for ($i = 0; $i < sizeof($p_filedescr_list); $i++) {
+
+ // ----- Get filedescr
+ $v_descr = $p_filedescr_list[$i];
+
+ // ----- Reduce the filename
+ $v_descr['filename'] = PclZipUtilTranslateWinPath($v_descr['filename'], false);
+ $v_descr['filename'] = PclZipUtilPathReduction($v_descr['filename']);
+
+ // ----- Look for real file or folder
+ if (file_exists($v_descr['filename'])) {
+ if (@is_file($v_descr['filename'])) {
+ $v_descr['type'] = 'file';
+ } elseif (@is_dir($v_descr['filename'])) {
+ $v_descr['type'] = 'folder';
+ } elseif (@is_link($v_descr['filename'])) {
+ // skip
+ continue;
+ } else {
+ // skip
+ continue;
+ }
+
+ // ----- Look for string added as file
+ } elseif (isset($v_descr['content'])) {
+ $v_descr['type'] = 'virtual_file';
+
+ // ----- Missing file
+ } else {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '" . $v_descr['filename'] . "' does not exist");
// ----- Return
- return $v_result;
+ return PclZip::errorCode();
}
- // ----- Read/write the data block
- if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) {
- // ----- Close the zip file
- $this->privCloseFd();
- $v_temp_zip->privCloseFd();
- @unlink($v_zip_temp_name);
+ // ----- Calculate the stored filename
+ $this->privCalculateStoredFilename($v_descr, $p_options);
- // ----- Return
- return $v_result;
+ // ----- Add the descriptor in result list
+ $v_result_list[sizeof($v_result_list)] = $v_descr;
+
+ // ----- Look for folder
+ if ($v_descr['type'] == 'folder') {
+ // ----- List of items in folder
+ $v_dirlist_descr = array();
+ $v_dirlist_nb = 0;
+ if ($v_folder_handler = @opendir($v_descr['filename'])) {
+ while (($v_item_handler = @readdir($v_folder_handler)) !== false) {
+
+ // ----- Skip '.' and '..'
+ if (($v_item_handler == '.') || ($v_item_handler == '..')) {
+ continue;
+ }
+
+ // ----- Compose the full filename
+ $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'] . '/' . $v_item_handler;
+
+ // ----- Look for different stored filename
+ // Because the name of the folder was changed, the name of the
+ // files/sub-folders also change
+ if (($v_descr['stored_filename'] != $v_descr['filename']) && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) {
+ if ($v_descr['stored_filename'] != '') {
+ $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'] . '/' . $v_item_handler;
+ } else {
+ $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler;
+ }
+ }
+
+ $v_dirlist_nb++;
+ }
+
+ @closedir($v_folder_handler);
+ } else {
+ // TBC : unable to open folder in read mode
+ }
+
+ // ----- Expand each element of the list
+ if ($v_dirlist_nb != 0) {
+ // ----- Expand
+ if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) {
+ return $v_result;
+ }
+
+ // ----- Concat the resulting list
+ $v_result_list = array_merge($v_result_list, $v_dirlist_descr);
+ } else {
+ }
+
+ // ----- Free local array
+ unset($v_dirlist_descr);
}
}
+ // ----- Get the result list
+ $p_filedescr_list = $v_result_list;
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privCreate()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privCreate($p_filedescr_list, &$p_result_list, &$p_options)
+ {
+ $v_result = 1;
+ $v_list_detail = array();
+
+ // ----- Magic quotes trick
+ $this->privDisableMagicQuotes();
+
+ // ----- Open the file in write mode
+ if (($v_result = $this->privOpenFd('wb')) != 1) {
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Add the list of files
+ $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options);
+
+ // ----- Close
+ $this->privCloseFd();
+
+ // ----- Magic quotes trick
+ $this->privSwapBackMagicQuotes();
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privAdd()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privAdd($p_filedescr_list, &$p_result_list, &$p_options)
+ {
+ $v_result = 1;
+ $v_list_detail = array();
+
+ // ----- Look if the archive exists or is empty
+ if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) {
+
+ // ----- Do a create
+ $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options);
+
+ // ----- Return
+ return $v_result;
+ }
+ // ----- Magic quotes trick
+ $this->privDisableMagicQuotes();
+
+ // ----- Open the zip file
+ if (($v_result = $this->privOpenFd('rb')) != 1) {
+ // ----- Magic quotes trick
+ $this->privSwapBackMagicQuotes();
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Read the central directory informations
+ $v_central_dir = array();
+ if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result;
+ }
+
+ // ----- Go to beginning of File
+ @rewind($this->zip_fd);
+
+ // ----- Creates a temporay file
+ $v_zip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.tmp';
+
+ // ----- Open the temporary file in write mode
+ if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) {
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_zip_temp_name . '\' in binary write mode');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Copy the files from the archive to the temporary file
+ // TBC : Here I should better append the file and go back to erase the central dir
+ $v_size = $v_central_dir['offset'];
+ while ($v_size != 0) {
+ $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = fread($this->zip_fd, $v_read_size);
+ @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
+ $v_size -= $v_read_size;
+ }
+
+ // ----- Swap the file descriptor
+ // Here is a trick : I swap the temporary fd with the zip fd, in order to use
+ // the following methods on the temporary fil and not the real archive
+ $v_swap = $this->zip_fd;
+ $this->zip_fd = $v_zip_temp_fd;
+ $v_zip_temp_fd = $v_swap;
+
+ // ----- Add the files
+ $v_header_list = array();
+ if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) {
+ fclose($v_zip_temp_fd);
+ $this->privCloseFd();
+ @unlink($v_zip_temp_name);
+ $this->privSwapBackMagicQuotes();
+
+ // ----- Return
+ return $v_result;
+ }
+
// ----- Store the offset of the central dir
- $v_offset = @ftell($v_temp_zip->zip_fd);
+ $v_offset = @ftell($this->zip_fd);
- // ----- Re-Create the Central Dir files header
- for ($i=0; $izip_fd, $v_buffer, $v_read_size);
+ $v_size -= $v_read_size;
+ }
+
+ // ----- Create the Central Dir files header
+ for ($i = 0, $v_count = 0; $i < sizeof($v_header_list); $i++) {
// ----- Create the file header
- if (($v_result = $v_temp_zip->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
- $v_temp_zip->privCloseFd();
- $this->privCloseFd();
- @unlink($v_zip_temp_name);
+ if ($v_header_list[$i]['status'] == 'ok') {
+ if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
+ fclose($v_zip_temp_fd);
+ $this->privCloseFd();
+ @unlink($v_zip_temp_name);
+ $this->privSwapBackMagicQuotes();
- // ----- Return
- return $v_result;
+ // ----- Return
+ return $v_result;
+ }
+ $v_count++;
}
// ----- Transform the header to a 'usable' info
- $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
+ $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
-
// ----- Zip file comment
- $v_comment = '';
+ $v_comment = $v_central_dir['comment'];
if (isset($p_options[PCLZIP_OPT_COMMENT])) {
- $v_comment = $p_options[PCLZIP_OPT_COMMENT];
+ $v_comment = $p_options[PCLZIP_OPT_COMMENT];
+ }
+ if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) {
+ $v_comment = $v_comment . $p_options[PCLZIP_OPT_ADD_COMMENT];
+ }
+ if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) {
+ $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT] . $v_comment;
}
// ----- Calculate the size of the central header
- $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset;
+ $v_size = @ftell($this->zip_fd) - $v_offset;
// ----- Create the central dir footer
- if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) {
+ if (($v_result = $this->privWriteCentralHeader($v_count + $v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) {
// ----- Reset the file list
unset($v_header_list);
- $v_temp_zip->privCloseFd();
- $this->privCloseFd();
- @unlink($v_zip_temp_name);
+ $this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
+ // ----- Swap back the file descriptor
+ $v_swap = $this->zip_fd;
+ $this->zip_fd = $v_zip_temp_fd;
+ $v_zip_temp_fd = $v_swap;
+
// ----- Close
- $v_temp_zip->privCloseFd();
$this->privCloseFd();
+ // ----- Close the temporary file
+ @fclose($v_zip_temp_fd);
+
+ // ----- Magic quotes trick
+ $this->privSwapBackMagicQuotes();
+
// ----- Delete the zip file
// TBC : I should test the result ...
@unlink($this->zipname);
@@ -4952,545 +2268,2965 @@
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
PclZipUtilRename($v_zip_temp_name, $this->zipname);
-
- // ----- Destroy the temporary archive
- unset($v_temp_zip);
+
+ // ----- Return
+ return $v_result;
}
-
- // ----- Remove every files : reset the file
- else if ($v_central_dir['entries'] != 0) {
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privOpenFd()
+ // Description :
+ // Parameters :
+ // --------------------------------------------------------------------------------
+ public function privOpenFd($p_mode)
+ {
+ $v_result = 1;
+
+ // ----- Look if already open
+ if ($this->zip_fd != 0) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \'' . $this->zipname . '\' already open');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Open the zip file
+ if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \'' . $this->zipname . '\' in ' . $p_mode . ' mode');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privCloseFd()
+ // Description :
+ // Parameters :
+ // --------------------------------------------------------------------------------
+ public function privCloseFd()
+ {
+ $v_result = 1;
+
+ if ($this->zip_fd != 0) {
+ @fclose($this->zip_fd);
+ }
+ $this->zip_fd = 0;
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privAddList()
+ // Description :
+ // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is
+ // different from the real path of the file. This is usefull if you want to have PclTar
+ // running in any directory, and memorize relative path from an other directory.
+ // Parameters :
+ // $p_list : An array containing the file or directory names to add in the tar
+ // $p_result_list : list of added files with their properties (specially the status field)
+ // $p_add_dir : Path to add in the filename path archived
+ // $p_remove_dir : Path to remove in the filename path archived
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ // function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options)
+ public function privAddList($p_filedescr_list, &$p_result_list, &$p_options)
+ {
+ $v_result = 1;
+
+ // ----- Add the files
+ $v_header_list = array();
+ if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) {
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Store the offset of the central dir
+ $v_offset = @ftell($this->zip_fd);
+
+ // ----- Create the Central Dir files header
+ for ($i = 0, $v_count = 0; $i < sizeof($v_header_list); $i++) {
+ // ----- Create the file header
+ if ($v_header_list[$i]['status'] == 'ok') {
+ if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
+ // ----- Return
+ return $v_result;
+ }
+ $v_count++;
+ }
+
+ // ----- Transform the header to a 'usable' info
+ $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
+ }
+
+ // ----- Zip file comment
+ $v_comment = '';
+ if (isset($p_options[PCLZIP_OPT_COMMENT])) {
+ $v_comment = $p_options[PCLZIP_OPT_COMMENT];
+ }
+
+ // ----- Calculate the size of the central header
+ $v_size = @ftell($this->zip_fd) - $v_offset;
+
+ // ----- Create the central dir footer
+ if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) {
+ // ----- Reset the file list
+ unset($v_header_list);
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privAddFileList()
+ // Description :
+ // Parameters :
+ // $p_filedescr_list : An array containing the file description
+ // or directory names to add in the zip
+ // $p_result_list : list of added files with their properties (specially the status field)
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options)
+ {
+ $v_result = 1;
+ $v_header = array();
+
+ // ----- Recuperate the current number of elt in list
+ $v_nb = sizeof($p_result_list);
+
+ // ----- Loop on the files
+ for ($j = 0; ($j < sizeof($p_filedescr_list)) && ($v_result == 1); $j++) {
+ // ----- Format the filename
+ $p_filedescr_list[$j]['filename'] = PclZipUtilTranslateWinPath($p_filedescr_list[$j]['filename'], false);
+
+ // ----- Skip empty file names
+ // TBC : Can this be possible ? not checked in DescrParseAtt ?
+ if ($p_filedescr_list[$j]['filename'] == "") {
+ continue;
+ }
+
+ // ----- Check the filename
+ if (($p_filedescr_list[$j]['type'] != 'virtual_file') && (!file_exists($p_filedescr_list[$j]['filename']))) {
+ PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '" . $p_filedescr_list[$j]['filename'] . "' does not exist");
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Look if it is a file or a dir with no all path remove option
+ // or a dir with all its path removed
+ // if ( (is_file($p_filedescr_list[$j]['filename']))
+ // || ( is_dir($p_filedescr_list[$j]['filename'])
+ if (($p_filedescr_list[$j]['type'] == 'file') || ($p_filedescr_list[$j]['type'] == 'virtual_file') || (($p_filedescr_list[$j]['type'] == 'folder') && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]) || !$p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) {
+
+ // ----- Add the file
+ $v_result = $this->privAddFile($p_filedescr_list[$j], $v_header, $p_options);
+ if ($v_result != 1) {
+ return $v_result;
+ }
+
+ // ----- Store the file infos
+ $p_result_list[$v_nb++] = $v_header;
+ }
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privAddFile()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privAddFile($p_filedescr, &$p_header, &$p_options)
+ {
+ $v_result = 1;
+
+ // ----- Working variable
+ $p_filename = $p_filedescr['filename'];
+
+ // TBC : Already done in the fileAtt check ... ?
+ if ($p_filename == "") {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Look for a stored different filename
+ /* TBC : Removed
+ if (isset($p_filedescr['stored_filename'])) {
+ $v_stored_filename = $p_filedescr['stored_filename'];
+ } else {
+ $v_stored_filename = $p_filedescr['stored_filename'];
+ }
+ */
+
+ // ----- Set the file properties
+ clearstatcache();
+ $p_header['version'] = 20;
+ $p_header['version_extracted'] = 10;
+ $p_header['flag'] = 0;
+ $p_header['compression'] = 0;
+ $p_header['crc'] = 0;
+ $p_header['compressed_size'] = 0;
+ $p_header['filename_len'] = strlen($p_filename);
+ $p_header['extra_len'] = 0;
+ $p_header['disk'] = 0;
+ $p_header['internal'] = 0;
+ $p_header['offset'] = 0;
+ $p_header['filename'] = $p_filename;
+ // TBC : Removed $p_header['stored_filename'] = $v_stored_filename;
+ $p_header['stored_filename'] = $p_filedescr['stored_filename'];
+ $p_header['extra'] = '';
+ $p_header['status'] = 'ok';
+ $p_header['index'] = -1;
+
+ // ----- Look for regular file
+ if ($p_filedescr['type'] == 'file') {
+ $p_header['external'] = 0x00000000;
+ $p_header['size'] = filesize($p_filename);
+
+ // ----- Look for regular folder
+ } elseif ($p_filedescr['type'] == 'folder') {
+ $p_header['external'] = 0x00000010;
+ $p_header['mtime'] = filemtime($p_filename);
+ $p_header['size'] = filesize($p_filename);
+
+ // ----- Look for virtual file
+ } elseif ($p_filedescr['type'] == 'virtual_file') {
+ $p_header['external'] = 0x00000000;
+ $p_header['size'] = strlen($p_filedescr['content']);
+ }
+
+ // ----- Look for filetime
+ if (isset($p_filedescr['mtime'])) {
+ $p_header['mtime'] = $p_filedescr['mtime'];
+ } elseif ($p_filedescr['type'] == 'virtual_file') {
+ $p_header['mtime'] = time();
+ } else {
+ $p_header['mtime'] = filemtime($p_filename);
+ }
+
+ // ------ Look for file comment
+ if (isset($p_filedescr['comment'])) {
+ $p_header['comment_len'] = strlen($p_filedescr['comment']);
+ $p_header['comment'] = $p_filedescr['comment'];
+ } else {
+ $p_header['comment_len'] = 0;
+ $p_header['comment'] = '';
+ }
+
+ // ----- Look for pre-add callback
+ if (isset($p_options[PCLZIP_CB_PRE_ADD])) {
+
+ // ----- Generate a local information
+ $v_local_header = array();
+ $this->privConvertHeader2FileInfo($p_header, $v_local_header);
+
+ // ----- Call the callback
+ // Here I do not use call_user_func() because I need to send a reference to the
+ // header.
+ // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);');
+ $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header);
+ if ($v_result == 0) {
+ // ----- Change the file status
+ $p_header['status'] = "skipped";
+ $v_result = 1;
+ }
+
+ // ----- Update the informations
+ // Only some fields can be modified
+ if ($p_header['stored_filename'] != $v_local_header['stored_filename']) {
+ $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']);
+ }
+ }
+
+ // ----- Look for empty stored filename
+ if ($p_header['stored_filename'] == "") {
+ $p_header['status'] = "filtered";
+ }
+
+ // ----- Check the path length
+ if (strlen($p_header['stored_filename']) > 0xFF) {
+ $p_header['status'] = 'filename_too_long';
+ }
+
+ // ----- Look if no error, or file not skipped
+ if ($p_header['status'] == 'ok') {
+
+ // ----- Look for a file
+ if ($p_filedescr['type'] == 'file') {
+ // ----- Look for using temporary file to zip
+ if ((!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])))) {
+ $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options);
+ if ($v_result < PCLZIP_ERR_NO_ERROR) {
+ return $v_result;
+ }
+
+ // ----- Use "in memory" zip algo
+ } else {
+
+ // ----- Open the source file
+ if (($v_file = @fopen($p_filename, "rb")) == 0) {
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Read the file content
+ $v_content = @fread($v_file, $p_header['size']);
+
+ // ----- Close the file
+ @fclose($v_file);
+
+ // ----- Calculate the CRC
+ $p_header['crc'] = @crc32($v_content);
+
+ // ----- Look for no compression
+ if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {
+ // ----- Set header parameters
+ $p_header['compressed_size'] = $p_header['size'];
+ $p_header['compression'] = 0;
+
+ // ----- Look for normal compression
+ } else {
+ // ----- Compress the content
+ $v_content = @gzdeflate($v_content);
+
+ // ----- Set header parameters
+ $p_header['compressed_size'] = strlen($v_content);
+ $p_header['compression'] = 8;
+ }
+
+ // ----- Call the header generation
+ if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
+ @fclose($v_file);
+
+ return $v_result;
+ }
+
+ // ----- Write the compressed (or not) content
+ @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
+
+ }
+
+ // ----- Look for a virtual file (a file from string)
+ } elseif ($p_filedescr['type'] == 'virtual_file') {
+
+ $v_content = $p_filedescr['content'];
+
+ // ----- Calculate the CRC
+ $p_header['crc'] = @crc32($v_content);
+
+ // ----- Look for no compression
+ if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {
+ // ----- Set header parameters
+ $p_header['compressed_size'] = $p_header['size'];
+ $p_header['compression'] = 0;
+
+ // ----- Look for normal compression
+ } else {
+ // ----- Compress the content
+ $v_content = @gzdeflate($v_content);
+
+ // ----- Set header parameters
+ $p_header['compressed_size'] = strlen($v_content);
+ $p_header['compression'] = 8;
+ }
+
+ // ----- Call the header generation
+ if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
+ @fclose($v_file);
+
+ return $v_result;
+ }
+
+ // ----- Write the compressed (or not) content
+ @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
+
+ // ----- Look for a directory
+ } elseif ($p_filedescr['type'] == 'folder') {
+ // ----- Look for directory last '/'
+ if (@substr($p_header['stored_filename'], -1) != '/') {
+ $p_header['stored_filename'] .= '/';
+ }
+
+ // ----- Set the file properties
+ $p_header['size'] = 0;
+ //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked
+ $p_header['external'] = 0x00000010; // Value for a folder : to be checked
+
+ // ----- Call the header generation
+ if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
+ return $v_result;
+ }
+ }
+ }
+
+ // ----- Look for post-add callback
+ if (isset($p_options[PCLZIP_CB_POST_ADD])) {
+
+ // ----- Generate a local information
+ $v_local_header = array();
+ $this->privConvertHeader2FileInfo($p_header, $v_local_header);
+
+ // ----- Call the callback
+ // Here I do not use call_user_func() because I need to send a reference to the
+ // header.
+ // eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);');
+ $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header);
+ if ($v_result == 0) {
+ // ----- Ignored
+ $v_result = 1;
+ }
+
+ // ----- Update the informations
+ // Nothing can be modified
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privAddFileUsingTempFile()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options)
+ {
+ $v_result = PCLZIP_ERR_NO_ERROR;
+
+ // ----- Working variable
+ $p_filename = $p_filedescr['filename'];
+
+ // ----- Open the source file
+ if (($v_file = @fopen($p_filename, "rb")) == 0) {
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Creates a compressed temporary file
+ $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.gz';
+ if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) {
+ fclose($v_file);
+ PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary write mode');
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
+ $v_size = filesize($p_filename);
+ while ($v_size != 0) {
+ $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = @fread($v_file, $v_read_size);
+ //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
+ @gzputs($v_file_compressed, $v_buffer, $v_read_size);
+ $v_size -= $v_read_size;
+ }
+
+ // ----- Close the file
+ @fclose($v_file);
+ @gzclose($v_file_compressed);
+
+ // ----- Check the minimum file size
+ if (filesize($v_gzip_temp_name) < 18) {
+ PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \'' . $v_gzip_temp_name . '\' has invalid filesize - should be minimum 18 bytes');
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Extract the compressed attributes
+ if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) {
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary read mode');
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Read the gzip file header
+ $v_binary_data = @fread($v_file_compressed, 10);
+ $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data);
+
+ // ----- Check some parameters
+ $v_data_header['os'] = bin2hex($v_data_header['os']);
+
+ // ----- Read the gzip file footer
+ @fseek($v_file_compressed, filesize($v_gzip_temp_name) - 8);
+ $v_binary_data = @fread($v_file_compressed, 8);
+ $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data);
+
+ // ----- Set the attributes
+ $p_header['compression'] = ord($v_data_header['cm']);
+ //$p_header['mtime'] = $v_data_header['mtime'];
+ $p_header['crc'] = $v_data_footer['crc'];
+ $p_header['compressed_size'] = filesize($v_gzip_temp_name) - 18;
+
+ // ----- Close the file
+ @fclose($v_file_compressed);
+
+ // ----- Call the header generation
+ if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
+ return $v_result;
+ }
+
+ // ----- Add the compressed data
+ if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) {
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary read mode');
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
+ fseek($v_file_compressed, 10);
+ $v_size = $p_header['compressed_size'];
+ while ($v_size != 0) {
+ $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = @fread($v_file_compressed, $v_read_size);
+ //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
+ @fwrite($this->zip_fd, $v_buffer, $v_read_size);
+ $v_size -= $v_read_size;
+ }
+
+ // ----- Close the file
+ @fclose($v_file_compressed);
+
+ // ----- Unlink the temporary file
+ @unlink($v_gzip_temp_name);
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privCalculateStoredFilename()
+ // Description :
+ // Based on file descriptor properties and global options, this method
+ // calculate the filename that will be stored in the archive.
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privCalculateStoredFilename(&$p_filedescr, &$p_options)
+ {
+ $v_result = 1;
+
+ // ----- Working variables
+ $p_filename = $p_filedescr['filename'];
+ if (isset($p_options[PCLZIP_OPT_ADD_PATH])) {
+ $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH];
+ } else {
+ $p_add_dir = '';
+ }
+ if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) {
+ $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH];
+ } else {
+ $p_remove_dir = '';
+ }
+ if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
+ $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH];
+ } else {
+ $p_remove_all_dir = 0;
+ }
+
+ // ----- Look for full name change
+ if (isset($p_filedescr['new_full_name'])) {
+ // ----- Remove drive letter if any
+ $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']);
+
+ // ----- Look for path and/or short name change
+ } else {
+
+ // ----- Look for short name change
+ // Its when we cahnge just the filename but not the path
+ if (isset($p_filedescr['new_short_name'])) {
+ $v_path_info = pathinfo($p_filename);
+ $v_dir = '';
+ if ($v_path_info['dirname'] != '') {
+ $v_dir = $v_path_info['dirname'] . '/';
+ }
+ $v_stored_filename = $v_dir . $p_filedescr['new_short_name'];
+ } else {
+ // ----- Calculate the stored filename
+ $v_stored_filename = $p_filename;
+ }
+
+ // ----- Look for all path to remove
+ if ($p_remove_all_dir) {
+ $v_stored_filename = basename($p_filename);
+
+ // ----- Look for partial path remove
+ } elseif ($p_remove_dir != "") {
+ if (substr($p_remove_dir, -1) != '/') {
+ $p_remove_dir .= "/";
+ }
+
+ if ((substr($p_filename, 0, 2) == "./") || (substr($p_remove_dir, 0, 2) == "./")) {
+
+ if ((substr($p_filename, 0, 2) == "./") && (substr($p_remove_dir, 0, 2) != "./")) {
+ $p_remove_dir = "./" . $p_remove_dir;
+ }
+ if ((substr($p_filename, 0, 2) != "./") && (substr($p_remove_dir, 0, 2) == "./")) {
+ $p_remove_dir = substr($p_remove_dir, 2);
+ }
+ }
+
+ $v_compare = PclZipUtilPathInclusion($p_remove_dir, $v_stored_filename);
+ if ($v_compare > 0) {
+ if ($v_compare == 2) {
+ $v_stored_filename = "";
+ } else {
+ $v_stored_filename = substr($v_stored_filename, strlen($p_remove_dir));
+ }
+ }
+ }
+
+ // ----- Remove drive letter if any
+ $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename);
+
+ // ----- Look for path to add
+ if ($p_add_dir != "") {
+ if (substr($p_add_dir, -1) == "/") {
+ $v_stored_filename = $p_add_dir . $v_stored_filename;
+ } else {
+ $v_stored_filename = $p_add_dir . "/" . $v_stored_filename;
+ }
+ }
+ }
+
+ // ----- Filename (reduce the path of stored name)
+ $v_stored_filename = PclZipUtilPathReduction($v_stored_filename);
+ $p_filedescr['stored_filename'] = $v_stored_filename;
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privWriteFileHeader()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privWriteFileHeader(&$p_header)
+ {
+ $v_result = 1;
+
+ // ----- Store the offset position of the file
+ $p_header['offset'] = ftell($this->zip_fd);
+
+ // ----- Transform UNIX mtime to DOS format mdate/mtime
+ $v_date = getdate($p_header['mtime']);
+ $v_mtime = ($v_date['hours'] << 11) + ($v_date['minutes'] << 5) + $v_date['seconds'] / 2;
+ $v_mdate = (($v_date['year'] - 1980) << 9) + ($v_date['mon'] << 5) + $v_date['mday'];
+
+ // ----- Packed data
+ $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len']);
+
+ // ----- Write the first 148 bytes of the header in the archive
+ fputs($this->zip_fd, $v_binary_data, 30);
+
+ // ----- Write the variable fields
+ if (strlen($p_header['stored_filename']) != 0) {
+ fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
+ }
+ if ($p_header['extra_len'] != 0) {
+ fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privWriteCentralFileHeader()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privWriteCentralFileHeader(&$p_header)
+ {
+ $v_result = 1;
+
+ // TBC
+ //for (reset($p_header); $key = key($p_header); next($p_header)) {
+ //}
+
+ // ----- Transform UNIX mtime to DOS format mdate/mtime
+ $v_date = getdate($p_header['mtime']);
+ $v_mtime = ($v_date['hours'] << 11) + ($v_date['minutes'] << 5) + $v_date['seconds'] / 2;
+ $v_mdate = (($v_date['year'] - 1980) << 9) + ($v_date['mon'] << 5) + $v_date['mday'];
+
+ // ----- Packed data
+ $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, $p_header['version'], $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len'], $p_header['comment_len'], $p_header['disk'], $p_header['internal'], $p_header['external'], $p_header['offset']);
+
+ // ----- Write the 42 bytes of the header in the zip file
+ fputs($this->zip_fd, $v_binary_data, 46);
+
+ // ----- Write the variable fields
+ if (strlen($p_header['stored_filename']) != 0) {
+ fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
+ }
+ if ($p_header['extra_len'] != 0) {
+ fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
+ }
+ if ($p_header['comment_len'] != 0) {
+ fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']);
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privWriteCentralHeader()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment)
+ {
+ $v_result = 1;
+
+ // ----- Packed data
+ $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, $p_nb_entries, $p_size, $p_offset, strlen($p_comment));
+
+ // ----- Write the 22 bytes of the header in the zip file
+ fputs($this->zip_fd, $v_binary_data, 22);
+
+ // ----- Write the variable fields
+ if (strlen($p_comment) != 0) {
+ fputs($this->zip_fd, $p_comment, strlen($p_comment));
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privList()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privList(&$p_list)
+ {
+ $v_result = 1;
+
+ // ----- Magic quotes trick
+ $this->privDisableMagicQuotes();
+
+ // ----- Open the zip file
+ if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) {
+ // ----- Magic quotes trick
+ $this->privSwapBackMagicQuotes();
+
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \'' . $this->zipname . '\' in binary read mode');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Read the central directory informations
+ $v_central_dir = array();
+ if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result;
+ }
+
+ // ----- Go to beginning of Central Dir
+ @rewind($this->zip_fd);
+ if (@fseek($this->zip_fd, $v_central_dir['offset'])) {
+ $this->privSwapBackMagicQuotes();
+
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Read each entry
+ for ($i = 0; $i < $v_central_dir['entries']; $i++) {
+ // ----- Read the file header
+ if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) {
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result;
+ }
+ $v_header['index'] = $i;
+
+ // ----- Get the only interesting attributes
+ $this->privConvertHeader2FileInfo($v_header, $p_list[$i]);
+ unset($v_header);
+ }
+
+ // ----- Close the zip file
$this->privCloseFd();
+ // ----- Magic quotes trick
+ $this->privSwapBackMagicQuotes();
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privConvertHeader2FileInfo()
+ // Description :
+ // This function takes the file informations from the central directory
+ // entries and extract the interesting parameters that will be given back.
+ // The resulting file infos are set in the array $p_info
+ // $p_info['filename'] : Filename with full path. Given by user (add),
+ // extracted in the filesystem (extract).
+ // $p_info['stored_filename'] : Stored filename in the archive.
+ // $p_info['size'] = Size of the file.
+ // $p_info['compressed_size'] = Compressed size of the file.
+ // $p_info['mtime'] = Last modification date of the file.
+ // $p_info['comment'] = Comment associated with the file.
+ // $p_info['folder'] = true/false : indicates if the entry is a folder or not.
+ // $p_info['status'] = status of the action on the file.
+ // $p_info['crc'] = CRC of the file content.
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privConvertHeader2FileInfo($p_header, &$p_info)
+ {
+ $v_result = 1;
+
+ // ----- Get the interesting attributes
+ $v_temp_path = PclZipUtilPathReduction($p_header['filename']);
+ $p_info['filename'] = $v_temp_path;
+ $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']);
+ $p_info['stored_filename'] = $v_temp_path;
+ $p_info['size'] = $p_header['size'];
+ $p_info['compressed_size'] = $p_header['compressed_size'];
+ $p_info['mtime'] = $p_header['mtime'];
+ $p_info['comment'] = $p_header['comment'];
+ $p_info['folder'] = (($p_header['external'] & 0x00000010) == 0x00000010);
+ $p_info['index'] = $p_header['index'];
+ $p_info['status'] = $p_header['status'];
+ $p_info['crc'] = $p_header['crc'];
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privExtractByRule()
+ // Description :
+ // Extract a file or directory depending of rules (by index, by name, ...)
+ // Parameters :
+ // $p_file_list : An array where will be placed the properties of each
+ // extracted file
+ // $p_path : Path to add while writing the extracted files
+ // $p_remove_path : Path to remove (from the file memorized path) while writing the
+ // extracted files. If the path does not match the file path,
+ // the file is extracted with its memorized path.
+ // $p_remove_path does not apply to 'list' mode.
+ // $p_path and $p_remove_path are commulative.
+ // Return Values :
+ // 1 on success,0 or less on error (see error code list)
+ // --------------------------------------------------------------------------------
+ public function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
+ {
+ $v_result = 1;
+
+ // ----- Magic quotes trick
+ $this->privDisableMagicQuotes();
+
+ // ----- Check the path
+ if (($p_path == "") || ((substr($p_path, 0, 1) != "/") && (substr($p_path, 0, 3) != "../") && (substr($p_path, 1, 2) != ":/"))) {
+ $p_path = "./" . $p_path;
+ }
+
+ // ----- Reduce the path last (and duplicated) '/'
+ if (($p_path != "./") && ($p_path != "/")) {
+ // ----- Look for the path end '/'
+ while (substr($p_path, -1) == "/") {
+ $p_path = substr($p_path, 0, strlen($p_path) - 1);
+ }
+ }
+
+ // ----- Look for path to remove format (should end by /)
+ if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) {
+ $p_remove_path .= '/';
+ }
+ $p_remove_path_size = strlen($p_remove_path);
+
+ // ----- Open the zip file
+ if (($v_result = $this->privOpenFd('rb')) != 1) {
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result;
+ }
+
+ // ----- Read the central directory informations
+ $v_central_dir = array();
+ if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
+ // ----- Close the zip file
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result;
+ }
+
+ // ----- Start at beginning of Central Dir
+ $v_pos_entry = $v_central_dir['offset'];
+
+ // ----- Read each entry
+ $j_start = 0;
+ for ($i = 0, $v_nb_extracted = 0; $i < $v_central_dir['entries']; $i++) {
+
+ // ----- Read next Central dir entry
+ @rewind($this->zip_fd);
+ if (@fseek($this->zip_fd, $v_pos_entry)) {
+ // ----- Close the zip file
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Read the file header
+ $v_header = array();
+ if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) {
+ // ----- Close the zip file
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result;
+ }
+
+ // ----- Store the index
+ $v_header['index'] = $i;
+
+ // ----- Store the file position
+ $v_pos_entry = ftell($this->zip_fd);
+
+ // ----- Look for the specific extract rules
+ $v_extract = false;
+
+ // ----- Look for extract by name rule
+ if ((isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
+
+ // ----- Look if the filename is in the list
+ for ($j = 0; ($j < sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_extract); $j++) {
+
+ // ----- Look for a directory
+ if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") {
+
+ // ----- Look if the directory is in the filename path
+ if ((strlen($v_header['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
+ $v_extract = true;
+ }
+
+ // ----- Look for a filename
+ } elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
+ $v_extract = true;
+ }
+ }
+ // ----- Look for extract by ereg rule
+ // ereg() is deprecated with PHP 5.3
+ /*
+ elseif ( (isset($p_options[PCLZIP_OPT_BY_EREG]))
+ && ($p_options[PCLZIP_OPT_BY_EREG] != "")) {
+
+ if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) {
+ $v_extract = true;
+ }
+ }
+ */
+
+ // ----- Look for extract by preg rule
+ } elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
+
+ if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) {
+ $v_extract = true;
+ }
+
+ // ----- Look for extract by index rule
+ } elseif ((isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
+
+ // ----- Look if the index is in the list
+ for ($j = $j_start; ($j < sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_extract); $j++) {
+
+ if (($i >= $p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i <= $p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
+ $v_extract = true;
+ }
+ if ($i >= $p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
+ $j_start = $j + 1;
+ }
+
+ if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start'] > $i) {
+ break;
+ }
+ }
+
+ // ----- Look for no rule, which means extract all the archive
+ } else {
+ $v_extract = true;
+ }
+
+ // ----- Check compression method
+ if (($v_extract) && (($v_header['compression'] != 8) && ($v_header['compression'] != 0))) {
+ $v_header['status'] = 'unsupported_compression';
+
+ // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
+ if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) {
+
+ $this->privSwapBackMagicQuotes();
+
+ PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, "Filename '" . $v_header['stored_filename'] . "' is " . "compressed by an unsupported compression " . "method (" . $v_header['compression'] . ") ");
+
+ return PclZip::errorCode();
+ }
+ }
+
+ // ----- Check encrypted files
+ if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
+ $v_header['status'] = 'unsupported_encryption';
+
+ // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
+ if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) {
+
+ $this->privSwapBackMagicQuotes();
+
+ PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, "Unsupported encryption for " . " filename '" . $v_header['stored_filename'] . "'");
+
+ return PclZip::errorCode();
+ }
+ }
+
+ // ----- Look for real extraction
+ if (($v_extract) && ($v_header['status'] != 'ok')) {
+ $v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++]);
+ if ($v_result != 1) {
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result;
+ }
+
+ $v_extract = false;
+ }
+
+ // ----- Look for real extraction
+ if ($v_extract) {
+
+ // ----- Go to the file position
+ @rewind($this->zip_fd);
+ if (@fseek($this->zip_fd, $v_header['offset'])) {
+ // ----- Close the zip file
+ $this->privCloseFd();
+
+ $this->privSwapBackMagicQuotes();
+
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Look for extraction as string
+ if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) {
+
+ $v_string = '';
+
+ // ----- Extracting the file
+ $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options);
+ if ($v_result1 < 1) {
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result1;
+ }
+
+ // ----- Get the only interesting attributes
+ if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) {
+ // ----- Close the zip file
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result;
+ }
+
+ // ----- Set the file content
+ $p_file_list[$v_nb_extracted]['content'] = $v_string;
+
+ // ----- Next extracted file
+ $v_nb_extracted++;
+
+ // ----- Look for user callback abort
+ if ($v_result1 == 2) {
+ break;
+ }
+
+ // ----- Look for extraction in standard output
+ } elseif ((isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) {
+ // ----- Extracting the file in standard output
+ $v_result1 = $this->privExtractFileInOutput($v_header, $p_options);
+ if ($v_result1 < 1) {
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result1;
+ }
+
+ // ----- Get the only interesting attributes
+ if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) {
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result;
+ }
+
+ // ----- Look for user callback abort
+ if ($v_result1 == 2) {
+ break;
+ }
+
+ // ----- Look for normal extraction
+ } else {
+ // ----- Extracting the file
+ $v_result1 = $this->privExtractFile($v_header, $p_path, $p_remove_path, $p_remove_all_path, $p_options);
+ if ($v_result1 < 1) {
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result1;
+ }
+
+ // ----- Get the only interesting attributes
+ if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) {
+ // ----- Close the zip file
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ return $v_result;
+ }
+
+ // ----- Look for user callback abort
+ if ($v_result1 == 2) {
+ break;
+ }
+ }
+ }
+ }
+
+ // ----- Close the zip file
+ $this->privCloseFd();
+ $this->privSwapBackMagicQuotes();
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privExtractFile()
+ // Description :
+ // Parameters :
+ // Return Values :
+ //
+ // 1 : ... ?
+ // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback
+ // --------------------------------------------------------------------------------
+ public function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
+ {
+ $v_result = 1;
+
+ // ----- Read the file header
+ if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Check that the file header is coherent with $p_entry info
+ if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
+ // TBC
+ }
+
+ // ----- Look for all path to remove
+ if ($p_remove_all_path == true) {
+ // ----- Look for folder entry that not need to be extracted
+ if (($p_entry['external'] & 0x00000010) == 0x00000010) {
+
+ $p_entry['status'] = "filtered";
+
+ return $v_result;
+ }
+
+ // ----- Get the basename of the path
+ $p_entry['filename'] = basename($p_entry['filename']);
+
+ // ----- Look for path to remove
+ } elseif ($p_remove_path != "") {
+ if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) {
+
+ // ----- Change the file status
+ $p_entry['status'] = "filtered";
+
+ // ----- Return
+ return $v_result;
+ }
+
+ $p_remove_path_size = strlen($p_remove_path);
+ if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) {
+
+ // ----- Remove the path
+ $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size);
+
+ }
+ }
+
+ // ----- Add the path
+ if ($p_path != '') {
+ $p_entry['filename'] = $p_path . "/" . $p_entry['filename'];
+ }
+
+ // ----- Check a base_dir_restriction
+ if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) {
+ $v_inclusion = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], $p_entry['filename']);
+ if ($v_inclusion == 0) {
+
+ PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, "Filename '" . $p_entry['filename'] . "' is " . "outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION");
+
+ return PclZip::errorCode();
+ }
+ }
+
+ // ----- Look for pre-extract callback
+ if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
+
+ // ----- Generate a local information
+ $v_local_header = array();
+ $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
+
+ // ----- Call the callback
+ // Here I do not use call_user_func() because I need to send a reference to the
+ // header.
+ // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
+ $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
+ if ($v_result == 0) {
+ // ----- Change the file status
+ $p_entry['status'] = "skipped";
+ $v_result = 1;
+ }
+
+ // ----- Look for abort result
+ if ($v_result == 2) {
+ // ----- This status is internal and will be changed in 'skipped'
+ $p_entry['status'] = "aborted";
+ $v_result = PCLZIP_ERR_USER_ABORTED;
+ }
+
+ // ----- Update the informations
+ // Only some fields can be modified
+ $p_entry['filename'] = $v_local_header['filename'];
+ }
+
+ // ----- Look if extraction should be done
+ if ($p_entry['status'] == 'ok') {
+
+ // ----- Look for specific actions while the file exist
+ if (file_exists($p_entry['filename'])) {
+
+ // ----- Look if file is a directory
+ if (is_dir($p_entry['filename'])) {
+
+ // ----- Change the file status
+ $p_entry['status'] = "already_a_directory";
+
+ // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
+ // For historical reason first PclZip implementation does not stop
+ // when this kind of error occurs.
+ if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) {
+
+ PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, "Filename '" . $p_entry['filename'] . "' is " . "already used by an existing directory");
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Look if file is write protected
+ } elseif (!is_writeable($p_entry['filename'])) {
+
+ // ----- Change the file status
+ $p_entry['status'] = "write_protected";
+
+ // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
+ // For historical reason first PclZip implementation does not stop
+ // when this kind of error occurs.
+ if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) {
+
+ PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Filename '" . $p_entry['filename'] . "' exists " . "and is write protected");
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Look if the extracted file is older
+ } elseif (filemtime($p_entry['filename']) > $p_entry['mtime']) {
+ // ----- Change the file status
+ if ((isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) && ($p_options[PCLZIP_OPT_REPLACE_NEWER] === true)) {
+ } else {
+ $p_entry['status'] = "newer_exist";
+
+ // ----- Look for PCLZIP_OPT_STOP_ON_ERROR
+ // For historical reason first PclZip implementation does not stop
+ // when this kind of error occurs.
+ if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) {
+
+ PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Newer version of '" . $p_entry['filename'] . "' exists " . "and option PCLZIP_OPT_REPLACE_NEWER is not selected");
+
+ return PclZip::errorCode();
+ }
+ }
+ } else {
+ }
+
+ // ----- Check the directory availability and create it if necessary
+ } else {
+ if ((($p_entry['external'] & 0x00000010) == 0x00000010) || (substr($p_entry['filename'], -1) == '/')) {
+ $v_dir_to_check = $p_entry['filename'];
+ } elseif (!strstr($p_entry['filename'], "/")) {
+ $v_dir_to_check = "";
+ } else {
+ $v_dir_to_check = dirname($p_entry['filename']);
+ }
+
+ if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external'] & 0x00000010) == 0x00000010))) != 1) {
+
+ // ----- Change the file status
+ $p_entry['status'] = "path_creation_fail";
+
+ // ----- Return
+ //return $v_result;
+ $v_result = 1;
+ }
+ }
+ }
+
+ // ----- Look if extraction should be done
+ if ($p_entry['status'] == 'ok') {
+
+ // ----- Do the extraction (if not a folder)
+ if (!(($p_entry['external'] & 0x00000010) == 0x00000010)) {
+ // ----- Look for not compressed file
+ if ($p_entry['compression'] == 0) {
+
+ // ----- Opening destination file
+ if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
+
+ // ----- Change the file status
+ $p_entry['status'] = "write_error";
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
+ $v_size = $p_entry['compressed_size'];
+ while ($v_size != 0) {
+ $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = @fread($this->zip_fd, $v_read_size);
+ /* Try to speed up the code
+ $v_binary_data = pack('a'.$v_read_size, $v_buffer);
+ @fwrite($v_dest_file, $v_binary_data, $v_read_size);
+ */
+ @fwrite($v_dest_file, $v_buffer, $v_read_size);
+ $v_size -= $v_read_size;
+ }
+
+ // ----- Closing the destination file
+ fclose($v_dest_file);
+
+ // ----- Change the file mtime
+ touch($p_entry['filename'], $p_entry['mtime']);
+
+ } else {
+ // ----- TBC
+ // Need to be finished
+ if (($p_entry['flag'] & 1) == 1) {
+ PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \'' . $p_entry['filename'] . '\' is encrypted. Encrypted files are not supported.');
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Look for using temporary file to unzip
+ if ((!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])))) {
+ $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options);
+ if ($v_result < PCLZIP_ERR_NO_ERROR) {
+ return $v_result;
+ }
+
+ // ----- Look for extract in memory
+ } else {
+
+ // ----- Read the compressed file in a buffer (one shot)
+ $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
+
+ // ----- Decompress the file
+ $v_file_content = @gzinflate($v_buffer);
+ unset($v_buffer);
+ if ($v_file_content === false) {
+
+ // ----- Change the file status
+ // TBC
+ $p_entry['status'] = "error";
+
+ return $v_result;
+ }
+
+ // ----- Opening destination file
+ if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
+
+ // ----- Change the file status
+ $p_entry['status'] = "write_error";
+
+ return $v_result;
+ }
+
+ // ----- Write the uncompressed data
+ @fwrite($v_dest_file, $v_file_content, $p_entry['size']);
+ unset($v_file_content);
+
+ // ----- Closing the destination file
+ @fclose($v_dest_file);
+
+ }
+
+ // ----- Change the file mtime
+ @touch($p_entry['filename'], $p_entry['mtime']);
+ }
+
+ // ----- Look for chmod option
+ if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) {
+
+ // ----- Change the mode of the file
+ @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]);
+ }
+
+ }
+ }
+
+ // ----- Change abort status
+ if ($p_entry['status'] == "aborted") {
+ $p_entry['status'] = "skipped";
+
+ // ----- Look for post-extract callback
+ } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
+
+ // ----- Generate a local information
+ $v_local_header = array();
+ $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
+
+ // ----- Call the callback
+ // Here I do not use call_user_func() because I need to send a reference to the
+ // header.
+ // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
+ $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
+
+ // ----- Look for abort result
+ if ($v_result == 2) {
+ $v_result = PCLZIP_ERR_USER_ABORTED;
+ }
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privExtractFileUsingTempFile()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privExtractFileUsingTempFile(&$p_entry, &$p_options)
+ {
+ $v_result = 1;
+
+ // ----- Creates a temporary file
+ $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.gz';
+ if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) {
+ fclose($v_file);
+ PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary write mode');
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Write gz file format header
+ $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3));
+ @fwrite($v_dest_file, $v_binary_data, 10);
+
+ // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
+ $v_size = $p_entry['compressed_size'];
+ while ($v_size != 0) {
+ $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = @fread($this->zip_fd, $v_read_size);
+ //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
+ @fwrite($v_dest_file, $v_buffer, $v_read_size);
+ $v_size -= $v_read_size;
+ }
+
+ // ----- Write gz file format footer
+ $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']);
+ @fwrite($v_dest_file, $v_binary_data, 8);
+
+ // ----- Close the temporary file
+ @fclose($v_dest_file);
+
+ // ----- Opening destination file
+ if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
+ $p_entry['status'] = "write_error";
+
+ return $v_result;
+ }
+
+ // ----- Open the temporary gz file
+ if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) {
+ @fclose($v_dest_file);
+ $p_entry['status'] = "read_error";
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary read mode');
+
+ return PclZip::errorCode();
+ }
+
+ // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
+ $v_size = $p_entry['size'];
+ while ($v_size != 0) {
+ $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = @gzread($v_src_file, $v_read_size);
+ //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
+ @fwrite($v_dest_file, $v_buffer, $v_read_size);
+ $v_size -= $v_read_size;
+ }
+ @fclose($v_dest_file);
+ @gzclose($v_src_file);
+
+ // ----- Delete the temporary file
+ @unlink($v_gzip_temp_name);
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privExtractFileInOutput()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privExtractFileInOutput(&$p_entry, &$p_options)
+ {
+ $v_result = 1;
+
+ // ----- Read the file header
+ if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
+ return $v_result;
+ }
+
+ // ----- Check that the file header is coherent with $p_entry info
+ if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
+ // TBC
+ }
+
+ // ----- Look for pre-extract callback
+ if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
+
+ // ----- Generate a local information
+ $v_local_header = array();
+ $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
+
+ // ----- Call the callback
+ // Here I do not use call_user_func() because I need to send a reference to the
+ // header.
+ // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
+ $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
+ if ($v_result == 0) {
+ // ----- Change the file status
+ $p_entry['status'] = "skipped";
+ $v_result = 1;
+ }
+
+ // ----- Look for abort result
+ if ($v_result == 2) {
+ // ----- This status is internal and will be changed in 'skipped'
+ $p_entry['status'] = "aborted";
+ $v_result = PCLZIP_ERR_USER_ABORTED;
+ }
+
+ // ----- Update the informations
+ // Only some fields can be modified
+ $p_entry['filename'] = $v_local_header['filename'];
+ }
+
+ // ----- Trace
+
+ // ----- Look if extraction should be done
+ if ($p_entry['status'] == 'ok') {
+
+ // ----- Do the extraction (if not a folder)
+ if (!(($p_entry['external'] & 0x00000010) == 0x00000010)) {
+ // ----- Look for not compressed file
+ if ($p_entry['compressed_size'] == $p_entry['size']) {
+
+ // ----- Read the file in a buffer (one shot)
+ $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
+
+ // ----- Send the file to the output
+ echo $v_buffer;
+ unset($v_buffer);
+ } else {
+
+ // ----- Read the compressed file in a buffer (one shot)
+ $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
+
+ // ----- Decompress the file
+ $v_file_content = gzinflate($v_buffer);
+ unset($v_buffer);
+
+ // ----- Send the file to the output
+ echo $v_file_content;
+ unset($v_file_content);
+ }
+ }
+ }
+
+ // ----- Change abort status
+ if ($p_entry['status'] == "aborted") {
+ $p_entry['status'] = "skipped";
+
+ // ----- Look for post-extract callback
+ } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
+
+ // ----- Generate a local information
+ $v_local_header = array();
+ $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
+
+ // ----- Call the callback
+ // Here I do not use call_user_func() because I need to send a reference to the
+ // header.
+ // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
+ $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
+
+ // ----- Look for abort result
+ if ($v_result == 2) {
+ $v_result = PCLZIP_ERR_USER_ABORTED;
+ }
+ }
+
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privExtractFileAsString()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privExtractFileAsString(&$p_entry, &$p_string, &$p_options)
+ {
+ $v_result = 1;
+
+ // ----- Read the file header
+ $v_header = array();
+ if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Check that the file header is coherent with $p_entry info
+ if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
+ // TBC
+ }
+
+ // ----- Look for pre-extract callback
+ if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
+
+ // ----- Generate a local information
+ $v_local_header = array();
+ $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
+
+ // ----- Call the callback
+ // Here I do not use call_user_func() because I need to send a reference to the
+ // header.
+ // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
+ $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
+ if ($v_result == 0) {
+ // ----- Change the file status
+ $p_entry['status'] = "skipped";
+ $v_result = 1;
+ }
+
+ // ----- Look for abort result
+ if ($v_result == 2) {
+ // ----- This status is internal and will be changed in 'skipped'
+ $p_entry['status'] = "aborted";
+ $v_result = PCLZIP_ERR_USER_ABORTED;
+ }
+
+ // ----- Update the informations
+ // Only some fields can be modified
+ $p_entry['filename'] = $v_local_header['filename'];
+ }
+
+ // ----- Look if extraction should be done
+ if ($p_entry['status'] == 'ok') {
+
+ // ----- Do the extraction (if not a folder)
+ if (!(($p_entry['external'] & 0x00000010) == 0x00000010)) {
+ // ----- Look for not compressed file
+ // if ($p_entry['compressed_size'] == $p_entry['size'])
+ if ($p_entry['compression'] == 0) {
+
+ // ----- Reading the file
+ $p_string = @fread($this->zip_fd, $p_entry['compressed_size']);
+ } else {
+
+ // ----- Reading the file
+ $v_data = @fread($this->zip_fd, $p_entry['compressed_size']);
+
+ // ----- Decompress the file
+ if (($p_string = @gzinflate($v_data)) === false) {
+ // TBC
+ }
+ }
+
+ // ----- Trace
+ } else {
+ // TBC : error : can not extract a folder in a string
+ }
+
+ }
+
+ // ----- Change abort status
+ if ($p_entry['status'] == "aborted") {
+ $p_entry['status'] = "skipped";
+
+ // ----- Look for post-extract callback
+ } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
+
+ // ----- Generate a local information
+ $v_local_header = array();
+ $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
+
+ // ----- Swap the content to header
+ $v_local_header['content'] = $p_string;
+ $p_string = '';
+
+ // ----- Call the callback
+ // Here I do not use call_user_func() because I need to send a reference to the
+ // header.
+ // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
+ $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
+
+ // ----- Swap back the content to header
+ $p_string = $v_local_header['content'];
+ unset($v_local_header['content']);
+
+ // ----- Look for abort result
+ if ($v_result == 2) {
+ $v_result = PCLZIP_ERR_USER_ABORTED;
+ }
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privReadFileHeader()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privReadFileHeader(&$p_header)
+ {
+ $v_result = 1;
+
+ // ----- Read the 4 bytes signature
+ $v_binary_data = @fread($this->zip_fd, 4);
+ $v_data = unpack('Vid', $v_binary_data);
+
+ // ----- Check signature
+ if ($v_data['id'] != 0x04034b50) {
+
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Read the first 42 bytes of the header
+ $v_binary_data = fread($this->zip_fd, 26);
+
+ // ----- Look for invalid block size
+ if (strlen($v_binary_data) != 26) {
+ $p_header['filename'] = "";
+ $p_header['status'] = "invalid_header";
+
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : " . strlen($v_binary_data));
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Extract the values
+ $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data);
+
+ // ----- Get filename
+ $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']);
+
+ // ----- Get extra_fields
+ if ($v_data['extra_len'] != 0) {
+ $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']);
+ } else {
+ $p_header['extra'] = '';
+ }
+
+ // ----- Extract properties
+ $p_header['version_extracted'] = $v_data['version'];
+ $p_header['compression'] = $v_data['compression'];
+ $p_header['size'] = $v_data['size'];
+ $p_header['compressed_size'] = $v_data['compressed_size'];
+ $p_header['crc'] = $v_data['crc'];
+ $p_header['flag'] = $v_data['flag'];
+ $p_header['filename_len'] = $v_data['filename_len'];
+
+ // ----- Recuperate date in UNIX format
+ $p_header['mdate'] = $v_data['mdate'];
+ $p_header['mtime'] = $v_data['mtime'];
+ if ($p_header['mdate'] && $p_header['mtime']) {
+ // ----- Extract time
+ $v_hour = ($p_header['mtime'] & 0xF800) >> 11;
+ $v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
+ $v_seconde = ($p_header['mtime'] & 0x001F) * 2;
+
+ // ----- Extract date
+ $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
+ $v_month = ($p_header['mdate'] & 0x01E0) >> 5;
+ $v_day = $p_header['mdate'] & 0x001F;
+
+ // ----- Get UNIX date format
+ $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
+
+ } else {
+ $p_header['mtime'] = time();
+ }
+
+ // TBC
+ //for (reset($v_data); $key = key($v_data); next($v_data)) {
+ //}
+
+ // ----- Set the stored filename
+ $p_header['stored_filename'] = $p_header['filename'];
+
+ // ----- Set the status field
+ $p_header['status'] = "ok";
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privReadCentralFileHeader()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privReadCentralFileHeader(&$p_header)
+ {
+ $v_result = 1;
+
+ // ----- Read the 4 bytes signature
+ $v_binary_data = @fread($this->zip_fd, 4);
+ $v_data = unpack('Vid', $v_binary_data);
+
+ // ----- Check signature
+ if ($v_data['id'] != 0x02014b50) {
+
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Read the first 42 bytes of the header
+ $v_binary_data = fread($this->zip_fd, 42);
+
+ // ----- Look for invalid block size
+ if (strlen($v_binary_data) != 42) {
+ $p_header['filename'] = "";
+ $p_header['status'] = "invalid_header";
+
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : " . strlen($v_binary_data));
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Extract the values
+ $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data);
+
+ // ----- Get filename
+ if ($p_header['filename_len'] != 0) {
+ $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']);
+ } else {
+ $p_header['filename'] = '';
+ }
+
+ // ----- Get extra
+ if ($p_header['extra_len'] != 0) {
+ $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']);
+ } else {
+ $p_header['extra'] = '';
+ }
+
+ // ----- Get comment
+ if ($p_header['comment_len'] != 0) {
+ $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']);
+ } else {
+ $p_header['comment'] = '';
+ }
+
+ // ----- Extract properties
+
+ // ----- Recuperate date in UNIX format
+ //if ($p_header['mdate'] && $p_header['mtime'])
+ // TBC : bug : this was ignoring time with 0/0/0
+ if (1) {
+ // ----- Extract time
+ $v_hour = ($p_header['mtime'] & 0xF800) >> 11;
+ $v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
+ $v_seconde = ($p_header['mtime'] & 0x001F) * 2;
+
+ // ----- Extract date
+ $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
+ $v_month = ($p_header['mdate'] & 0x01E0) >> 5;
+ $v_day = $p_header['mdate'] & 0x001F;
+
+ // ----- Get UNIX date format
+ $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
+
+ } else {
+ $p_header['mtime'] = time();
+ }
+
+ // ----- Set the stored filename
+ $p_header['stored_filename'] = $p_header['filename'];
+
+ // ----- Set default status to ok
+ $p_header['status'] = 'ok';
+
+ // ----- Look if it is a directory
+ if (substr($p_header['filename'], -1) == '/') {
+ //$p_header['external'] = 0x41FF0010;
+ $p_header['external'] = 0x00000010;
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privCheckFileHeaders()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // 1 on success,
+ // 0 on error;
+ // --------------------------------------------------------------------------------
+ public function privCheckFileHeaders(&$p_local_header, &$p_central_header)
+ {
+ $v_result = 1;
+
+ // ----- Check the static values
+ // TBC
+ if ($p_local_header['filename'] != $p_central_header['filename']) {
+ }
+ if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
+ }
+ if ($p_local_header['flag'] != $p_central_header['flag']) {
+ }
+ if ($p_local_header['compression'] != $p_central_header['compression']) {
+ }
+ if ($p_local_header['mtime'] != $p_central_header['mtime']) {
+ }
+ if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
+ }
+
+ // ----- Look for flag bit 3
+ if (($p_local_header['flag'] & 8) == 8) {
+ $p_local_header['size'] = $p_central_header['size'];
+ $p_local_header['compressed_size'] = $p_central_header['compressed_size'];
+ $p_local_header['crc'] = $p_central_header['crc'];
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privReadEndCentralDir()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privReadEndCentralDir(&$p_central_dir)
+ {
+ $v_result = 1;
+
+ // ----- Go to the end of the zip file
+ $v_size = filesize($this->zipname);
+ @fseek($this->zip_fd, $v_size);
+ if (@ftell($this->zip_fd) != $v_size) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \'' . $this->zipname . '\'');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- First try : look if this is an archive with no commentaries (most of the time)
+ // in this case the end of central dir is at 22 bytes of the file end
+ $v_found = 0;
+ if ($v_size > 26) {
+ @fseek($this->zip_fd, $v_size - 22);
+ if (($v_pos = @ftell($this->zip_fd)) != ($v_size - 22)) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \'' . $this->zipname . '\'');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Read for bytes
+ $v_binary_data = @fread($this->zip_fd, 4);
+ $v_data = @unpack('Vid', $v_binary_data);
+
+ // ----- Check signature
+ if ($v_data['id'] == 0x06054b50) {
+ $v_found = 1;
+ }
+
+ $v_pos = ftell($this->zip_fd);
+ }
+
+ // ----- Go back to the maximum possible size of the Central Dir End Record
+ if (!$v_found) {
+ $v_maximum_size = 65557; // 0xFFFF + 22;
+ if ($v_maximum_size > $v_size) {
+ $v_maximum_size = $v_size;
+ }
+ @fseek($this->zip_fd, $v_size - $v_maximum_size);
+ if (@ftell($this->zip_fd) != ($v_size - $v_maximum_size)) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \'' . $this->zipname . '\'');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Read byte per byte in order to find the signature
+ $v_pos = ftell($this->zip_fd);
+ $v_bytes = 0x00000000;
+ while ($v_pos < $v_size) {
+ // ----- Read a byte
+ $v_byte = @fread($this->zip_fd, 1);
+
+ // ----- Add the byte
+ //$v_bytes = ($v_bytes << 8) | Ord($v_byte);
+ // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number
+ // Otherwise on systems where we have 64bit integers the check below for the magic number will fail.
+ $v_bytes = (($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte);
+
+ // ----- Compare the bytes
+ if ($v_bytes == 0x504b0506) {
+ $v_pos++;
+ break;
+ }
+
+ $v_pos++;
+ }
+
+ // ----- Look if not found end of central dir
+ if ($v_pos == $v_size) {
+
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+ }
+
+ // ----- Read the first 18 bytes of the header
+ $v_binary_data = fread($this->zip_fd, 18);
+
+ // ----- Look for invalid block size
+ if (strlen($v_binary_data) != 18) {
+
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : " . strlen($v_binary_data));
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Extract the values
+ $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data);
+
+ // ----- Check the global size
+ if (($v_pos + $v_data['comment_size'] + 18) != $v_size) {
+
+ // ----- Removed in release 2.2 see readme file
+ // The check of the file size is a little too strict.
+ // Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
+ // While decrypted, zip has training 0 bytes
+ if (0) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'The central dir is not at the end of the archive.' . ' Some trailing bytes exists after the archive.');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+ }
+
+ // ----- Get comment
+ if ($v_data['comment_size'] != 0) {
+ $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']);
+ } else {
+ $p_central_dir['comment'] = '';
+ }
+
+ $p_central_dir['entries'] = $v_data['entries'];
+ $p_central_dir['disk_entries'] = $v_data['disk_entries'];
+ $p_central_dir['offset'] = $v_data['offset'];
+ $p_central_dir['size'] = $v_data['size'];
+ $p_central_dir['disk'] = $v_data['disk'];
+ $p_central_dir['disk_start'] = $v_data['disk_start'];
+
+ // TBC
+ //for (reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) {
+ //}
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privDeleteByRule()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privDeleteByRule(&$p_result_list, &$p_options)
+ {
+ $v_result = 1;
+ $v_list_detail = array();
+
+ // ----- Open the zip file
+ if (($v_result = $this->privOpenFd('rb')) != 1) {
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Read the central directory informations
+ $v_central_dir = array();
+ if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
+ $this->privCloseFd();
+
+ return $v_result;
+ }
+
+ // ----- Go to beginning of File
+ @rewind($this->zip_fd);
+
+ // ----- Scan all the files
+ // ----- Start at beginning of Central Dir
+ $v_pos_entry = $v_central_dir['offset'];
+ @rewind($this->zip_fd);
+ if (@fseek($this->zip_fd, $v_pos_entry)) {
+ // ----- Close the zip file
+ $this->privCloseFd();
+
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Read each entry
+ $v_header_list = array();
+ $j_start = 0;
+ for ($i = 0, $v_nb_extracted = 0; $i < $v_central_dir['entries']; $i++) {
+
+ // ----- Read the file header
+ $v_header_list[$v_nb_extracted] = array();
+ if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) {
+ // ----- Close the zip file
+ $this->privCloseFd();
+
+ return $v_result;
+ }
+
+ // ----- Store the index
+ $v_header_list[$v_nb_extracted]['index'] = $i;
+
+ // ----- Look for the specific extract rules
+ $v_found = false;
+
+ // ----- Look for extract by name rule
+ if ((isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
+
+ // ----- Look if the filename is in the list
+ for ($j = 0; ($j < sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_found); $j++) {
+
+ // ----- Look for a directory
+ if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") {
+
+ // ----- Look if the directory is in the filename path
+ if ((strlen($v_header_list[$v_nb_extracted]['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
+ $v_found = true;
+ } elseif ((($v_header_list[$v_nb_extracted]['external'] & 0x00000010) == 0x00000010) /* Indicates a folder */ && ($v_header_list[$v_nb_extracted]['stored_filename'] . '/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
+ $v_found = true;
+ }
+
+ // ----- Look for a filename
+ } elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
+ $v_found = true;
+ }
+ }
+
+ // ----- Look for extract by ereg rule
+ // ereg() is deprecated with PHP 5.3
+ /*
+ elseif ( (isset($p_options[PCLZIP_OPT_BY_EREG]))
+ && ($p_options[PCLZIP_OPT_BY_EREG] != "")) {
+
+ if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
+ $v_found = true;
+ }
+ }
+ */
+
+ // ----- Look for extract by preg rule
+ } elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
+
+ if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
+ $v_found = true;
+ }
+
+ // ----- Look for extract by index rule
+ } elseif ((isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
+
+ // ----- Look if the index is in the list
+ for ($j = $j_start; ($j < sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_found); $j++) {
+
+ if (($i >= $p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i <= $p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
+ $v_found = true;
+ }
+ if ($i >= $p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
+ $j_start = $j + 1;
+ }
+
+ if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start'] > $i) {
+ break;
+ }
+ }
+ } else {
+ $v_found = true;
+ }
+
+ // ----- Look for deletion
+ if ($v_found) {
+ unset($v_header_list[$v_nb_extracted]);
+ } else {
+ $v_nb_extracted++;
+ }
+ }
+
+ // ----- Look if something need to be deleted
+ if ($v_nb_extracted > 0) {
+
+ // ----- Creates a temporay file
+ $v_zip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.tmp';
+
+ // ----- Creates a temporary zip archive
+ $v_temp_zip = new PclZip($v_zip_temp_name);
+
+ // ----- Open the temporary zip file in write mode
+ if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) {
+ $this->privCloseFd();
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Look which file need to be kept
+ for ($i = 0; $i < sizeof($v_header_list); $i++) {
+
+ // ----- Calculate the position of the header
+ @rewind($this->zip_fd);
+ if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) {
+ // ----- Close the zip file
+ $this->privCloseFd();
+ $v_temp_zip->privCloseFd();
+ @unlink($v_zip_temp_name);
+
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Read the file header
+ $v_local_header = array();
+ if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) {
+ // ----- Close the zip file
+ $this->privCloseFd();
+ $v_temp_zip->privCloseFd();
+ @unlink($v_zip_temp_name);
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Check that local file header is same as central file header
+ if ($this->privCheckFileHeaders($v_local_header, $v_header_list[$i]) != 1) {
+ // TBC
+ }
+ unset($v_local_header);
+
+ // ----- Write the file header
+ if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) {
+ // ----- Close the zip file
+ $this->privCloseFd();
+ $v_temp_zip->privCloseFd();
+ @unlink($v_zip_temp_name);
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Read/write the data block
+ if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) {
+ // ----- Close the zip file
+ $this->privCloseFd();
+ $v_temp_zip->privCloseFd();
+ @unlink($v_zip_temp_name);
+
+ // ----- Return
+ return $v_result;
+ }
+ }
+
+ // ----- Store the offset of the central dir
+ $v_offset = @ftell($v_temp_zip->zip_fd);
+
+ // ----- Re-Create the Central Dir files header
+ for ($i = 0; $i < sizeof($v_header_list); $i++) {
+ // ----- Create the file header
+ if (($v_result = $v_temp_zip->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
+ $v_temp_zip->privCloseFd();
+ $this->privCloseFd();
+ @unlink($v_zip_temp_name);
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Transform the header to a 'usable' info
+ $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
+ }
+
+ // ----- Zip file comment
+ $v_comment = '';
+ if (isset($p_options[PCLZIP_OPT_COMMENT])) {
+ $v_comment = $p_options[PCLZIP_OPT_COMMENT];
+ }
+
+ // ----- Calculate the size of the central header
+ $v_size = @ftell($v_temp_zip->zip_fd) - $v_offset;
+
+ // ----- Create the central dir footer
+ if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) {
+ // ----- Reset the file list
+ unset($v_header_list);
+ $v_temp_zip->privCloseFd();
+ $this->privCloseFd();
+ @unlink($v_zip_temp_name);
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Close
+ $v_temp_zip->privCloseFd();
+ $this->privCloseFd();
+
+ // ----- Delete the zip file
+ // TBC : I should test the result ...
+ @unlink($this->zipname);
+
+ // ----- Rename the temporary file
+ // TBC : I should test the result ...
+ //@rename($v_zip_temp_name, $this->zipname);
+ PclZipUtilRename($v_zip_temp_name, $this->zipname);
+
+ // ----- Destroy the temporary archive
+ unset($v_temp_zip);
+
+ // ----- Remove every files : reset the file
+ } elseif ($v_central_dir['entries'] != 0) {
+ $this->privCloseFd();
+
+ if (($v_result = $this->privOpenFd('wb')) != 1) {
+ return $v_result;
+ }
+
+ if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) {
+ return $v_result;
+ }
+
+ $this->privCloseFd();
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privDirCheck()
+ // Description :
+ // Check if a directory exists, if not it creates it and all the parents directory
+ // which may be useful.
+ // Parameters :
+ // $p_dir : Directory path to check.
+ // Return Values :
+ // 1 : OK
+ // -1 : Unable to create directory
+ // --------------------------------------------------------------------------------
+ public function privDirCheck($p_dir, $p_is_dir = false)
+ {
+ $v_result = 1;
+
+ // ----- Remove the final '/'
+ if (($p_is_dir) && (substr($p_dir, -1) == '/')) {
+ $p_dir = substr($p_dir, 0, strlen($p_dir) - 1);
+ }
+
+ // ----- Check the directory availability
+ if ((is_dir($p_dir)) || ($p_dir == "")) {
+ return 1;
+ }
+
+ // ----- Extract parent directory
+ $p_parent_dir = dirname($p_dir);
+
+ // ----- Just a check
+ if ($p_parent_dir != $p_dir) {
+ // ----- Look for parent directory
+ if ($p_parent_dir != "") {
+ if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) {
+ return $v_result;
+ }
+ }
+ }
+
+ // ----- Create the directory
+ if (!@mkdir($p_dir, 0777)) {
+ // ----- Error log
+ PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'");
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privMerge()
+ // Description :
+ // If $p_archive_to_add does not exist, the function exit with a success result.
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privMerge(&$p_archive_to_add)
+ {
+ $v_result = 1;
+
+ // ----- Look if the archive_to_add exists
+ if (!is_file($p_archive_to_add->zipname)) {
+
+ // ----- Nothing to merge, so merge is a success
+ $v_result = 1;
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Look if the archive exists
+ if (!is_file($this->zipname)) {
+
+ // ----- Do a duplicate
+ $v_result = $this->privDuplicate($p_archive_to_add->zipname);
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Open the zip file
+ if (($v_result = $this->privOpenFd('rb')) != 1) {
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Read the central directory informations
+ $v_central_dir = array();
+ if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
+ $this->privCloseFd();
+
+ return $v_result;
+ }
+
+ // ----- Go to beginning of File
+ @rewind($this->zip_fd);
+
+ // ----- Open the archive_to_add file
+ if (($v_result = $p_archive_to_add->privOpenFd('rb')) != 1) {
+ $this->privCloseFd();
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Read the central directory informations
+ $v_central_dir_to_add = array();
+ if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) {
+ $this->privCloseFd();
+ $p_archive_to_add->privCloseFd();
+
+ return $v_result;
+ }
+
+ // ----- Go to beginning of File
+ @rewind($p_archive_to_add->zip_fd);
+
+ // ----- Creates a temporay file
+ $v_zip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.tmp';
+
+ // ----- Open the temporary file in write mode
+ if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) {
+ $this->privCloseFd();
+ $p_archive_to_add->privCloseFd();
+
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_zip_temp_name . '\' in binary write mode');
+
+ // ----- Return
+ return PclZip::errorCode();
+ }
+
+ // ----- Copy the files from the archive to the temporary file
+ // TBC : Here I should better append the file and go back to erase the central dir
+ $v_size = $v_central_dir['offset'];
+ while ($v_size != 0) {
+ $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = fread($this->zip_fd, $v_read_size);
+ @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
+ $v_size -= $v_read_size;
+ }
+
+ // ----- Copy the files from the archive_to_add into the temporary file
+ $v_size = $v_central_dir_to_add['offset'];
+ while ($v_size != 0) {
+ $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size);
+ @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
+ $v_size -= $v_read_size;
+ }
+
+ // ----- Store the offset of the central dir
+ $v_offset = @ftell($v_zip_temp_fd);
+
+ // ----- Copy the block of file headers from the old archive
+ $v_size = $v_central_dir['size'];
+ while ($v_size != 0) {
+ $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = @fread($this->zip_fd, $v_read_size);
+ @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
+ $v_size -= $v_read_size;
+ }
+
+ // ----- Copy the block of file headers from the archive_to_add
+ $v_size = $v_central_dir_to_add['size'];
+ while ($v_size != 0) {
+ $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size);
+ @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
+ $v_size -= $v_read_size;
+ }
+
+ // ----- Merge the file comments
+ $v_comment = $v_central_dir['comment'] . ' ' . $v_central_dir_to_add['comment'];
+
+ // ----- Calculate the size of the (new) central header
+ $v_size = @ftell($v_zip_temp_fd) - $v_offset;
+
+ // ----- Swap the file descriptor
+ // Here is a trick : I swap the temporary fd with the zip fd, in order to use
+ // the following methods on the temporary fil and not the real archive fd
+ $v_swap = $this->zip_fd;
+ $this->zip_fd = $v_zip_temp_fd;
+ $v_zip_temp_fd = $v_swap;
+
+ // ----- Create the central dir footer
+ if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries'] + $v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) {
+ $this->privCloseFd();
+ $p_archive_to_add->privCloseFd();
+ @fclose($v_zip_temp_fd);
+ $this->zip_fd = null;
+
+ // ----- Reset the file list
+ unset($v_header_list);
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Swap back the file descriptor
+ $v_swap = $this->zip_fd;
+ $this->zip_fd = $v_zip_temp_fd;
+ $v_zip_temp_fd = $v_swap;
+
+ // ----- Close
+ $this->privCloseFd();
+ $p_archive_to_add->privCloseFd();
+
+ // ----- Close the temporary file
+ @fclose($v_zip_temp_fd);
+
+ // ----- Delete the zip file
+ // TBC : I should test the result ...
+ @unlink($this->zipname);
+
+ // ----- Rename the temporary file
+ // TBC : I should test the result ...
+ //@rename($v_zip_temp_name, $this->zipname);
+ PclZipUtilRename($v_zip_temp_name, $this->zipname);
+
+ // ----- Return
+ return $v_result;
+ }
+ // --------------------------------------------------------------------------------
+
+ // --------------------------------------------------------------------------------
+ // Function : privDuplicate()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privDuplicate($p_archive_filename)
+ {
+ $v_result = 1;
+
+ // ----- Look if the $p_archive_filename exists
+ if (!is_file($p_archive_filename)) {
+
+ // ----- Nothing to duplicate, so duplicate is a success.
+ $v_result = 1;
+
+ // ----- Return
+ return $v_result;
+ }
+
+ // ----- Open the zip file
if (($v_result = $this->privOpenFd('wb')) != 1) {
- return $v_result;
+ // ----- Return
+ return $v_result;
}
- if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) {
- return $v_result;
+ // ----- Open the temporary file in write mode
+ if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) {
+ $this->privCloseFd();
+
+ PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \'' . $p_archive_filename . '\' in binary write mode');
+
+ // ----- Return
+ return PclZip::errorCode();
}
+ // ----- Copy the files from the archive to the temporary file
+ // TBC : Here I should better append the file and go back to erase the central dir
+ $v_size = filesize($p_archive_filename);
+ while ($v_size != 0) {
+ $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = fread($v_zip_temp_fd, $v_read_size);
+ @fwrite($this->zip_fd, $v_buffer, $v_read_size);
+ $v_size -= $v_read_size;
+ }
+
+ // ----- Close
$this->privCloseFd();
+
+ // ----- Close the temporary file
+ @fclose($v_zip_temp_fd);
+
+ // ----- Return
+ return $v_result;
}
+ // --------------------------------------------------------------------------------
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privDirCheck()
- // Description :
- // Check if a directory exists, if not it creates it and all the parents directory
- // which may be useful.
- // Parameters :
- // $p_dir : Directory path to check.
- // Return Values :
- // 1 : OK
- // -1 : Unable to create directory
- // --------------------------------------------------------------------------------
- function privDirCheck($p_dir, $p_is_dir=false)
- {
- $v_result = 1;
-
-
- // ----- Remove the final '/'
- if (($p_is_dir) && (substr($p_dir, -1)=='/'))
+ // --------------------------------------------------------------------------------
+ // Function : privErrorLog()
+ // Description :
+ // Parameters :
+ // --------------------------------------------------------------------------------
+ public function privErrorLog($p_error_code = 0, $p_error_string = '')
{
- $p_dir = substr($p_dir, 0, strlen($p_dir)-1);
- }
-
- // ----- Check the directory availability
- if ((is_dir($p_dir)) || ($p_dir == ""))
- {
- return 1;
- }
-
- // ----- Extract parent directory
- $p_parent_dir = dirname($p_dir);
-
- // ----- Just a check
- if ($p_parent_dir != $p_dir)
- {
- // ----- Look for parent directory
- if ($p_parent_dir != "")
- {
- if (($v_result = $this->privDirCheck($p_parent_dir)) != 1)
- {
- return $v_result;
+ if (PCLZIP_ERROR_EXTERNAL == 1) {
+ PclError($p_error_code, $p_error_string);
+ } else {
+ $this->error_code = $p_error_code;
+ $this->error_string = $p_error_string;
}
- }
}
+ // --------------------------------------------------------------------------------
- // ----- Create the directory
- if (!@mkdir($p_dir, 0777))
+ // --------------------------------------------------------------------------------
+ // Function : privErrorReset()
+ // Description :
+ // Parameters :
+ // --------------------------------------------------------------------------------
+ public function privErrorReset()
{
- // ----- Error log
- PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'");
-
- // ----- Return
- return PclZip::errorCode();
+ if (PCLZIP_ERROR_EXTERNAL == 1) {
+ PclErrorReset();
+ } else {
+ $this->error_code = 0;
+ $this->error_string = '';
+ }
}
+ // --------------------------------------------------------------------------------
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privMerge()
- // Description :
- // If $p_archive_to_add does not exist, the function exit with a success result.
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privMerge(&$p_archive_to_add)
- {
- $v_result=1;
-
- // ----- Look if the archive_to_add exists
- if (!is_file($p_archive_to_add->zipname))
+ // --------------------------------------------------------------------------------
+ // Function : privDisableMagicQuotes()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privDisableMagicQuotes()
{
+ $v_result = 1;
- // ----- Nothing to merge, so merge is a success
- $v_result = 1;
+ // ----- Look if function exists
+ if ((!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) {
+ return $v_result;
+ }
- // ----- Return
- return $v_result;
+ // ----- Look if already done
+ if ($this->magic_quotes_status != -1) {
+ return $v_result;
+ }
+
+ // ----- Get and memorize the magic_quote value
+ $this->magic_quotes_status = @get_magic_quotes_runtime();
+
+ // ----- Disable magic_quotes
+ if ($this->magic_quotes_status == 1) {
+ @set_magic_quotes_runtime(0);
+ }
+
+ // ----- Return
+ return $v_result;
}
+ // --------------------------------------------------------------------------------
- // ----- Look if the archive exists
- if (!is_file($this->zipname))
+ // --------------------------------------------------------------------------------
+ // Function : privSwapBackMagicQuotes()
+ // Description :
+ // Parameters :
+ // Return Values :
+ // --------------------------------------------------------------------------------
+ public function privSwapBackMagicQuotes()
{
+ $v_result = 1;
- // ----- Do a duplicate
- $v_result = $this->privDuplicate($p_archive_to_add->zipname);
+ // ----- Look if function exists
+ if ((!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) {
+ return $v_result;
+ }
- // ----- Return
- return $v_result;
+ // ----- Look if something to do
+ if ($this->magic_quotes_status != -1) {
+ return $v_result;
+ }
+
+ // ----- Swap back magic_quotes
+ if ($this->magic_quotes_status == 1) {
+ @set_magic_quotes_runtime($this->magic_quotes_status);
+ }
+
+ // ----- Return
+ return $v_result;
}
+ // --------------------------------------------------------------------------------
+}
- // ----- Open the zip file
- if (($v_result=$this->privOpenFd('rb')) != 1)
- {
- // ----- Return
- return $v_result;
- }
+// End of class
+// --------------------------------------------------------------------------------
- // ----- Read the central directory informations
- $v_central_dir = array();
- if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
- {
- $this->privCloseFd();
- return $v_result;
- }
-
- // ----- Go to beginning of File
- @rewind($this->zip_fd);
-
- // ----- Open the archive_to_add file
- if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1)
- {
- $this->privCloseFd();
-
- // ----- Return
- return $v_result;
- }
-
- // ----- Read the central directory informations
- $v_central_dir_to_add = array();
- if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1)
- {
- $this->privCloseFd();
- $p_archive_to_add->privCloseFd();
-
- return $v_result;
- }
-
- // ----- Go to beginning of File
- @rewind($p_archive_to_add->zip_fd);
-
- // ----- Creates a temporay file
- $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
-
- // ----- Open the temporary file in write mode
- if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0)
- {
- $this->privCloseFd();
- $p_archive_to_add->privCloseFd();
-
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Copy the files from the archive to the temporary file
- // TBC : Here I should better append the file and go back to erase the central dir
- $v_size = $v_central_dir['offset'];
- while ($v_size != 0)
- {
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = fread($this->zip_fd, $v_read_size);
- @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
- $v_size -= $v_read_size;
- }
-
- // ----- Copy the files from the archive_to_add into the temporary file
- $v_size = $v_central_dir_to_add['offset'];
- while ($v_size != 0)
- {
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size);
- @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
- $v_size -= $v_read_size;
- }
-
- // ----- Store the offset of the central dir
- $v_offset = @ftell($v_zip_temp_fd);
-
- // ----- Copy the block of file headers from the old archive
- $v_size = $v_central_dir['size'];
- while ($v_size != 0)
- {
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = @fread($this->zip_fd, $v_read_size);
- @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
- $v_size -= $v_read_size;
- }
-
- // ----- Copy the block of file headers from the archive_to_add
- $v_size = $v_central_dir_to_add['size'];
- while ($v_size != 0)
- {
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size);
- @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
- $v_size -= $v_read_size;
- }
-
- // ----- Merge the file comments
- $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment'];
-
- // ----- Calculate the size of the (new) central header
- $v_size = @ftell($v_zip_temp_fd)-$v_offset;
-
- // ----- Swap the file descriptor
- // Here is a trick : I swap the temporary fd with the zip fd, in order to use
- // the following methods on the temporary fil and not the real archive fd
- $v_swap = $this->zip_fd;
- $this->zip_fd = $v_zip_temp_fd;
- $v_zip_temp_fd = $v_swap;
-
- // ----- Create the central dir footer
- if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1)
- {
- $this->privCloseFd();
- $p_archive_to_add->privCloseFd();
- @fclose($v_zip_temp_fd);
- $this->zip_fd = null;
-
- // ----- Reset the file list
- unset($v_header_list);
-
- // ----- Return
- return $v_result;
- }
-
- // ----- Swap back the file descriptor
- $v_swap = $this->zip_fd;
- $this->zip_fd = $v_zip_temp_fd;
- $v_zip_temp_fd = $v_swap;
-
- // ----- Close
- $this->privCloseFd();
- $p_archive_to_add->privCloseFd();
-
- // ----- Close the temporary file
- @fclose($v_zip_temp_fd);
-
- // ----- Delete the zip file
- // TBC : I should test the result ...
- @unlink($this->zipname);
-
- // ----- Rename the temporary file
- // TBC : I should test the result ...
- //@rename($v_zip_temp_name, $this->zipname);
- PclZipUtilRename($v_zip_temp_name, $this->zipname);
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privDuplicate()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privDuplicate($p_archive_filename)
- {
- $v_result=1;
-
- // ----- Look if the $p_archive_filename exists
- if (!is_file($p_archive_filename))
- {
-
- // ----- Nothing to duplicate, so duplicate is a success.
- $v_result = 1;
-
- // ----- Return
- return $v_result;
- }
-
- // ----- Open the zip file
- if (($v_result=$this->privOpenFd('wb')) != 1)
- {
- // ----- Return
- return $v_result;
- }
-
- // ----- Open the temporary file in write mode
- if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0)
- {
- $this->privCloseFd();
-
- PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode');
-
- // ----- Return
- return PclZip::errorCode();
- }
-
- // ----- Copy the files from the archive to the temporary file
- // TBC : Here I should better append the file and go back to erase the central dir
- $v_size = filesize($p_archive_filename);
- while ($v_size != 0)
- {
- $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = fread($v_zip_temp_fd, $v_read_size);
- @fwrite($this->zip_fd, $v_buffer, $v_read_size);
- $v_size -= $v_read_size;
- }
-
- // ----- Close
- $this->privCloseFd();
-
- // ----- Close the temporary file
- @fclose($v_zip_temp_fd);
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privErrorLog()
- // Description :
- // Parameters :
- // --------------------------------------------------------------------------------
- function privErrorLog($p_error_code=0, $p_error_string='')
- {
- if (PCLZIP_ERROR_EXTERNAL == 1) {
- PclError($p_error_code, $p_error_string);
- }
- else {
- $this->error_code = $p_error_code;
- $this->error_string = $p_error_string;
- }
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privErrorReset()
- // Description :
- // Parameters :
- // --------------------------------------------------------------------------------
- function privErrorReset()
- {
- if (PCLZIP_ERROR_EXTERNAL == 1) {
- PclErrorReset();
- }
- else {
- $this->error_code = 0;
- $this->error_string = '';
- }
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privDisableMagicQuotes()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privDisableMagicQuotes()
- {
- $v_result=1;
-
- // ----- Look if function exists
- if ( (!function_exists("get_magic_quotes_runtime"))
- || (!function_exists("set_magic_quotes_runtime"))) {
- return $v_result;
- }
-
- // ----- Look if already done
- if ($this->magic_quotes_status != -1) {
- return $v_result;
- }
-
- // ----- Get and memorize the magic_quote value
- $this->magic_quotes_status = @get_magic_quotes_runtime();
-
- // ----- Disable magic_quotes
- if ($this->magic_quotes_status == 1) {
- @set_magic_quotes_runtime(0);
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : privSwapBackMagicQuotes()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function privSwapBackMagicQuotes()
- {
- $v_result=1;
-
- // ----- Look if function exists
- if ( (!function_exists("get_magic_quotes_runtime"))
- || (!function_exists("set_magic_quotes_runtime"))) {
- return $v_result;
- }
-
- // ----- Look if something to do
- if ($this->magic_quotes_status != -1) {
- return $v_result;
- }
-
- // ----- Swap back magic_quotes
- if ($this->magic_quotes_status == 1) {
- @set_magic_quotes_runtime($this->magic_quotes_status);
- }
-
- // ----- Return
- return $v_result;
- }
- // --------------------------------------------------------------------------------
-
- }
- // End of class
- // --------------------------------------------------------------------------------
-
- // --------------------------------------------------------------------------------
- // Function : PclZipUtilPathReduction()
- // Description :
- // Parameters :
- // Return Values :
- // --------------------------------------------------------------------------------
- function PclZipUtilPathReduction($p_dir)
- {
+// --------------------------------------------------------------------------------
+// Function : PclZipUtilPathReduction()
+// Description :
+// Parameters :
+// Return Values :
+// --------------------------------------------------------------------------------
+function PclZipUtilPathReduction($p_dir)
+{
$v_result = "";
// ----- Look for not empty path
if ($p_dir != "") {
- // ----- Explode path by directory names
- $v_list = explode("/", $p_dir);
+ // ----- Explode path by directory names
+ $v_list = explode("/", $p_dir);
- // ----- Study directories from last to first
- $v_skip = 0;
- for ($i=sizeof($v_list)-1; $i>=0; $i--) {
- // ----- Look for current path
- if ($v_list[$i] == ".") {
- // ----- Ignore this directory
- // Should be the first $i=0, but no check is done
+ // ----- Study directories from last to first
+ $v_skip = 0;
+ for ($i = sizeof($v_list) - 1; $i >= 0; $i--) {
+ // ----- Look for current path
+ if ($v_list[$i] == ".") {
+ // ----- Ignore this directory
+ // Should be the first $i=0, but no check is done
+ } elseif ($v_list[$i] == "..") {
+ $v_skip++;
+ } elseif ($v_list[$i] == "") {
+ // ----- First '/' i.e. root slash
+ if ($i == 0) {
+ $v_result = "/" . $v_result;
+ if ($v_skip > 0) {
+ // ----- It is an invalid path, so the path is not modified
+ // TBC
+ $v_result = $p_dir;
+ $v_skip = 0;
+ }
+
+ // ----- Last '/' i.e. indicates a directory
+ } elseif ($i == (sizeof($v_list) - 1)) {
+ $v_result = $v_list[$i];
+
+ // ----- Double '/' inside the path
+ } else {
+ // ----- Ignore only the double '//' in path,
+ // but not the first and last '/'
+ }
+ } else {
+ // ----- Look for item to skip
+ if ($v_skip > 0) {
+ $v_skip--;
+ } else {
+ $v_result = $v_list[$i] . ($i != (sizeof($v_list) - 1) ? "/" . $v_result : "");
+ }
+ }
}
- else if ($v_list[$i] == "..") {
- $v_skip++;
+
+ // ----- Look for skip
+ if ($v_skip > 0) {
+ while ($v_skip > 0) {
+ $v_result = '../' . $v_result;
+ $v_skip--;
+ }
}
- else if ($v_list[$i] == "") {
- // ----- First '/' i.e. root slash
- if ($i == 0) {
- $v_result = "/".$v_result;
- if ($v_skip > 0) {
- // ----- It is an invalid path, so the path is not modified
- // TBC
- $v_result = $p_dir;
- $v_skip = 0;
- }
- }
- // ----- Last '/' i.e. indicates a directory
- else if ($i == (sizeof($v_list)-1)) {
- $v_result = $v_list[$i];
- }
- // ----- Double '/' inside the path
- else {
- // ----- Ignore only the double '//' in path,
- // but not the first and last '/'
- }
- }
- else {
- // ----- Look for item to skip
- if ($v_skip > 0) {
- $v_skip--;
- }
- else {
- $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:"");
- }
- }
- }
-
- // ----- Look for skip
- if ($v_skip > 0) {
- while ($v_skip > 0) {
- $v_result = '../'.$v_result;
- $v_skip--;
- }
- }
}
// ----- Return
return $v_result;
- }
- // --------------------------------------------------------------------------------
+}
+// --------------------------------------------------------------------------------
- // --------------------------------------------------------------------------------
- // Function : PclZipUtilPathInclusion()
- // Description :
- // This function indicates if the path $p_path is under the $p_dir tree. Or,
- // said in an other way, if the file or sub-dir $p_path is inside the dir
- // $p_dir.
- // The function indicates also if the path is exactly the same as the dir.
- // This function supports path with duplicated '/' like '//', but does not
- // support '.' or '..' statements.
- // Parameters :
- // Return Values :
- // 0 if $p_path is not inside directory $p_dir
- // 1 if $p_path is inside directory $p_dir
- // 2 if $p_path is exactly the same as $p_dir
- // --------------------------------------------------------------------------------
- function PclZipUtilPathInclusion($p_dir, $p_path)
- {
+// --------------------------------------------------------------------------------
+// Function : PclZipUtilPathInclusion()
+// Description :
+// This function indicates if the path $p_path is under the $p_dir tree. Or,
+// said in an other way, if the file or sub-dir $p_path is inside the dir
+// $p_dir.
+// The function indicates also if the path is exactly the same as the dir.
+// This function supports path with duplicated '/' like '//', but does not
+// support '.' or '..' statements.
+// Parameters :
+// Return Values :
+// 0 if $p_path is not inside directory $p_dir
+// 1 if $p_path is inside directory $p_dir
+// 2 if $p_path is exactly the same as $p_dir
+// --------------------------------------------------------------------------------
+function PclZipUtilPathInclusion($p_dir, $p_path)
+{
$v_result = 1;
-
+
// ----- Look for path beginning by ./
- if ( ($p_dir == '.')
- || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) {
- $p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1);
+ if (($p_dir == '.') || ((strlen($p_dir) >= 2) && (substr($p_dir, 0, 2) == './'))) {
+ $p_dir = PclZipUtilTranslateWinPath(getcwd(), false) . '/' . substr($p_dir, 1);
}
- if ( ($p_path == '.')
- || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) {
- $p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1);
+ if (($p_path == '.') || ((strlen($p_path) >= 2) && (substr($p_path, 0, 2) == './'))) {
+ $p_path = PclZipUtilTranslateWinPath(getcwd(), false) . '/' . substr($p_path, 1);
}
// ----- Explode dir and path by directory separator
- $v_list_dir = explode("/", $p_dir);
- $v_list_dir_size = sizeof($v_list_dir);
- $v_list_path = explode("/", $p_path);
+ $v_list_dir = explode("/", $p_dir);
+ $v_list_dir_size = sizeof($v_list_dir);
+ $v_list_path = explode("/", $p_path);
$v_list_path_size = sizeof($v_list_path);
// ----- Study directories paths
@@ -5498,196 +5234,182 @@
$j = 0;
while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) {
- // ----- Look for empty dir (path reduction)
- if ($v_list_dir[$i] == '') {
+ // ----- Look for empty dir (path reduction)
+ if ($v_list_dir[$i] == '') {
+ $i++;
+ continue;
+ }
+ if ($v_list_path[$j] == '') {
+ $j++;
+ continue;
+ }
+
+ // ----- Compare the items
+ if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ($v_list_path[$j] != '')) {
+ $v_result = 0;
+ }
+
+ // ----- Next items
$i++;
- continue;
- }
- if ($v_list_path[$j] == '') {
$j++;
- continue;
- }
-
- // ----- Compare the items
- if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) {
- $v_result = 0;
- }
-
- // ----- Next items
- $i++;
- $j++;
}
// ----- Look if everything seems to be the same
if ($v_result) {
- // ----- Skip all the empty items
- while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++;
- while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++;
+ // ----- Skip all the empty items
+ while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) {
+ $j++;
+ }
+ while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) {
+ $i++;
+ }
- if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) {
- // ----- There are exactly the same
- $v_result = 2;
- }
- else if ($i < $v_list_dir_size) {
- // ----- The path is shorter than the dir
- $v_result = 0;
- }
+ if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) {
+ // ----- There are exactly the same
+ $v_result = 2;
+ } elseif ($i < $v_list_dir_size) {
+ // ----- The path is shorter than the dir
+ $v_result = 0;
+ }
}
// ----- Return
return $v_result;
- }
- // --------------------------------------------------------------------------------
+}
+// --------------------------------------------------------------------------------
- // --------------------------------------------------------------------------------
- // Function : PclZipUtilCopyBlock()
- // Description :
- // Parameters :
- // $p_mode : read/write compression mode
- // 0 : src & dest normal
- // 1 : src gzip, dest normal
- // 2 : src normal, dest gzip
- // 3 : src & dest gzip
- // Return Values :
- // --------------------------------------------------------------------------------
- function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0)
- {
+// --------------------------------------------------------------------------------
+// Function : PclZipUtilCopyBlock()
+// Description :
+// Parameters :
+// $p_mode : read/write compression mode
+// 0 : src & dest normal
+// 1 : src gzip, dest normal
+// 2 : src normal, dest gzip
+// 3 : src & dest gzip
+// Return Values :
+// --------------------------------------------------------------------------------
+function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode = 0)
+{
$v_result = 1;
- if ($p_mode==0)
- {
- while ($p_size != 0)
- {
- $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = @fread($p_src, $v_read_size);
- @fwrite($p_dest, $v_buffer, $v_read_size);
- $p_size -= $v_read_size;
- }
- }
- else if ($p_mode==1)
- {
- while ($p_size != 0)
- {
- $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = @gzread($p_src, $v_read_size);
- @fwrite($p_dest, $v_buffer, $v_read_size);
- $p_size -= $v_read_size;
- }
- }
- else if ($p_mode==2)
- {
- while ($p_size != 0)
- {
- $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = @fread($p_src, $v_read_size);
- @gzwrite($p_dest, $v_buffer, $v_read_size);
- $p_size -= $v_read_size;
- }
- }
- else if ($p_mode==3)
- {
- while ($p_size != 0)
- {
- $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
- $v_buffer = @gzread($p_src, $v_read_size);
- @gzwrite($p_dest, $v_buffer, $v_read_size);
- $p_size -= $v_read_size;
- }
+ if ($p_mode == 0) {
+ while ($p_size != 0) {
+ $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = @fread($p_src, $v_read_size);
+ @fwrite($p_dest, $v_buffer, $v_read_size);
+ $p_size -= $v_read_size;
+ }
+ } elseif ($p_mode == 1) {
+ while ($p_size != 0) {
+ $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = @gzread($p_src, $v_read_size);
+ @fwrite($p_dest, $v_buffer, $v_read_size);
+ $p_size -= $v_read_size;
+ }
+ } elseif ($p_mode == 2) {
+ while ($p_size != 0) {
+ $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = @fread($p_src, $v_read_size);
+ @gzwrite($p_dest, $v_buffer, $v_read_size);
+ $p_size -= $v_read_size;
+ }
+ } elseif ($p_mode == 3) {
+ while ($p_size != 0) {
+ $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
+ $v_buffer = @gzread($p_src, $v_read_size);
+ @gzwrite($p_dest, $v_buffer, $v_read_size);
+ $p_size -= $v_read_size;
+ }
}
// ----- Return
return $v_result;
- }
- // --------------------------------------------------------------------------------
+}
+// --------------------------------------------------------------------------------
- // --------------------------------------------------------------------------------
- // Function : PclZipUtilRename()
- // Description :
- // This function tries to do a simple rename() function. If it fails, it
- // tries to copy the $p_src file in a new $p_dest file and then unlink the
- // first one.
- // Parameters :
- // $p_src : Old filename
- // $p_dest : New filename
- // Return Values :
- // 1 on success, 0 on failure.
- // --------------------------------------------------------------------------------
- function PclZipUtilRename($p_src, $p_dest)
- {
+// --------------------------------------------------------------------------------
+// Function : PclZipUtilRename()
+// Description :
+// This function tries to do a simple rename() function. If it fails, it
+// tries to copy the $p_src file in a new $p_dest file and then unlink the
+// first one.
+// Parameters :
+// $p_src : Old filename
+// $p_dest : New filename
+// Return Values :
+// 1 on success, 0 on failure.
+// --------------------------------------------------------------------------------
+function PclZipUtilRename($p_src, $p_dest)
+{
$v_result = 1;
// ----- Try to rename the files
if (!@rename($p_src, $p_dest)) {
- // ----- Try to copy & unlink the src
- if (!@copy($p_src, $p_dest)) {
- $v_result = 0;
- }
- else if (!@unlink($p_src)) {
- $v_result = 0;
- }
+ // ----- Try to copy & unlink the src
+ if (!@copy($p_src, $p_dest)) {
+ $v_result = 0;
+ } elseif (!@unlink($p_src)) {
+ $v_result = 0;
+ }
}
// ----- Return
return $v_result;
- }
- // --------------------------------------------------------------------------------
+}
+// --------------------------------------------------------------------------------
+
+// --------------------------------------------------------------------------------
+// Function : PclZipUtilOptionText()
+// Description :
+// Translate option value in text. Mainly for debug purpose.
+// Parameters :
+// $p_option : the option value.
+// Return Values :
+// The option text value.
+// --------------------------------------------------------------------------------
+function PclZipUtilOptionText($p_option)
+{
- // --------------------------------------------------------------------------------
- // Function : PclZipUtilOptionText()
- // Description :
- // Translate option value in text. Mainly for debug purpose.
- // Parameters :
- // $p_option : the option value.
- // Return Values :
- // The option text value.
- // --------------------------------------------------------------------------------
- function PclZipUtilOptionText($p_option)
- {
-
$v_list = get_defined_constants();
for (reset($v_list); $v_key = key($v_list); next($v_list)) {
- $v_prefix = substr($v_key, 0, 10);
- if (( ($v_prefix == 'PCLZIP_OPT')
- || ($v_prefix == 'PCLZIP_CB_')
- || ($v_prefix == 'PCLZIP_ATT'))
- && ($v_list[$v_key] == $p_option)) {
- return $v_key;
- }
+ $v_prefix = substr($v_key, 0, 10);
+ if ((($v_prefix == 'PCLZIP_OPT') || ($v_prefix == 'PCLZIP_CB_') || ($v_prefix == 'PCLZIP_ATT')) && ($v_list[$v_key] == $p_option)) {
+ return $v_key;
+ }
}
-
+
$v_result = 'Unknown';
return $v_result;
- }
- // --------------------------------------------------------------------------------
+}
+// --------------------------------------------------------------------------------
- // --------------------------------------------------------------------------------
- // Function : PclZipUtilTranslateWinPath()
- // Description :
- // Translate windows path by replacing '\' by '/' and optionally removing
- // drive letter.
- // Parameters :
- // $p_path : path to translate.
- // $p_remove_disk_letter : true | false
- // Return Values :
- // The path translated.
- // --------------------------------------------------------------------------------
- function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true)
- {
+// --------------------------------------------------------------------------------
+// Function : PclZipUtilTranslateWinPath()
+// Description :
+// Translate windows path by replacing '\' by '/' and optionally removing
+// drive letter.
+// Parameters :
+// $p_path : path to translate.
+// $p_remove_disk_letter : true | false
+// Return Values :
+// The path translated.
+// --------------------------------------------------------------------------------
+function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter = true)
+{
if (stristr(php_uname(), 'windows')) {
- // ----- Look for potential disk letter
- if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) {
- $p_path = substr($p_path, $v_position+1);
- }
- // ----- Change potential windows directory separator
- if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
- $p_path = strtr($p_path, '\\', '/');
- }
+ // ----- Look for potential disk letter
+ if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) {
+ $p_path = substr($p_path, $v_position + 1);
+ }
+ // ----- Change potential windows directory separator
+ if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0, 1) == '\\')) {
+ $p_path = strtr($p_path, '\\', '/');
+ }
}
+
return $p_path;
- }
- // --------------------------------------------------------------------------------
-
-
-?>
+}
+// --------------------------------------------------------------------------------
diff --git a/htdocs/includes/odtphp/zip/pclzip/readme.txt b/htdocs/includes/odtphp/zip/pclzip/readme.txt
index c5d2486d3ef..f0281349345 100644
--- a/htdocs/includes/odtphp/zip/pclzip/readme.txt
+++ b/htdocs/includes/odtphp/zip/pclzip/readme.txt
@@ -1,15 +1,14 @@
// --------------------------------------------------------------------------------
-// PclZip 2.8.2 - readme.txt
+// PclZip 2.8.4 - readme.txt
// --------------------------------------------------------------------------------
// License GNU/LGPL - August 2009
// Vincent Blavet - vincent@phpconcept.net
// http://www.phpconcept.net
// --------------------------------------------------------------------------------
-// --------------------------------------------------------------------------------
-0 - Sommaire
+0 - Summary
============
1 - Introduction
2 - What's new
@@ -31,12 +30,18 @@
2 - What's new
==============
+ Version 2.8.4 :
+ - Update composer.json to indicate that pclzip/pclzip is replaced
+
+ Version 2.8.3 :
+ - Fix compatibility with PHP v7.1
+
Version 2.8.2 :
- - PCLZIP_CB_PRE_EXTRACT and PCLZIP_CB_POST_EXTRACT are now supported with
+ - PCLZIP_CB_PRE_EXTRACT and PCLZIP_CB_POST_EXTRACT are now supported with
extraction as a string (PCLZIP_OPT_EXTRACT_AS_STRING). The string
can also be modified in the post-extract call back.
**Bugs correction :
- - PCLZIP_OPT_REMOVE_ALL_PATH was not working correctly
+ - PCLZIP_OPT_REMOVE_ALL_PATH was not working correctly
- Remove use of eval() and do direct call to callback functions
- Correct support of 64bits systems (Thanks to WordPress team)
@@ -44,7 +49,7 @@
- Move option PCLZIP_OPT_BY_EREG to PCLZIP_OPT_BY_PREG because ereg() is
deprecated in PHP 5.3. When using option PCLZIP_OPT_BY_EREG, PclZip will
automatically replace it by PCLZIP_OPT_BY_PREG.
-
+
Version 2.8 :
- Improve extraction of zip archive for large files by using temporary files
This feature is working like the one defined in r2.7.
@@ -61,7 +66,7 @@
when large file is suspected.
This feature can also ne triggered by manual options in create() and add()
methods. 'PCLZIP_OPT_ADD_TEMP_FILE_ON' force the use of temporary files,
- 'PCLZIP_OPT_ADD_TEMP_FILE_OFF' disable the autosense technic,
+ 'PCLZIP_OPT_ADD_TEMP_FILE_OFF' disable the autosense technic,
'PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD' allow for configuration of a size
threshold to use temporary files.
Using "temporary files" rather than "memory" might take more time, but
@@ -78,7 +83,7 @@
- Code optimisation
- New attributes PCLZIP_ATT_FILE_COMMENT gives the ability to
add a comment for a specific file. (Don't really know if this is usefull)
- - New attribute PCLZIP_ATT_FILE_CONTENT gives the ability to add a string
+ - New attribute PCLZIP_ATT_FILE_CONTENT gives the ability to add a string
as a file.
- New attribute PCLZIP_ATT_FILE_MTIME modify the timestamp associated with
a file.
@@ -88,12 +93,12 @@
action.
- Add missing closedir() statement.
- When adding a folder, and removing the path of this folder, files were
- incorrectly added with a '/' at the beginning. Which means files are
+ incorrectly added with a '/' at the beginning. Which means files are
related to root in unix systems. Corrected.
- Add conditional if before constant definition. This will allow users
to redefine constants without changing the file, and then improve
upgrade of pclzip code for new versions.
-
+
Version 2.5 :
- Introduce the ability to add file/folder with individual properties (file descriptor).
This gives for example the ability to change the filename of a zipped file.
@@ -111,19 +116,19 @@
- New error code : PCLZIP_ERR_DIRECTORY_RESTRICTION
- Modification in PclZipUtilPathInclusion() : dir and path beginning with ./ will be prepend
by current path (getcwd())
-
+
Version 2.4 :
- Code improvment : try to speed up the code by removing unusefull call to pack()
- Correct bug in delete() : delete() should be called with no argument. This was not
the case in 2.3. This is corrected in 2.4.
- Correct a bug in path_inclusion function. When the path has several '../../', the
result was bad.
- - Add a check for magic_quotes_runtime configuration. If enabled, PclZip will
+ - Add a check for magic_quotes_runtime configuration. If enabled, PclZip will
disable it while working and det it back to its original value.
This resolve a lots of bad formated archive errors.
- Bug correction : PclZip now correctly unzip file in some specific situation,
when compressed content has same size as uncompressed content.
- - Bug correction : When selecting option 'PCLZIP_OPT_REMOVE_ALL_PATH',
+ - Bug correction : When selecting option 'PCLZIP_OPT_REMOVE_ALL_PATH',
directories are not any more created.
- Code improvment : correct unclosed opendir(), better handling of . and .. in
loops.
@@ -174,7 +179,7 @@
- Add support for parameters PCLZIP_OPT_COMMENT, PCLZIP_OPT_ADD_COMMENT,
PCLZIP_OPT_PREPEND_COMMENT. This will create, replace, add, or prepend comments
in the zip archive.
- - When merging two archives, the comments are not any more lost, but merged, with a
+ - When merging two archives, the comments are not any more lost, but merged, with a
blank space separator.
- Corrected bug : Files are not deleted when all files are asked to be deleted.
- Corrected bug : Folders with name '0' made PclZip to abort the create or add feature.
@@ -183,12 +188,12 @@
Version 2.0 :
***** Warning : Some new features may break the backward compatibility for your scripts.
Please carefully read the readme file.
- - Add the ability to delete by Index, name and regular expression. This feature is
+ - Add the ability to delete by Index, name and regular expression. This feature is
performed by the method delete(), which uses the optional parameters
PCLZIP_OPT_BY_INDEX, PCLZIP_OPT_BY_NAME, PCLZIP_OPT_BY_EREG or PCLZIP_OPT_BY_PREG.
- Add the ability to extract by regular expression. To extract by regexp you must use the method
- extract(), with the option PCLZIP_OPT_BY_EREG or PCLZIP_OPT_BY_PREG
- (depending if you want to use ereg() or preg_match() syntax) followed by the
+ extract(), with the option PCLZIP_OPT_BY_EREG or PCLZIP_OPT_BY_PREG
+ (depending if you want to use ereg() or preg_match() syntax) followed by the
regular expression pattern.
- Add the ability to extract by index, directly with the extract() method. This is a
code improvment of the extractByIndex() method.
@@ -204,7 +209,7 @@
The default separator is now a comma (,) and not any more a blank space.
THIS BREAK THE BACKWARD COMPATIBILITY : Please check if this may have an impact with
your script.
- - Improve algorythm performance by removing the use of temporary files when adding or
+ - Improve algorythm performance by removing the use of temporary files when adding or
extracting files in an archive.
- Add (correct) detection of empty filename zipping. This can occurs when the removed
path is the same
@@ -299,7 +304,7 @@
Corrected in Version 2.0 :
- Corrected : During an extraction, if a call-back fucntion is used and try to skip
- a file, all the extraction process is stopped.
+ a file, all the extraction process is stopped.
Corrected in Version 1.3 :
- Corrected : Support of static synopsis for method extract() is broken.
@@ -344,7 +349,7 @@
In Version 2.x :
- PclZip does only support file uncompressed or compressed with deflate (compression method 8)
- PclZip does not support password protected zip archive
- - Some concern were seen when changing mtime of a file while archiving.
+ - Some concern were seen when changing mtime of a file while archiving.
Seems to be linked to Daylight Saving Time (PclTest_changing_mtime).
In Version 1.2 :
diff --git a/htdocs/index.php b/htdocs/index.php
index ebc343b5e8d..5290e2623a2 100644
--- a/htdocs/index.php
+++ b/htdocs/index.php
@@ -68,7 +68,7 @@ if (GETPOST('addbox')) // Add box (when submit is done from a form when ajax dis
* View
*/
-if (!is_object($form)) $form = new Form($db);
+if (!isset($form) || !is_object($form)) $form = new Form($db);
// Title
$title = $langs->trans("HomeArea").' - Dolibarr '.DOL_VERSION;
@@ -295,7 +295,7 @@ if (empty($user->socid) && empty($conf->global->MAIN_DISABLE_GLOBAL_BOXSTATS))
$class = $classes[$val];
// Search in cache if load_state_board is already realized
$classkeyforcache = $class;
- if ($classkeyforcache == 'ProductService') $classkeyforcache = 'Product'; // ProductService use same load_state_board than Product
+ if ($classkeyforcache == 'ProductService') $classkeyforcache = 'Product'; // ProductService use same load_state_board than Product
if (!isset($boardloaded[$classkeyforcache]) || !is_object($boardloaded[$classkeyforcache]))
{
diff --git a/htdocs/install/check.php b/htdocs/install/check.php
index 267e1629f36..bd34a0ac30c 100644
--- a/htdocs/install/check.php
+++ b/htdocs/install/check.php
@@ -68,10 +68,10 @@ print ' '.$langs->trans("WarningBrowserTooOld")." \n";
+ $tmp = getBrowserInfo($_SERVER["HTTP_USER_AGENT"]);
+ $browserversion = $tmp['browserversion'];
+ $browsername = $tmp['browsername'];
+ if ($browsername == 'ie' && $browserversion < 7) print ' '.$langs->trans("WarningBrowserTooOld")." \n";
}
@@ -84,8 +84,8 @@ if (versioncompare(versionphparray(), $arrayphpminversionerror) < 0) // M
$checksok = 0; // 0=error, 1=warning
} elseif (versioncompare(versionphparray(), $arrayphpminversionwarning) < 0) // Minimum supported (warning if lower)
{
- print ' '.$langs->trans("ErrorPHPVersionTooLow", versiontostring($arrayphpminversionwarning));
- $checksok = 0; // 0=error, 1=warning
+ print ' '.$langs->trans("ErrorPHPVersionTooLow", versiontostring($arrayphpminversionwarning));
+ $checksok = 0; // 0=error, 1=warning
} else {
print ' '.$langs->trans("PHPVersion")." ".versiontostring(versionphparray());
}
@@ -129,19 +129,19 @@ if (!function_exists("imagecreate"))
// Check if Curl supported
if (!function_exists("curl_init"))
{
- $langs->load("errors");
- print ' '.$langs->trans("ErrorPHPDoesNotSupportCurl")." \n";
- // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install)
+ $langs->load("errors");
+ print ' '.$langs->trans("ErrorPHPDoesNotSupportCurl")." \n";
+ // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install)
} else {
- print ' '.$langs->trans("PHPSupportCurl")." \n";
+ print ' '.$langs->trans("PHPSupportCurl")." \n";
}
// Check if PHP calendar extension is available
if (!function_exists("easter_date"))
{
- print ' '.$langs->trans("ErrorPHPDoesNotSupportCalendar")." \n";
+ print ' '.$langs->trans("ErrorPHPDoesNotSupportCalendar")." \n";
} else {
- print ' '.$langs->trans("PHPSupportCalendar")." \n";
+ print ' '.$langs->trans("PHPSupportCalendar")." \n";
}
@@ -161,11 +161,11 @@ if (empty($_SERVER["SERVER_ADMIN"]) || $_SERVER["SERVER_ADMIN"] != 'doliwamp@loc
{
if (!function_exists("locale_get_primary_language") || !function_exists("locale_get_region"))
{
- $langs->load("errors");
- print ' '.$langs->trans("ErrorPHPDoesNotSupportIntl")." \n";
- // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install)
+ $langs->load("errors");
+ print ' '.$langs->trans("ErrorPHPDoesNotSupportIntl")." \n";
+ // $checksok = 0; // If ko, just warning. So check must still be 1 (otherwise no way to install)
} else {
- print ' '.$langs->trans("PHPSupportIntl")." \n";
+ print ' '.$langs->trans("PHPSupportIntl")." \n";
}
}
@@ -307,35 +307,35 @@ if (!file_exists($conffile))
{
if (!file_exists($dolibarr_main_document_root."/core/lib/admin.lib.php"))
{
- print 'A '.$conffiletoshow.' file exists with a dolibarr_main_document_root to '.$dolibarr_main_document_root.' that seems wrong. Try to fix or remove the '.$conffiletoshow.' file. '."\n";
- dol_syslog("A '".$conffiletoshow."' file exists with a dolibarr_main_document_root to ".$dolibarr_main_document_root." that seems wrong. Try to fix or remove the '".$conffiletoshow."' file.", LOG_WARNING);
+ print 'A '.$conffiletoshow.' file exists with a dolibarr_main_document_root to '.$dolibarr_main_document_root.' that seems wrong. Try to fix or remove the '.$conffiletoshow.' file. '."\n";
+ dol_syslog("A '".$conffiletoshow."' file exists with a dolibarr_main_document_root to ".$dolibarr_main_document_root." that seems wrong. Try to fix or remove the '".$conffiletoshow."' file.", LOG_WARNING);
} else {
- require_once $dolibarr_main_document_root.'/core/lib/admin.lib.php';
+ require_once $dolibarr_main_document_root.'/core/lib/admin.lib.php';
- // If password is encoded, we decode it
- if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass))
- {
- require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
- if (preg_match('/crypted:/i', $dolibarr_main_db_pass))
- {
- $dolibarr_main_db_encrypted_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass); // We need to set this as it is used to know the password was initially crypted
- $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
- } else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
- }
+ // If password is encoded, we decode it
+ if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass))
+ {
+ require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
+ if (preg_match('/crypted:/i', $dolibarr_main_db_pass))
+ {
+ $dolibarr_main_db_encrypted_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass); // We need to set this as it is used to know the password was initially crypted
+ $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
+ } else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
+ }
- // $conf already created in inc.php
- $conf->db->type = $dolibarr_main_db_type;
- $conf->db->host = $dolibarr_main_db_host;
- $conf->db->port = $dolibarr_main_db_port;
- $conf->db->name = $dolibarr_main_db_name;
- $conf->db->user = $dolibarr_main_db_user;
- $conf->db->pass = $dolibarr_main_db_pass;
- $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port);
- if ($db->connected && $db->database_selected)
- {
- $ok = true;
- }
- }
+ // $conf already created in inc.php
+ $conf->db->type = $dolibarr_main_db_type;
+ $conf->db->host = $dolibarr_main_db_host;
+ $conf->db->port = $dolibarr_main_db_port;
+ $conf->db->name = $dolibarr_main_db_name;
+ $conf->db->user = $dolibarr_main_db_user;
+ $conf->db->pass = $dolibarr_main_db_pass;
+ $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port);
+ if ($db->connected && $db->database_selected)
+ {
+ $ok = true;
+ }
+ }
}
}
@@ -361,8 +361,8 @@ if (!file_exists($conffile))
// Show title
if (!empty($conf->global->MAIN_VERSION_LAST_UPGRADE) || !empty($conf->global->MAIN_VERSION_LAST_INSTALL))
{
- print $langs->trans("VersionLastUpgrade").': '.(empty($conf->global->MAIN_VERSION_LAST_UPGRADE) ? $conf->global->MAIN_VERSION_LAST_INSTALL : $conf->global->MAIN_VERSION_LAST_UPGRADE).' - ';
- print $langs->trans("VersionProgram").': '.DOL_VERSION.' ';
+ print $langs->trans("VersionLastUpgrade").': '.(empty($conf->global->MAIN_VERSION_LAST_UPGRADE) ? $conf->global->MAIN_VERSION_LAST_INSTALL : $conf->global->MAIN_VERSION_LAST_UPGRADE).' - ';
+ print $langs->trans("VersionProgram").': '.DOL_VERSION.' ';
//print ' '.img_warning($langs->trans("RunningUpdateProcessMayBeRequired"));
print ' ';
print ' ';
@@ -373,19 +373,19 @@ if (!file_exists($conffile))
$foundrecommandedchoice = 0;
- $available_choices = array();
- $notavailable_choices = array();
+ $available_choices = array();
+ $notavailable_choices = array();
- if (empty($dolibarr_main_db_host)) // This means install process was not run
- {
- $foundrecommandedchoice = 1; // To show only once
- }
+ if (empty($dolibarr_main_db_host)) // This means install process was not run
+ {
+ $foundrecommandedchoice = 1; // To show only once
+ }
- // Show line of first install choice
- $choice = ''."\n";
- $choice .= ''.$langs->trans("FreshInstall").' ';
+ // Show line of first install choice
+ $choice = ' '."\n";
+ $choice .= ''.$langs->trans("FreshInstall").' ';
$choice .= ' ';
- $choice .= '';
+ $choice .= ' ';
$choice .= $langs->trans("FreshInstallDesc");
if (empty($dolibarr_main_db_host)) // This means install process was not run
{
@@ -395,23 +395,23 @@ if (!file_exists($conffile))
// ';
}
- $choice .= ' ';
- $choice .= '';
+ $choice .= ' ';
+ $choice .= '';
if ($allowinstall)
{
- $choice .= ''.$langs->trans("Start").' ';
+ $choice .= ''.$langs->trans("Start").' ';
} else {
$choice .= ($foundrecommandedchoice ? '' : '').$langs->trans("InstallNotAllowed").($foundrecommandedchoice ? ' ' : '');
}
- $choice .= ' '."\n";
- $choice .= ' '."\n";
+ $choice .= ''."\n";
+ $choice .= ''."\n";
- $positionkey = ($foundrecommandedchoice ? 999 : 0);
- if ($allowinstall) {
- $available_choices[$positionkey] = $choice;
- } else {
- $notavailable_choices[$positionkey] = $choice;
- }
+ $positionkey = ($foundrecommandedchoice ? 999 : 0);
+ if ($allowinstall) {
+ $available_choices[$positionkey] = $choice;
+ } else {
+ $notavailable_choices[$positionkey] = $choice;
+ }
// Show upgrade lines
$allowupgrade = true;
@@ -445,64 +445,64 @@ if (!file_exists($conffile))
$count = 0;
foreach ($migrationscript as $migarray)
{
- $choice = '';
+ $choice = '';
$count++;
- $recommended_choice = false;
- $version = DOL_VERSION;
+ $recommended_choice = false;
+ $version = DOL_VERSION;
$versionfrom = $migarray['from'];
- $versionto = $migarray['to'];
- $versionarray = preg_split('/[\.-]/', $version);
- $dolibarrversionfromarray = preg_split('/[\.-]/', $versionfrom);
- $dolibarrversiontoarray = preg_split('/[\.-]/', $versionto);
- // Define string newversionxxx that are used for text to show
- $newversionfrom = preg_replace('/(\.[0-9]+)$/i', '.*', $versionfrom);
- $newversionto = preg_replace('/(\.[0-9]+)$/i', '.*', $versionto);
- $newversionfrombis = '';
- if (versioncompare($dolibarrversiontoarray, $versionarray) < -2) // From x.y.z -> x.y.z+1
- {
- $newversionfrombis = ' '.$langs->trans("or").' '.$versionto;
- }
+ $versionto = $migarray['to'];
+ $versionarray = preg_split('/[\.-]/', $version);
+ $dolibarrversionfromarray = preg_split('/[\.-]/', $versionfrom);
+ $dolibarrversiontoarray = preg_split('/[\.-]/', $versionto);
+ // Define string newversionxxx that are used for text to show
+ $newversionfrom = preg_replace('/(\.[0-9]+)$/i', '.*', $versionfrom);
+ $newversionto = preg_replace('/(\.[0-9]+)$/i', '.*', $versionto);
+ $newversionfrombis = '';
+ if (versioncompare($dolibarrversiontoarray, $versionarray) < -2) // From x.y.z -> x.y.z+1
+ {
+ $newversionfrombis = ' '.$langs->trans("or").' '.$versionto;
+ }
- if ($ok)
- {
- if (count($dolibarrlastupgradeversionarray) >= 2) // If database access is available and last upgrade version is known
- {
- // Now we check if this is the first qualified choice
- if ($allowupgrade && empty($foundrecommandedchoice) &&
- (versioncompare($dolibarrversiontoarray, $dolibarrlastupgradeversionarray) > 0 || versioncompare($dolibarrversiontoarray, $versionarray) < -2)
- )
- {
- $foundrecommandedchoice = 1; // To show only once
- $recommended_choice = true;
- }
- } else {
- // We cannot recommend a choice.
- // A version of install may be known, but we need last upgrade.
- }
- }
+ if ($ok)
+ {
+ if (count($dolibarrlastupgradeversionarray) >= 2) // If database access is available and last upgrade version is known
+ {
+ // Now we check if this is the first qualified choice
+ if ($allowupgrade && empty($foundrecommandedchoice) &&
+ (versioncompare($dolibarrversiontoarray, $dolibarrlastupgradeversionarray) > 0 || versioncompare($dolibarrversiontoarray, $versionarray) < -2)
+ )
+ {
+ $foundrecommandedchoice = 1; // To show only once
+ $recommended_choice = true;
+ }
+ } else {
+ // We cannot recommend a choice.
+ // A version of install may be known, but we need last upgrade.
+ }
+ }
- $choice .= "\n".''."\n";
- $choice .= '';
- $choice .= ''.$langs->trans("Upgrade").' '.$newversionfrom.$newversionfrombis.' -> '.$newversionto.' ';
- $choice .= '';
- $choice .= $langs->trans("UpgradeDesc");
+ $choice .= "\n".''."\n";
+ $choice .= ' ';
+ $choice .= ''.$langs->trans("Upgrade").' '.$newversionfrom.$newversionfrombis.' -> '.$newversionto.' ';
+ $choice .= '';
+ $choice .= $langs->trans("UpgradeDesc");
- if ($recommended_choice)
- {
- $choice .= ' ';
- //print $langs->trans("InstallChoiceRecommanded",DOL_VERSION,$conf->global->MAIN_VERSION_LAST_UPGRADE);
- $choice .= '';
- $choice .= '
'.$langs->trans("InstallChoiceSuggested").'
';
- if ($count < count($migarray)) // There are other choices after
- {
- print $langs->trans("MigrateIsDoneStepByStep", DOL_VERSION);
- }
- $choice .= '
';
- }
+ if ($recommended_choice)
+ {
+ $choice .= ' ';
+ //print $langs->trans("InstallChoiceRecommanded",DOL_VERSION,$conf->global->MAIN_VERSION_LAST_UPGRADE);
+ $choice .= '';
+ $choice .= '
'.$langs->trans("InstallChoiceSuggested").'
';
+ if ($count < count($migarray)) // There are other choices after
+ {
+ print $langs->trans("MigrateIsDoneStepByStep", DOL_VERSION);
+ }
+ $choice .= '
';
+ }
- $choice .= ' ';
- $choice .= '';
+ $choice .= ' ';
+ $choice .= '';
if ($allowupgrade)
{
$disabled = false;
@@ -515,22 +515,22 @@ if (!file_exists($conffile))
$foundrecommandedchoice = 2;
}
if ($disabled)
- {
- $choice .= ''.$langs->trans("NotYetAvailable").' ';
- } else {
- $choice .= ''.$langs->trans("Start").' ';
- }
+ {
+ $choice .= ''.$langs->trans("NotYetAvailable").' ';
+ } else {
+ $choice .= ''.$langs->trans("Start").' ';
+ }
} else {
- $choice .= $langs->trans("NotAvailable");
+ $choice .= $langs->trans("NotAvailable");
}
- $choice .= ' ';
- $choice .= ' '."\n";
+ $choice .= '';
+ $choice .= ''."\n";
- if ($allowupgrade) {
- $available_choices[$count] = $choice;
- } else {
- $notavailable_choices[$count] = $choice;
- }
+ if ($allowupgrade) {
+ $available_choices[$count] = $choice;
+ } else {
+ $notavailable_choices[$count] = $choice;
+ }
}
// If there is no choice at all, we show all of them.
@@ -540,32 +540,32 @@ if (!file_exists($conffile))
$notavailable_choices = array();
}
- // Array of install choices
+ // Array of install choices
krsort($available_choices, SORT_NATURAL);
- print"\n";
- print '';
- foreach ($available_choices as $choice) {
- print $choice;
- }
+ print"\n";
+ print '';
+ foreach ($available_choices as $choice) {
+ print $choice;
+ }
- print '
'."\n";
+ print '
'."\n";
- if (count($notavailable_choices)) {
- print '';
- print '> '.$langs->trans('ShowNotAvailableOptions').'...';
- print '
';
+ if (count($notavailable_choices)) {
+ print '';
+ print '> '.$langs->trans('ShowNotAvailableOptions').'...';
+ print '
';
- print '';
- print "
\n";
- print '
';
- foreach ($notavailable_choices as $choice) {
- print $choice;
- }
+ print '';
+ print "
\n";
+ print '
';
+ foreach ($notavailable_choices as $choice) {
+ print $choice;
+ }
- print '
'."\n";
- print '
';
- }
- }
+ print '
'."\n";
+ print '
';
+ }
+ }
}
print ''."\n";
- else print ''."\n";
- if ($jQueryUiCustomPath) print ''."\n";
- else print ''."\n";
+ print ''."\n";
+ if ($jQueryCustomPath) print ''."\n";
+ else print ''."\n";
+ if ($jQueryUiCustomPath) print ''."\n";
+ else print ''."\n";
- print ''.$langs->trans("DolibarrSetup").' '."\n";
- print ''."\n";
+ print ''.$langs->trans("DolibarrSetup").' '."\n";
+ print ''."\n";
- print ''."\n";
+ print ''."\n";
- print '';
- print '
';
- print DOL_VERSION;
- print '
';
+ print '';
+ print '
';
+ print DOL_VERSION;
+ print '
';
- print ''.$langs->trans("DolibarrSetup");
- if ($subtitle) {
- print ' - '.$subtitle;
- }
- print ' '."\n";
+ print ''.$langs->trans("DolibarrSetup");
+ if ($subtitle) {
+ print ' - '.$subtitle;
+ }
+ print ' '."\n";
- print ''."\n";
- print ' '."\n";
- print ' '."\n";
+ print ' '."\n";
+ print ' '."\n";
+ print ' '."\n";
- print ''."\n";
+ print ''."\n";
- print ''."\n";
+ print ''."\n";
}
/**
@@ -423,52 +423,52 @@ function pHeader($subtitle, $next, $action = 'set', $param = '', $forcejqueryurl
*/
function pFooter($nonext = 0, $setuplang = '', $jscheckfunction = '', $withpleasewait = 0)
{
- global $conf, $langs;
+ global $conf, $langs;
- $langs->load("main");
- $langs->load("other");
- $langs->load("admin");
+ $langs->load("main");
+ $langs->load("other");
+ $langs->load("admin");
- print '
'."\n";
- print '
'."\n";
+ print '
'."\n";
+ print '
'."\n";
- if (!$nonext || ($nonext == '2'))
- {
- print '';
+ if ($withpleasewait) print ''.$langs->trans("NextStepMightLastALongTime").'
'.$langs->trans("PleaseBePatient").'
';
+ }
+ if ($setuplang)
+ {
+ print ' ';
+ }
- print ' '."\n";
+ print ''."\n";
- // If there is some logs in buffer to show
- if (isset($conf->logbuffer) && count($conf->logbuffer))
- {
- print "\n";
- print "\n";
- print "\n";
- }
+ // If there is some logs in buffer to show
+ if (isset($conf->logbuffer) && count($conf->logbuffer))
+ {
+ print "\n";
+ print "\n";
+ print "\n";
+ }
- print ''."\n";
- print ''."\n";
+ print '