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

This commit is contained in:
Laurent Destailleur 2017-07-12 20:34:22 +02:00
commit 24863337da
40 changed files with 1201 additions and 941 deletions

View File

@ -55,7 +55,7 @@ if ($action == 'setvalue' && $user->admin)
$result=dolibarr_set_const($db, "NOTIFICATION_EMAIL_FROM", $_POST["email_from"], 'chaine', 0, '', $conf->entity);
if ($result < 0) $error++;
if (! $error)
if (! $error && is_array($_POST))
{
//var_dump($_POST);
foreach($_POST as $key => $val)
@ -172,7 +172,7 @@ $var=true;
$i=0;
foreach($listofnotifiedevents as $notifiedevent)
{
$label=$langs->trans("Notify_".$notifiedevent['code']); //!=$langs->trans("Notify_".$notifiedevent['code'])?$langs->trans("Notify_".$notifiedevent['code']):$notifiedevent['label'];
if ($notifiedevent['elementtype'] == 'order_supplier') $elementLabel = $langs->trans('SupplierOrder');
@ -183,7 +183,7 @@ foreach($listofnotifiedevents as $notifiedevent)
if ($i) print ', ';
print $label;
$i++;
}
print '</td></tr>';
@ -213,7 +213,7 @@ $listofnotifiedevents=$notificationtrigger->getListOfManagedEvents();
$var=true;
foreach($listofnotifiedevents as $notifiedevent)
{
$label=$langs->trans("Notify_".$notifiedevent['code']); //!=$langs->trans("Notify_".$notifiedevent['code'])?$langs->trans("Notify_".$notifiedevent['code']):$notifiedevent['label'];
if ($notifiedevent['elementtype'] == 'order_supplier') $elementLabel = $langs->trans('SupplierOrder');

View File

@ -1,5 +1,5 @@
<?php
/* Copyright (C) 2004-2015 Laurent Destailleur <eldy@users.sourceforge.net>
/* Copyright (C) 2004-2017 Laurent Destailleur <eldy@users.sourceforge.net>
*
* 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
@ -48,24 +48,21 @@ $acts[1] = "disable";
$actl[0] = img_picto($langs->trans("Disabled"),'switch_off');
$actl[1] = img_picto($langs->trans("Activated"),'switch_on');
$listoffset=GETPOST('listoffset');
$listlimit=GETPOST('listlimit')>0?GETPOST('listlimit'):1000;
$status = 1;
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
if ($page == -1 || $page == null) { $page = 0 ; }
$offset = $listlimit * $page ;
// Load variable for pagination
$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
$sortfield = GETPOST('sortfield','alpha');
$sortorder = GETPOST('sortorder','alpha');
$page = GETPOST('page','int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$hookmanager->initHooks(array('admin'));
// This page is a generic page to edit dictionaries
// Put here declaration of dictionaries properties
// Name of SQL tables of dictionaries
$tabname=array();
$tabname[1] = MAIN_DB_PREFIX."website";
@ -118,7 +115,7 @@ $elementList = array();
$sourceList=array();
// Actions add or modify an entry into a dictionary
if (GETPOST('actionadd') || GETPOST('actionmodify'))
if (GETPOST('actionadd','alpha') || GETPOST('actionmodify','alpha'))
{
$listfield=explode(',',$tabfield[$id]);
$listfieldinsert=explode(',',$tabfieldinsert[$id]);
@ -138,7 +135,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify'))
}
// Si verif ok et action add, on ajoute la ligne
if ($ok && GETPOST('actionadd'))
if ($ok && GETPOST('actionadd','alpha'))
{
if ($tabrowid[$id])
{
@ -200,7 +197,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify'))
}
// Si verif ok et action modify, on modifie la ligne
if ($ok && GETPOST('actionmodify'))
if ($ok && GETPOST('actionmodify','alpha'))
{
if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
else { $rowidcol="rowid"; }
@ -252,7 +249,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify'))
//$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition
}
if (GETPOST('actioncancel'))
if (GETPOST('actioncancel','alpha'))
{
//$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition
}
@ -262,7 +259,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete
if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
else { $rowidcol="rowid"; }
$sql = "DELETE from ".MAIN_DB_PREFIX."website_pages WHERE fk_website ='".$rowid."'";
$sql = "DELETE from ".MAIN_DB_PREFIX."website_page WHERE fk_website ='".$rowid."'";
$result = $db->query($sql);
$sql = "DELETE from ".MAIN_DB_PREFIX."website WHERE rowid ='".$rowid."'";
@ -341,7 +338,7 @@ if ($action == 'delete')
//var_dump($elementList);
/*
* Show a dictionary
* Show website list
*/
if ($id)
{
@ -412,11 +409,11 @@ if ($id)
$obj = new stdClass();
// If data was already input, we define them in obj to populate input fields.
if (GETPOST('actionadd'))
if (GETPOST('actionadd','alpha'))
{
foreach ($fieldlist as $key=>$val)
{
if (GETPOST($val))
if (GETPOST($val,'alpha'))
$obj->$val=GETPOST($val);
}
}
@ -447,8 +444,7 @@ if ($id)
// List of available values in database
dol_syslog("htdocs/admin/dict", LOG_DEBUG);
// List of websites in database
$resql=$db->query($sql);
if ($resql)
{
@ -465,14 +461,6 @@ if ($id)
print '<table class="noborder" width="100%">';
// There is several pages
if ($num > $listlimit)
{
print '<tr class="none"><td align="right" colspan="'.(3+count($fieldlist)).'">';
print_fleche_navigation($page, $_SERVER["PHP_SELF"], '', ($num > $listlimit), '<li class="pagination"><span>'.$langs->trans("Page").' '.($page+1).'</span></li>');
print '</td></tr>';
}
// Title of lines
print '<tr class="liste_titre">';
foreach ($fieldlist as $field => $value)

View File

@ -53,11 +53,13 @@ function printBookmarksList($aDb, $aLangs)
// No urlencode, all param $url will be urlencoded later
if ($sortfield) $tmpurl.=($tmpurl?'&':'').'sortfield='.$sortfield;
if ($sortorder) $tmpurl.=($tmpurl?'&':'').'sortorder='.$sortorder;
foreach($_POST as $key => $val)
if (is_array($_POST))
{
if (preg_match('/^search_/', $key) && $val != '') $tmpurl.=($tmpurl?'&':'').$key.'='.$val;
foreach($_POST as $key => $val)
{
if (preg_match('/^search_/', $key) && $val != '') $tmpurl.=($tmpurl?'&':'').$key.'='.$val;
}
}
$url.=($tmpurl?'?'.$tmpurl:'');
}

View File

@ -133,7 +133,7 @@ class Categorie extends CommonObject
);
public $element='category';
public $table_element='categories';
public $table_element='categorie';
public $fk_parent;
public $label;

View File

@ -35,14 +35,14 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
$langs->load("categories");
$id=GETPOST('id','int');
$ref=GETPOST('ref');
$label=GETPOST('label');
$type=GETPOST('type');
$action=GETPOST('action','aZ09');
$confirm=GETPOST('confirm');
$removeelem = GETPOST('removeelem','int');
$elemid=GETPOST('elemid');
if ($id == "")
if ($id == "" && $label == "")
{
dol_print_error('','Missing parameter id');
exit();
@ -52,7 +52,7 @@ if ($id == "")
$result = restrictedArea($user, 'categorie', $id, '&category');
$object = new Categorie($db);
$result=$object->fetch($id);
$result=$object->fetch($id, $label);
$object->fetch_optionals($id,$extralabels);
if ($result <= 0)
{
@ -195,7 +195,7 @@ $head = categories_prepare_head($object,$type);
dol_fiche_head($head, 'card', $title, -1, 'category');
$linkback = '<a href="'.DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.$type.'">'.$langs->trans("BackToList").'</a>';
$object->next_prev_filter=" type = ".$object->type;
$object->ref = $object->label;
$morehtmlref='<br><div class="refidno"><a href="'.DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.$type.'">'.$langs->trans("Root").'</a> >> ';
$ways = $object->print_all_ways(" &gt;&gt; ", '', 1);
@ -205,7 +205,7 @@ foreach ($ways as $way)
}
$morehtmlref.='</div>';
dol_banner_tab($object, 'ref', $linkback, ($user->societe_id?0:1), 'ref', 'ref', $morehtmlref, '', 0, '', '', 1);
dol_banner_tab($object, 'label', $linkback, ($user->societe_id?0:1), 'label', 'label', $morehtmlref, '', 0, '', '', 1);
/*

View File

@ -129,10 +129,13 @@ $hookmanager->initHooks(array('agenda'));
if (GETPOST("viewlist") || $action == 'show_list')
{
$param='';
foreach($_POST as $key => $val)
if (is_array($_POST))
{
if ($key=='token') continue;
$param.='&'.$key.'='.urlencode($val);
foreach($_POST as $key => $val)
{
if ($key=='token') continue;
$param.='&'.$key.'='.urlencode($val);
}
}
//print $param;
header("Location: ".DOL_URL_ROOT.'/comm/action/listactions.php?'.$param);
@ -142,10 +145,13 @@ if (GETPOST("viewlist") || $action == 'show_list')
if (GETPOST("viewperuser") || $action == 'show_peruser')
{
$param='';
foreach($_POST as $key => $val)
if (is_array($_POST))
{
if ($key=='token') continue;
$param.='&'.$key.'='.urlencode($val);
foreach($_POST as $key => $val)
{
if ($key=='token') continue;
$param.='&'.$key.'='.urlencode($val);
}
}
//print $param;
header("Location: ".DOL_URL_ROOT.'/comm/action/peruser.php?'.$param);

View File

@ -120,10 +120,13 @@ $hookmanager->initHooks(array('agendalist'));
if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday"))
{
$param='';
foreach($_POST as $key => $val)
{
$param.='&'.$key.'='.urlencode($val);
}
if (is_array($_POST))
{
foreach($_POST as $key => $val)
{
$param.='&'.$key.'='.urlencode($val);
}
}
//print $param;
header("Location: ".DOL_URL_ROOT.'/comm/action/index.php?'.$param);
exit;

View File

@ -32,16 +32,19 @@ if ($action == 'setModuleOptions')
$db->begin();
// Process common param fields
foreach($_POST as $key => $val)
if (is_array($_POST))
{
if (preg_match('/^param(\d*)$/', $key, $reg)) // Works for POST['param'], POST['param1'], POST['param2'], ...
foreach($_POST as $key => $val)
{
$param=GETPOST("param".$reg[1],'alpha');
$value=GETPOST("value".$reg[1],'alpha');
if ($param)
if (preg_match('/^param(\d*)$/', $key, $reg)) // Works for POST['param'], POST['param1'], POST['param2'], ...
{
$res = dolibarr_set_const($db,$param,$value,'chaine',0,'',$conf->entity);
if (! $res > 0) $error++;
$param=GETPOST("param".$reg[1],'alpha');
$value=GETPOST("value".$reg[1],'alpha');
if ($param)
{
$res = dolibarr_set_const($db,$param,$value,'chaine',0,'',$conf->entity);
if (! $res > 0) $error++;
}
}
}
}

View File

@ -599,7 +599,7 @@ abstract class CommonObject
}
$datecreate = dol_now();
// Socpeople must have already been added by some a trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
$TListeContacts=$this->liste_contact(-1, $source);
$already_added=false;
@ -611,11 +611,11 @@ abstract class CommonObject
}
}
}
if(!$already_added) {
$this->db->begin();
// Insertion dans la base
$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
$sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
@ -623,7 +623,7 @@ abstract class CommonObject
$sql.= "'".$this->db->idate($datecreate)."'";
$sql.= ", 4, ". $id_type_contact;
$sql.= ")";
$resql=$this->db->query($sql);
if ($resql)
{
@ -636,7 +636,7 @@ abstract class CommonObject
return -1;
}
}
$this->db->commit();
return 1;
}
@ -4726,6 +4726,9 @@ abstract class CommonObject
return $buyPrice;
}
/**
* Function test if type is date
*
@ -4734,7 +4737,7 @@ abstract class CommonObject
*/
protected function isDate($info)
{
if(isset($info['type']) && $info['type']=='date') return true;
if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true;
else return false;
}
@ -4880,40 +4883,6 @@ abstract class CommonObject
return $query;
}
/**
* Create object into database
*
* @param User $user User that creates
* @param bool $notrigger false=launch triggers after, true=disable triggers
*
* @return int <0 if KO, Id of created object if OK
*/
public function createCommon(User $user, $notrigger = false)
{
$fields = array_merge(array('datec'=>$this->db->idate(dol_now())), $this->set_save_query());
foreach ($fields as $k => $v) {
$keys[] = $k;
$values[] = $this->quote($v);
}
$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'
( '.implode( ",", $keys ).' )
VALUES ( '.implode( ",", $values ).' ) ';
$res = $this->db->query( $sql );
if($res===false) {
return false;
}
// TODO Add triggers
return true;
}
/**
* Function to load data into current object this
*
@ -4921,39 +4890,39 @@ abstract class CommonObject
*/
private function set_vars_by_db(&$obj)
{
foreach ($this->fields as $field => $info)
{
if($this->isDate($info))
{
if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
else $this->{$field} = strtotime($obj->{$field});
}
elseif($this->isArray($info))
{
$this->{$field} = @unserialize($obj->{$field});
// Hack for data not in UTF8
if($this->{$field } === FALSE) @unserialize(utf8_decode($obj->{$field}));
}
elseif($this->isInt($info))
{
$this->{$field} = (int) $obj->{$field};
}
elseif($this->isFloat($info))
{
$this->{$field} = (double) $obj->{$field};
}
elseif($this->isNull($info))
{
$val = $obj->{$field};
// zero is not null
$this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
}
else
{
$this->{$field} = $obj->{$field};
}
foreach ($this->fields as $field => $info)
{
if($this->isDate($info))
{
if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
else $this->{$field} = strtotime($obj->{$field});
}
elseif($this->isArray($info))
{
$this->{$field} = @unserialize($obj->{$field});
// Hack for data not in UTF8
if($this->{$field } === FALSE) @unserialize(utf8_decode($obj->{$field}));
}
elseif($this->isInt($info))
{
$this->{$field} = (int) $obj->{$field};
}
elseif($this->isFloat($info))
{
$this->{$field} = (double) $obj->{$field};
}
elseif($this->isNull($info))
{
$val = $obj->{$field};
// zero is not null
$this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
}
else
{
$this->{$field} = $obj->{$field};
}
}
}
}
/**
@ -4963,21 +4932,134 @@ abstract class CommonObject
*/
private function get_field_list()
{
$keys = array_keys($this->fields);
return implode(',', $keys);
$keys = array_keys($this->fields);
return implode(',', $keys);
}
/**
* Add quote to field value if necessary
*
* @param string|int $value value to protect
* @return string|int
*/
protected function quote($value) {
if(is_null($value)) return 'NULL';
else if(is_numeric($value)) return $value;
else return "'".$this->db->escape( $value )."'";
}
/**
* Create object into database
*
* @param User $user User that creates
* @param bool $notrigger false=launch triggers after, true=disable triggers
* @return int <0 if KO, Id of created object if OK
*/
public function createCommon(User $user, $notrigger = false)
{
$error = 0;
$fields = array_merge(array('datec'=>$this->db->idate(dol_now())), $this->set_save_query());
foreach ($fields as $k => $v) {
$keys[] = $k;
$values[] = $this->quote($v);
}
$this->db->begin();
if (! $error)
{
$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'
( '.implode( ",", $keys ).' )
VALUES ( '.implode( ",", $values ).' ) ';
$res = $this->db->query( $sql );
if ($res===false) {
$error++;
$this->errors[] = $this->db->lasterror();
}
}
if (! $error && ! $notrigger) {
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
if (!$notrigger) {
// Call triggers
$result=$this->call_trigger(strtoupper(get_class(self)).'_CREATE',$user);
if ($result < 0) { $error++; }
// End call triggers
}
}
// Commit or rollback
if ($error) {
$this->db->rollback();
return -1;
} else {
$this->db->commit();
return $this->id;
}
}
/**
* Load an object from its id and create a new one in database
*
* @param User $user User that creates
* @param int $fromid Id of object to clone
* @return int New id of clone
*/
public function createFromCloneCommon(User $user, $fromid)
{
global $user;
$error = 0;
dol_syslog(__METHOD__, LOG_DEBUG);
$object = new self($this->db);
$this->db->begin();
// Load source object
$object->fetchCommon($fromid);
// Reset object
$object->id = 0;
// Clear fields
// ...
// Create clone
$result = $object->createCommon($user);
// Other options
if ($result < 0) {
$error ++;
$this->errors = $object->errors;
dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
}
// End
if (!$error) {
$this->db->commit();
return $object->id;
} else {
$this->db->rollback();
return -1;
}
}
/**
* Load object in memory from the database
*
* @param int $id Id object
* @param string $ref Ref
*
* @return int <0 if KO, 0 if not found, >0 if OK
* @param int $id Id object
* @param string $ref Ref
* @return int <0 if KO, 0 if not found, >0 if OK
*/
public function fetchCommon($id, $ref = null)
{
if (empty($id) && empty($ref)) return false;
$sql = 'SELECT '.$this->get_field_list().', datec, tms';
@ -4991,13 +5073,20 @@ abstract class CommonObject
{
if ($obj = $this->db->fetch_object($res))
{
$this->id = $id;
$this->set_vars_by_db($obj);
if ($obj)
{
$this->id = $id;
$this->set_vars_by_db($obj);
$this->datec = $this->db->idate($obj->datec);
$this->tms = $this->db->idate($obj->tms);
$this->datec = $this->db->idate($obj->datec);
$this->tms = $this->db->idate($obj->tms);
return $this->id;
return $this->id;
}
else
{
return 0;
}
}
else
{
@ -5019,15 +5108,15 @@ abstract class CommonObject
*
* @param User $user User that modifies
* @param bool $notrigger false=launch triggers after, true=disable triggers
*
* @return int <0 if KO, >0 if OK
* @return int <0 if KO, >0 if OK
*/
public function updateCommon(User $user, $notrigger = false)
{
$error = 0;
$fields = $this->set_save_query();
foreach ($fields as $k => $v) {
if (is_array($key)){
$i=array_search($k, $key);
if ( $i !== false) {
@ -5040,57 +5129,93 @@ abstract class CommonObject
continue;
}
}
$tmp[] = $k.'='.$this->quote($v);
}
$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ;
$res = $this->db->query( $sql );
if($res===false) {
//error
return false;
$this->db->begin();
if (! $error)
{
$res = $this->db->query($sql);
if ($res===false)
{
$error++;
$this->errors[] = $this->db->lasterror();
}
}
// TODO Add triggers
if (! $error && ! $notrigger) {
// Call triggers
$result=$this->call_trigger(strtoupper(get_class(self)).'_MODIFY',$user);
if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail
// End call triggers
}
return true;
// Commit or rollback
if ($error) {
$this->db->rollback();
return -1;
} else {
$this->db->commit();
return $this->id;
}
}
/**
* Delete object in database
*
* @param User $user User that deletes
* @param bool $notrigger false=launch triggers after, true=disable triggers
*
* @return int <0 if KO, >0 if OK
* @param User $user User that deletes
* @param bool $notrigger false=launch triggers after, true=disable triggers
* @return int <0 if KO, >0 if OK
*/
public function deleteCommon(User $user, $notrigger = false)
{
$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
$error=0;
$res = $this->db->query( $sql );
if($res===false) {
return false;
$this->db->begin();
if (! $error) {
if (! $notrigger) {
// Call triggers
$result=$this->call_trigger(strtoupper(get_class(self)).'_DELETE', $user);
if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
// End call triggers
}
}
if (! $error)
{
$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
$res = $this->db->query($sql);
if($res===false) {
$error++;
$this->errors[] = $this->db->lasterror();
}
}
// Commit or rollback
if ($error) {
$this->db->rollback();
return -1;
} else {
$this->db->commit();
return 1;
}
// TODO Add triggers
return true;
}
/**
* Add quote to field value if necessary
* Initialise object with example values
* Id must be 0 if object instance is a specimen
*
* @param string|int $value value to protect
* @return string|int
* @return void
*/
protected function quote($value) {
if(is_null($value)) return 'NULL';
else if(is_numeric($value)) return $value;
else return "'".$this->db->escape( $value )."'";
public function initAsSpecimenCommon()
{
$this->id = 0;
// TODO...
}
}

View File

@ -314,7 +314,7 @@ class FormFile
if (preg_match('/massfilesarea_/', $modulepart))
{
$out.='<div id="show_files"><br></div>';
$out.='<div id="show_files"><br></div>'."\n";
$title=$langs->trans("MassFilesArea").' <a href="" id="togglemassfilesarea" ref="shown">('.$langs->trans("Hide").')</a>';
$title.='<script type="text/javascript" language="javascript">
jQuery(document).ready(function() {
@ -788,14 +788,14 @@ class FormFile
$out.=dol_print_date($file->datea,'dayhour');
$out.='</td>';
if ($delallowed || $printer || $morepicto) $out.='<td></td>';
$out.='</tr>';
$out.='</tr>'."\n";
}
$this->numoffiles++;
}
if (count($file_list) == 0 && count($link_list) == 0 && $headershown)
{
$out.='<tr class="oddeven"><td colspan="3" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
$out.='<tr class="oddeven"><td colspan="3" class="opacitymedium">'.$langs->trans("None").'</td></tr>'."\n";
}
}

View File

@ -28,10 +28,10 @@
class Utils
{
var $db;
var $output; // Used by Cron method to return message
var $result; // Used by Cron method to return data
/**
* Constructor
*
@ -47,21 +47,21 @@ class Utils
* Purge files into directory of data files.
* CAN BE A CRON TASK
*
* @param string $choice Choice of purge mode ('tempfiles', 'tempfilesold' to purge temp older than 24h, 'allfiles', 'logfiles')
* @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
* @param string $choice Choice of purge mode ('tempfiles', 'tempfilesold' to purge temp older than 24h, 'allfiles', 'logfile')
* @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
*/
function purgeFiles($choice='tempfilesold')
{
global $conf, $langs, $dolibarr_main_data_root;
$langs->load("admin");
dol_syslog("Utils::purgeFiles choice=".$choice, LOG_DEBUG);
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$filesarray=array();
if (empty($choice)) $choice='tempfilesold';
if ($choice=='tempfiles' || $choice=='tempfilesold')
{
// Delete temporary files
@ -78,29 +78,39 @@ class Utils
}
}
}
if ($choice=='allfiles')
{
// Delete all files
// Delete all files (except install.lock)
if ($dolibarr_main_data_root)
{
$filesarray=dol_dir_list($dolibarr_main_data_root,"all",0,'','install\.lock$');
}
}
if ($choice=='logfile')
{
// Define filelog to discard it from purge
// Define files log
if ($dolibarr_main_data_root)
{
$filesarray=dol_dir_list($dolibarr_main_data_root, "files", 0, '.*\.log[\.0-9]*$', 'install\.lock$');
}
$filelog='';
if (! empty($conf->syslog->enabled))
{
$filelog=$conf->global->SYSLOG_FILE;
$filelog=preg_replace('/DOL_DATA_ROOT/i',DOL_DATA_ROOT,$filelog);
}
$filesarray[]=array('fullname'=>$filelog,'type'=>'file');
$alreadyincluded=false;
foreach ($filesarray as $tmpcursor)
{
if ($tmpcursor['fullname'] == $filelog) { $alreadyincluded=true; }
}
if (! $alreadyincluded) $filesarray[]=array('fullname'=>$filelog,'type'=>'file');
}
}
$count=0;
if (count($filesarray))
{
@ -120,7 +130,7 @@ class Utils
}
}
}
// Update cachenbofdoc
if (! empty($conf->ecm->enabled) && $choice=='allfiles')
{
@ -129,14 +139,14 @@ class Utils
$result = $ecmdirstatic->refreshcachenboffile(1);
}
}
if ($count > 0) $this->output=$langs->trans("PurgeNDirectoriesDeleted", $count);
else $this->output=$langs->trans("PurgeNothingToDelete");
//return $count;
return 0; // This function can be called by cron so must return 0 if OK
}
/**
* Make a backup of database
@ -147,16 +157,16 @@ class Utils
* @param int $usedefault 1=Use default backup profile (Set this to 1 when used as cron)
* @param string $file 'auto' or filename to build
* @param int $keeplastnfiles Keep only last n files (not used yet)
* @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
* @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
*/
function dumpDatabase($compression='none', $type='auto', $usedefault=1, $file='auto', $keeplastnfiles=0)
{
global $db, $conf, $langs, $dolibarr_main_data_root;
global $dolibarr_main_db_name, $dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_port, $dolibarr_main_db_pass;
$langs->load("admin");
dol_syslog("Utils::dumpDatabase type=".$type." compression=".$compression." file=".$file, LOG_DEBUG);
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
@ -190,14 +200,14 @@ class Utils
$outputdir = $conf->admin->dir_output.'/backup';
$result=dol_mkdir($outputdir);
// MYSQL
if ($type == 'mysql' || $type == 'mysqli')
{
$cmddump=$conf->global->SYSTEMTOOLS_MYSQLDUMP;
$outputfile = $outputdir.'/'.$file;
// for compression format, we add extension
$compression=$compression ? $compression : 'none';
@ -205,11 +215,11 @@ class Utils
if ($compression == 'bz') $outputfile.='.bz2';
$outputerror = $outputfile.'.err';
dol_mkdir($conf->admin->dir_output.'/backup');
// Parameteres execution
$command=$cmddump;
if (preg_match("/\s/",$command)) $command=escapeshellarg($command); // Use quotes on command
//$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
$param=$dolibarr_main_db_name." -h ".$dolibarr_main_db_host;
$param.=" -u ".$dolibarr_main_db_user;
@ -250,16 +260,16 @@ class Utils
$paramcrypted.=' -p"'.preg_replace('/./i','*',$dolibarr_main_db_pass).'"';
$paramclear.=' -p"'.str_replace(array('"','`'),array('\"','\`'),$dolibarr_main_db_pass).'"';
}
$errormsg='';
// Debut appel methode execution
$fullcommandcrypted=$command." ".$paramcrypted." 2>&1";
$fullcommandclear=$command." ".$paramclear." 2>&1";
if ($compression == 'none') $handle = fopen($outputfile, 'w');
if ($compression == 'gz') $handle = gzopen($outputfile, 'w');
if ($compression == 'bz') $handle = bzopen($outputfile, 'w');
if ($handle)
{
$ok=0;
@ -277,11 +287,11 @@ class Utils
elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i',$read)) $ok=1;
}
pclose($handlein);
if ($compression == 'none') fclose($handle);
if ($compression == 'gz') gzclose($handle);
if ($compression == 'bz') bzclose($handle);
if (! empty($conf->global->MAIN_UMASK))
@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
}
@ -291,7 +301,7 @@ class Utils
dol_syslog("Failed to open file ".$outputfile,LOG_ERR);
$errormsg=$langs->trans("ErrorFailedToWriteInDir");
}
// Get errorstring
if ($compression == 'none') $handle = fopen($outputfile, 'r');
if ($compression == 'gz') $handle = gzopen($outputfile, 'r');
@ -320,13 +330,13 @@ class Utils
}
}
// Fin execution commande
$this->output = $errormsg;
$this->error = $errormsg;
$this->result = array("commandbackuplastdone" => $command." ".$paramcrypted, "commandbackuptorun" => "");
//if (empty($this->output)) $this->output=$this->result['commandbackuplastdone'];
}
// MYSQL NO BIN
if ($type == 'mysqlnobin')
{
@ -338,7 +348,7 @@ class Utils
if ($compression == 'bz') $outputfile.='.bz2';
$outputerror = $outputfile.'.err';
dol_mkdir($conf->admin->dir_output.'/backup');
if ($compression == 'gz' or $compression == 'bz')
{
backup_tables($outputfiletemp);
@ -349,16 +359,16 @@ class Utils
{
backup_tables($outputfile);
}
$this->output = "";
$this->result = array("commandbackuplastdone" => "", "commandbackuptorun" => "");
}
// POSTGRESQL
if ($type == 'postgresql')
{
$cmddump=$conf->global->SYSTEMTOOLS_POSTGRESQLDUMP;
$outputfile = $outputdir.'/'.$file;
// for compression format, we add extension
$compression=$compression ? $compression : 'none';
@ -366,11 +376,11 @@ class Utils
if ($compression == 'bz') $outputfile.='.bz2';
$outputerror = $outputfile.'.err';
dol_mkdir($conf->admin->dir_output.'/backup');
// Parameteres execution
$command=$cmddump;
if (preg_match("/\s/",$command)) $command=escapeshellarg($command); // Use quotes on command
//$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass);
//$param="-F c";
$param="-F p";
@ -419,8 +429,8 @@ class Utils
dol_delete_file($val['fullname']);
}
}
return 0;
}
}

View File

@ -0,0 +1,207 @@
<?php
/* Copyright (C) 2009-2010 Laurent Destailleur <eldy@users.sourceforge.net>
*
* 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
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* or see http://www.gnu.org/
*/
/**
* \file htdocs/core/lib/memory.lib.php
* \brief Set of function for memory/cache management
*/
/**
* Save data into a memory area shared by all users, all sessions on server
*
* @param string $destdir Directory
* @param string $module Module name
* @param string $objectname Name of object
* @param string $newmask New mask
* @return int <0 if KO, >0 if OK
*/
function rebuildObjectClass($destdir, $module, $objectname, $newmask)
{
global $db, $langs;
if (empty($objectname)) return -1;
$pathoffiletoeditsrc=$destdir.'/class/'.strtolower($objectname).'.class.php';
$pathoffiletoedittarget=$destdir.'/class/'.strtolower($objectname).'.class.php';
if (! dol_is_file($pathoffiletoeditsrc))
{
//$pathoffiletoeditsrc=DOL_DOCUMENT_ROOT.'/modulebuilder/template/class/myobject.class.php';
setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
return -1;
}
//$pathoffiletoedittmp=$destdir.'/class/'.strtolower($objectname).'.class.php.tmp';
//dol_delete_file($pathoffiletoedittmp, 0, 1, 1);
try
{
include_once $pathoffiletoeditsrc;
if (class_exists($objectname)) $object=new $objectname($db);
// Backup old file
dol_copy($pathoffiletoeditsrc, $pathoffiletoeditsrc.'.back', $newmask, 1);
// Edit class files
$contentclass = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
$i=0;
$texttoinsert = '// BEGIN MODULEBUILDER PROPERTIES'."\n";
$texttoinsert.= "\t".'/**'."\n";
$texttoinsert.= "\t".' * @var array Array with all fields and their property'."\n";
$texttoinsert.= "\t".' */'."\n";
$texttoinsert.= "\t".'public $fields=array('."\n";
if (count($object->fields))
{
foreach($object->fields as $key => $val)
{
$i++;
$typephp='';
$texttoinsert.= "\t\t'".$key."' => array('type'=>'".$val['type']."', 'label'=>'".$val['label']."',";
if ($val['position']) $texttoinsert.= " 'position'=>".$val['position'].",";
if ($val['notnull']) $texttoinsert.= " 'notnull'=>".$val['notnull'].",";
if ($val['index']) $texttoinsert.= " 'index'=>".$val['index'].",";
if ($val['searchall']) $texttoinsert.= " 'searchall'=>".$val['searchall'].",";
if ($val['comment']) $texttoinsert.= " 'comment'=>'".$val['comment']."',";
$texttoinsert.= "),\n";
}
}
$texttoinsert.= "\t".');'."\n";
$texttoinsert.= "\n";
if (count($object->fields))
{
foreach($object->fields as $key => $val)
{
$i++;
$typephp='';
$texttoinsert.= "\t".'public $'.$key.$typephp.";";
//if ($key == 'rowid') $texttoinsert.= ' AUTO_INCREMENT PRIMARY KEY';
//if ($key == 'entity') $texttoinsert.= ' DEFAULT 1';
//$texttoinsert.= ($val['notnull']?' NOT NULL':'');
//if ($i < count($object->fields)) $texttoinsert.=";";
$texttoinsert.= "\n";
}
}
$texttoinsert.= "\t".'// END MODULEBUILDER PROPERTIES';
$contentclass = preg_replace('/\/\/ BEGIN MODULEBUILDER PROPERTIES.*END MODULEBUILDER PROPERTIES/ims', $texttoinsert, $contentclass);
//file_put_contents($pathoffiletoedittmp, $contentclass);
file_put_contents(dol_osencode($pathoffiletoedittarget), $contentclass);
@chmod($pathoffiletoedit, octdec($newmask));
return 1;
}
catch(Exception $e)
{
print $e->getMessage();
return -1;
}
}
/**
* Save data into a memory area shared by all users, all sessions on server
*
* @param string $destdir Directory
* @param string $module Module name
* @param string $objectname Name of object
* @param string $newmask New mask
* @return int <0 if KO, >0 if OK
*/
function rebuildObjectSql($destdir, $module, $objectname, $newmask)
{
global $db, $langs;
if (empty($objectname)) return -1;
try
{
dol_include_once(strtolower($module).'/class/'.strtolower($objectname).'.class.php');
if (class_exists($objectname)) $object=new $objectname($db);
}
catch(Exception $e)
{
print $e->getMessage();
}
// Edit .sql file
$pathoffiletoeditsrc=dol_osencode($destdir.'/sql/llx_'.strtolower($objectname).'.sql');
$pathoffiletoedittarget=dol_osencode($destdir.'/sql/llx_'.strtolower($objectname).'.sql');
$contentsql = file_get_contents($pathoffiletoeditsrc, 'r');
$i=0;
$texttoinsert = '-- BEGIN MODULEBUILDER FIELDS'."\n";
if (count($object->fields))
{
foreach($object->fields as $key => $val)
{
$i++;
$texttoinsert.= "\t".$key." ".$val['type'];
if ($key == 'rowid') $texttoinsert.= ' AUTO_INCREMENT PRIMARY KEY';
if ($key == 'entity') $texttoinsert.= ' DEFAULT 1';
$texttoinsert.= ($val['notnull']?' NOT NULL':'');
if ($i < count($object->fields)) $texttoinsert.=", ";
$texttoinsert.= "\n";
}
}
$texttoinsert.= "\t".'-- END MODULEBUILDER FIELDS';
$contentsql = preg_replace('/-- BEGIN MODULEBUILDER FIELDS.*END MODULEBUILDER FIELDS/ims', $texttoinsert, $contentsql);
file_put_contents($pathoffiletoedittarget, $contentsql);
@chmod($pathoffiletoedit, octdec($newmask));
// Edit .key.sql file
$pathoffiletoeditsrc=dol_osencode($destdir.'/sql/llx_'.strtolower($objectname).'.key.sql');
$pathoffiletoedittarget=dol_osencode($destdir.'/sql/llx_'.strtolower($objectname).'.key.sql');
$contentsql = file_get_contents($pathoffiletoeditsrc, 'r');
$i=0;
$texttoinsert = '-- BEGIN MODULEBUILDER INDEXES'."\n";
if (count($object->fields))
{
foreach($object->fields as $key => $val)
{
$i++;
if ($val['index'])
{
$texttoinsert.= "ALTER TABLE llx_".strtolower($objectname)." ADD INDEX idx_".strtolower($objectname)."_".$key." (".$key.");";
$texttoinsert.= "\n";
}
}
}
$texttoinsert.= '-- END MODULEBUILDER INDEXES';
$contentsql = preg_replace('/-- BEGIN MODULEBUILDER INDEXES.*END MODULEBUILDER INDEXES/ims', $texttoinsert, $contentsql);
file_put_contents($pathoffiletoedittarget, $contentsql);
@chmod($pathoffiletoedit, octdec($newmask));
return 1;
}

View File

@ -333,7 +333,7 @@ if (empty($user->societe_id))
$boxstat.='<a href="'.$links[$key].'" class="boxstatsindicator thumbstat nobold nounderline">';
$boxstat.='<div class="boxstats">';
$boxstat.='<span class="boxstatstext" title="'.dol_escape_htmltag($text).'">'.img_object("",$icons[$key]).' '.$text.'</span><br>';
$boxstat.='<span class="boxstatsindicator">'.$board->nb[$val].'</span>';
$boxstat.='<span class="boxstatsindicator">'.($board->nb[$val]?$board->nb[$val]:0).'</span>';
$boxstat.='</div>';
$boxstat.='</a>';
}

View File

@ -495,6 +495,31 @@ ALTER TABLE llx_usergroup_rights DROP INDEX fk_usergroup;
ALTER TABLE llx_usergroup_rights ADD UNIQUE INDEX uk_usergroup_rights (entity, fk_usergroup, fk_id);
ALTER TABLE llx_usergroup_rights ADD CONSTRAINT fk_usergroup_rights_fk_usergroup FOREIGN KEY (fk_usergroup) REFERENCES llx_usergroup (rowid);
-- For new module website
CREATE TABLE llx_website_page
(
rowid integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
fk_website integer NOT NULL,
pageurl varchar(16) NOT NULL,
title varchar(255),
description varchar(255),
keywords varchar(255),
content mediumtext, -- text is not enough in size
status integer,
fk_user_create integer,
fk_user_modif integer,
date_creation datetime,
tms timestamp
) ENGINE=innodb;
ALTER TABLE llx_website_page ADD UNIQUE INDEX uk_website_page_url (fk_website,pageurl);
ALTER TABLE llx_website_page ADD CONSTRAINT fk_website_page_website FOREIGN KEY (fk_website) REFERENCES llx_website (rowid);
-- For new module blockedlog
CREATE TABLE llx_blockedlog
(
rowid integer AUTO_INCREMENT PRIMARY KEY,

View File

@ -330,7 +330,7 @@ drop table tmp_c_shipment_mode;
-- Restore id of user on link for payment of expense report
drop table tmp_bank_url_expense_user;
create table tmp_bank_url_expense_user (select e.fk_user_author, bu2.fk_bank from llx_expensereport as e, llx_bank_url as bu2 where bu2.url_id = e.rowid and bu2.type = 'payment_expensereport');
update llx_bank_url as bu set url_id = (select e.fk_user_author from tmp_bank_url_expense_user as e where e.fk_bank = bu.fk_bank) where bu.url_id = 0 and bu.type ='user';
update llx_bank_url as bu set url_id = (select e.fk_user_author from tmp_bank_url_expense_user as e where e.fk_bank = bu.fk_bank) where (bu.url_id = 0 OR bu.url_id IS NULL) and bu.type ='user';
drop table tmp_bank_url_expense_user;

View File

@ -16,7 +16,7 @@
--
-- ===========================================================================
ALTER TABLE llx_website_page ADD UNIQUE INDEX uk_website_page_url (fk_website,pageurl);
ALTER TABLE llx_website_page ADD UNIQUE INDEX uk_website_page_url (fk_website, pageurl);
ALTER TABLE llx_website_page ADD CONSTRAINT fk_website_page_website FOREIGN KEY (fk_website) REFERENCES llx_website (rowid);

View File

@ -345,11 +345,14 @@ if (! $error && $db->connected)
if (! $error && $db->connected && $action == "set")
{
umask(0);
foreach($_POST as $key => $value)
if (is_array($_POST))
{
if (! preg_match('/^db_pass/i', $key)) {
dolibarr_install_syslog("step1: choice for " . $key . " = " . $value);
}
foreach($_POST as $key => $value)
{
if (! preg_match('/^db_pass/i', $key)) {
dolibarr_install_syslog("step1: choice for " . $key . " = " . $value);
}
}
}
// Show title of step

View File

@ -103,7 +103,7 @@ LineOfExpenseReport=Line of expense report
NoAccountSelected=No accounting account selected
VentilatedinAccount=Binded successfully to the accounting account
NotVentilatedinAccount=Not bound to the accounting account
XLineSuccessfullyBinded=%s products/services successfuly bound to an accounting account
XLineSuccessfullyBinded=%s products/services successfully bound to an accounting account
XLineFailedToBeBinded=%s products/services were not bound to any accounting account
ACCOUNTING_LIMIT_LIST_VENTILATION=Number of elements to bind shown by page (maximum recommended : 50)

View File

@ -140,7 +140,7 @@ SystemToolsArea=System tools area
SystemToolsAreaDesc=This area provides administration features. Use the menu to choose the feature you're looking for.
Purge=Purge
PurgeAreaDesc=This page allows you to delete all files generated or stored by Dolibarr (temporary files or all files in <b>%s</b> directory). Using this feature is not necessary. It is provided as a workaround for users whose Dolibarr is hosted by a provider that does not offer permissions to delete files generated by the web server.
PurgeDeleteLogFile=Delete log file <b>%s</b> defined for Syslog module (no risk of losing data)
PurgeDeleteLogFile=Delete log files, including <b>%s</b> defined for Syslog module (no risk of losing data)
PurgeDeleteTemporaryFiles=Delete all temporary files (no risk of losing data)
PurgeDeleteTemporaryFilesShort=Delete temporary files
PurgeDeleteAllFilesInDocumentsDir=Delete all files in directory <b>%s</b>. Temporary files but also database backup dumps, files attached to elements (third parties, invoices, ...) and uploaded into the ECM module will be deleted.

View File

@ -75,7 +75,8 @@ FileRenamed=The file was successfully renamed
FileGenerated=The file was successfully generated
FileSaved=The file was successfully saved
FileUploaded=The file was successfully uploaded
FileTransferComplete=File(s) was uploaded successfuly
FileTransferComplete=File(s) was uploaded successfully
FilesDeleted=File(s) successfully deleted
FileWasNotUploaded=A file is selected for attachment but was not yet uploaded. Click on "Attach file" for this.
NbOfEntries=Nb of entries
GoToWikiHelpPage=Read online help (Internet access needed)
@ -196,6 +197,7 @@ Parameter=Parameter
Parameters=Parameters
Value=Value
PersonalValue=Personal value
NewObject=New %s
NewValue=New value
CurrentValue=Current value
Code=Code
@ -736,6 +738,7 @@ ShowTransaction=Show entry on bank account
GoIntoSetupToChangeLogo=Go into Home - Setup - Company to change logo or go into Home - Setup - Display to hide.
Deny=Deny
Denied=Denied
ListOf=List of %s
ListOfTemplates=List of templates
Gender=Gender
Genderman=Man

View File

@ -9,7 +9,8 @@ NewObject=New object
ModuleKey=Module key
ObjectKey=Object key
ModuleInitialized=Module initialized
FilesForObjectInitialized=Files for new object initialized
FilesForObjectInitialized=Files for new object '%s' initialized
FilesForObjectUpdated=Files for object '%s' updated (.sql files and .class.php file)
ModuleBuilderDescdescription=Enter here all general information that describe your module
ModuleBuilderDescspecifications=You can enter here a long text to describe the specifications of your module that is not already structured into other tabs. So you have on hand the rules to develop. Also this text content will be included into the generated documentation (see last tab).
ModuleBuilderDescobjects=Define here the objects you want to manage with your module. A sql file, a page to list them, to create/edit/view a card and an API will be generated.
@ -38,3 +39,9 @@ PathToModulePackage=Path to zip of module/application package
PathToModuleDocumentation=Path to file of module/application documentation
SpaceOrSpecialCharAreNotAllowed=Spaces or special characters are not allowed.
FileNotYetGenerated=File not yet generated
SpecificationFile=File with business rules
ConfirmDeleteProperty=Are you sure you want to delete the property <strong>%s</strong> ? This will change code in PHP class but also remove column from table definition of object.
NotNull=Not NULL
SearchAll=Used for 'search all'
DatabaseIndex=Database index
FileAlreadyExists=File %s already exists

View File

@ -4,6 +4,7 @@ WebsiteSetupDesc=Create here as much entry as number of different websites you n
DeleteWebsite=Delete website
ConfirmDeleteWebsite=Are you sure you want to delete this web site. All its pages and content will also be removed.
WEBSITE_PAGENAME=Page name/alias
WEBSITE_HTML_HEADER=HTML Header
WEBSITE_CSS_URL=URL of external CSS file
WEBSITE_CSS_INLINE=CSS content
PageNameAliasHelp=Name or alias of the page.<br>This alias is also used to forge a SEO URL when website is read from a Virtual host of a Web server (like Apacke, Nginx, ...). Use the button "<strong>%s</strong>" to edit this alias.

View File

@ -1498,10 +1498,12 @@ function top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $a
{
$qs=dol_escape_htmltag($_SERVER["QUERY_STRING"]);
foreach($_POST as $key=>$value) {
if ($key!=='action' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);
}
if (is_array($_POST))
{
foreach($_POST as $key=>$value) {
if ($key!=='action' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);
}
}
$qs.=(($qs && $morequerystring)?'&':'').$morequerystring;
$text ='<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs?'&':'').'optioncss=print" target="_blank">';
//$text.= img_picto(":".$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');

View File

@ -24,6 +24,7 @@ if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1');
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/modulebuilder.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
$langs->load("admin");
@ -37,9 +38,10 @@ $cancel=GETPOST('cancel','alpha');
$module=GETPOST('module','alpha');
$tab=GETPOST('tab','aZ09');
$tabobj=GETPOST('tabobj','alpha');
$propertykey=GETPOST('propertykey','alpha');
if (empty($module)) $module='initmodule';
if (empty($tab)) $tab='description';
if (empty($tabobj)) $tabobj='newobject';
if (empty($tabobj)) $tabobj='newobjectifnoobj';
$file=GETPOST('file','alpha');
$modulename=dol_sanitizeFileName(GETPOST('modulename','alpha'));
@ -57,6 +59,13 @@ $dirins = $tmp[0];
$FILEFLAG='modulebuilder.txt';
$now=dol_now();
$newmask = 0;
if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
if (empty($newmask)) // This should no happen
{
$newmask='0664';
}
/*
* Actions
@ -156,14 +165,6 @@ if ($dirins && $action == 'initobject' && $module && $objectname)
$srcdir = DOL_DOCUMENT_ROOT.'/modulebuilder/template';
$destdir = $dirins.'/'.strtolower($module);
$arrayreplacement=array(
'mymodule'=>strtolower($module),
'MyModule'=>$module,
'myobject'=>strtolower($objectname),
'MyObject'=>$objectname
);
// Delete some files
$filetogenerate = array(
'myobject_card.php'=>strtolower($objectname).'_card.php',
@ -180,7 +181,7 @@ if ($dirins && $action == 'initobject' && $module && $objectname)
foreach($filetogenerate as $srcfile => $destfile)
{
$result = dol_copy($srcdir.'/'.$srcfile, $destdir.'/'.$destfile);
$result = dol_copy($srcdir.'/'.$srcfile, $destdir.'/'.$destfile, $newmask, 0);
if ($result <= 0)
{
if ($result < 0)
@ -191,7 +192,7 @@ if ($dirins && $action == 'initobject' && $module && $objectname)
}
else // $result == 0
{
setEventMessages($langs->trans("FileAlreadyExists", $srcdir.'/'.$srcfile, $destdir.'/'.$destfile), null, 'warnings');
setEventMessages($langs->trans("FileAlreadyExists", $destfile), null, 'warnings');
}
}
else
@ -210,10 +211,10 @@ if ($dirins && $action == 'initobject' && $module && $objectname)
//var_dump($phpfileval['fullname']);
$arrayreplacement=array(
'mymodule'=>strtolower($modulename),
'MyModule'=>$modulename,
'MYMODULE'=>strtoupper($modulename),
'My module'=>$modulename,
'mymodule'=>strtolower($module),
'MyModule'=>$module,
'MYMODULE'=>strtoupper($module),
'My module'=>$module,
'htdocs/modulebuilder/template/'=>'',
'myobject'=>strtolower($objectname),
'MyObject'=>$objectname
@ -230,7 +231,36 @@ if ($dirins && $action == 'initobject' && $module && $objectname)
if (! $error)
{
setEventMessages('FilesForObjectInitialized', null);
// Edit the class file to write properties
rebuildObjectClass($destdir, $module, $objectname, $newmask);
// Edit sql with new properties
rebuildObjectSql($destdir, $module, $objectname, $newmask);
}
if (! $error)
{
setEventMessages($langs->trans('FilesForObjectInitialized', $objectname), null);
}
}
if ($dirins && $action == 'addproperty' && !empty($module) && ! empty($tabobj))
{
$objectname = $tabobj;
$destdir = $dirins.'/'.strtolower($module);
// TODO Complete list of fields with new one
// Edit the class file to write properties
rebuildObjectClass($destdir, $module, $objectname, $newmask);
// Edit sql with new properties
rebuildObjectSql($destdir, $module, $objectname, $newmask);
if (! $error)
{
setEventMessages($langs->trans('FilesForObjectUpdated', $objectname), null);
}
}
@ -320,6 +350,29 @@ if ($dirins && $action == 'confirm_deleteobject' && $objectname)
$tabobj = 'deleteobject';
}
if ($dirins && $action == 'confirm_deleteproperty' && $propertykey)
{
if (! $error)
{
$modulelowercase=strtolower($module);
$objectlowercase=strtolower($objectname);
// File of class
$fileforclass = $dirins.'/'.$modulelowercase.'/class/'.$objectlowercase.'.class.php';
// TODO
// File of sql
$fileforsql = $dirins.'/'.$modulelowercase.'/sql/'.$objectlowercase.'.sql';
$fileforsqlkey = $dirins.'/'.$modulelowercase.'/sql/'.$objectlowercase.'.key.sql';
// TODO
}
}
if ($dirins && $action == 'generatepackage')
{
$modulelowercase=strtolower($module);
@ -401,15 +454,7 @@ if ($action == 'savefile' && empty($cancel))
$content = GETPOST('editfilecontent');
// Save file on disk
$newmask = 0;
file_put_contents($pathoffile, $content);
if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
if (empty($newmask)) // This should no happen
{
$newmask='0664';
}
@chmod($pathoffile, octdec($newmask));
setEventMessages($langs->trans("FileSaved"), null);
@ -838,9 +883,11 @@ elseif (! empty($module))
$h++;
$listofobject = dol_dir_list($dir, 'files', 0, '\.txt$');
$firstobjectname='';
foreach($listofobject as $fileobj)
{
$objectname = preg_replace('/\.txt$/', '', $fileobj['name']);
if (empty($firstobjectname)) $firstobjectname = $objectname;
$head3[$h][0] = $_SERVER["PHP_SELF"].'?tab=objects&module='.$module.'&tabobj='.$objectname;
$head3[$h][1] = $objectname;
@ -853,6 +900,12 @@ elseif (! empty($module))
$head3[$h][2] = 'deleteobject';
$h++;
// If tabobj was not defined, then we check if there is one obj. If yes, we force on it, if no, we will show tab to create new objects.
if ($tabobj == 'newobjectifnoobj')
{
if ($firstobjectname) $tabobj=$firstobjectname;
else $tabobj = 'newobject';
}
dol_fiche_head($head3, $tabobj, '', -1, '');
@ -888,92 +941,186 @@ elseif (! empty($module))
}
else
{
try {
$pathtoclass = strtolower($module).'/class/'.strtolower($tabobj).'.class.php';
$pathtoapi = strtolower($module).'/class/api_'.strtolower($tabobj).'.class.php';
$pathtolist = strtolower($module).'/'.strtolower($tabobj).'_list.class.php';
$pathtocard = strtolower($module).'/'.strtolower($tabobj).'_card.class.php';
print '<span class="fa fa-file"></span> '.$langs->trans("ClassFile").' : <strong>'.$pathtoclass.'</strong><br>';
print '<span class="fa fa-file"></span> '.$langs->trans("ApiClassFile").' : <strong>'.$pathtoapi.'</strong><br>';
print '<span class="fa fa-file"></span> '.$langs->trans("PageForList").' : <strong>'.$pathtolist.'</strong><br>';
print '<span class="fa fa-file"></span> '.$langs->trans("PageForCreateEditView").' : <strong>'.$pathtocard.'</strong><br>';
if ($action == 'deleteproperty')
{
$formconfirm = $form->formconfirm(
$_SERVER["PHP_SELF"].'?propertykey='.urlencode(GETPOST('propertykey','alpha')).'&objectname='.urlencode($objectname).'&tab='.urlencode($tab).'&module='.urlencode($module).'&tabobj='.urlencode($tabobj),
$langs->trans('Delete'), $langs->trans('ConfirmDeleteProperty', GETPOST('propertykey','alpha')), 'confirm_deleteproperty', '', 0, 1
);
$result = dol_include_once($pathtoclass);
$tmpobjet = new $tabobj($db);
// Print form confirm
print $formconfirm;
}
$reflector = new ReflectionClass($tabobj);
$properties = $reflector->getProperties(); // Can also use get_object_vars
$propdefault = $reflector->getDefaultProperties(); // Can also use get_object_vars
//$propstat = $reflector->getStaticProperties();
if ($action != 'editfile' || empty($file))
{
try {
$pathtoclass = strtolower($module).'/class/'.strtolower($tabobj).'.class.php';
$pathtoapi = strtolower($module).'/class/api_'.strtolower($tabobj).'.class.php';
$pathtolist = strtolower($module).'/'.strtolower($tabobj).'_list.php';
$pathtocard = strtolower($module).'/'.strtolower($tabobj).'_card.php';
print '<div class="fichehalfleft">';
print '<span class="fa fa-file"></span> '.$langs->trans("ClassFile").' : <strong>'.$pathtoclass.'</strong>';
print ' <a href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.'&action=editfile&file='.urlencode($pathtoclass).'">'.img_picto($langs->trans("Edit"), 'edit').'</a>';
print '<br>';
print '<span class="fa fa-file"></span> '.$langs->trans("ApiClassFile").' : <strong>'.$pathtoapi.'</strong>';
print ' <a href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.'&action=editfile&file='.urlencode($pathtoapi).'">'.img_picto($langs->trans("Edit"), 'edit').'</a>';
print '</div>';
print '<div class="fichehalfleft">';
print '<span class="fa fa-file"></span> '.$langs->trans("PageForList").' : <strong>'.$pathtolist.'</strong>';
print ' <a href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.'&action=editfile&file='.urlencode($pathtolist).'">'.img_picto($langs->trans("Edit"), 'edit').'</a>';
print '<br>';
print '<span class="fa fa-file"></span> '.$langs->trans("PageForCreateEditView").' : <strong>'.$pathtocard.'</strong>';
print ' <a href="'.$_SERVER['PHP_SELF'].'?tab='.$tab.'&module='.$module.'&action=editfile&file='.urlencode($pathtocard).'">'.img_picto($langs->trans("Edit"), 'edit').'</a>';
print '</div>';
print load_fiche_titre($langs->trans("Properties"), '', '');
print '<br><br><br>';
print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="initobject">';
print '<input type="hidden" name="tab" value="objects">';
print '<input type="hidden" name="module" value="'.dol_escape_htmltag($module).'">';
print '<input type="hidden" name="tabobj" value="'.dol_escape_htmltag($tabobj).'">';
$result = dol_include_once($pathtoclass);
if (class_exists($tabobj)) $tmpobjet = new $tabobj($db);
print '<table class="noborder">';
print '<tr class="liste_titre">';
print '<td>'.$langs->trans("Property");
print ' (<a href="https://wiki.dolibarr.org/index.php/Language_and_development_rules#Table_and_fields_structures" target="_blank">'.$langs->trans("Example").'</a>)';
print '</td>';
print '<td>'.$langs->trans("Comment").'</td>';
print '<td>'.$langs->trans("Type").'</td>';
print '<td>'.$langs->trans("DefaultValue").'</td>';
print '<td></td>';
print '</tr>';
print '<tr>';
print '<td><input class="text" name="propname" value=""></td>';
print '<td><input class="text" name="propname" value=""></td>';
print '<td><input class="text" name="propname" value=""></td>';
print '<td><input class="text" name="propname" value=""></td>';
print '<td align="center">';
print '<input class="button" type="submit" name="add" value="'.$langs->trans("Add").'">';
print '</td></tr>';
foreach($properties as $propkey => $propval)
{
if ($propval->class == $tabobj)
$reflector = new ReflectionClass($tabobj);
$properties = $reflector->getProperties(); // Can also use get_object_vars
$propdefault = $reflector->getDefaultProperties(); // Can also use get_object_vars
//$propstat = $reflector->getStaticProperties();
print load_fiche_titre($langs->trans("Properties"), '', '');
print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="addproperty">';
print '<input type="hidden" name="tab" value="objects">';
print '<input type="hidden" name="module" value="'.dol_escape_htmltag($module).'">';
print '<input type="hidden" name="tabobj" value="'.dol_escape_htmltag($tabobj).'">';
print '<table class="noborder">';
print '<tr class="liste_titre">';
print '<td>'.$langs->trans("Property");
print ' (<a href="https://wiki.dolibarr.org/index.php/Language_and_development_rules#Table_and_fields_structures" target="_blank">'.$langs->trans("Example").'</a>)';
print '</td>';
print '<td>';
print $form->textwithpicto($langs->trans("Label"), $langs->trans("YouCanUseTranslationKey"));
print '</td>';
print '<td>'.$langs->trans("Type").'</td>';
print '<td class="right">'.$langs->trans("Position").'</td>';
print '<td class="center">'.$langs->trans("NotNull").'</td>';
print '<td class="center">'.$langs->trans("SearchAll").'</td>';
//print '<td>'.$langs->trans("DefaultValue").'</td>';
print '<td class="center">'.$langs->trans("DatabaseIndex").'</td>';
print '<td>'.$langs->trans("Comment").'</td>';
print '<td></td>';
print '</tr>';
print '<tr>';
print '<td><input class="text" name="propname" value=""></td>';
print '<td><input class="text" name="proplabel" value=""></td>';
print '<td><input class="text" name="proptype" value=""></td>';
print '<td class="right"><input class="text right" size="2" name="propposition" value=""></td>';
print '<td class="center"><input class="text" size="2" name="propnotnull" value=""></td>';
print '<td class="center"><input class="text" size="2" name="propsearchall" value=""></td>';
//print '<td><input class="text" name="propdefault" value=""></td>';
print '<td class="center"><input class="text" size="2" name="propindex" value=""></td>';
print '<td><input class="text" name="propcomment" value=""></td>';
print '<td align="center">';
print '<input class="button" type="submit" name="add" value="'.$langs->trans("Add").'">';
print '</td></tr>';
$properties = $tmpobjet->fields;
foreach($properties as $propkey => $propval)
{
$propname=$propval->getName();
/* If from Reflection
if ($propval->class == $tabobj)
{
$propname=$propval->getName();
$comment=$propval->getDocComment();
$type=gettype($tmpobjet->$propname);
$default=$propdefault[$propname];
// Discard generic properties
if (in_array($propname, array('element', 'childtables', 'table_element', 'table_element_line', 'class_element_line', 'isnolinkedbythird', 'ismultientitymanaged'))) continue;
// Discard generic properties
if (in_array($propname, array('element', 'childtables', 'table_element', 'table_element_line', 'class_element_line', 'isnolinkedbythird', 'ismultientitymanaged'))) continue;
// Keep or not lines
if (in_array($propname, array('fk_element', 'lines'))) continue;
}*/
// Keep or not lines
if (in_array($propname, array('fk_element', 'lines'))) continue;
$propname=$propkey;
$proplabel=$propval['label'];
$proptype=$propval['type'];
$propposition=$propval['position'];
$propnotnull=$propval['notnull'];
$propsearchall=$propval['searchall'];
//$propdefault=$propval['default'];
$propindex=$propval['index'];
$propcomment=$propval['comment'];
print '<tr class="oddeven">';
print '<tr class="oddeven"><td>';
print '<td>';
print $propname;
print '</td>';
print '<td>';
print $propval->getDocComment();
print $proplabel;
print '</td>';
print '<td>';
print gettype($tmpobjet->$propname);
print $proptype;
print '</td>';
print '<td align="right">';
print $propposition;
print '</td>';
print '<td class="center">';
print $propnotnull?'X':'';
print '</td>';
print '<td class="center">';
print $propsearchall?'X':'';
print '</td>';
/*print '<td>';
print $propdefault;
print '</td>';*/
print '<td class="center">';
print $propindex?'X':'';
print '</td>';
print '<td>';
print $propdefault[$propname];
print $propcomment;
print '</td>';
print '<td class="center">';
print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteproperty&propertykey='.urlencode($propname).'&tab='.urlencode($tab).'&module='.urlencode($module).'&tabobj='.urlencode($tabobj).'">'.img_delete().'</a>';
print '</td>';
print '<td>';
print '</td>';
print '</tr>';
}
print '</table>';
print '</form>';
}
print '</table>';
catch(Exception $e)
{
print $e->getMessage();
}
}
else
{
$fullpathoffile=dol_buildpath($file, 0);
$content = file_get_contents($fullpathoffile);
// New module
print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="savefile">';
print '<input type="hidden" name="file" value="'.dol_escape_htmltag($file).'">';
print '<input type="hidden" name="tab" value="'.$tab.'">';
print '<input type="hidden" name="module" value="'.$module.'">';
$doleditor=new DolEditor('editfilecontent', $content, '', '600', 'Full', 'In', true, false, false, 0, '99%');
print $doleditor->Create(1, '', false);
print '<br>';
print '<center>';
print '<input type="submit" class="button" name="savefile" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
print ' &nbsp; ';
print '<input type="submit" class="button" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
print '</center>';
print '</form>';
}
catch(Exception $e)
{
print $e->getMessage();
}
}
}

View File

@ -47,27 +47,30 @@ class MyObject extends CommonObject
/**
* @var array Does this field is linked to a thirdparty ?
*/
protected $isnolinkedbythird=1;
protected $isnolinkedbythird = 1;
/**
* @var array Does myobject support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
*/
protected $ismultientitymanaged = 1;
/**
* @var string String with name of icon for myobject
*/
* @var string String with name of icon for myobject
*/
public $picto = 'myobject';
/**
* @var int Entity Id
*/
public $entity;
// BEGIN MODULEBUILDER PROPERTIES
/**
* @var array Array with all fields and their property
*/
public $fields;
public $fields=array(
'ref' =>array('type'=>'varchar(64)', 'label'=>'Ref', 'position'=>10, 'notnull'=>true, 'index'=>true, 'searchall'=>1, 'comment'=>'Reference of object'),
'entity'=>array('type'=>'integer', 'label'=>'Entity', 'notnull'=>true, 'index'=>true),
'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'searchall'=>1),
'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'notnull'=>true, 'position'=>500),
'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'notnull'=>true, 'position'=>500),
'status'=>array('type'=>'integer', 'label'=>'Status', 'index'=>true, 'position'=>1000),
);
// END MODULEBUILDER PROPERTIES
@ -106,366 +109,6 @@ class MyObject extends CommonObject
$this->db = $db;
}
/**
* Create object into database
*
* @param User $user User that creates
* @param bool $notrigger false=launch triggers after, true=disable triggers
*
* @return int <0 if KO, Id of created object if OK
*/
public function create(User $user, $notrigger = false)
{
dol_syslog(__METHOD__, LOG_DEBUG);
$error = 0;
// Clean parameters
if (isset($this->prop1)) {
$this->prop1 = trim($this->prop1);
}
if (isset($this->prop2)) {
$this->prop2 = trim($this->prop2);
}
//...
// Check parameters
// Put here code to add control on parameters values
// Insert request
$sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '(';
$sql .= ' field1,';
$sql .= ' field2';
//...
$sql .= ') VALUES (';
$sql .= ' \'' . $this->prop1 . '\',';
$sql .= ' \'' . $this->prop2 . '\'';
//...
$sql .= ')';
$this->db->begin();
$resql = $this->db->query($sql);
if (!$resql) {
$error ++;
$this->errors[] = 'Error ' . $this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
}
if (!$error) {
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
if (!$notrigger) {
// Uncomment this and change MYOBJECT to your own tag if you
// want this action to call a trigger.
//// Call triggers
//$result=$this->call_trigger('MYOBJECT_CREATE',$user);
//if ($result < 0) $error++;
//// End call triggers
}
}
// Commit or rollback
if ($error) {
$this->db->rollback();
return - 1 * $error;
} else {
$this->db->commit();
return $this->id;
}
}
/**
* Load object in memory from the database
*
* @param int $id Id object
* @param string $ref Ref
* @return int <0 if KO, 0 if not found, >0 if OK
*/
public function fetch($id, $ref = null)
{
dol_syslog(__METHOD__, LOG_DEBUG);
$sql = 'SELECT';
$sql .= ' t.rowid,';
$sql .= ' t.field1,';
$sql .= ' t.field2';
//...
$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
$sql.= ' WHERE 1 = 1';
if (! empty($conf->multicompany->enabled)) {
$sql .= " AND entity IN (" . getEntity('mymoduleobject') . ")";
}
if (null !== $ref) {
$sql .= ' AND t.ref = ' . '\'' . $ref . '\'';
} else {
$sql .= ' AND t.rowid = ' . $id;
}
$resql = $this->db->query($sql);
if ($resql) {
$numrows = $this->db->num_rows($resql);
if ($numrows) {
$obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid;
$this->prop1 = $obj->field1;
$this->prop2 = $obj->field2;
//...
}
$this->db->free($resql);
$this->fetch_optionals();
// $this->fetch_lines();
if ($numrows) {
return 1;
} else {
return 0;
}
} else {
$this->errors[] = 'Error ' . $this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
return - 1;
}
}
/**
* Load object in memory from the database
*
* @param string $sortorder Sort Order
* @param string $sortfield Sort field
* @param int $limit offset limit
* @param int $offset offset limit
* @param array $filter filter array
* @param string $filtermode filter mode (AND or OR)
*
* @return int <0 if KO, >0 if OK
*/
public function fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter = array(), $filtermode='AND')
{
dol_syslog(__METHOD__, LOG_DEBUG);
$sql = 'SELECT';
$sql .= ' t.rowid,';
$sql .= ' t.field1,';
$sql .= ' t.field2';
//...
$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t';
// Manage filter
$sqlwhere = array();
if (count($filter) > 0) {
foreach ($filter as $key => $value) {
$sqlwhere [] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
}
}
$sql.= ' WHERE 1 = 1';
if (! empty($conf->multicompany->enabled)) {
$sql .= " AND entity IN (" . getEntity('mymoduleobject') . ")";
}
if (count($sqlwhere) > 0) {
$sql .= ' AND ' . implode(' '.$filtermode.' ', $sqlwhere);
}
if (!empty($sortfield)) {
$sql .= $this->db->order($sortfield,$sortorder);
}
if (!empty($limit)) {
$sql .= ' ' . $this->db->plimit($limit, $offset);
}
$resql = $this->db->query($sql);
if ($resql) {
$num = $this->db->num_rows($resql);
while ($obj = $this->db->fetch_object($resql)) {
$line = new self($this->db);
$line->id = $obj->rowid;
$line->prop1 = $obj->field1;
$line->prop2 = $obj->field2;
//...
}
$this->db->free($resql);
return $num;
} else {
$this->errors[] = 'Error ' . $this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
return - 1;
}
}
/**
* Update object into database
*
* @param User $user User that modifies
* @param bool $notrigger false=launch triggers after, true=disable triggers
*
* @return int <0 if KO, >0 if OK
*/
public function update(User $user, $notrigger = false)
{
dol_syslog(__METHOD__, LOG_DEBUG);
$error = 0;
// Clean parameters
if (isset($this->prop1)) {
$this->prop1 = trim($this->prop1);
}
if (isset($this->prop2)) {
$this->prop2 = trim($this->prop2);
}
//...
// Check parameters
// Put here code to add a control on parameters values
// Update request
$sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET';
$sql .= " field1=".(isset($this->field1)?"'".$this->db->escape($this->field1)."'":"null").",";
$sql .= " field2=".(isset($this->field2)?"'".$this->db->escape($this->field2)."'":"null")."";
//...
$sql .= ' WHERE rowid=' . $this->id;
$this->db->begin();
$resql = $this->db->query($sql);
if (!$resql) {
$error ++;
$this->errors[] = 'Error ' . $this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
}
if (!$error && !$notrigger) {
// Uncomment this and change MYOBJECT to your own tag if you
// want this action calls a trigger.
//// Call triggers
//$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
//// End call triggers
}
// Commit or rollback
if ($error) {
$this->db->rollback();
return - 1 * $error;
} else {
$this->db->commit();
return 1;
}
}
/**
* Delete object in database
*
* @param User $user User that deletes
* @param bool $notrigger false=launch triggers after, true=disable triggers
*
* @return int <0 if KO, >0 if OK
*/
public function delete(User $user, $notrigger = false)
{
dol_syslog(__METHOD__, LOG_DEBUG);
$error = 0;
$this->db->begin();
if (!$error) {
if (!$notrigger) {
// Uncomment this and change MYOBJECT to your own tag if you
// want this action calls a trigger.
//// Call triggers
//$result=$this->call_trigger('MYOBJECT_DELETE',$user);
//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
//// End call triggers
}
}
// If you need to delete child tables to, you can insert them here
if (!$error) {
$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element;
$sql .= ' WHERE rowid=' . $this->id;
$resql = $this->db->query($sql);
if (!$resql) {
$error ++;
$this->errors[] = 'Error ' . $this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
}
}
// Commit or rollback
if ($error) {
$this->db->rollback();
return - 1 * $error;
} else {
$this->db->commit();
return 1;
}
}
/**
* Load an object from its id and create a new one in database
*
* @param int $fromid Id of object to clone
*
* @return int New id of clone
*/
public function createFromClone($fromid)
{
dol_syslog(__METHOD__, LOG_DEBUG);
global $user;
$error = 0;
$object = new self($this->db);
$this->db->begin();
// Load source object
$object->fetch($fromid);
// Reset object
$object->id = 0;
// Clear fields
// ...
// Create clone
$result = $object->create($user);
// Other options
if ($result < 0) {
$error ++;
$this->errors = $object->errors;
dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
}
// End
if (!$error) {
$this->db->commit();
return $object->id;
} else {
$this->db->rollback();
return - 1;
}
}
/**
* Return a link to the object card (with optionaly the picto)
@ -589,9 +232,7 @@ class MyObject extends CommonObject
*/
public function initAsSpecimen()
{
$this->id = 0;
$this->prop1 = 'prop1';
$this->prop2 = 'prop2';
$this->initAsSpecimenCommon();
}
}

View File

@ -99,7 +99,7 @@ class modMyModule extends DolibarrModules
);
// Data directories to create when module is enabled.
// Example: this->dirs = array("/mymodule/temp");
// Example: this->dirs = array("/mymodule/temp","/mymodule/subdir");
$this->dirs = array();
// Config pages. Put here list of php page, stored into mymodule/admin directory, to use to setup module.
@ -288,6 +288,12 @@ class modMyModule extends DolibarrModules
$this->_load_tables('/mymodule/sql/');
// Create extrafields
include_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
$extrafields = new ExtraFields($this->db);
//$result1=$extrafields->addExtraField('myattr1', "New Attr 1 label", 'boolean', 1, 3, 'thirdparty');
//$result2=$extrafields->addExtraField('myattr2', "New Attr 2 label", 'string', 1, 10, 'project');
return $this->_init($sql, $options);
}

View File

@ -58,14 +58,27 @@ dol_include_once('/mymodule/class/myobject.class.php');
$langs->loadLangs(array("mymodule","other"));
// Get parameters
$id = GETPOST('id','int');
$action = GETPOST('action','alpha');
$cancel = GETPOST('cancel');
$backtopage = GETPOST('backtopage');
$myparam = GETPOST('myparam','alpha');
$id = GETPOST('id', 'int');
$action = GETPOST('action', 'alpha');
$cancel = GETPOST('cancel', 'aZ09');
$backtopage = GETPOST('backtopage', 'alpha');
$search_field1=GETPOST("search_field1");
$search_field2=GETPOST("search_field2");
// Initialize technical objects
$object=new MyObject($db);
$extrafields = new ExtraFields($db);
$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id;
$hookmanager->initHooks(array('myobjectcard')); // Note that conf->hooks_modules contains array
// Fetch optionals attributes and labels
$extralabels = $extrafields->fetch_name_optionals_label('myobject');
$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_');
// Initialize array of search criterias
$search_all=trim(GETPOST("search_all",'alpha'));
$search=array();
foreach($object->fields as $key => $val)
{
if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha');
}
if (empty($action) && empty($id) && empty($ref)) $action='view';
@ -76,19 +89,12 @@ if ($user->societe_id > 0)
}
//$result = restrictedArea($user, 'mymodule', $id);
$object = new MyObject_Class($db);
$extrafields = new ExtraFields($db);
// fetch optionals attributes and labels
$extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
// Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
// Initialize technical object to manage hooks of modules. Note that conf->hooks_modules contains array array
$hookmanager->initHooks(array('mymodule'));
/*
@ -107,7 +113,7 @@ if (empty($reshook))
{
if ($action != 'addlink')
{
$urltogo=$backtopage?$backtopage:dol_buildpath('/mymodule/list.php',1);
$urltogo=$backtopage?$backtopage:dol_buildpath('/mymodule/myobject_list.php',1);
header("Location: ".$urltogo);
exit;
}
@ -120,33 +126,35 @@ if (empty($reshook))
{
if ($cancel)
{
$urltogo=$backtopage?$backtopage:dol_buildpath('/mymodule/list.php',1);
$urltogo=$backtopage?$backtopage:dol_buildpath('/mymodule/myobject_list.php',1);
header("Location: ".$urltogo);
exit;
}
$error=0;
/* object_prop_getpost_prop */
$object->prop1=GETPOST("field1");
$object->prop2=GETPOST("field2");
if (empty($object->ref))
{
$error++;
setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), null, 'errors');
}
foreach ($object->fields as $key => $val)
{
$object->$key=GETPOST($key,'alpha');
if (in_array($key, array('entity', 'datec', 'tms'))) continue;
if ($val['notnull'] && $object->$key == '')
{
$error++;
setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv($val['label'])), null, 'errors');
}
}
if (! $error)
{
$result=$object->create($user);
$result=$object->createCommon($user);
if ($result > 0)
{
// Creation OK
$urltogo=$backtopage?$backtopage:dol_buildpath('/mymodule/list.php',1);
$urltogo=$backtopage?$backtopage:dol_buildpath('/mymodule/myobject_list.php',1);
header("Location: ".$urltogo);
exit;
}
else
{
// Creation KO
if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors');
@ -203,7 +211,7 @@ if (empty($reshook))
{
// Delete OK
setEventMessages("RecordDeleted", null, 'mesgs');
header("Location: ".dol_buildpath('/mymodule/list.php',1));
header("Location: ".dol_buildpath('/mymodule/myobject_list.php',1));
exit;
}
else
@ -225,10 +233,7 @@ if (empty($reshook))
$form=new Form($db);
llxHeader('','MyPageName','');
// Put here content of your page
llxHeader('','MyObject','');
// Example : Adding jquery code
print '<script type="text/javascript" language="javascript">
@ -249,7 +254,7 @@ jQuery(document).ready(function() {
// Part to create
if ($action == 'create')
{
print load_fiche_titre($langs->trans("NewMyModule"));
print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("MyObject")));
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="action" value="add">';
@ -258,8 +263,15 @@ if ($action == 'create')
dol_fiche_head();
print '<table class="border centpercent">'."\n";
// print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td><td><input class="flat" type="text" size="36" name="label" value="'.$label.'"></td></tr>';
// LIST_OF_TD_LABEL_FIELDS_CREATE
foreach($object->fields as $key => $val)
{
if (in_array($key, array('rowid', 'entity', 'datec', 'tms'))) continue;
print '<tr><td';
print ' class="titlefieldcreate';
if ($val['notnull']) print ' fieldrequired';
print '"';
print '>'.$langs->trans($val['label']).'</td><td><input class="flat" type="text" name="'.$key.'" value="'.(GETPOST($key,'alpha')?GETPOST($key,'alpha'):'').'"></td></tr>';
}
print '</table>'."\n";
dol_fiche_end();
@ -343,7 +355,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Object card
// ------------------------------------------------------------
$linkback = '<a href="' . DOL_URL_ROOT . '/mymodule/list.php' . (! empty($socid) ? '?socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
$linkback = '<a href="' . DOL_URL_ROOT . '/mymodule/myobject_list.php' . (! empty($socid) ? '?socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
$morehtmlref='<div class="refidno">';

View File

@ -65,16 +65,11 @@ $massaction = GETPOST('massaction','alpha');
$show_files = GETPOST('show_files','int');
$confirm = GETPOST('confirm','alpha');
$toselect = GETPOST('toselect', 'array');
$contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'myobjectlist'; // To manage different context of search
$id = GETPOST('id','int');
$backtopage = GETPOST('backtopage');
$myparam = GETPOST('myparam','alpha');
$search_all=trim(GETPOST("sall"));
$search_field1=GETPOST("search_field1");
$search_field2=GETPOST("search_field2");
$search_myfield=GETPOST('search_myfield');
$optioncss = GETPOST('optioncss','alpha');
$optioncss = GETPOST('optioncss','alpha');
// Load variable for pagination
$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
@ -85,44 +80,49 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined,
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
if (! $sortfield) $sortfield="t.rowid"; // Set here default search field
// Initialize technical objects
$object=new MyObject($db);
$extrafields = new ExtraFields($db);
$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id;
$hookmanager->initHooks(array('myobjectlist')); // Note that conf->hooks_modules contains array
// Fetch optionals attributes and labels
$extralabels = $extrafields->fetch_name_optionals_label('myobject');
$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_');
// Default sort order (if not yet defined by previous GETPOST)
if (! $sortfield) $sortfield="t.".key($object->fields); // Set here default search field. By default 1st field in definition.
if (! $sortorder) $sortorder="ASC";
// Protection if external user
$socid=0;
if ($user->societe_id > 0)
{
$socid = $user->societe_id;
//accessforbidden();
//$socid = $user->societe_id;
accessforbidden();
}
// Initialize technical object to manage context to save list fields
$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'myobjectlist';
// Initialize technical object to manage hooks. Note that conf->hooks_modules contains array
$hookmanager->initHooks(array('myobjectlist'));
$extrafields = new ExtraFields($db);
// fetch optionals attributes and labels
$extralabels = $extrafields->fetch_name_optionals_label('myobject');
$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_');
// Initialize array of search criterias
$search_all=trim(GETPOST("search_all",'alpha'));
$search=array();
foreach($object->fields as $key => $val)
{
if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha');
}
// List of fields to search into when doing a "search in all"
$fieldstosearchall = array(
't.ref'=>'Ref',
't.note_public'=>'NotePublic',
);
if (empty($user->socid)) $fieldstosearchall["t.note_private"]="NotePrivate";
$fieldstosearchall = array();
foreach($object->fields as $key => $val)
{
if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label'];
}
// Definition of fields for list
$arrayfields=array(
't.field1'=>array('label'=>"Field1", 'checked'=>1),
't.field2'=>array('label'=>"Field2", 'checked'=>1),
//'t.entity'=>array('label'=>"Entity", 'checked'=>1, 'enabled'=>(! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))),
't.datec'=>array('label'=>"DateCreationShort", 'checked'=>0, 'position'=>500),
't.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500),
//'t.statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000),
);
$arrayfields=array();
foreach($object->fields as $key => $val)
{
$arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>1);
}
// Extra fields
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
{
@ -133,15 +133,12 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab
}
$object=new Skeleton_Class($db);
/*
* ACTIONS
*
* Put here all code to do according to value of "action" parameter
* Put here all code to do according to value of "$action" parameter
*/
if (GETPOST('cancel')) { $action='list'; $massaction=''; }
@ -159,20 +156,20 @@ if (empty($reshook))
// Purge search criteria
if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") ||GETPOST("button_removefilter")) // All tests are required to be compatible with all browsers
{
$search_field1='';
$search_field2='';
$search_date_creation='';
$search_date_update='';
foreach($object->fields as $key => $val)
{
$search[$key]='';
}
$toselect='';
$search_array_options=array();
}
// Mass actions
$objectclass='Skeleton';
$objectlabel='Skeleton';
$permtoread = $user->rights->skeleton->read;
$permtodelete = $user->rights->skeleton->delete;
$uploaddir = $conf->skeleton->dir_output;
$objectclass='MyObject';
$objectlabel='MyObject';
$permtoread = $user->rights->mymodule->read;
$permtodelete = $user->rights->mymodule->delete;
$uploaddir = $conf->mymodule->dir_output;
include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
}
@ -184,49 +181,37 @@ if (empty($reshook))
* Put here all code to build page
*/
$now=dol_now();
$form=new Form($db);
//$help_url="EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes";
$now=dol_now();
//$help_url="EN:Module_MyObject|FR:Module_MyObject_FR|ES:Módulo_MyObject";
$help_url='';
$title = $langs->trans('MyModuleListTitle');
// Put here content of your page
// Example : Adding jquery code
print '<script type="text/javascript" language="javascript">
jQuery(document).ready(function() {
function init_myfunc()
{
jQuery("#myid").removeAttr(\'disabled\');
jQuery("#myid").attr(\'disabled\',\'disabled\');
}
init_myfunc();
jQuery("#mybutton").click(function() {
init_myfunc();
});
});
</script>';
$title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("MyObjects"));
$sql = "SELECT";
$sql.= " t.rowid,";
$sql.= " t.field1,";
$sql.= " t.field2";
// Build and execute select
// --------------------------------------------------------------------
$sql = 'SELECT ';
foreach($object->fields as $key => $val)
{
$sql.='t.'.$key.', ';
}
// Add fields from extrafields
foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : '');
foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
// Add fields from hooks
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters); // Note that $action and $object may have been modified by hook
$sql.=$hookmanager->resPrint;
$sql.= " FROM ".MAIN_DB_PREFIX."mytable as t";
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."mytable_extrafields as ef on (t.rowid = ef.fk_object)";
$sql.= " WHERE 1 = 1";
//$sql.= " WHERE u.entity IN (".getEntity('mytable').")";
if ($search_field1) $sql.= natural_search("field1",$search_field1);
if ($search_field2) $sql.= natural_search("field2",$search_field2);
if ($sall) $sql.= natural_search(array_keys($fieldstosearchall), $sall);
$sql=preg_replace('/, $/','', $sql);
$sql.= " FROM ".MAIN_DB_PREFIX."myobject as t";
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."myobject_extrafields as ef on (t.rowid = ef.fk_object)";
$sql.= " WHERE t.entity IN (".getEntity('myobject').")";
foreach($search as $key => $val)
{
if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:($object->fields[$key]['type'] == 'integer'?1:0)));
}
if ($search_all) $sql.= natural_search(array_keys($fieldstosearchall), $search_all);
// Add where from extra fields
foreach ($search_array_options as $key => $val)
{
@ -275,16 +260,37 @@ if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) &&
exit;
}
// Output page
// --------------------------------------------------------------------
llxHeader('', $title, $help_url);
// Example : Adding jquery code
print '<script type="text/javascript" language="javascript">
jQuery(document).ready(function() {
function init_myfunc()
{
jQuery("#myid").removeAttr(\'disabled\');
jQuery("#myid").attr(\'disabled\',\'disabled\');
}
init_myfunc();
jQuery("#mybutton").click(function() {
init_myfunc();
});
});
</script>';
$arrayofselected=is_array($toselect)?$toselect:array();
$param='';
if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage;
if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
if ($search_field1 != '') $param.= '&amp;search_field1='.urlencode($search_field1);
if ($search_field2 != '') $param.= '&amp;search_field2='.urlencode($search_field2);
if ($optioncss != '') $param.='&optioncss='.$optioncss;
foreach($search as $key => $val)
{
$param.= '&search_'.$key.'='.urlencode($search[$key]);
}
if ($optioncss != '') $param.='&optioncss='.$optioncss;
// Add $param from extra fields
foreach ($search_array_options as $key => $val)
{
@ -345,10 +351,16 @@ print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"")
// Fields title search
// --------------------------------------------------------------------
print '<tr class="liste_titre">';
// LIST_OF_TD_TITLE_SEARCH
//if (! empty($arrayfields['t.field1']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_field1" value="'.$search_field1.'" size="10"></td>';
//if (! empty($arrayfields['t.field2']['checked'])) print '<td class="liste_titre"><input type="text" class="flat" name="search_field2" value="'.$search_field2.'" size="10"></td>';
foreach($object->fields as $key => $val)
{
if (in_array($key, array('datec','tms','status'))) continue;
$align='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center';
if (in_array($val['type'], array('timestamp'))) $align.=' nowrap';
if (! empty($arrayfields['t.'.$key]['checked'])) print '<td class="liste_titre'.($align?' '.$align:'').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>';
}
// Extra fields
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
{
@ -376,25 +388,15 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab
$parameters=array('arrayfields'=>$arrayfields);
$reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
if (! empty($arrayfields['t.datec']['checked']))
// Rest of fields search
foreach($object->fields as $key => $val)
{
// Date creation
print '<td class="liste_titre">';
print '</td>';
if (! in_array($key, array('datec','tms','status'))) continue;
$align='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center';
if (in_array($val['type'], array('timestamp'))) $align.=' nowrap';
if (! empty($arrayfields['t.'.$key]['checked'])) print '<td class="liste_titre'.($align?' '.$align:'').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>';
}
if (! empty($arrayfields['t.tms']['checked']))
{
// Date modification
print '<td class="liste_titre">';
print '</td>';
}
/*if (! empty($arrayfields['u.statut']['checked']))
{
// Status
print '<td class="liste_titre" align="center">';
print $form->selectarray('search_statut', array('-1'=>'','0'=>$langs->trans('Disabled'),'1'=>$langs->trans('Enabled')),$search_statut);
print '</td>';
}*/
// Action column
print '<td class="liste_titre" align="right">';
$searchpicto=$form->showFilterButtons();
@ -402,11 +404,18 @@ print $searchpicto;
print '</td>';
print '</tr>'."\n";
// Fields title
// Fields title label
// --------------------------------------------------------------------
print '<tr class="liste_titre">';
// LIST_OF_TD_TITLE_FIELDS
//if (! empty($arrayfields['t.field1']['checked'])) print_liste_field_titre($arrayfields['t.field1']['label'],$_SERVER['PHP_SELF'],'t.field1','',$param,'',$sortfield,$sortorder);
//if (! empty($arrayfields['t.field2']['checked'])) print_liste_field_titre($arrayfields['t.field2']['label'],$_SERVER['PHP_SELF'],'t.field2','',$param,'',$sortfield,$sortorder);
foreach($object->fields as $key => $val)
{
if (in_array($key, array('datec','tms','status'))) continue;
$align='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center';
if (in_array($val['type'], array('timestamp'))) $align.='nowrap';
if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n";
}
// Extra fields
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
{
@ -417,7 +426,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab
$align=$extrafields->getAlignFlag($key);
$sortonfield = "ef.".$key;
if (! empty($extrafields->attribute_computed[$key])) $sortonfield='';
print_liste_field_titre($langs->trans($extralabels[$key]),$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder);
print getTitleFieldOfList($langs->trans($extralabels[$key]), 0, $_SERVER["PHP_SELF"], $sortonfield, "", $param, ($align?'align="'.$align.'"':''), $sortfield, $sortorder)."\n";
}
}
}
@ -425,10 +434,16 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab
$parameters=array('arrayfields'=>$arrayfields);
$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
if (! empty($arrayfields['t.datec']['checked'])) print_liste_field_titre($arrayfields['t.datec']['label'],$_SERVER["PHP_SELF"],"t.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
if (! empty($arrayfields['t.tms']['checked'])) print_liste_field_titre($arrayfields['t.tms']['label'],$_SERVER["PHP_SELF"],"t.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
//if (! empty($arrayfields['t.status']['checked'])) print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"t.status","",$param,'align="center"',$sortfield,$sortorder);
print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ');
// Rest of fields title
foreach($object->fields as $key => $val)
{
if (! in_array($key, array('datec','tms','status'))) continue;
$align='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center';
if (in_array($val['type'], array('timestamp'))) $align.=' nowrap';
if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n";
}
print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ')."\n";
print '</tr>'."\n";
@ -440,6 +455,8 @@ foreach ($extrafields->attribute_computed as $key => $val)
}
// Loop on record
// --------------------------------------------------------------------
$i=0;
$totalarray=array();
while ($i < min($num, $limit))
@ -449,18 +466,22 @@ while ($i < min($num, $limit))
{
// Show here line of result
print '<tr class="oddeven">';
// LIST_OF_TD_FIELDS_LIST
/*
if (! empty($arrayfields['t.field1']['checked']))
foreach($object->fields as $key => $val)
{
print '<td>'.$obj->field1.'</td>';
if (! $i) $totalarray['nbfield']++;
if (in_array($key, array('datec','tms','status'))) continue;
$align='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center';
if (in_array($val['type'], array('timestamp'))) $align.='nowrap';
if (! empty($arrayfields['t.'.$key]['checked']))
{
print '<td'.($align?' class="'.$align.'"':'').'>';
if (in_array($val['type'], array('date','datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour');
elseif ($key == 'status') print '<td align="center">'.$object->getLibStatut(3).'</td>';
else print $obj->$key;
print '</td>';
if (! $i) $totalarray['nbfield']++;
}
}
if (! empty($arrayfields['t.field2']['checked']))
{
print '<td>'.$obj->field2.'</td>';
if (! $i) $totalarray['nbfield']++;
}*/
// Extra fields
if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
{
@ -483,30 +504,23 @@ while ($i < min($num, $limit))
$parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj);
$reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
// Date creation
if (! empty($arrayfields['t.datec']['checked']))
// Rest of fields
foreach($object->fields as $key => $val)
{
print '<td align="center">';
print dol_print_date($db->jdate($obj->date_creation), 'dayhour');
print '</td>';
if (! $i) $totalarray['nbfield']++;
if (! in_array($key, array('datec','tms','status'))) continue;
$align='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center';
if (in_array($val['type'], array('timestamp'))) $align.='nowrap';
if (! empty($arrayfields['t.'.$key]['checked']))
{
print '<td'.($align?' class="'.$align.'"':'').'>';
if (in_array($val['type'], array('date','datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour');
elseif ($key == 'status') print '<td align="center">'.$object->getLibStatut(3).'</td>';
else print $obj->$key;
print '</td>';
if (! $i) $totalarray['nbfield']++;
}
}
// Date modification
if (! empty($arrayfields['t.tms']['checked']))
{
print '<td align="center">';
print dol_print_date($db->jdate($obj->date_update), 'dayhour');
print '</td>';
if (! $i) $totalarray['nbfield']++;
}
// Status
/*
if (! empty($arrayfields['u.statut']['checked']))
{
$userstatic->statut=$obj->statut;
print '<td align="center">'.$userstatic->getLibStatut(3).'</td>';
}*/
// Action column
print '<td class="nowrap" align="center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
@ -536,7 +550,7 @@ if (isset($totalarray['totalhtfield']))
if ($num < $limit) print '<td align="left">'.$langs->trans("Total").'</td>';
else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>';
}
elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>';
elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>';
elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>';
elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>';
else print '<td></td>';
@ -564,24 +578,28 @@ print '</div>'."\n";
print '</form>'."\n";
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files)
if ($nbtotalofrecords === '' || $nbtotalofrecords)
{
// Show list of available documents
$urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
$urlsource.=str_replace('&amp;','&',$param);
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files)
{
require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php');
$formfile = new FormFile($db);
$filedir=$diroutputmassaction;
$genallowed=$user->rights->facture->lire;
$delallowed=$user->rights->facture->lire;
// Show list of available documents
$urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
$urlsource.=str_replace('&amp;','&',$param);
print $formfile->showdocuments('massfilesarea_mymodule','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'');
$filedir=$diroutputmassaction;
$genallowed=$user->rights->mymodule->read;
$delallowed=$user->rights->mymodule->read;
print $formfile->showdocuments('massfilesarea_mymodule','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'');
}
else
{
print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>';
}
}
else
{
print '<br><a name="show_files"></a><a href="'.$_SERVER["PHP_SELF"].'?show_files=1'.$param.'#show_files">'.$langs->trans("ShowTempMassFilesArea").'</a>';
}
// End of page
llxFooter();

View File

@ -14,6 +14,9 @@
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
ALTER TABLE llx_myobject ADD UNIQUE INDEX uk_fk_othertable (fk_othertable);
--ALTER TABLE llx_myobject ADD CONSTRAINT llx_mytable_field_id FOREIGN KEY (fk_field) REFERENCES llx_myOthertable(rowid);
-- BEGIN MODULEBUILDER INDEXES
ALTER TABLE llx_myobject ADD UNIQUE INDEX idx_fieldobject (fieldobject);
-- END MODULEBUILDER INDEXES
--ALTER TABLE llx_myobject ADD CONSTRAINT llx_myobject_field_id FOREIGN KEY (fk_field) REFERENCES llx_myotherobject(rowid);

View File

@ -13,9 +13,14 @@
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
CREATE TABLE llx_myobject(
rowid INTEGER AUTO_INCREMENT PRIMARY KEY,
-- BEGIN MODULEBUILDER FIELDS
entity INTEGER DEFAULT 1 NOT NULL,
fk_othertable INTEGER NOT NULL,
name VARCHAR(189)
);
label VARCHAR(255),
datec DATETIME NOT NULL,
tms TIMESTAMP NOT NULL,
status INTEGER
-- END MODULEBUILDER FIELDS
) ENGINE=innodb;

View File

@ -561,7 +561,7 @@ if (empty($reshook))
{
if (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->supprimer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->supprimer))
{
$result = $object->delete(DolibarrApiAccess::$user);
$result = $object->delete($user);
}
if ($result > 0)

View File

@ -200,22 +200,25 @@ if ($action == 'addtime' && $user->rights->projet->lire)
{
$timespent_duration=array();
foreach($_POST as $key => $time)
if (is_array($_POST))
{
if (intval($time) > 0)
foreach($_POST as $key => $time)
{
// Hours or minutes of duration
if (preg_match("/([0-9]+)duration(hour|min)/",$key,$matches))
if (intval($time) > 0)
{
$id = $matches[1];
if ($id > 0)
{
// We store HOURS in seconds
if($matches[2]=='hour') $timespent_duration[$id] += $time*60*60;
// Hours or minutes of duration
if (preg_match("/([0-9]+)duration(hour|min)/",$key,$matches))
{
$id = $matches[1];
if ($id > 0)
{
// We store HOURS in seconds
if($matches[2]=='hour') $timespent_duration[$id] += $time*60*60;
// We store MINUTES in seconds
if($matches[2]=='min') $timespent_duration[$id] += $time*60;
}
// We store MINUTES in seconds
if($matches[2]=='min') $timespent_duration[$id] += $time*60;
}
}
}
}
}

View File

@ -187,7 +187,7 @@ if (! empty($conf->notification->enabled))
$langs->load("mails");
$head = societe_prepare_head($object);
dol_fiche_head($head, 'price', $langs->trans("ThirdParty"), 0, 'company');
dol_fiche_head($head, 'price', $langs->trans("ThirdParty"), -1, 'company');
$linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php">'.$langs->trans("BackToList").'</a>';
@ -200,11 +200,11 @@ print '<table class="border centpercent">';
if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field
{
print '<tr><td>' . $langs->trans('Prefix') . '</td><td colspan="3">' . $object->prefix_comm . '</td></tr>';
print '<tr><td class="titlefield">' . $langs->trans('Prefix') . '</td><td colspan="3">' . $object->prefix_comm . '</td></tr>';
}
if ($object->client) {
print '<tr><td>';
print '<tr><td class="titlefield">';
print $langs->trans('CustomerCode') . '</td><td colspan="3">';
print $object->code_client;
if ($object->check_codeclient() != 0)
@ -213,7 +213,7 @@ if ($object->client) {
}
if ($object->fournisseur) {
print '<tr><td>';
print '<tr><td class="titlefield">';
print $langs->trans('SupplierCode') . '</td><td colspan="3">';
print $object->code_fournisseur;
if ($object->check_codefournisseur() != 0)

View File

@ -2841,7 +2841,7 @@ class SupplierProposalLine extends CommonObjectLine
$sql.= " ".price2num($this->localtax2_tx).",";
$sql.= " '".$this->localtax1_type."',";
$sql.= " '".$this->localtax2_type."',";
$sql.= " ".price2num($this->subprice).",";
$sql.= " ".(!empty($this->subprice)?price2num($this->subprice):"null").",";
$sql.= " ".price2num($this->remise_percent).",";
$sql.= " ".(isset($this->info_bits)?"'".$this->info_bits."'":"null").",";
$sql.= " ".price2num($this->total_ht).",";

View File

@ -15,6 +15,7 @@ CKEDITOR.editorConfig = function( config )
//config.height = '300px';
//config.resize_dir = 'vertical'; // horizontal, vertical, both
config.removePlugins = 'elementspath,save'; // config.removePlugins = 'elementspath,save,font';
//config.extraPlugins = 'docprops,scayt,showprotected';
config.removeDialogTabs = 'flash:advanced'; // config.removeDialogTabs = 'flash:advanced;image:Link';
config.protectedSource.push( /<\?[\s\S]*?\?>/g ); // Prevent PHP Code to be formatted
//config.menu_groups = 'clipboard,table,anchor,link,image'; // for context menu 'clipboard,form,tablecell,tablecellproperties,tablerow,tablecolumn,table,anchor,link,image,flash,checkbox,radio,textfield,hiddenfield,imagebutton,button,select,textarea'
@ -25,7 +26,10 @@ CKEDITOR.editorConfig = function( config )
config.dialog_backgroundCoverColor = 'rgb(255, 254, 253)';
//config.contentsCss = '/css/mysitestyles.css';
config.image_previewText=' '; // Must no be empty
//config.autoParagraph = false;
//config.removeFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd'; // See also rules on this.dataProcessor.writer.setRules
//config.forcePasteAsPlainText = true;
config.toolbar_Full =
[
['Templates','NewPage'],

View File

@ -15,6 +15,7 @@ CKEDITOR.editorConfig = function( config )
//config.height = '300px';
//config.resize_dir = 'vertical'; // horizontal, vertical, both
config.removePlugins = 'elementspath,save'; // config.removePlugins = 'elementspath,save,font';
//config.extraPlugins = 'docprops,scayt,showprotected';
config.removeDialogTabs = 'flash:advanced'; // config.removeDialogTabs = 'flash:advanced;image:Link';
config.protectedSource.push( /<\?[\s\S]*?\?>/g ); // Prevent PHP Code to be formatted
//config.menu_groups = 'clipboard,table,anchor,link,image'; // for context menu 'clipboard,form,tablecell,tablecellproperties,tablerow,tablecolumn,table,anchor,link,image,flash,checkbox,radio,textfield,hiddenfield,imagebutton,button,select,textarea'
@ -25,7 +26,10 @@ CKEDITOR.editorConfig = function( config )
config.dialog_backgroundCoverColor = 'rgb(255, 254, 253)';
//config.contentsCss = '/css/mysitestyles.css';
config.image_previewText=' '; // Must no be empty
//config.autoParagraph = false;
//config.removeFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd'; // See also rules on this.dataProcessor.writer.setRules
//config.forcePasteAsPlainText = true;
config.toolbar_Full =
[
['Templates','NewPage'],

View File

@ -129,7 +129,7 @@ class WebsitePage extends CommonObject
$sql.= 'content,';
$sql.= 'status,';
$sql.= 'date_creation,';
$sql.= 'date_modification';
$sql.= 'tms';
$sql .= ') VALUES (';
$sql .= ' '.(! isset($this->fk_website)?'NULL':$this->fk_website).',';
$sql .= ' '.(! isset($this->pageurl)?'NULL':"'".$this->db->escape($this->pageurl)."'").',';

View File

@ -129,6 +129,7 @@ if ($pageid > 0 && $action != 'add')
global $dolibarr_main_data_root;
$pathofwebsite=$dolibarr_main_data_root.'/websites/'.$website;
$filehtmlheader=$pathofwebsite.'/header.html';
$filecss=$pathofwebsite.'/styles.css.php';
$filetpl=$pathofwebsite.'/page'.$pageid.'.tpl.php';
$fileindex=$pathofwebsite.'/index.php';
@ -240,25 +241,30 @@ if ($action == 'delete')
// Update css
if ($action == 'updatecss')
{
//$db->begin();
$res = $object->fetch(0, $website);
/*
$res = $object->update($user);
if ($res > 0)
{
$db->commit();
$action='';
}
else
// Html header file
$htmlheadercontent = '<!-- BEGIN DOLIBARR-WEBSITE-ADDED-HEADER -->'."\n";
$htmlheadercontent.= '<!-- File generated to save common html header - YOU CAN MODIFY DIRECTLY THIS FILE. Change affects all pages of website. -->'."\n";
$htmlheadercontent.= '<!-- END -->'."\n";
$htmlheadercontent.= GETPOST('WEBSITE_HTML_HEADER');
dol_syslog("Save file css into ".$filehtmlheader);
dol_mkdir($pathofwebsite);
$result = file_put_contents($filehtmlheader, $htmlheadercontent);
if (! empty($conf->global->MAIN_UMASK))
@chmod($filehtmlheader, octdec($conf->global->MAIN_UMASK));
if (! $result)
{
$error++;
$db->rollback();
}*/
setEventMessages('Failed to write file '.$filehtmlheader, null, 'errors');
}
// Css file
$csscontent = '<!-- BEGIN DOLIBARR-WEBSITE-ADDED-HEADER -->'."\n";
$csscontent.= '<!-- File generated to wrap the css file - DO NOT MODIFY - It is just a copy of database css content -->'."\n";
$csscontent.= '<!-- File generated to wrap the css file - YOU CAN MODIFY DIRECTLY THIS FILE. Change affects all pages of website. -->'."\n";
$csscontent.= '<?php '."\n";
$csscontent.= "header('Content-type: text/css');\n";
$csscontent.= "?>"."\n";
@ -278,6 +284,7 @@ if ($action == 'updatecss')
setEventMessages('Failed to write file '.$filecss, null, 'errors');
}
if (! $error)
{
setEventMessages($langs->trans("Saved"), null, 'mesgs');
@ -310,7 +317,7 @@ if ($action == 'setashome')
dol_delete_file($fileindex);
$indexcontent = '<?php'."\n";
$indexcontent.= '// File generated to wrap the home page - DO NOT MODIFY - It is just an include'."\n";
$indexcontent.= '// File generated to provide a shortcut to the Home Page - DO NOT MODIFY - It is just an include.'."\n";
$indexcontent.= "include_once './".basename($filetpl)."'\n";
$indexcontent.= '?>'."\n";
$result = file_put_contents($fileindex, $indexcontent);
@ -406,6 +413,7 @@ if ($action == 'updatemeta')
$tplcontent.= '<?php require "./master.inc.php"; ?>'."\n";
$tplcontent.= '<html>'."\n";
$tplcontent.= '<header>'."\n";
$tplcontent.= '<title>'.dol_escape_htmltag($objectpage->title).'</title>'."\n";
$tplcontent.= '<meta http-equiv="content-type" content="text/html; charset=utf-8" />'."\n";
$tplcontent.= '<meta name="robots" content="index, follow" />'."\n";
$tplcontent.= '<meta name="viewport" content="width=device-width, initial-scale=0.8">'."\n";
@ -414,8 +422,10 @@ if ($action == 'updatemeta')
$tplcontent.= '<meta name="title" content="'.dol_escape_htmltag($objectpage->title).'" />'."\n";
$tplcontent.= '<meta name="description" content="'.dol_escape_htmltag($objectpage->description).'" />'."\n";
$tplcontent.= '<meta name="generator" content="'.DOL_APPLICATION_TITLE.'" />'."\n";
$tplcontent.= '<!-- Include link to CSS file -->'."\n";
$tplcontent.= '<link rel="stylesheet" href="styles.css.php?websiteid='.$object->id.'" type="text/css" />'."\n";
$tplcontent.= '<title>'.dol_escape_htmltag($objectpage->title).'</title>'."\n";
$tplcontent.= '<!-- Include common page header file -->'."\n";
$tplcontent.= '<?php print file_get_contents(DOL_DATA_ROOT."/websites/'.$object->ref.'/header.html"); ?>'."\n";
$tplcontent.= '</header>'."\n";
$tplcontent.= '<body>'."\n";
@ -458,7 +468,8 @@ if ($action == 'updatecontent' || GETPOST('refreshsite') || GETPOST('refreshpage
if (! is_link(dol_osencode($pathtomediasinwebsite)))
{
dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
symlink($pathtomedias, $pathtomediasinwebsite);
dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists
$result = symlink($pathtomedias, $pathtomediasinwebsite);
}
/*if (GETPOST('savevirtualhost') && $object->virtualhost != GETPOST('previewsite'))
@ -560,6 +571,7 @@ if ($action == 'updatecontent' || GETPOST('refreshsite') || GETPOST('refreshpage
$tplcontent.= "// END PHP ?>\n";
$tplcontent.= '<html>'."\n";
$tplcontent.= '<header>'."\n";
$tplcontent.= '<title>'.dol_escape_htmltag($objectpage->title).'</title>'."\n";
$tplcontent.= '<meta http-equiv="content-type" content="text/html; charset=utf-8" />'."\n";
$tplcontent.= '<meta name="robots" content="index, follow" />'."\n";
$tplcontent.= '<meta name="viewport" content="width=device-width, initial-scale=0.8">'."\n";
@ -567,8 +579,10 @@ if ($action == 'updatecontent' || GETPOST('refreshsite') || GETPOST('refreshpage
$tplcontent.= '<meta name="title" content="'.dol_escape_htmltag($objectpage->title).'" />'."\n";
$tplcontent.= '<meta name="description" content="'.dol_escape_htmltag($objectpage->description).'" />'."\n";
$tplcontent.= '<meta name="generator" content="'.DOL_APPLICATION_TITLE.'" />'."\n";
$tplcontent.= '<link rel="stylesheet" href="styles.css.php?websiteid='.$object->id.'" type="text/css" />'."\n";
$tplcontent.= '<title>'.dol_escape_htmltag($objectpage->title).'</title>'."\n";
$tplcontent.= '<!-- Include link to CSS file -->'."\n";
$tplcontent.= '<link rel="stylesheet" href="styles.css.php?websiteid='.$object->id.'" type="text/css" />'."\n";
$tplcontent.= '<!-- Include common page header file -->'."\n";
$tplcontent.= '<?php print file_get_contents(DOL_DATA_ROOT."/websites/'.$object->ref.'/header.html"); ?>'."\n";
$tplcontent.= '</header>'."\n";
$tplcontent.= '<body>'."\n";
@ -939,6 +953,11 @@ if ($action == 'editcss')
print '<br>';
$htmlheader = @file_get_contents($filehtmlheader);
// Clean the php css file to remove php code and get only html part
$htmlheader = preg_replace('/<!-- BEGIN DOLIBARR.*END -->/s', '', $htmlheader);
$csscontent = @file_get_contents($filecss);
// Clean the php css file to remove php code and get only css part
$csscontent = preg_replace('/<!-- BEGIN DOLIBARR.*END -->/s', '', $csscontent);
@ -957,11 +976,19 @@ if ($action == 'editcss')
print '<tr><td class="tdtop">';
print $langs->trans('WEBSITE_CSS_INLINE');
print '</td><td>';
print '<textarea class="flat centpercent" rows="32" name="WEBSITE_CSS_INLINE">';
print '<textarea class="flat centpercent" rows="20" name="WEBSITE_CSS_INLINE">';
print $csscontent;
print '</textarea>';
print '</td></tr>';
print '<tr><td class="tdtop">';
print $langs->trans('WEBSITE_HTML_HEADER');
print '</td><td>';
print '<textarea class="flat centpercent" rows="20" name="WEBSITE_HTML_HEADER">';
print $htmlheader;
print '</textarea>';
print '</td></tr>';
/*print '<tr><td>';
print $langs->trans('WEBSITE_CSS_URL');
print '</td><td>';
@ -1089,7 +1116,10 @@ if ($action == 'preview')
$out.=$csscontent;
$out.='</style>'."\n";
$out.=$objectpage->content."\n";
// Replace php code
$content = preg_replace('/<\?php.*\?>/ims', '<span style="background: #ddd; border: 1px solid #ccc; border-radius: 4px;">...php...</span>', $objectpage->content);
$out.=$content."\n";
$out.='</div>';

View File

@ -144,11 +144,11 @@ class RestAPIDocumentTest extends PHPUnit_Framework_TestCase
echo __METHOD__.' Request POST url='.$url."\n";
// Send to non existant directory
dol_delete_dir_recursive(DOL_DATA_ROOT.'/medias/tmpphpunit');
//$data = '{ "filename": "mynewfile.txt", "modulepart": "medias", "ref": "", "subdir": "mysubdir1/mysubdir2", "filecontent": "content text", "fileencoding": "" }';
$data = array(
'filename'=>"mynewfile.txt",
@ -158,7 +158,7 @@ class RestAPIDocumentTest extends PHPUnit_Framework_TestCase
'filecontent'=>"content text",
'fileencoding'=>""
);
$result = getURLContent($url, 'POST', $data, 1);
echo __METHOD__.' Result for sending document: '.var_export($result, true)."\n";
echo __METHOD__.' curl_error_no: '.$result['curl_error_no']."\n";
@ -166,11 +166,11 @@ class RestAPIDocumentTest extends PHPUnit_Framework_TestCase
$this->assertNotNull($object, 'Parsing of json result must no be null');
$this->assertEquals('401', $object['error']['code']);
// Send to existant directory
dol_mkdir(DOL_DATA_ROOT.'/medias/tmpphpunit/tmpphpunit2');
$data = array(
'filename'=>"mynewfile.txt",
'modulepart'=>"medias",
@ -187,5 +187,7 @@ class RestAPIDocumentTest extends PHPUnit_Framework_TestCase
$this->assertNotNull($object2, 'Parsing of json result must no be null');
$this->assertEquals($result2['curl_error_no'], '');
$this->assertEquals($result2['content'], 'true');
dol_delete_dir_recursive(DOL_DATA_ROOT.'/medias/tmpphpunit');
}
}