예제 #1
0
 /**
  * testFactureBuild
  *
  * @return int
  */
 public function testFactureBuild()
 {
     global $conf, $user, $langs, $db;
     $conf = $this->savconf;
     $user = $this->savuser;
     $langs = $this->savlangs;
     $db = $this->savdb;
     $conf->facture->dir_output .= '/temp';
     $localobjectcom = new Commande($this->savdb);
     $localobjectcom->initAsSpecimen();
     $localobject = new Facture($this->savdb);
     $localobject->createFromOrder($localobjectcom);
     $localobject->date_lim_reglement = dol_now() + 3600 * 24 * 30;
     // Crabe (english)
     $localobject->modelpdf = 'crabe';
     $result = $localobject->generateDocument($localobject->modelpdf, $langs);
     $this->assertLessThan($result, 0);
     print __METHOD__ . " result=" . $result . "\n";
     // Crabe (japanese)
     $newlangs1 = new Translate("", $conf);
     $newlangs1->setDefaultLang('ja_JP');
     $localobject->modelpdf = 'crabe';
     $result = $localobject->generateDocument($localobject->modelpdf, $newlangs1);
     $this->assertLessThan($result, 0);
     print __METHOD__ . " result=" . $result . "\n";
     // Crabe (saudiarabia)
     $newlangs2a = new Translate("", $conf);
     $newlangs2a->setDefaultLang('sa_SA');
     $localobject->modelpdf = 'crabe';
     $result = $localobject->generateDocument($localobject->modelpdf, $newlangs2a);
     $this->assertLessThan($result, 0);
     print __METHOD__ . " result=" . $result . "\n";
     // Crabe (english_saudiarabia)
     $newlangs2b = new Translate("", $conf);
     $newlangs2b->setDefaultLang('en_SA');
     $localobject->modelpdf = 'crabe';
     $result = $localobject->generateDocument($localobject->modelpdf, $newlangs2b);
     $this->assertLessThan($result, 0);
     print __METHOD__ . " result=" . $result . "\n";
     // Crabe (greek)
     $newlangs3 = new Translate("", $conf);
     $newlangs3->setDefaultLang('el_GR');
     $localobject->modelpdf = 'crabe';
     $result = $localobject->generateDocument($localobject->modelpdf, $newlangs3);
     $this->assertLessThan($result, 0);
     print __METHOD__ . " result=" . $result . "\n";
     // Crabe (chinese)
     $newlangs4 = new Translate("", $conf);
     $newlangs4->setDefaultLang('zh_CN');
     $localobject->modelpdf = 'crabe';
     $result = $localobject->generateDocument($localobject->modelpdf, $newlangs4);
     $this->assertLessThan($result, 0);
     print __METHOD__ . " result=" . $result . "\n";
     // Crabe (russian)
     $newlangs5 = new Translate("", $conf);
     $newlangs5->setDefaultLang('ru_RU');
     $localobject->modelpdf = 'crabe';
     $result = $localobject->generateDocument($localobject->modelpdf, $newlangs5);
     $this->assertLessThan($result, 0);
     print __METHOD__ . " result=" . $result . "\n";
     return 0;
 }
예제 #2
0
 /**
  * testDolPrintDateTzFrance
  * Same than official testDolPrintDate but with parameter tzoutput that is false='tzserver'.
  * This test works only onto a server using TZ+1 Europe/Paris.
  *
  * You can use http://www.epochconverter.com/ to generate more tests.
  *
  * @return void
  */
 public function testDolPrintDateTzFrance()
 {
     global $conf, $user, $langs, $db;
     $conf = $this->savconf;
     $user = $this->savuser;
     $langs = $this->savlangs;
     $db = $this->savdb;
     // Check %Y-%m-%d %H:%M:%S format
     $result = dol_print_date(0, '%Y-%m-%d %H:%M:%S', false);
     print __METHOD__ . " result=" . $result . "\n";
     $this->assertEquals('1970-01-01 01:00:00', $result);
     // Check %Y-%m-%d %H:%M:%S format
     $result = dol_print_date(16725225600, '%Y-%m-%d %H:%M:%S', false);
     print __METHOD__ . " result=" . $result . "\n";
     $this->assertEquals('2500-01-01 01:00:00', $result);
     // Check %Y-%m-%d %H:%M:%S format
     $result = dol_print_date(-1830384000, '%Y-%m-%d %H:%M:%S', false);
     // http://www.epochconverter.com/
     print __METHOD__ . " result=" . $result . "\n";
     $this->assertEquals('1912-01-01 01:00:00', $result);
     // dol_print_date use a timezone, not epoch converter as it did not exists this year
     // Specific cas during war
     // 1940, no timezone
     $result = dol_print_date(-946771200, '%Y-%m-%d %H:%M:%S', false);
     // http://www.epochconverter.com/
     print __METHOD__ . " result=" . $result . "\n";
     $this->assertEquals('1940-01-01 01:00:00', $result);
     //  dol_print_date use a modern timezone, not epoch converter as it did not exists this year
     // 1941, timezone is added by germany to +2 (same for 1942)
     $result = dol_print_date(-915148800, '%Y-%m-%d %H:%M:%S', false);
     // http://www.epochconverter.com/
     print __METHOD__ . " result=" . $result . "\n";
     $this->assertEquals('1941-01-01 01:00:00', $result);
     // dol_print_date use a modern timezone, epoch converter use historic timezone
     // 1943, timezone is +1
     $result = dol_print_date(-852076800, '%Y-%m-%d %H:%M:%S', false);
     // http://www.epochconverter.com/
     print __METHOD__ . " result=" . $result . "\n";
     $this->assertEquals('1943-01-01 01:00:00', $result);
     // test with negative timezone
     $result = dol_print_date(-1, '%Y-%m-%d %H:%M:%S', false);
     // http://www.epochconverter.com/
     print __METHOD__ . " result=" . $result . "\n";
     $this->assertEquals('1970-01-01 00:59:59', $result);
     // Check dayhour format for fr_FR
     $outputlangs = new Translate('', $conf);
     $outputlangs->setDefaultLang('fr_FR');
     $outputlangs->load("main");
     $result = dol_print_date(0 + 24 * 3600, 'dayhour', false, $outputlangs);
     print __METHOD__ . " result=" . $result . "\n";
     $this->assertEquals('02/01/1970 01:00', $result);
     // Check day format for en_US
     $outputlangs = new Translate('', $conf);
     $outputlangs->setDefaultLang('en_US');
     $outputlangs->load("main");
     $result = dol_print_date(0 + 24 * 3600, 'day', false, $outputlangs);
     print __METHOD__ . " result=" . $result . "\n";
     $this->assertEquals('01/02/1970', $result);
     // Check %a and %b format for en_US
     $result = dol_print_date(0, '%a %b', false, $outputlangs);
     print __METHOD__ . " result=" . $result . "\n";
     $this->assertEquals('Thu Jan', $result);
     return $result;
 }
예제 #3
0
        // Off mode (recommended, you just do $db->escape when an insert / update.
        function stripslashes_deep($value)
        {
            return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
        }
        $_GET = array_map('stripslashes_deep', $_GET);
        $_POST = array_map('stripslashes_deep', $_POST);
        $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
        $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
        @set_magic_quotes_runtime(0);
    }
}
// Defini objet langs
$langs = new Translate('..', $conf);
if (GETPOST('lang')) {
    $langs->setDefaultLang(GETPOST('lang'));
} else {
    $langs->setDefaultLang('auto');
}
$bc[false] = ' class="bg1"';
$bc[true] = ' class="bg2"';
/**
 * Load conf file (file must exists)
 *
 * @param	string		$dolibarr_main_document_root		Root directory of Dolibarr bin files
 * @return	int												<0 if KO, >0 if OK
 */
function conf($dolibarr_main_document_root)
{
    global $conf;
    global $dolibarr_main_db_type;
예제 #4
0
 /**
  *	Close the commercial proposal
  *
  *	@param      User	$user		Object user that close
  *	@param      int		$statut		Statut
  *	@param      string	$note		Comment
  *	@return     int         		<0 if KO, >0 if OK
  */
 function cloture($user, $statut, $note)
 {
     global $langs, $conf;
     $this->statut = $statut;
     $error = 0;
     $now = dol_now();
     $this->db->begin();
     $sql = "UPDATE " . MAIN_DB_PREFIX . "propal";
     $sql .= " SET fk_statut = " . $statut . ", note_private = '" . $this->db->escape($note) . "', date_cloture='" . $this->db->idate($now) . "', fk_user_cloture=" . $user->id;
     $sql .= " WHERE rowid = " . $this->id;
     $resql = $this->db->query($sql);
     if ($resql) {
         $modelpdf = $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED ? $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED : $this->modelpdf;
         $trigger_name = 'PROPAL_CLOSE_REFUSED';
         if ($statut == 2) {
             $trigger_name = 'PROPAL_CLOSE_SIGNED';
             $modelpdf = $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL ? $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL : $this->modelpdf;
             // The connected company is classified as a client
             $soc = new Societe($this->db);
             $soc->id = $this->socid;
             $result = $soc->set_as_client();
             if ($result < 0) {
                 $this->error = $this->db->error();
                 $this->db->rollback();
                 return -2;
             }
         }
         if ($statut == 4) {
             $trigger_name = 'PROPAL_CLASSIFY_BILLED';
         }
         if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
             // Define output language
             $outputlangs = $langs;
             if (!empty($conf->global->MAIN_MULTILANGS)) {
                 $outputlangs = new Translate("", $conf);
                 $newlang = GETPOST('lang_id') ? GETPOST('lang_id') : $this->client->default_lang;
                 $outputlangs->setDefaultLang($newlang);
             }
             //$ret=$object->fetch($id);    // Reload to get new records
             $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
         }
         // Call trigger
         $result = $this->call_trigger($trigger_name, $user);
         if ($result < 0) {
             $error++;
         }
         // End call triggers
         if (!$error) {
             $this->db->commit();
             return 1;
         } else {
             $this->db->rollback();
             return -1;
         }
     } else {
         $this->error = $this->db->error();
         $this->db->rollback();
         return -1;
     }
 }
 /**
  *	Load data control
  *
  *	@param	int		$action	Action code
  *	@return	void
  */
 function doActions(&$action)
 {
     global $conf, $user, $langs;
     if ($_POST["getcustomercode"]) {
         // We defined value code_client
         $_POST["code_client"] = "Acompleter";
     }
     if ($_POST["getsuppliercode"]) {
         // We defined value code_fournisseur
         $_POST["code_fournisseur"] = "Acompleter";
     }
     // Add new third party
     if (!$_POST["getcustomercode"] && !$_POST["getsuppliercode"] && ($action == 'add' || $action == 'update')) {
         require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
         $error = 0;
         if (GETPOST("private") == 1) {
             $this->object->particulier = GETPOST("private");
             $this->object->name = empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? trim($_POST["firstname"] . ' ' . $_POST["lastname"]) : trim($_POST["lastname"] . ' ' . $_POST["firstname"]);
             $this->object->civility_id = $_POST["civility_id"];
             // Add non official properties
             $this->object->name_bis = $_POST["lastname"];
             $this->object->firstname = $_POST["firstname"];
         } else {
             $this->object->name = $_POST["nom"];
         }
         $this->object->address = $_POST["adresse"];
         $this->object->zip = $_POST["zipcode"];
         $this->object->town = $_POST["town"];
         $this->object->country_id = $_POST["country_id"];
         $this->object->state_id = $_POST["state_id"];
         $this->object->phone = $_POST["tel"];
         $this->object->fax = $_POST["fax"];
         $this->object->email = trim($_POST["email"]);
         $this->object->url = $_POST["url"];
         $this->object->idprof1 = $_POST["idprof1"];
         $this->object->idprof2 = $_POST["idprof2"];
         $this->object->idprof3 = $_POST["idprof3"];
         $this->object->idprof4 = $_POST["idprof4"];
         $this->object->prefix_comm = $_POST["prefix_comm"];
         $this->object->code_client = $_POST["code_client"];
         $this->object->code_fournisseur = $_POST["code_fournisseur"];
         $this->object->capital = $_POST["capital"];
         $this->object->barcode = $_POST["barcode"];
         $this->object->canvas = GETPOST("canvas");
         $this->object->tva_assuj = $_POST["assujtva_value"];
         // Local Taxes
         $this->object->localtax1_assuj = $_POST["localtax1assuj_value"];
         $this->object->localtax2_assuj = $_POST["localtax2assuj_value"];
         $this->object->tva_intra = $_POST["tva_intra"];
         $this->object->forme_juridique_code = $_POST["forme_juridique_code"];
         $this->object->effectif_id = $_POST["effectif_id"];
         if (GETPOST("private") == 1) {
             $this->object->typent_id = dol_getIdFromCode($db, 'TE_PRIVATE', 'c_typent');
         } else {
             $this->object->typent_id = $_POST["typent_id"];
         }
         $this->object->client = $_POST["client"];
         $this->object->fournisseur = $_POST["fournisseur"];
         $this->object->commercial_id = $_POST["commercial_id"];
         $this->object->default_lang = $_POST["default_lang"];
         // Check parameters
         if (empty($_POST["cancel"])) {
             if (!empty($this->object->email) && !isValidEMail($this->object->email)) {
                 $error = 1;
                 $langs->load("errors");
                 $this->error = $langs->trans("ErrorBadEMail", $this->object->email);
                 $action = $action == 'add' ? 'create' : 'edit';
             }
             if (!empty($this->object->url) && !isValidUrl($this->object->url)) {
                 $error = 1;
                 $langs->load("errors");
                 $this->error = $langs->trans("ErrorBadUrl", $this->object->url);
                 $action = $action == 'add' ? 'create' : 'edit';
             }
             if ($this->object->fournisseur && !$conf->fournisseur->enabled) {
                 $error = 1;
                 $langs->load("errors");
                 $this->error = $langs->trans("ErrorSupplierModuleNotEnabled");
                 $action = $action == 'add' ? 'create' : 'edit';
             }
         }
         if (!$error) {
             if ($action == 'add') {
                 $this->db->begin();
                 if (empty($this->object->client)) {
                     $this->object->code_client = '';
                 }
                 if (empty($this->object->fournisseur)) {
                     $this->object->code_fournisseur = '';
                 }
                 $result = $this->object->create($user);
                 if ($result >= 0) {
                     if ($this->object->particulier) {
                         dol_syslog(get_class($this) . "::doActions This thirdparty is a personal people", LOG_DEBUG);
                         $contact = new Contact($this->db);
                         $contact->civility_id = $this->object->civility_id;
                         $contact->name = $this->object->name_bis;
                         $contact->firstname = $this->object->firstname;
                         $contact->address = $this->object->address;
                         $contact->zip = $this->object->zip;
                         $contact->town = $this->object->town;
                         $contact->country_id = $this->object->country_id;
                         $contact->socid = $this->object->id;
                         // fk_soc
                         $contact->status = 1;
                         $contact->email = $this->object->email;
                         $contact->priv = 0;
                         $result = $contact->create($user);
                     }
                 } else {
                     $this->errors = $this->object->errors;
                 }
                 if ($result >= 0) {
                     $this->db->commit();
                     if ($this->object->client == 1) {
                         header("Location: " . DOL_URL_ROOT . "/comm/fiche.php?socid=" . $this->object->id);
                         return;
                     } else {
                         if ($this->object->fournisseur == 1) {
                             header("Location: " . DOL_URL_ROOT . "/fourn/fiche.php?socid=" . $this->object->id);
                             return;
                         } else {
                             header("Location: " . $_SERVER["PHP_SELF"] . "?socid=" . $this->object->id);
                             return;
                         }
                     }
                     exit;
                 } else {
                     $this->db->rollback();
                     $this->errors = $this->object->errors;
                     $action = 'create';
                 }
             }
             if ($action == 'update') {
                 if ($_POST["cancel"]) {
                     header("Location: " . $_SERVER["PHP_SELF"] . "?socid=" . $this->object->id);
                     exit;
                 }
                 $oldsoccanvas = dol_clone($this->object);
                 // To avoid setting code if third party is not concerned. But if it had values, we keep them.
                 if (empty($this->object->client) && empty($oldsoccanvas->code_client)) {
                     $this->object->code_client = '';
                 }
                 if (empty($this->object->fournisseur) && empty($oldsoccanvas->code_fournisseur)) {
                     $this->object->code_fournisseur = '';
                 }
                 $result = $this->object->update($this->object->id, $user, 1, $oldsoccanvas->codeclient_modifiable(), $oldsoccanvas->codefournisseur_modifiable());
                 if ($result >= 0) {
                     header("Location: " . $_SERVER["PHP_SELF"] . "?socid=" . $this->object->id);
                     exit;
                 } else {
                     $reload = 0;
                     $this->errors = $this->object->errors;
                     $action = "edit";
                 }
             }
         }
     }
     if ($action == 'confirm_delete' && GETPOST("confirm") == 'yes') {
         $result = $this->object->delete($this->object->id);
         if ($result >= 0) {
             header("Location: " . DOL_URL_ROOT . "/societe/societe.php?delsoc=" . $this->object->nom . "");
             exit;
         } else {
             $reload = 0;
             $this->errors = $this->object->errors;
             $action = '';
         }
     }
     /*
      * Generate document
      */
     if ($action == 'builddoc') {
         if (is_numeric(GETPOST('model'))) {
             $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Model"));
         } else {
             require_once DOL_DOCUMENT_ROOT . '/core/modules/societe/modules_societe.class.php';
             $this->object->fetch_thirdparty();
             // Define output language
             $outputlangs = $langs;
             $newlang = '';
             if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) {
                 $newlang = GETPOST('lang_id');
             }
             if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
                 $newlang = $this->object->default_lang;
             }
             if (!empty($newlang)) {
                 $outputlangs = new Translate("", $conf);
                 $outputlangs->setDefaultLang($newlang);
             }
             $result = thirdparty_doc_create($this->db, $this->object->id, '', GETPOST('model', 'alpha'), $outputlangs);
             if ($result <= 0) {
                 dol_print_error($this->db, $result);
                 exit;
             }
         }
     }
 }
예제 #6
0
 // If error, we will put error message in session under the name dol_loginmesg
 $goontestloop = false;
 if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) {
     $goontestloop = true;
 }
 if ($dolibarr_main_authentication == 'forceuser' && !empty($dolibarr_auto_user)) {
     $goontestloop = true;
 }
 if (GETPOST("username", "alpha", 2) || !empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode', 'alpha', 1)) {
     $goontestloop = true;
 }
 if (!is_object($langs)) {
     include_once DOL_DOCUMENT_ROOT . '/core/class/translate.class.php';
     $langs = new Translate("", $conf);
     $langcode = GETPOST('lang') ? GETPOST('lang', 'alpha', 1) : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
     $langs->setDefaultLang($langcode);
 }
 if ($test && $goontestloop) {
     $login = checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode);
     if ($login) {
         $dol_authmode = $conf->authmode;
         // This properties is defined only when logged, to say what mode was successfully used
         $dol_tz = $_POST["tz"];
         $dol_tz_string = $_POST["tz_string"];
         $dol_tz_string = preg_replace('/\\s*\\(.+\\)$/', '', $dol_tz_string);
         $dol_tz_string = preg_replace('/,/', '/', $dol_tz_string);
         $dol_tz_string = preg_replace('/\\s/', '_', $dol_tz_string);
         $dol_dst = 0;
         if (isset($_POST["dst_first"]) && isset($_POST["dst_second"])) {
             include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
             $datenow = dol_now();
예제 #7
0
        // Off mode (recommended, you just do $db->escape when an insert / update.
        function stripslashes_deep($value)
        {
            return (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value));
        }
        $_GET     = array_map('stripslashes_deep', $_GET);
        $_POST    = array_map('stripslashes_deep', $_POST);
        $_COOKIE  = array_map('stripslashes_deep', $_COOKIE);
        $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
        @set_magic_quotes_runtime(0);
    }
}

// Defini objet langs
$langs = new Translate('..',$conf);
if (GETPOST('lang')) $langs->setDefaultLang(GETPOST('lang'));
else $langs->setDefaultLang('auto');

$bc[false]=' class="bg1"';
$bc[true]=' class="bg2"';


/**
 * Load conf file (file must exists)
 *
 * @param	string		$dolibarr_main_document_root		Root directory of Dolibarr bin files
 * @return	int												<0 if KO, >0 if OK
 */
function conf($dolibarr_main_document_root)
{
    global $conf;
    /**
     *    Load data control
     */
    function doActions($socid)
    {
        global $conf, $user, $langs;

        if ($_POST["getcustomercode"])
        {
            // We defined value code_client
            $_POST["code_client"]="Acompleter";
        }

        if ($_POST["getsuppliercode"])
        {
            // We defined value code_fournisseur
            $_POST["code_fournisseur"]="Acompleter";
        }

        // Add new third party
        if ((! $_POST["getcustomercode"] && ! $_POST["getsuppliercode"])
        && ($_POST["action"] == 'add' || $_POST["action"] == 'update'))
        {
            require_once(DOL_DOCUMENT_ROOT."/lib/functions2.lib.php");
            $error=0;

            if ($_POST["action"] == 'update')
            {
                // Load properties of company
                $this->object->fetch($socid);
            }

            if ($_REQUEST["private"] == 1)
            {
                $this->object->particulier           = $_REQUEST["private"];

                $this->object->nom                   = empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)?trim($_POST["prenom"].' '.$_POST["nom"]):trim($_POST["nom"].' '.$_POST["prenom"]);
                $this->object->nom_particulier       = $_POST["nom"];
                $this->object->prenom                = $_POST["prenom"];
                $this->object->civilite_id           = $_POST["civilite_id"];
            }
            else
            {
                $this->object->nom                   = $_POST["nom"];
            }

            $this->object->address                  = $_POST["adresse"];
            $this->object->adresse                  = $_POST["adresse"]; // TODO obsolete
            $this->object->cp                       = $_POST["zipcode"];
            $this->object->ville                    = $_POST["town"];
            $this->object->pays_id                  = $_POST["pays_id"];
            $this->object->departement_id           = $_POST["departement_id"];
            $this->object->tel                      = $_POST["tel"];
            $this->object->fax                      = $_POST["fax"];
            $this->object->email                    = trim($_POST["email"]);
            $this->object->url                      = $_POST["url"];
            $this->object->siren                    = $_POST["idprof1"];
            $this->object->siret                    = $_POST["idprof2"];
            $this->object->ape                      = $_POST["idprof3"];
            $this->object->idprof4                  = $_POST["idprof4"];
            $this->object->prefix_comm              = $_POST["prefix_comm"];
            $this->object->code_client              = $_POST["code_client"];
            $this->object->code_fournisseur         = $_POST["code_fournisseur"];
            $this->object->capital                  = $_POST["capital"];
            $this->object->gencod                   = $_POST["gencod"];
            $this->object->canvas                   = $_REQUEST["canvas"];

            $this->object->tva_assuj                = $_POST["assujtva_value"];

            // Local Taxes
            $this->object->localtax1_assuj          = $_POST["localtax1assuj_value"];
            $this->object->localtax2_assuj          = $_POST["localtax2assuj_value"];
            $this->object->tva_intra                = $_POST["tva_intra"];

            $this->object->forme_juridique_code     = $_POST["forme_juridique_code"];
            $this->object->effectif_id              = $_POST["effectif_id"];
            if ($_REQUEST["private"] == 1)
            {
                $this->object->typent_id            = 8; // TODO predict another method if the field "special" change of rowid
            }
            else
            {
                $this->object->typent_id            = $_POST["typent_id"];
            }
            $this->object->client                   = $_POST["client"];
            $this->object->fournisseur              = $_POST["fournisseur"];
            $this->object->fournisseur_categorie    = $_POST["fournisseur_categorie"];

            $this->object->commercial_id            = $_POST["commercial_id"];
            $this->object->default_lang             = $_POST["default_lang"];

            // Check parameters
            if (empty($_POST["cancel"]))
            {
                if (! empty($this->object->email) && ! isValidEMail($this->object->email))
                {
                    $error = 1;
                    $langs->load("errors");
                    $this->error = $langs->trans("ErrorBadEMail",$this->object->email);
                    $_GET["action"] = $_POST["action"]=='add'?'create':'edit';
                }
                if (! empty($this->object->url) && ! isValidUrl($this->object->url))
                {
                    $error = 1;
                    $langs->load("errors");
                    $this->error = $langs->trans("ErrorBadUrl",$this->object->url);
                    $_GET["action"] = $_POST["action"]=='add'?'create':'edit';
                }
                if ($this->object->fournisseur && ! $conf->fournisseur->enabled)
                {
                    $error = 1;
                    $langs->load("errors");
                    $this->error = $langs->trans("ErrorSupplierModuleNotEnabled");
                    $_GET["action"] = $_POST["action"]=='add'?'create':'edit';
                }
            }

            if (! $error)
            {
                if ($_POST["action"] == 'add')
                {
                    $this->db->begin();

                    if (empty($this->object->client))      $this->object->code_client='';
                    if (empty($this->object->fournisseur)) $this->object->code_fournisseur='';

                    $result = $this->object->create($user);
                    if ($result >= 0)
                    {
                        if ($this->object->particulier)
                        {
                            dol_syslog("This thirdparty is a personal people",LOG_DEBUG);
                            $contact=new Contact($this->db);

                            $contact->civilite_id   = $this->object->civilite_id;
                            $contact->name          = $this->object->nom_particulier;
                            $contact->firstname     = $this->object->prenom;
                            $contact->address       = $this->object->address;
                            $contact->cp            = $this->object->cp;
                            $contact->ville         = $this->object->ville;
                            $contact->fk_pays       = $this->object->fk_pays;
                            $contact->socid         = $this->object->id;                // fk_soc
                            $contact->status        = 1;
                            $contact->email         = $this->object->email;
                            $contact->priv          = 0;

                            $result=$contact->create($user);
                        }
                    }
                    else
                    {
                        $this->errors=$this->object->errors;
                    }

                    if ($result >= 0)
                    {
                        $this->db->commit();

                        if ( $this->object->client == 1 )
                        {
                            Header("Location: ".DOL_URL_ROOT."/comm/fiche.php?socid=".$this->object->id);
                            return;
                        }
                        else
                        {
                            if (  $this->object->fournisseur == 1 )
                            {
                                Header("Location: ".DOL_URL_ROOT."/fourn/fiche.php?socid=".$this->object->id);
                                return;
                            }
                            else
                            {
                                Header("Location: ".$_SERVER["PHP_SELF"]."?socid=".$this->object->id);
                                return;
                            }
                        }
                        exit;
                    }
                    else
                    {
                        $this->db->rollback();

                        $this->errors=$this->object->errors;
                        $_GET["action"]='create';
                    }
                }

                if ($_POST["action"] == 'update')
                {
                    if ($_POST["cancel"])
                    {
                        Header("Location: ".$_SERVER["PHP_SELF"]."?socid=".$socid);
                        exit;
                    }

                    $oldsoccanvas = new Canvas($this->db);
                    $oldsoccanvas->getCanvas('thirdparty','card',$this->object->canvas);
                    $result=$oldsoccanvas->control->object->fetch($socid);

                    // To avoid setting code if third party is not concerned. But if it had values, we keep them.
                    if (empty($this->object->client) && empty($oldsoccanvas->control->object->code_client))             $this->object->code_client='';
                    if (empty($this->object->fournisseur)&& empty($oldsoccanvas->control->object->code_fournisseur))    $this->object->code_fournisseur='';                    //var_dump($soccanvas);exit;

                    $result = $this->object->update($socid,$user,1,$oldsoccanvas->control->object->codeclient_modifiable(),$oldsoccanvas->control->object->codefournisseur_modifiable());
                    if ($result >= 0)
                    {
                        Header("Location: ".$_SERVER["PHP_SELF"]."?socid=".$socid);
                        exit;
                    }
                    else
                    {
                        $this->object->id = $socid;
                        $reload = 0;
                        $this->errors = $this->object->errors;
                        $_GET["action"]="edit";
                    }
                }
            }
        }

        if (GETPOST("action") == 'confirm_delete' && GETPOST("confirm") == 'yes')
        {
            $this->object->fetch($socid);

            $result = $this->object->delete($socid);

            if ($result >= 0)
            {
                Header("Location: ".DOL_URL_ROOT."/societe/societe.php?delsoc=".$this->object->nom."");
                exit;
            }
            else
            {
                $reload = 0;
                $this->errors=$this->object->errors;
                $_GET["action"]='';
            }
        }

        /*
         * Generate document
         */
        if (GETPOST('action') == 'builddoc')    // En get ou en post
        {
            if (is_numeric(GETPOST('model')))
            {
                $this->error=$langs->trans("ErrorFieldRequired",$langs->transnoentities("Model"));
            }
            else
            {
                require_once(DOL_DOCUMENT_ROOT.'/includes/modules/societe/modules_societe.class.php');

                $this->object->fetch($socid);
                $this->object->fetch_thirdparty();

                // Define output language
                $outputlangs = $langs;
                $newlang='';
                if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id') ) $newlang=GETPOST('lang_id');
                if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$this->object->default_lang;
                if (! empty($newlang))
                {
                    $outputlangs = new Translate("",$conf);
                    $outputlangs->setDefaultLang($newlang);
                }
                $result=thirdparty_doc_create($this->db, $this->object->id, '', GETPOST('model'), $outputlangs);
                if ($result <= 0)
                {
                    dol_print_error($this->db,$result);
                    exit;
                }
                else
                {
                    Header ('Location: '.$_SERVER["PHP_SELF"].'?socid='.$this->object->id.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc'));
                    exit;
                }
            }
        }
    }
    /**
     *	Get the form to input an email
     *  this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files
     *  this->param:	Contains more parameteres like email templates info
     *
     *	@param	string	$addfileaction		Name of action when posting file attachments
     *	@param	string	$removefileaction	Name of action when removing file attachments
     *	@return string						Form to show
     */
    function get_form($addfileaction = 'addfile', $removefileaction = 'removefile')
    {
        global $conf, $langs, $user, $hookmanager, $form;
        if (!is_object($form)) {
            $form = new Form($this->db);
        }
        $langs->load("other");
        $langs->load("mails");
        $hookmanager->initHooks(array('formmail'));
        $parameters = array('addfileaction' => $addfileaction, 'removefileaction' => $removefileaction);
        $reshook = $hookmanager->executeHooks('getFormMail', $parameters, $this);
        if (!empty($reshook)) {
            return $hookmanager->resPrint;
        } else {
            $out = '';
            // Define list of attached files
            $listofpaths = array();
            $listofnames = array();
            $listofmimes = array();
            if (!empty($_SESSION["listofpaths"])) {
                $listofpaths = explode(';', $_SESSION["listofpaths"]);
            }
            if (!empty($_SESSION["listofnames"])) {
                $listofnames = explode(';', $_SESSION["listofnames"]);
            }
            if (!empty($_SESSION["listofmimes"])) {
                $listofmimes = explode(';', $_SESSION["listofmimes"]);
            }
            // Define output language
            $outputlangs = $langs;
            $newlang = '';
            if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
                $newlang = $this->param['langsmodels'];
            }
            if (!empty($newlang)) {
                $outputlangs = new Translate("", $conf);
                $outputlangs->setDefaultLang($newlang);
                $outputlangs->load('other');
            }
            // Get message template
            $model_id = 0;
            if (array_key_exists('models_id', $this->param)) {
                $model_id = $this->param["models_id"];
            }
            $arraydefaultmessage = $this->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id);
            //var_dump($arraydefaultmessage);
            $out .= "\n<!-- Begin form mail -->\n";
            if ($this->withform == 1) {
                $out .= '<form method="POST" name="mailform" id="mailform" enctype="multipart/form-data" action="' . $this->param["returnurl"] . '#formmail">' . "\n";
                $out .= '<input style="display:none" type="submit" id="sendmail" name="sendmail">';
                $out .= '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '" />';
                $out .= '<input type="hidden" name="trackid" value="' . $this->trackid . '" />';
                $out .= '<a id="formmail" name="formmail"></a>';
            }
            foreach ($this->param as $key => $value) {
                $out .= '<input type="hidden" id="' . $key . '" name="' . $key . '" value="' . $value . '" />' . "\n";
            }
            $result = $this->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs);
            if ($result < 0) {
                setEventMessage($this->error, 'errors');
            }
            $modelmail_array = array();
            foreach ($this->lines_model as $line) {
                $modelmail_array[$line->id] = $line->label;
            }
            // Zone to select its email template
            if (count($modelmail_array) > 0) {
                $out .= '<div style="padding: 3px 0 3px 0">' . "\n";
                $out .= $langs->trans('SelectMailModel') . ': ' . $this->selectarray('modelmailselected', $modelmail_array, 0, 1);
                if ($user->admin) {
                    $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
                }
                $out .= ' &nbsp; ';
                $out .= '<input class="button" type="submit" value="' . $langs->trans('Valid') . '" name="modelselected" id="modelselected">';
                $out .= ' &nbsp; ';
                $out .= '</div>';
            }
            $out .= '<table class="border" width="100%">' . "\n";
            // Substitution array
            if (!empty($this->withsubstit)) {
                $out .= '<tr><td colspan="2">';
                $help = "";
                foreach ($this->substit as $key => $val) {
                    $help .= $key . ' -> ' . $langs->trans($val) . '<br>';
                }
                $out .= $form->textwithpicto($langs->trans("EMailTestSubstitutionReplacedByGenericValues"), $help);
                $out .= "</td></tr>\n";
            }
            // From
            if (!empty($this->withfrom)) {
                if (!empty($this->withfromreadonly)) {
                    $out .= '<input type="hidden" id="fromname" name="fromname" value="' . $this->fromname . '" />';
                    $out .= '<input type="hidden" id="frommail" name="frommail" value="' . $this->frommail . '" />';
                    $out .= '<tr><td width="180">' . $langs->trans("MailFrom") . '</td><td>';
                    if ($this->fromtype == 'user' && $this->fromid > 0) {
                        $langs->load("users");
                        $fuser = new User($this->db);
                        $fuser->fetch($this->fromid);
                        $out .= $fuser->getNomUrl(1);
                    } else {
                        $out .= $this->fromname;
                    }
                    if ($this->frommail) {
                        $out .= " &lt;" . $this->frommail . "&gt;";
                    } else {
                        if ($this->fromtype) {
                            $langs->load("errors");
                            $out .= '<font class="warning"> &lt;' . $langs->trans("ErrorNoMailDefinedForThisUser") . '&gt; </font>';
                        }
                    }
                    $out .= "</td></tr>\n";
                    $out .= "</td></tr>\n";
                } else {
                    $out .= "<tr><td>" . $langs->trans("MailFrom") . "</td><td>";
                    $out .= $langs->trans("Name") . ':<input type="text" id="fromname" name="fromname" size="32" value="' . $this->fromname . '" />';
                    $out .= '&nbsp; &nbsp; ';
                    $out .= $langs->trans("EMail") . ':&lt;<input type="text" id="frommail" name="frommail" size="32" value="' . $this->frommail . '" />&gt;';
                    $out .= "</td></tr>\n";
                }
            }
            // Replyto
            if (!empty($this->withreplyto)) {
                if ($this->withreplytoreadonly) {
                    $out .= '<input type="hidden" id="replyname" name="replyname" value="' . $this->replytoname . '" />';
                    $out .= '<input type="hidden" id="replymail" name="replymail" value="' . $this->replytomail . '" />';
                    $out .= "<tr><td>" . $langs->trans("MailReply") . "</td><td>" . $this->replytoname . ($this->replytomail ? " &lt;" . $this->replytomail . "&gt;" : "");
                    $out .= "</td></tr>\n";
                }
            }
            // Errorsto
            if (!empty($this->witherrorsto)) {
                //if (! $this->errorstomail) $this->errorstomail=$this->frommail;
                $errorstomail = !empty($conf->global->MAIN_MAIL_ERRORS_TO) ? $conf->global->MAIN_MAIL_ERRORS_TO : $this->errorstomail;
                if ($this->witherrorstoreadonly) {
                    $out .= '<input type="hidden" id="errorstomail" name="errorstomail" value="' . $errorstomail . '" />';
                    $out .= '<tr><td>' . $langs->trans("MailErrorsTo") . '</td><td>';
                    $out .= $errorstomail;
                    $out .= "</td></tr>\n";
                } else {
                    $out .= '<tr><td>' . $langs->trans("MailErrorsTo") . '</td><td>';
                    $out .= '<input size="30" id="errorstomail" name="errorstomail" value="' . $errorstomail . '" />';
                    $out .= "</td></tr>\n";
                }
            }
            // To
            if (!empty($this->withto) || is_array($this->withto)) {
                $out .= '<tr><td width="180">';
                if ($this->withtofree) {
                    $out .= $form->textwithpicto($langs->trans("MailTo"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
                } else {
                    $out .= $langs->trans("MailTo");
                }
                $out .= '</td><td>';
                if ($this->withtoreadonly) {
                    if (!empty($this->toname) && !empty($this->tomail)) {
                        $out .= '<input type="hidden" id="toname" name="toname" value="' . $this->toname . '" />';
                        $out .= '<input type="hidden" id="tomail" name="tomail" value="' . $this->tomail . '" />';
                        if ($this->totype == 'thirdparty') {
                            $soc = new Societe($this->db);
                            $soc->fetch($this->toid);
                            $out .= $soc->getNomUrl(1);
                        } else {
                            if ($this->totype == 'contact') {
                                $contact = new Contact($this->db);
                                $contact->fetch($this->toid);
                                $out .= $contact->getNomUrl(1);
                            } else {
                                $out .= $this->toname;
                            }
                        }
                        $out .= ' &lt;' . $this->tomail . '&gt;';
                        if ($this->withtofree) {
                            $out .= '<br>' . $langs->trans("or") . ' <input size="' . (is_array($this->withto) ? "30" : "60") . '" id="sendto" name="sendto" value="' . (!is_array($this->withto) && !is_numeric($this->withto) ? isset($_REQUEST["sendto"]) ? $_REQUEST["sendto"] : $this->withto : "") . '" />';
                        }
                    } else {
                        $out .= !is_array($this->withto) && !is_numeric($this->withto) ? $this->withto : "";
                    }
                } else {
                    if (!empty($this->withtofree)) {
                        $out .= '<input size="' . (is_array($this->withto) ? "30" : "60") . '" id="sendto" name="sendto" value="' . (!is_array($this->withto) && !is_numeric($this->withto) ? isset($_REQUEST["sendto"]) ? $_REQUEST["sendto"] : $this->withto : "") . '" />';
                    }
                    if (!empty($this->withto) && is_array($this->withto)) {
                        if (!empty($this->withtofree)) {
                            $out .= " " . $langs->trans("or") . " ";
                        }
                        $out .= $form->selectarray("receiver", $this->withto, GETPOST("receiver"), 1);
                    }
                    if (isset($this->withtosocid) && $this->withtosocid > 0) {
                        $liste = array();
                        $soc = new Societe($this->db);
                        $soc->fetch($this->withtosocid);
                        foreach ($soc->thirdparty_and_contact_email_array(1) as $key => $value) {
                            $liste[$key] = $value;
                        }
                        if ($this->withtofree) {
                            $out .= " " . $langs->trans("or") . " ";
                        }
                        $out .= $form->selectarray("receiver", $liste, GETPOST("receiver"), 1);
                    }
                }
                $out .= "</td></tr>\n";
            }
            // CC
            if (!empty($this->withtocc) || is_array($this->withtocc)) {
                $out .= '<tr><td width="180">';
                $out .= $form->textwithpicto($langs->trans("MailCC"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
                $out .= '</td><td>';
                if ($this->withtoccreadonly) {
                    $out .= !is_array($this->withtocc) && !is_numeric($this->withtocc) ? $this->withtocc : "";
                } else {
                    $out .= '<input size="' . (is_array($this->withtocc) ? "30" : "60") . '" id="sendtocc" name="sendtocc" value="' . (!is_array($this->withtocc) && !is_numeric($this->withtocc) ? isset($_POST["sendtocc"]) ? $_POST["sendtocc"] : $this->withtocc : (isset($_POST["sendtocc"]) ? $_POST["sendtocc"] : "")) . '" />';
                    if (!empty($this->withtocc) && is_array($this->withtocc)) {
                        $out .= " " . $langs->trans("or") . " ";
                        $out .= $form->selectarray("receivercc", $this->withtocc, GETPOST("receivercc"), 1);
                    }
                }
                $out .= "</td></tr>\n";
            }
            // CCC
            if (!empty($this->withtoccc) || is_array($this->withtoccc)) {
                $out .= '<tr><td width="180">';
                $out .= $form->textwithpicto($langs->trans("MailCCC"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
                $out .= '</td><td>';
                if (!empty($this->withtocccreadonly)) {
                    $out .= !is_array($this->withtoccc) && !is_numeric($this->withtoccc) ? $this->withtoccc : "";
                } else {
                    $out .= '<input size="' . (is_array($this->withtoccc) ? "30" : "60") . '" id="sendtoccc" name="sendtoccc" value="' . (!is_array($this->withtoccc) && !is_numeric($this->withtoccc) ? isset($_POST["sendtoccc"]) ? $_POST["sendtoccc"] : $this->withtoccc : (isset($_POST["sendtoccc"]) ? $_POST["sendtoccc"] : "")) . '" />';
                    if (!empty($this->withtoccc) && is_array($this->withtoccc)) {
                        $out .= " " . $langs->trans("or") . " ";
                        $out .= $form->selectarray("receiverccc", $this->withtoccc, GETPOST("receiverccc"), 1);
                    }
                }
                $showinfobcc = '';
                if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) && !empty($this->param['models']) && $this->param['models'] == 'propal_send') {
                    $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO;
                }
                if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_ASKPRICESUPPLIER_TO) && !empty($this->param['models']) && $this->param['models'] == 'askpricesupplier_send') {
                    $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_ASKPRICESUPPLIER_TO;
                }
                if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) && !empty($this->param['models']) && $this->param['models'] == 'order_send') {
                    $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO;
                }
                if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) && !empty($this->param['models']) && $this->param['models'] == 'facture_send') {
                    $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO;
                }
                if ($showinfobcc) {
                    $out .= ' + ' . $showinfobcc;
                }
                $out .= "</td></tr>\n";
            }
            // Ask delivery receipt
            if (!empty($this->withdeliveryreceipt)) {
                $out .= '<tr><td width="180">' . $langs->trans("DeliveryReceipt") . '</td><td>';
                if (!empty($this->withdeliveryreceiptreadonly)) {
                    $out .= yn($this->withdeliveryreceipt);
                } else {
                    $defaultvaluefordeliveryreceipt = 0;
                    if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_PROPAL) && !empty($this->param['models']) && $this->param['models'] == 'propal_send') {
                        $defaultvaluefordeliveryreceipt = 1;
                    }
                    if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_ASKPRICESUPPLIER) && !empty($this->param['models']) && $this->param['models'] == 'askpricesupplier_send') {
                        $defaultvaluefordeliveryreceipt = 1;
                    }
                    if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_ORDER) && !empty($this->param['models']) && $this->param['models'] == 'order_send') {
                        $defaultvaluefordeliveryreceipt = 1;
                    }
                    if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_INVOICE) && !empty($this->param['models']) && $this->param['models'] == 'facture_send') {
                        $defaultvaluefordeliveryreceipt = 1;
                    }
                    $out .= $form->selectyesno('deliveryreceipt', isset($_POST["deliveryreceipt"]) ? $_POST["deliveryreceipt"] : $defaultvaluefordeliveryreceipt, 1);
                }
                $out .= "</td></tr>\n";
            }
            // Topic
            if (!empty($this->withtopic)) {
                $defaulttopic = "";
                if (count($arraydefaultmessage) > 0 && $arraydefaultmessage['topic']) {
                    $defaulttopic = $arraydefaultmessage['topic'];
                } elseif (!is_numeric($this->withtopic)) {
                    $defaulttopic = $this->withtopic;
                }
                $defaulttopic = make_substitutions($defaulttopic, $this->substit);
                $out .= '<tr>';
                $out .= '<td width="180">' . $langs->trans("MailTopic") . '</td>';
                $out .= '<td>';
                if ($this->withtopicreadonly) {
                    $out .= $defaulttopic;
                    $out .= '<input type="hidden" size="60" id="subject" name="subject" value="' . $defaulttopic . '" />';
                } else {
                    $out .= '<input type="text" size="60" id="subject" name="subject" value="' . (isset($_POST["subject"]) && !$_POST['modelselected'] ? $_POST["subject"] : ($defaulttopic ? $defaulttopic : '')) . '" />';
                }
                $out .= "</td></tr>\n";
            }
            // Attached files
            if (!empty($this->withfile)) {
                $out .= '<tr>';
                $out .= '<td width="180">' . $langs->trans("MailFile") . '</td>';
                $out .= '<td>';
                if (is_numeric($this->withfile)) {
                    // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript
                    $out .= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">' . "\n";
                    $out .= '<script type="text/javascript" language="javascript">';
                    $out .= 'jQuery(document).ready(function () {';
                    $out .= '    jQuery(".removedfile").click(function() {';
                    $out .= '        jQuery(".removedfilehidden").val(jQuery(this).val());';
                    $out .= '    });';
                    $out .= '})';
                    $out .= '</script>' . "\n";
                    if (count($listofpaths)) {
                        foreach ($listofpaths as $key => $val) {
                            $out .= '<div id="attachfile_' . $key . '">';
                            $out .= img_mime($listofnames[$key]) . ' ' . $listofnames[$key];
                            if (!$this->withfilereadonly) {
                                $out .= ' <input type="image" style="border: 0px;" src="' . DOL_URL_ROOT . '/theme/' . $conf->theme . '/img/delete.png" value="' . ($key + 1) . '" class="removedfile" id="removedfile_' . $key . '" name="removedfile_' . $key . '" />';
                                //$out.= ' <a href="'.$_SERVER["PHP_SELF"].'?removedfile='.($key+1).' id="removedfile_'.$key.'">'.img_delete($langs->trans("Delete").'</a>';
                            }
                            $out .= '<br></div>';
                        }
                    } else {
                        $out .= $langs->trans("NoAttachedFiles") . '<br>';
                    }
                    if ($this->withfile == 2) {
                        $out .= '<input type="file" class="flat" id="addedfile" name="addedfile" value="' . $langs->trans("Upload") . '" />';
                        $out .= ' ';
                        $out .= '<input type="submit" class="button" id="' . $addfileaction . '" name="' . $addfileaction . '" value="' . $langs->trans("MailingAddFile") . '" />';
                    }
                } else {
                    $out .= $this->withfile;
                }
                $out .= "</td></tr>\n";
            }
            // Message
            if (!empty($this->withbody)) {
                $defaultmessage = "";
                if (count($arraydefaultmessage) > 0 && $arraydefaultmessage['content']) {
                    $defaultmessage = $arraydefaultmessage['content'];
                } elseif (!is_numeric($this->withbody)) {
                    $defaultmessage = $this->withbody;
                }
                // Complete substitution array
                if (!empty($conf->paypal->enabled) && !empty($conf->global->PAYPAL_ADD_PAYMENT_URL)) {
                    require_once DOL_DOCUMENT_ROOT . '/paypal/lib/paypal.lib.php';
                    $langs->load('paypal');
                    if ($this->param["models"] == 'order_send') {
                        $url = getPaypalPaymentUrl(0, 'order', $this->substit['__ORDERREF__']);
                        $this->substit['__PERSONALIZED__'] = str_replace('\\n', "\n", $langs->transnoentitiesnoconv("PredefinedMailContentLink", $url));
                    }
                    if ($this->param["models"] == 'facture_send') {
                        $url = getPaypalPaymentUrl(0, 'invoice', $this->substit['__FACREF__']);
                        $this->substit['__PERSONALIZED__'] = str_replace('\\n', "\n", $langs->transnoentitiesnoconv("PredefinedMailContentLink", $url));
                    }
                }
                $defaultmessage = str_replace('\\n', "\n", $defaultmessage);
                // Deal with format differences between message and signature (text / HTML)
                if (dol_textishtml($defaultmessage) && !dol_textishtml($this->substit['__SIGNATURE__'])) {
                    $this->substit['__SIGNATURE__'] = dol_nl2br($this->substit['__SIGNATURE__']);
                } else {
                    if (!dol_textishtml($defaultmessage) && dol_textishtml($this->substit['__SIGNATURE__'])) {
                        $defaultmessage = dol_nl2br($defaultmessage);
                    }
                }
                if (isset($_POST["message"]) && !$_POST['modelselected']) {
                    $defaultmessage = $_POST["message"];
                } else {
                    $defaultmessage = make_substitutions($defaultmessage, $this->substit);
                    // Clean first \n and br (to avoid empty line when CONTACTCIVNAME is empty)
                    $defaultmessage = preg_replace("/^(<br>)+/", "", $defaultmessage);
                    $defaultmessage = preg_replace("/^\n+/", "", $defaultmessage);
                }
                $out .= '<tr>';
                $out .= '<td width="180" valign="top">' . $langs->trans("MailText") . '</td>';
                $out .= '<td>';
                if ($this->withbodyreadonly) {
                    $out .= nl2br($defaultmessage);
                    $out .= '<input type="hidden" id="message" name="message" value="' . $defaultmessage . '" />';
                } else {
                    if (!isset($this->ckeditortoolbar)) {
                        $this->ckeditortoolbar = 'dolibarr_notes';
                    }
                    // Editor wysiwyg
                    require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
                    if ($this->withfckeditor == -1) {
                        if (!empty($conf->global->FCKEDITOR_ENABLE_MAIL)) {
                            $this->withfckeditor = 1;
                        } else {
                            $this->withfckeditor = 0;
                        }
                    }
                    $doleditor = new DolEditor('message', $defaultmessage, '', 280, $this->ckeditortoolbar, 'In', true, true, $this->withfckeditor, 8, 72);
                    $out .= $doleditor->Create(1);
                }
                $out .= "</td></tr>\n";
            }
            if ($this->withform == 1 || $this->withform == -1) {
                $out .= '<tr><td align="center" colspan="2"><div class="center">';
                $out .= '<input class="button" type="submit" id="sendmail" name="sendmail" value="' . $langs->trans("SendMail") . '"';
                // Add a javascript test to avoid to forget to submit file before sending email
                if ($this->withfile == 2 && $conf->use_javascript_ajax) {
                    $out .= ' onClick="if (document.mailform.addedfile.value != \'\') { alert(\'' . dol_escape_js($langs->trans("FileWasNotUploaded")) . '\'); return false; } else { return true; }"';
                }
                $out .= ' />';
                if ($this->withcancel) {
                    $out .= ' &nbsp; &nbsp; ';
                    $out .= '<input class="button" type="submit" id="cancel" name="cancel" value="' . $langs->trans("Cancel") . '" />';
                }
                $out .= '</div></td></tr>' . "\n";
            }
            $out .= '</table>' . "\n";
            if ($this->withform == 1) {
                $out .= '</form>' . "\n";
            }
            // Disable enter key if option MAIN_MAILFORM_DISABLE_ENTERKEY is set
            if (!empty($conf->global->MAIN_MAILFORM_DISABLE_ENTERKEY)) {
                $out .= '<script type="text/javascript" language="javascript">';
                $out .= 'jQuery(document).ready(function () {';
                $out .= '	$(document).on("keypress", \'#mailform\', function (e) {		/* Note this is calle at every key pressed ! */
	    						var code = e.keyCode || e.which;
	    						if (code == 13) {
	        						e.preventDefault();
	        						return false;
	    						}
							});';
                $out .= '		})';
                $out .= '</script>';
            }
            $out .= "<!-- End form mail -->\n";
            return $out;
        }
    }
/**
 * 	Send email
 *
 * 	@param	string	$mode			Mode (test | confirm)
 *  @param	string	$oldemail		Target email
 * 	@param	string	$message		Message to send
 * 	@param	string	$total			Total amount of unpayed invoices
 *  @param	string	$userlang		Code lang to use for email output.
 *  @param	string	$oldtarget		Target name
 * 	@return	int						<0 if KO, >0 if OK
 */
function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget)
{
    global $conf, $langs;
    if (getenv('DOL_FORCE_EMAIL_TO')) {
        $oldemail = getenv('DOL_FORCE_EMAIL_TO');
    }
    $newlangs = new Translate('', $conf);
    $newlangs->setDefaultLang(empty($userlang) ? empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT : $userlang);
    $newlangs->load("main");
    $newlangs->load("bills");
    $subject = empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT) ? $newlangs->trans("ListOfYourUnpaidInvoices") : $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT;
    $sendto = $oldemail;
    $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
    $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
    $msgishtml = -1;
    print "- Send email to '" . $oldtarget . "' (" . $oldemail . "), total: " . $total . "\n";
    dol_syslog("email_unpaid_invoices_to_customers.php: send mail to " . $oldemail);
    $usehtml = 0;
    if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) {
        $usehtml += 1;
    }
    if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER)) {
        $usehtml += 1;
    }
    $allmessage = '';
    if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER)) {
        $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER;
    } else {
        $allmessage .= "Dear customer" . ($usehtml ? "<br>\n" : "\n") . ($usehtml ? "<br>\n" : "\n");
        $allmessage .= "Please, find a summary of the bills with pending payments from you." . ($usehtml ? "<br>\n" : "\n") . ($usehtml ? "<br>\n" : "\n");
        $allmessage .= "Note: This list contains only unpaid invoices." . ($usehtml ? "<br>\n" : "\n");
    }
    $allmessage .= $message . ($usehtml ? "<br>\n" : "\n");
    $allmessage .= $langs->trans("Total") . " = " . price($total, 0, $userlang, 0, 0, -1, $conf->currency) . ($usehtml ? "<br>\n" : "\n");
    if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) {
        $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER;
        if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) {
            $usehtml += 1;
        }
    }
    $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
    $mail->errors_to = $errorsto;
    // Send or not email
    if ($mode == 'confirm') {
        $result = $mail->sendfile();
        if (!$result) {
            print "Error sending email " . $mail->error . "\n";
            dol_syslog("Error sending email " . $mail->error . "\n");
        }
    } else {
        print "No email sent (test mode)\n";
        dol_syslog("No email sent (test mode)");
        $mail->dump_mail();
        $result = 1;
    }
    unset($newlangs);
    if ($result) {
        return 1;
    } else {
        return -1;
    }
}
예제 #11
0
 /**
  * testBank
  *
  * @return string
  */
 public function testLang()
 {
     global $conf, $user, $langs, $db;
     $conf = $this->savconf;
     $user = $this->savuser;
     $langs = $this->savlangs;
     $db = $this->savdb;
     include_once DOL_DOCUMENT_ROOT . '/core/class/translate.class.php';
     $filesarray = scandir(DOL_DOCUMENT_ROOT . '/langs');
     foreach ($filesarray as $key => $code) {
         if (!preg_match('/^[a-z]+_[A-Z]+$/', $code)) {
             continue;
         }
         print 'Check language file for lang code=' . $code . "\n";
         $tmplangs = new Translate('', $conf);
         $langcode = $code;
         $tmplangs->setDefaultLang($langcode);
         $tmplangs->load("main");
         $result = $tmplangs->trans("SeparatorDecimal");
         print __METHOD__ . " SeparatorDecimal=" . $result . "\n";
         $this->assertContains($result, array('.', ',', '/', ' ', '', 'None'), 'Error for decimal separator for lang code ' . $code);
         // Note that ، that is coma for RTL languages is not supported
         $result = $tmplangs->trans("SeparatorThousand");
         print __METHOD__ . " SeparatorThousand=" . $result . "\n";
         $this->assertContains($result, array('.', ',', '/', ' ', '', 'None', 'Space'), 'Error for thousand separator for lang code ' . $code);
         // Note that ، that is coma for RTL languages is not supported
         // Test java string contains only d,M,y,/,-,. and not m,...
         $result = $tmplangs->trans("FormatDateShortJava");
         print __METHOD__ . " FormatDateShortJava=" . $result . "\n";
         $this->assertRegExp('/^[dMy\\/\\-\\.]+$/', $result, 'FormatDateShortJava KO for lang code ' . $code);
         $result = $tmplangs->trans("FormatDateShortJavaInput");
         print __METHOD__ . " FormatDateShortJavaInput=" . $result . "\n";
         $this->assertRegExp('/^[dMy\\/\\-\\.]+$/', $result, 'FormatDateShortJavaInput KO for lang code ' . $code);
         unset($tmplangs);
     }
     return;
 }
/**
 * 	Send email
 *
 * 	@param	string	$mode			Mode (test | confirm)
 *  @param	string	$oldemail		Target email
 * 	@param	string	$message		Message to send
 * 	@param	string	$total			Total amount of unpayed invoices
 *  @param	string	$userlang		Code lang to use for email output.
 *  @param	string	$oldtarget		Target name
 *  @param  int		$duration_value	duration value
 * 	@return	int						<0 if KO, >0 if OK
 */
function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget, $duration_value)
{
    global $conf, $langs;
    if (getenv('DOL_FORCE_EMAIL_TO')) {
        $oldemail = getenv('DOL_FORCE_EMAIL_TO');
    }
    $newlangs = new Translate('', $conf);
    $newlangs->setDefaultLang(empty($userlang) ? empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT : $userlang);
    $newlangs->load("main");
    $newlangs->load("contracts");
    if ($duration_value) {
        if ($duration_value > 0) {
            $title = $newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value);
        } else {
            $title = $newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value);
        }
    } else {
        $title = $newlangs->transnoentities("ListOfServicesToExpire");
    }
    $subject = empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT) ? $title : $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT;
    $sendto = $oldemail;
    $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
    $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
    $msgishtml = -1;
    print "- Send email to '" . $oldtarget . "' (" . $oldemail . "), total: " . $total . "\n";
    dol_syslog("email_expire_services_to_customers.php: send mail to " . $oldemail);
    $usehtml = 0;
    if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) {
        $usehtml += 1;
    }
    if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER)) {
        $usehtml += 1;
    }
    $allmessage = '';
    if (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER)) {
        $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER;
    } else {
        $allmessage .= "Dear customer" . ($usehtml ? "<br>\n" : "\n") . ($usehtml ? "<br>\n" : "\n");
        $allmessage .= "Please, find a summary of the services contracted by you that are about to expire." . ($usehtml ? "<br>\n" : "\n") . ($usehtml ? "<br>\n" : "\n");
    }
    $allmessage .= $message . ($usehtml ? "<br>\n" : "\n");
    //$allmessage.= $langs->trans("Total")." = ".price($total,0,$userlang,0,0,-1,$conf->currency).($usehtml?"<br>\n":"\n");
    if (!empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) {
        $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER;
        if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) {
            $usehtml += 1;
        }
    }
    $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
    $mail->errors_to = $errorsto;
    // Send or not email
    if ($mode == 'confirm') {
        $result = $mail->sendfile();
        if (!$result) {
            print "Error sending email " . $mail->error . "\n";
            dol_syslog("Error sending email " . $mail->error . "\n");
        }
    } else {
        print "No email sent (test mode)\n";
        dol_syslog("No email sent (test mode)");
        $mail->dump_mail();
        $result = 1;
    }
    unset($newlangs);
    if ($result) {
        return 1;
    } else {
        return -1;
    }
}
예제 #13
0
    if ($action == 1) {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    } else {
        if ($action == 2) {
            $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
        }
    }
    return $output;
}
if (file_exists('conf/conf.php')) {
    include 'conf/conf.php';
    if (!empty($_GET['lang'])) {
        $conf->user->lang = $_GET['lang'];
    }
    $langs->setDefaultLang($conf->user->lang);
    $langs->load("main");
} else {
    chmod('conf', 755);
    $capfile = fopen('conf/conf.php', "w");
    fwrite($capfile, "\n\t\t<?php\n\t\t\$" . "conf->lang['en-GB']                                   = 'english';\n\t\t\$" . "conf->lang['ca']                                      = 'català';\n\t\t\$" . "conf->lang['cs']                                      = 'ceština';\n\t\t\$" . "conf->lang['da-DK']                                   = 'dansk';\n\t\t\$" . "conf->lang['de-DE']                                   = 'deutsch';\n\t\t\$" . "conf->lang['es-ES']                                   = 'español';\n\t\t\$" . "conf->lang['et']                                      = 'eesti';\n\t\t\$" . "conf->lang['eu']                                      = 'euskera';\n\t\t\$" . "conf->lang['fr-FR']                                   = 'français';\n\t\t\$" . "conf->lang['gl']                                      = 'galego';\n\t\t\$" . "conf->lang['hr-HR']                                   = 'hrvatski';\n\t\t\$" . "conf->lang['is']                                      = 'íslenska';\n\t\t\$" . "conf->lang['it-IT']                                   = 'italiano';\n\t\t\$" . "conf->lang['lt']                                      = 'lietuviu';\n\t\t\$" . "conf->lang['lv']                                      = 'latviešu';\n\t\t\$" . "conf->lang['hu-HU']                                   = 'magyar';\n\t\t\$" . "conf->lang['mt']                                      = 'malti';\n\t\t\$" . "conf->lang['nl-NL']                                   = 'nederlands';\n\t\t\$" . "conf->lang['no']                                      = 'norsk';\n\t\t\$" . "conf->lang['pl']                                      = 'polski';\n\t\t\$" . "conf->lang['pt-PT']                                   = 'português';\n\t\t\$" . "conf->lang['ro']                                      = 'româna';\n\t\t\$" . "conf->lang['sr']                                      = 'српски';\n\t\t\$" . "conf->lang['sl']                                      = 'slovenšcina';\n\t\t\$" . "conf->lang['sk']                                      = 'slovencina';\n\t\t\$" . "conf->lang['fi-FI']                                   = 'suomi';\n\t\t\$" . "conf->lang['sv-SE']                                   = 'svenska';\n\t\t\$" . "conf->lang['el-GR']                                   = 'Ελληνικά';\n\t\t\$" . "conf->lang['bg']                                      = 'bulgarian';\n\t\t\$" . "conf->lang['mk']                                      = 'македонски';\n\t\t\$" . "conf->lang['name']                                    = '';\n\t\t\n\t\t\$" . "conf->select->lang['en-GB']                           = 1;\n\t\t\$" . "conf->select->lang['ca']                              = 0;\n\t\t\$" . "conf->select->lang['cs']                              = 0;\n\t\t\$" . "conf->select->lang['da-DK']                           = 0;\n\t\t\$" . "conf->select->lang['de-DE']                           = 1;\n\t\t\$" . "conf->select->lang['es-ES']                           = 0;\n\t\t\$" . "conf->select->lang['et']                              = 0;\n\t\t\$" . "conf->select->lang['eu']                              = 0;\n\t\t\$" . "conf->select->lang['fr-FR']                           = 0;\n\t\t\$" . "conf->select->lang['gl']                              = 0;\n\t\t\$" . "conf->select->lang['hr-HR']                           = 0;\n\t\t\$" . "conf->select->lang['is']                              = 0;\n\t\t\$" . "conf->select->lang['it-IT']                           = 0;\n\t\t\$" . "conf->select->lang['lt']                              = 0;\n\t\t\$" . "conf->select->lang['lv']                              = 0;\n\t\t\$" . "conf->select->lang['hu-HU']                           = 0;\n\t\t\$" . "conf->select->lang['mt']                              = 0;\n\t\t\$" . "conf->select->lang['nl-NL']                           = 0;\n\t\t\$" . "conf->select->lang['no']                              = 0;\n\t\t\$" . "conf->select->lang['pl']                              = 0;\n\t\t\$" . "conf->select->lang['pt-PT']                           = 0;\n\t\t\$" . "conf->select->lang['ro']                              = 0;\n\t\t\$" . "conf->select->lang['sr']                              = 0;\n\t\t\$" . "conf->select->lang['sl']                              = 0;\n\t\t\$" . "conf->select->lang['sk']                              = 0;\n\t\t\$" . "conf->select->lang['fi-FI']                           = 0;\n\t\t\$" . "conf->select->lang['sv-SE']                           = 0;\n\t\t\$" . "conf->select->lang['el-GR']                           = 0;\n\t\t\$" . "conf->select->lang['bg']                              = 0;\n\t\t\$" . "conf->select->lang['mk']                              = 0;\n\t\t\$" . "conf->trans['en_US']                                  = 'english';\n\t\t\$" . "conf->trans['de_DE']                                  = 'deutsch';\n\t\t\$" . "conf->trans['fr_FR']                                  = 'français';\n\t\t\$" . "conf->trans['es_ES']                                  = 'Español';\n\t\t?>\n\t\t");
    fclose($capfile);
    $conf->user->lang = 'en_US';
    $langs->setDefaultLang($conf->user->lang);
    $langs->load("main");
    // index.php#conf
    if (file_exists('conf/conf.php')) {
        header('Location: index.php#conf');
        exit;
    } else {
        die('Permision problems detectet pleas fix this: Can\'t create conf.php file in folder conf/<br>Please give this folder conf/ the group apache and the mod rwxrwxr-x');
 function shipment_generate_pdf(&$shipment, $hidedetails, $hidedesc, $hideref)
 {
     global $conf, $langs;
     $db =& $this->db;
     // Il faut recharger les lignes qui viennent juste d'être créées
     $shipment->fetch($shipment->id);
     /*echo '<pre>';
     		print_r($shipment);
     		exit;*/
     $outputlangs = $langs;
     if ($conf->global->MAIN_MULTILANGS) {
         $newlang = $shipment->client->default_lang;
     }
     if (!empty($newlang)) {
         $outputlangs = new Translate("", $conf);
         $outputlangs->setDefaultLang($newlang);
     }
     $result = expedition_pdf_create($db, $shipment, $shipment->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
     if ($result > 0) {
         $objectref = dol_sanitizeFileName($shipment->ref);
         $dir = $conf->expedition->dir_output . "/sending/" . $objectref;
         $file = $dir . "/" . $objectref . ".pdf";
         return $file;
     }
     return '';
 }
예제 #15
0
 /**
  *  Check if notification are active for couple action/company.
  * 	If yes, send mail and save trace into llx_notify.
  *
  * 	@param	string	$notifcode		Code of action in llx_c_action_trigger (new usage) or Id of action in llx_c_action_trigger (old usage)
  * 	@param	Object	$object			Object the notification deals on
  *	@return	int						<0 if KO, or number of changes if OK
  */
 function send($notifcode, $object)
 {
     global $user, $conf, $langs, $mysoc, $dolibarr_main_url_root;
     include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
     dol_syslog(get_class($this) . "::send notifcode=" . $notifcode . ", object=" . $object->id);
     $langs->load("other");
     // Define $urlwithroot
     $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', trim($dolibarr_main_url_root));
     $urlwithroot = $urlwithouturlroot . DOL_URL_ROOT;
     // This is to use external domain name found into config file
     //$urlwithroot=DOL_MAIN_URL_ROOT;						// This is to use same domain name than current
     // Define some vars
     $application = $mysoc->name;
     //if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $application = $conf->global->MAIN_APPLICATION_TITLE;
     $replyto = $conf->notification->email_from;
     $filename = basename($file);
     $mimefile = dol_mimetype($file);
     $object_type = '';
     $link = '';
     $num = 0;
     if (!in_array($notifcode, array('BILL_VALIDATE', 'ORDER_VALIDATE', 'PROPAL_VALIDATE', 'FICHINTER_VALIDATE', 'ORDER_SUPPLIER_VALIDATE', 'ORDER_SUPPLIER_APPROVE', 'ORDER_SUPPLIER_REFUSE', 'SHIPPING_VALIDATE'))) {
         return 0;
     }
     $oldref = empty($object->oldref) ? $object->ref : $object->oldref;
     $newref = empty($object->newref) ? $object->ref : $object->newref;
     // Check notification per third party
     $sql = "SELECT s.nom, c.email, c.rowid as cid, c.lastname, c.firstname, c.default_lang,";
     $sql .= " a.rowid as adid, a.label, a.code, n.rowid, n.type";
     $sql .= " FROM " . MAIN_DB_PREFIX . "socpeople as c,";
     $sql .= " " . MAIN_DB_PREFIX . "c_action_trigger as a,";
     $sql .= " " . MAIN_DB_PREFIX . "notify_def as n,";
     $sql .= " " . MAIN_DB_PREFIX . "societe as s";
     $sql .= " WHERE n.fk_contact = c.rowid AND a.rowid = n.fk_action";
     $sql .= " AND n.fk_soc = s.rowid";
     if (is_numeric($notifcode)) {
         $sql .= " AND n.fk_action = " . $notifcode;
     } else {
         $sql .= " AND a.code = '" . $notifcode . "'";
     }
     // New usage
     $sql .= " AND s.rowid = " . $object->socid;
     $result = $this->db->query($sql);
     if ($result) {
         $num = $this->db->num_rows($result);
         if ($num > 0) {
             $i = 0;
             while ($i < $num && !$error) {
                 $obj = $this->db->fetch_object($result);
                 $sendto = dolGetFirstLastname($obj->firstname, $obj->lastname) . " <" . $obj->email . ">";
                 $notifcodedefid = $obj->adid;
                 if (dol_strlen($obj->email)) {
                     // Set output language
                     $outputlangs = $langs;
                     if ($obj->default_lang && $obj->default_lang != $langs->defaultlang) {
                         $outputlangs = new Translate('', $conf);
                         $outputlangs->setDefaultLang($obj->default_lang);
                     }
                     switch ($notifcode) {
                         case 'BILL_VALIDATE':
                             $link = '/compta/facture.php?facid=' . $object->id;
                             $dir_output = $conf->facture->dir_output;
                             $object_type = 'facture';
                             $mesg = $langs->transnoentitiesnoconv("EMailTextInvoiceValidated", $newref);
                             break;
                         case 'ORDER_VALIDATE':
                             $link = '/commande/card.php?id=' . $object->id;
                             $dir_output = $conf->commande->dir_output;
                             $object_type = 'order';
                             $mesg = $langs->transnoentitiesnoconv("EMailTextOrderValidated", $newref);
                             break;
                         case 'PROPAL_VALIDATE':
                             $link = '/comm/propal.php?id=' . $object->id;
                             $dir_output = $conf->propal->dir_output;
                             $object_type = 'propal';
                             $mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated", $newref);
                             break;
                         case 'FICHINTER_VALIDATE':
                             $link = '/fichinter/card.php?id=' . $object->id;
                             $dir_output = $conf->facture->dir_output;
                             $object_type = 'ficheinter';
                             $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionValidated", $object->ref);
                             break;
                         case 'ORDER_SUPPLIER_VALIDATE':
                             $link = '/fourn/commande/card.php?id=' . $object->id;
                             $dir_output = $conf->fournisseur->dir_output . '/commande/';
                             $object_type = 'order_supplier';
                             $mesg = $langs->transnoentitiesnoconv("Hello") . ",\n\n";
                             $mesg .= $langs->transnoentitiesnoconv("EMailTextOrderValidatedBy", $object->ref, $user->getFullName($langs));
                             $mesg .= "\n\n" . $langs->transnoentitiesnoconv("Sincerely") . ".\n\n";
                             break;
                         case 'ORDER_SUPPLIER_APPROVE':
                             $link = '/fourn/commande/card.php?id=' . $object->id;
                             $dir_output = $conf->fournisseur->dir_output . '/commande/';
                             $object_type = 'order_supplier';
                             $mesg = $langs->transnoentitiesnoconv("Hello") . ",\n\n";
                             $mesg .= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy", $newref, $user->getFullName($langs));
                             $mesg .= "\n\n" . $langs->transnoentitiesnoconv("Sincerely") . ".\n\n";
                             break;
                         case 'ORDER_SUPPLIER_REFUSE':
                             $link = '/fourn/commande/card.php?id=' . $object->id;
                             $dir_output = $conf->fournisseur->dir_output . '/commande/';
                             $object_type = 'order_supplier';
                             $mesg = $langs->transnoentitiesnoconv("Hello") . ",\n\n";
                             $mesg .= $langs->transnoentitiesnoconv("EMailTextOrderRefusedBy", $newref, $user->getFullName($langs));
                             $mesg .= "\n\n" . $langs->transnoentitiesnoconv("Sincerely") . ".\n\n";
                             break;
                         case 'SHIPPING_VALIDATE':
                             $dir_output = $conf->expedition->dir_output . '/sending/';
                             $object_type = 'order_supplier';
                             $mesg = $langs->transnoentitiesnoconv("EMailTextExpeditionValidated", $newref);
                             break;
                     }
                     $ref = dol_sanitizeFileName($newref);
                     $pdf_path = $dir_output . "/" . $ref . "/" . $ref . ".pdf";
                     if (!dol_is_file($pdf_path)) {
                         // We can't add PDF as it is not generated yet.
                         $filepdf = '';
                     } else {
                         $filepdf = $pdf_path;
                     }
                     $subject = '[' . $application . '] ' . $outputlangs->transnoentitiesnoconv("DolibarrNotification");
                     $message = $outputlangs->transnoentities("YouReceiveMailBecauseOfNotification", $application, $mysoc->name) . "\n";
                     $message .= $outputlangs->transnoentities("YouReceiveMailBecauseOfNotification2", $application, $mysoc->name) . "\n";
                     $message .= "\n";
                     $message .= $mesg;
                     if ($link) {
                         $message = dol_concatdesc($message, $urlwithroot . $link);
                     }
                     $mailfile = new CMailFile($subject, $sendto, $replyto, $message, array($file), array($mimefile), array($filename[count($filename) - 1]), '', '', 0, -1);
                     if ($mailfile->sendfile()) {
                         $sql = "INSERT INTO " . MAIN_DB_PREFIX . "notify (daten, fk_action, fk_soc, fk_contact, type, objet_type, objet_id, email)";
                         $sql .= " VALUES ('" . $this->db->idate(dol_now()) . "', " . $notifcodedefid . ", " . $object->socid . ", " . $obj->cid . ", '" . $obj->type . "', '" . $object_type . "', " . $object->id . ", '" . $this->db->escape($obj->email) . "')";
                         if (!$this->db->query($sql)) {
                             dol_print_error($this->db);
                         }
                     } else {
                         $error++;
                         $this->errors[] = $mailfile->error;
                     }
                 } else {
                     dol_syslog("No notification sent for " . $sendto . " because email is empty");
                 }
                 $i++;
             }
         } else {
             dol_syslog("No notification to thirdparty sent, nothing into notification setup for the thirdparty socid = " . $object->socid);
         }
     } else {
         $error++;
         $this->errors[] = $this->db->lasterror();
         return -1;
     }
     // Check notification using fixed email
     if (!$error) {
         foreach ($conf->global as $key => $val) {
             if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_' . $notifcode . '_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) {
                 continue;
             }
             $threshold = (double) $reg[1];
             if ($object->total_ht <= $threshold) {
                 dol_syslog("A notification is requested for notifcode = " . $notifcode . " but amount = " . $object->total_ht . " so lower than threshold = " . $threshold . ". We discard this notification");
                 continue;
             }
             $param = 'NOTIFICATION_FIXEDEMAIL_' . $notifcode . '_THRESHOLD_HIGHER_' . $reg[1];
             $sendto = $conf->global->{$param};
             $notifcodedefid = dol_getIdFromCode($this->db, $notifcode, 'c_action_trigger', 'code', 'rowid');
             if ($notifcodedefid <= 0) {
                 dol_print_error($this->db, 'Failed to get id from code');
             }
             $object_type = '';
             $link = '';
             $num++;
             switch ($notifcode) {
                 case 'BILL_VALIDATE':
                     $link = '/compta/facture.php?facid=' . $object->id;
                     $dir_output = $conf->facture->dir_output;
                     $object_type = 'facture';
                     $mesg = $langs->transnoentitiesnoconv("EMailTextInvoiceValidated", $newref);
                     break;
                 case 'ORDER_VALIDATE':
                     $link = '/commande/card.php?id=' . $object->id;
                     $dir_output = $conf->commande->dir_output;
                     $object_type = 'order';
                     $mesg = $langs->transnoentitiesnoconv("EMailTextOrderValidated", $newref);
                     break;
                 case 'PROPAL_VALIDATE':
                     $link = '/comm/propal.php?id=' . $object->id;
                     $dir_output = $conf->propal->dir_output;
                     $object_type = 'propal';
                     $mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated", $newref);
                     break;
                 case 'FICHINTER_VALIDATE':
                     $link = '/fichinter/card.php?id=' . $object->id;
                     $dir_output = $conf->facture->dir_output;
                     $object_type = 'ficheinter';
                     $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionValidated", $newref);
                     break;
                 case 'ORDER_SUPPLIER_VALIDATE':
                     $link = '/fourn/commande/card.php?id=' . $object->id;
                     $dir_output = $conf->fournisseur->dir_output . '/commande/';
                     $object_type = 'order_supplier';
                     $mesg = $langs->transnoentitiesnoconv("Hello") . ",\n\n";
                     $mesg .= $langs->transnoentitiesnoconv("EMailTextOrderValidatedBy", $newref, $user->getFullName($langs));
                     $mesg .= "\n\n" . $langs->transnoentitiesnoconv("Sincerely") . ".\n\n";
                     break;
                 case 'ORDER_SUPPLIER_APPROVE':
                     $link = '/fourn/commande/card.php?id=' . $object->id;
                     $dir_output = $conf->fournisseur->dir_output . '/commande/';
                     $object_type = 'order_supplier';
                     $mesg = $langs->transnoentitiesnoconv("Hello") . ",\n\n";
                     $mesg .= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy", $newref, $user->getFullName($langs));
                     $mesg .= "\n\n" . $langs->transnoentitiesnoconv("Sincerely") . ".\n\n";
                     break;
                 case 'ORDER_SUPPLIER_APPROVE2':
                     $link = '/fourn/commande/card.php?id=' . $object->id;
                     $dir_output = $conf->fournisseur->dir_output . '/commande/';
                     $object_type = 'order_supplier';
                     $mesg = $langs->transnoentitiesnoconv("Hello") . ",\n\n";
                     $mesg .= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy", $newref, $user->getFullName($langs));
                     $mesg .= "\n\n" . $langs->transnoentitiesnoconv("Sincerely") . ".\n\n";
                     break;
                 case 'ORDER_SUPPLIER_REFUSE':
                     $link = '/fourn/commande/card.php?id=' . $object->id;
                     $dir_output = $conf->fournisseur->dir_output . '/commande/';
                     $object_type = 'order_supplier';
                     $mesg = $langs->transnoentitiesnoconv("Hello") . ",\n\n";
                     $mesg .= $langs->transnoentitiesnoconv("EMailTextOrderRefusedBy", $newref, $user->getFullName($langs));
                     $mesg .= "\n\n" . $langs->transnoentitiesnoconv("Sincerely") . ".\n\n";
                     break;
                 case 'SHIPPING_VALIDATE':
                     $dir_output = $conf->expedition->dir_output . '/sending/';
                     $object_type = 'order_supplier';
                     $mesg = $langs->transnoentitiesnoconv("EMailTextExpeditionValidated", $newref);
                     break;
             }
             $ref = dol_sanitizeFileName($newref);
             $pdf_path = $dir_output . "/" . $ref . "/" . $ref . ".pdf";
             if (!dol_is_file($pdf_path)) {
                 // We can't add PDF as it is not generated yet.
                 $filepdf = '';
             } else {
                 $filepdf = $pdf_path;
             }
             $subject = '[' . $application . '] ' . $langs->transnoentitiesnoconv("DolibarrNotification");
             $message = $langs->transnoentities("YouReceiveMailBecauseOfNotification", $application, $mysoc->name) . "\n";
             $message .= $langs->transnoentities("YouReceiveMailBecauseOfNotification2", $application, $mysoc->name) . "\n";
             $message .= "\n";
             $message .= $mesg;
             if ($link) {
                 $message = dol_concatdesc($message, $urlwithroot . $link);
             }
             // Replace keyword __SUPERVISOREMAIL__
             if (preg_match('/__SUPERVISOREMAIL__/', $sendto)) {
                 $newval = '';
                 if ($user->fk_user > 0) {
                     $supervisoruser = new User($this->db);
                     $supervisoruser->fetch($user->fk_user);
                     if ($supervisoruser->email) {
                         $newval = trim(dolGetFirstLastname($supervisoruser->firstname, $supervisoruser->lastname) . ' <' . $supervisoruser->email . '>');
                     }
                 }
                 dol_syslog("Replace the __SUPERVISOREMAIL__ key into recipient email string with " . $newval);
                 $sendto = preg_replace('/__SUPERVISOREMAIL__/', $newval, $sendto);
                 $sendto = preg_replace('/^[\\s,]+/', '', $sendto);
                 // Clean start of string
                 $sendto = preg_replace('/[\\s,]+$/', '', $sendto);
                 // Clean end of string
             }
             if ($sendto) {
                 $mailfile = new CMailFile($subject, $sendto, $replyto, $message, array($file), array($mimefile), array($filename[count($filename) - 1]), '', '', 0, -1);
                 if ($mailfile->sendfile()) {
                     $sql = "INSERT INTO " . MAIN_DB_PREFIX . "notify (daten, fk_action, fk_soc, fk_contact, type, objet_type, objet_id, email)";
                     $sql .= " VALUES ('" . $this->db->idate(dol_now()) . "', " . $notifcodedefid . ", " . $object->socid . ", null, 'email', '" . $object_type . "', " . $object->id . ", '" . $this->db->escape($conf->global->{$param}) . "')";
                     if (!$this->db->query($sql)) {
                         dol_print_error($this->db);
                     }
                 } else {
                     $error++;
                     $this->errors[] = $mailfile->error;
                 }
             }
         }
     }
     if (!$error) {
         return $num;
     } else {
         return -1 * $error;
     }
 }
예제 #16
0
파일: geo.php 프로젝트: remyyounes/dolibarr
    {
        $label=$langs->trans("Country");
        $label2=$langs->trans("Town");
        $tab='statstown';

        $data = array();
        $sql.="SELECT COUNT(d.rowid) as nb, MAX(d.datevalid) as lastdate, p.code, p.libelle as label, d.ville as label2";
        $sql.=" FROM ".MAIN_DB_PREFIX."adherent as d";
        $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."c_pays as p on d.pays = p.rowid";
        $sql.=" WHERE d.statut = 1";
        $sql.=" GROUP BY p.libelle, p.code, d.ville";
        //print $sql;
    }

    $langsen=new Translate('',$conf);
    $langsen->setDefaultLang('en_US');
    $langsen->load("dict");
    //print $langsen->trans("Country"."FI");exit;

    // Define $data array
    dol_syslog("Count member sql=".$sql);
    $resql=$db->query($sql);
    if ($resql)
    {
        $num=$db->num_rows($resql);
        $i=0;
        while ($i < $num)
        {
            $obj=$db->fetch_object($resql);
            if ($mode == 'memberbycountry')
            {
예제 #17
0
파일: inc.php 프로젝트: netors/dolibarr
        // Reading stripslashes variable according to state get_magic_quotes_gpc).
        // Off mode (recommended, you just do $db->escape when an insert / update.
        function stripslashes_deep($value)
        {
            return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
        }
        $_GET = array_map('stripslashes_deep', $_GET);
        $_POST = array_map('stripslashes_deep', $_POST);
        $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
        $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
        @set_magic_quotes_runtime(0);
    }
}
// Defini objet langs
$langs = new Translate('..', $conf);
$langs->setDefaultLang('auto');
$bc[false] = ' class="bg1"';
$bc[true] = ' class="bg2"';
/**
 *	\brief		Load conf file (file must exists)
 *	\param		dolibarr_main_document_root		Root directory of Dolibarr bin files
 *	\return		int								<0 if KO, >0 if OK
 */
function conf($dolibarr_main_document_root)
{
    global $conf;
    global $dolibarr_main_db_type;
    global $dolibarr_main_db_host;
    global $dolibarr_main_db_port;
    global $dolibarr_main_db_name;
    global $dolibarr_main_db_user;
예제 #18
0
 /**
  * Adds a product to the order
  *
  * @param Commande $object Order object
  * @param Product $prod Product to add
  * @param int $qty Quantity of the product
  * @throws Exception
  */
 public static function addOrderLine(Commande $object, Product $prod, $qty)
 {
     global $db, $conf, $mysoc, $langs;
     require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
     $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
     $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
     if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) {
         $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
         $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
         $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
         if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) {
             $tva_tx = $prod->multiprices_tva_tx[$object->thirdparty->price_level];
         }
         if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) {
             $tva_npr = $prod->multiprices_recuperableonly[$object->thirdparty->price_level];
         }
     } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
         require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
         $prodcustprice = new Productcustomerprice($db);
         $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $object->thirdparty->id);
         $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
         if ($result >= 0) {
             if (count($prodcustprice->lines) > 0) {
                 $pu_ht = price($prodcustprice->lines[0]->price);
                 $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
                 $price_base_type = $prodcustprice->lines[0]->price_base_type;
                 $prod->tva_tx = $prodcustprice->lines[0]->tva_tx;
             } else {
                 $pu_ht = $prod->price;
                 $pu_ttc = $prod->price_ttc;
                 $price_base_type = $prod->price_base_type;
             }
         } else {
             throw new Exception($prodcustprice->error);
         }
     } else {
         $pu_ht = $prod->price;
         $pu_ttc = $prod->price_ttc;
         $price_base_type = $prod->price_base_type;
     }
     // if price ht is forced (ie: calculated by margin rate and cost price)
     if (!empty($price_ht)) {
         $pu_ht = price2num($price_ht, 'MU');
         $pu_ttc = price2num($pu_ht * (1 + $tva_tx / 100), 'MU');
     } elseif ($tva_tx != $prod->tva_tx) {
         if ($price_base_type != 'HT') {
             $pu_ht = price2num($pu_ttc / (1 + $tva_tx / 100), 'MU');
         } else {
             $pu_ttc = price2num($pu_ht * (1 + $tva_tx / 100), 'MU');
         }
     }
     // Define output language
     if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
         $outputlangs = $langs;
         $newlang = '';
         if (empty($newlang) && GETPOST('lang_id')) {
             $newlang = GETPOST('lang_id');
         }
         if (empty($newlang)) {
             $newlang = $object->thirdparty->default_lang;
         }
         if (!empty($newlang)) {
             $outputlangs = new Translate("", $conf);
             $outputlangs->setDefaultLang($newlang);
         }
         $desc = !empty($prod->multilangs[$outputlangs->defaultlang]["description"]) ? $prod->multilangs[$outputlangs->defaultlang]["description"] : $prod->description;
     } else {
         $desc = $prod->description;
     }
     // Add custom code and origin country into description
     if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) {
         $tmptxt = '(';
         if (!empty($prod->customcode)) {
             $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode;
         }
         if (!empty($prod->customcode) && !empty($prod->country_code)) {
             $tmptxt .= ' - ';
         }
         if (!empty($prod->country_code)) {
             $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0);
         }
         $tmptxt .= ')';
         $desc = dol_concatdesc($desc, $tmptxt);
     }
     //3.9.0 version added support for price units
     if (versioncompare(versiondolibarrarray(), array(3, 9, 0)) >= 0) {
         $fk_unit = $prod->fk_unit;
     } else {
         $fk_unit = null;
     }
     // Local Taxes
     $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty);
     $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty);
     $info_bits = 0;
     if ($tva_npr) {
         $info_bits |= 0x1;
     }
     //Percent remise
     if (!empty($object->thirdparty->remise_percent)) {
         $percent_remise = $object->thirdparty->remise_percent;
     } else {
         $percent_remise = 0;
     }
     // Insert line
     $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $prod->id, $percent_remise, $info_bits, 0, $price_base_type, $pu_ttc, '', '', $prod->type, -1, 0, 0, null, 0, '', 0, $fk_unit);
     if ($result < 0) {
         throw new Exception($langs->trans('ErrorAddOrderLine', $prod->ref));
     }
 }
예제 #19
0
 /**
  *	Return HTML content of a detail line
  *	TODO Move this into an output class file (htmlline.class.php)
  *	If lines are into a template, title must also be into a template
  *	But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  *
  *	@param	string		$action				GET/POST action
  *	@param	array	    $line		       	Selected object line to output
  *	@param  string	    $var               	Is it a an odd line (true)
  *	@param  int		    $num               	Number of line (0)
  *	@param  int		    $i					I
  *	@param  int		    $dateSelector      	1=Show also date range input fields
  *	@param  string	    $seller            	Object of seller third party
  *	@param  string	    $buyer             	Object of buyer third party
  *	@param	string		$selected		   	Object line selected
  *	@param	HookManager	$hookmanager		Hook manager
  *	@return	void
  */
 function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $hookmanager = false)
 {
     global $conf, $langs, $user;
     global $form, $bc, $bcdd;
     $element = $this->element;
     // Show product and description
     $type = $line->product_type ? $line->product_type : $line->fk_product_type;
     // Try to enhance type detection using date_start and date_end for free lines where type
     // was not saved.
     if (!empty($line->date_start)) {
         $type = 1;
     }
     if (!empty($line->date_end)) {
         $type = 1;
     }
     // Ligne en mode visu
     if ($action != 'editline' || $selected != $line->id) {
         // Produit
         if ($line->fk_product > 0) {
             $product_static = new Product($this->db);
             // Define output language
             if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
                 $this->fetch_thirdparty();
                 $prod = new Product($this->db, $line->fk_product);
                 $outputlangs = $langs;
                 $newlang = '';
                 if (empty($newlang) && GETPOST('lang_id')) {
                     $newlang = GETPOST('lang_id');
                 }
                 if (empty($newlang)) {
                     $newlang = $this->client->default_lang;
                 }
                 if (!empty($newlang)) {
                     $outputlangs = new Translate("", $conf);
                     $outputlangs->setDefaultLang($newlang);
                 }
                 $label = !empty($prod->multilangs[$outputlangs->defaultlang]["libelle"]) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $line->product_label;
             } else {
                 $label = $line->product_label;
             }
             $product_static->type = $line->fk_product_type;
             $product_static->id = $line->fk_product;
             $product_static->ref = $line->ref;
             $product_static->libelle = $label;
             $text = $product_static->getNomUrl(1);
             $text .= ' - ' . $label;
             $description = $conf->global->PRODUIT_DESC_IN_FORM ? '' : dol_htmlentitiesbr($line->description);
             // Output template part (modules that overwrite templates must declare this into descriptor)
             // Use global variables + $dateSelector + $seller and $buyer
             $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
             foreach ($dirtpls as $reldir) {
                 $res = @(include dol_buildpath($reldir . '/predefinedproductline_view.tpl.php'));
                 if ($res) {
                     break;
                 }
             }
         } else {
             // Output template part (modules that overwrite templates must declare this into descriptor)
             // Use global variables + $dateSelector + $seller and $buyer
             $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
             foreach ($dirtpls as $reldir) {
                 $res = @(include dol_buildpath($reldir . '/freeproductline_view.tpl.php'));
                 if ($res) {
                     break;
                 }
             }
         }
     }
     // Ligne en mode update
     if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
         if ($line->fk_product > 0) {
             // Output template part (modules that overwrite templates must declare this into descriptor)
             // Use global variables + $dateSelector + $seller and $buyer
             $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
             foreach ($dirtpls as $reldir) {
                 $res = @(include dol_buildpath($reldir . '/predefinedproductline_edit.tpl.php'));
                 if ($res) {
                     break;
                 }
             }
         } else {
             // Output template part (modules that overwrite templates must declare this into descriptor)
             // Use global variables + $dateSelector + $seller and $buyer
             $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
             foreach ($dirtpls as $reldir) {
                 $res = @(include dol_buildpath($reldir . '/freeproductline_edit.tpl.php'));
                 if ($res) {
                     break;
                 }
             }
         }
     }
 }
예제 #20
0
    /**
     * testDolTimePlusDuree
     *
     * @return int
     */
    public function testDolTimePlusDuree()
    {
        global $conf,$user,$langs,$db;
        $conf=$this->savconf;
        $user=$this->savuser;
        $langs=$this->savlangs;
        $db=$this->savdb;

        // Check dayhour format for fr_FR
        $outputlangs=new Translate('',$conf);
        $outputlangs->setDefaultLang('fr_FR');
        $outputlangs->load("main");

        $result=dol_print_date(dol_time_plus_duree(dol_time_plus_duree(dol_time_plus_duree(0,1,'m'),1,'y'),1,'d'),'dayhour',true,$outputlangs);
       	print __METHOD__." result=".$result."\n";
    	$this->assertEquals('02/02/1971 00:00',$result);

    	return $result;
    }
/**
 * List sendings and receive receipts
 *
 * @param   string		$origin			Origin ('commande', ...)
 * @param	int			$origin_id		Origin id
 * @param	string		$filter			Filter
 * @return	int							<0 if KO, >0 if OK
 */
function show_list_sending_receive($origin, $origin_id, $filter = '')
{
    global $db, $conf, $langs, $bc;
    global $form;
    $product_static = new Product($db);
    $expedition = new Expedition($db);
    $sql = "SELECT obj.rowid, obj.fk_product, obj.label, obj.description, obj.product_type as fk_product_type, obj.qty as qty_asked, obj.date_start, obj.date_end";
    $sql .= ", ed.qty as qty_shipped, ed.fk_expedition as expedition_id, ed.fk_origin_line";
    $sql .= ", e.rowid as sendingid, e.ref as exp_ref, e.date_creation, e.date_delivery, e.date_expedition,";
    //if ($conf->livraison_bon->enabled) $sql .= " l.rowid as livraison_id, l.ref as livraison_ref, l.date_delivery, ld.qty as qty_received,";
    $sql .= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid,';
    $sql .= ' p.description as product_desc';
    $sql .= " FROM " . MAIN_DB_PREFIX . "expeditiondet as ed";
    $sql .= ", " . MAIN_DB_PREFIX . "expedition as e";
    $sql .= ", " . MAIN_DB_PREFIX . $origin . "det as obj";
    //if ($conf->livraison_bon->enabled) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."livraison as l ON l.fk_expedition = e.rowid LEFT JOIN ".MAIN_DB_PREFIX."livraisondet as ld ON ld.fk_livraison = l.rowid  AND obj.rowid = ld.fk_origin_line";
    $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON obj.fk_product = p.rowid";
    $sql .= " WHERE e.entity = " . $conf->entity;
    $sql .= " AND obj.fk_" . $origin . " = " . $origin_id;
    $sql .= " AND obj.rowid = ed.fk_origin_line";
    $sql .= " AND ed.fk_expedition = e.rowid";
    if ($filter) {
        $sql .= $filter;
    }
    $sql .= " ORDER BY obj.fk_product";
    dol_syslog("show_list_sending_receive sql=" . $sql, LOG_DEBUG);
    $resql = $db->query($sql);
    if ($resql) {
        $num = $db->num_rows($resql);
        $i = 0;
        if ($num) {
            if ($filter) {
                print_titre($langs->trans("OtherSendingsForSameOrder"));
            } else {
                print_titre($langs->trans("SendingsAndReceivingForSameOrder"));
            }
            print '<table class="liste" width="100%">';
            print '<tr class="liste_titre">';
            //print '<td align="left">'.$langs->trans("QtyOrdered").'</td>';
            print '<td align="left">' . $langs->trans("SendingSheet") . '</td>';
            print '<td align="left">' . $langs->trans("Description") . '</td>';
            print '<td align="center">' . $langs->trans("DateCreation") . '</td>';
            print '<td align="center">' . $langs->trans("DateDeliveryPlanned") . '</td>';
            print '<td align="center">' . $langs->trans("QtyShipped") . '</td>';
            if ($conf->livraison_bon->enabled) {
                print '<td>' . $langs->trans("DeliveryOrder") . '</td>';
                //print '<td align="center">'.$langs->trans("QtyReceived").'</td>';
                print '<td align="right">' . $langs->trans("DeliveryDate") . '</td>';
            }
            print "</tr>\n";
            $var = True;
            while ($i < $num) {
                $var = !$var;
                $objp = $db->fetch_object($resql);
                print "<tr " . $bc[$var] . ">";
                // Sending id
                print '<td align="left" class="nowrap"><a href="' . DOL_URL_ROOT . '/expedition/fiche.php?id=' . $objp->expedition_id . '">' . img_object($langs->trans("ShowSending"), 'sending') . ' ' . $objp->exp_ref . '<a></td>';
                // Description
                if ($objp->fk_product > 0) {
                    // Define output language
                    if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
                        $object = new $origin($db);
                        $object->fetch($origin_id);
                        $object->fetch_thirdparty();
                        $prod = new Product($db);
                        $prod->id = $objp->fk_product;
                        $prod->getMultiLangs();
                        $outputlangs = $langs;
                        $newlang = '';
                        if (empty($newlang) && !empty($_REQUEST['lang_id'])) {
                            $newlang = $_REQUEST['lang_id'];
                        }
                        if (empty($newlang)) {
                            $newlang = $object->client->default_lang;
                        }
                        if (!empty($newlang)) {
                            $outputlangs = new Translate("", $conf);
                            $outputlangs->setDefaultLang($newlang);
                        }
                        $label = !empty($prod->multilangs[$outputlangs->defaultlang]["label"]) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $objp->product_label;
                    } else {
                        $label = !empty($objp->label) ? $objp->label : $objp->product_label;
                    }
                    print '<td>';
                    // Show product and description
                    $product_static->type = $objp->fk_product_type;
                    $product_static->id = $objp->fk_product;
                    $product_static->ref = $objp->ref;
                    $text = $product_static->getNomUrl(1);
                    $text .= ' - ' . $label;
                    $description = !empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($objp->description);
                    print $form->textwithtooltip($text, $description, 3, '', '', $i);
                    // Show range
                    print_date_range($objp->date_start, $objp->date_end);
                    // Add description in form
                    if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) {
                        print !empty($objp->description) && $objp->description != $objp->product ? '<br>' . dol_htmlentitiesbr($objp->description) : '';
                    }
                    print '</td>';
                } else {
                    print "<td>";
                    if ($objp->fk_product_type == 1) {
                        $text = img_object($langs->trans('Service'), 'service');
                    } else {
                        $text = img_object($langs->trans('Product'), 'product');
                    }
                    if (!empty($objp->label)) {
                        $text .= ' <strong>' . $objp->label . '</strong>';
                        print $form->textwithtooltip($text, $objp->description, 3, '', '', $i);
                    } else {
                        print $text . ' ' . nl2br($objp->description);
                    }
                    // Show range
                    print_date_range($objp->date_start, $objp->date_end);
                    print "</td>\n";
                }
                //print '<td align="center">'.$objp->qty_asked.'</td>';
                // Date creation
                print '<td align="center" class="nowrap">' . dol_print_date($db->jdate($objp->date_creation), 'day') . '</td>';
                // Date shipping creation
                print '<td align="center" class="nowrap">' . dol_print_date($db->jdate($objp->date_delivery), 'day') . '</td>';
                // Qty shipped
                print '<td align="center">' . $objp->qty_shipped . '</td>';
                // Informations on receipt
                if (!empty($conf->livraison_bon->enabled)) {
                    include_once DOL_DOCUMENT_ROOT . '/livraison/class/livraison.class.php';
                    $expedition->id = $objp->sendingid;
                    $expedition->fetchObjectLinked($expedition->id, $expedition->element);
                    //var_dump($expedition->linkedObjects);
                    $receiving = !empty($expedition->linkedObjects['delivery'][0]) ? $expedition->linkedObjects['delivery'][0] : '';
                    if (!empty($receiving)) {
                        // $expedition->fk_origin_line = id of det line of order
                        // $receiving->fk_origin_line = id of det line of order
                        // $receiving->origin may be 'shipping'
                        // $receiving->origin_id may be id of shipping
                        // Ref
                        print '<td>';
                        print $receiving->getNomUrl($db);
                        //print '<a href="'.DOL_URL_ROOT.'/livraison/fiche.php?id='.$livraison_id.'">'.img_object($langs->trans("ShowReceiving"),'sending').' '.$objp->livraison_ref.'<a>';
                        print '</td>';
                        // Qty received
                        //print '<td align="center">';
                        // TODO No solution for the moment to link a line det of receipt with a line det of shipping,
                        // so no way to know the qty received for this line of shipping.
                        //print $langs->trans("FeatureNotYetAvailable");
                        //print '</td>';
                        // Date shipping real
                        print '<td align="right">';
                        print dol_print_date($receiving->date_delivery, 'day');
                        print '</td>';
                    } else {
                        //print '<td>&nbsp;</td>';
                        print '<td>&nbsp;</td>';
                        print '<td>&nbsp;</td>';
                    }
                }
                print '</tr>';
                $i++;
            }
            print '</table>';
        }
        $db->free($resql);
    } else {
        dol_print_error($db);
    }
    return 1;
}
예제 #22
0
 /**
  *	Return HTML content of a detail line
  *	TODO Move this into an output class file (htmlline.class.php)
  *
  *	@param	string		$action				GET/POST action
  *	@param CommonObjectLine $line		       	Selected object line to output
  *	@param  string	    $var               	Is it a an odd line (true)
  *	@param  int		    $num               	Number of line (0)
  *	@param  int		    $i					I
  *	@param  int		    $dateSelector      	1=Show also date range input fields
  *	@param  string	    $seller            	Object of seller third party
  *	@param  string	    $buyer             	Object of buyer third party
  *	@param	int			$selected		   	Object line selected
  *  @param  int			$extrafieldsline	Object of extrafield line attribute
  *	@return	void
  */
 function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafieldsline = 0)
 {
     global $conf, $langs, $user, $object, $hookmanager;
     global $form, $bc, $bcdd, $object_rights;
     $object_rights = $this->getRights();
     $element = $this->element;
     $text = '';
     $description = '';
     $type = 0;
     // Show product and description
     $type = !empty($line->product_type) ? $line->product_type : $line->fk_product_type;
     // Try to enhance type detection using date_start and date_end for free lines where type was not saved.
     if (!empty($line->date_start)) {
         $type = 1;
     }
     // deprecated
     if (!empty($line->date_end)) {
         $type = 1;
     }
     // deprecated
     // Ligne en mode visu
     if ($action != 'editline' || $selected != $line->id) {
         // Product
         if ($line->fk_product > 0) {
             $product_static = new Product($this->db);
             $product_static->fetch($line->fk_product);
             $product_static->ref = $line->ref;
             //can change ref in hook
             $product_static->label = $line->label;
             //can change label in hook
             $text = $product_static->getNomUrl(1);
             // Define output language and label
             if (!empty($conf->global->MAIN_MULTILANGS)) {
                 if (!is_object($this->thirdparty)) {
                     dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
                     return;
                 }
                 $prod = new Product($this->db);
                 $prod->fetch($line->fk_product);
                 $outputlangs = $langs;
                 $newlang = '';
                 if (empty($newlang) && GETPOST('lang_id')) {
                     $newlang = GETPOST('lang_id');
                 }
                 if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang)) {
                     $newlang = $this->thirdparty->default_lang;
                 }
                 // For language to language of customer
                 if (!empty($newlang)) {
                     $outputlangs = new Translate("", $conf);
                     $outputlangs->setDefaultLang($newlang);
                 }
                 $label = !empty($prod->multilangs[$outputlangs->defaultlang]["label"]) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
             } else {
                 $label = $line->product_label;
             }
             $text .= ' - ' . (!empty($line->label) ? $line->label : $label);
             $description .= !empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($line->description);
             // Description is what to show on popup. We shown nothing if already into desc.
         }
         // Output template part (modules that overwrite templates must declare this into descriptor)
         // Use global variables + $dateSelector + $seller and $buyer
         $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
         foreach ($dirtpls as $reldir) {
             $tpl = dol_buildpath($reldir . '/objectline_view.tpl.php');
             if (empty($conf->file->strict_mode)) {
                 $res = @(include $tpl);
             } else {
                 $res = (include $tpl);
                 // for debug
             }
             if ($res) {
                 break;
             }
         }
     }
     // Ligne en mode update
     if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
         $label = !empty($line->label) ? $line->label : ($line->fk_product > 0 ? $line->product_label : '');
         if (!empty($conf->global->MAIN_HTML5_PLACEHOLDER)) {
             $placeholder = ' placeholder="' . $langs->trans("Label") . '"';
         } else {
             $placeholder = ' title="' . $langs->trans("Label") . '"';
         }
         $pu_ttc = price2num($line->subprice * (1 + $line->tva_tx / 100), 'MU');
         // Output template part (modules that overwrite templates must declare this into descriptor)
         // Use global variables + $dateSelector + $seller and $buyer
         $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
         foreach ($dirtpls as $reldir) {
             $tpl = dol_buildpath($reldir . '/objectline_edit.tpl.php');
             if (empty($conf->file->strict_mode)) {
                 $res = @(include $tpl);
             } else {
                 $res = (include $tpl);
                 // for debug
             }
             if ($res) {
                 break;
             }
         }
     }
 }
/**
 * 	Send email
 *
 * 	@param	string	$mode					Mode (test | confirm)
 *  @param	string	$oldemail				Old email
 * 	@param	string	$message				Message to send
 * 	@param	string	$total					Total amount of unpayed invoices
 *  @param	string	$userlang				Code lang to use for email output.
 *  @param	string	$oldsalerepresentative	Old sale representative
 * 	@return	int								<0 if KO, >0 if OK
 */
function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldsalerepresentative)
{
    global $conf, $langs;
    if (getenv('DOL_FORCE_EMAIL_TO')) {
        $oldemail = getenv('DOL_FORCE_EMAIL_TO');
    }
    $newlangs = new Translate('', $conf);
    $newlangs->setDefaultLang(empty($userlang) ? empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT : $userlang);
    $newlangs->load("main");
    $newlangs->load("bills");
    $subject = empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_SUBJECT) ? $newlangs->trans("ListOfYourUnpaidInvoices") : $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_SUBJECT;
    $sendto = $oldemail;
    $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
    $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
    $msgishtml = -1;
    print "- Send email for " . $oldsalerepresentative . " (" . $oldemail . "), total: " . $total . "\n";
    dol_syslog("email_unpaid_invoices_to_representatives.php: send mail to " . $oldemail);
    $usehtml = 0;
    if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) {
        $usehtml += 1;
    }
    if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER)) {
        $usehtml += 1;
    }
    $allmessage = '';
    if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER)) {
        $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER;
    } else {
        $allmessage .= $newlangs->transnoentities("ListOfYourUnpaidInvoices") . ($usehtml ? "<br>\n" : "\n") . ($usehtml ? "<br>\n" : "\n");
        $allmessage .= $newlangs->transnoentities("NoteListOfYourUnpaidInvoices") . ($usehtml ? "<br>\n" : "\n");
    }
    $allmessage .= $message . ($usehtml ? "<br>\n" : "\n");
    $allmessage .= $langs->trans("Total") . " = " . price($total, 0, $newlangs, 0, 0, -1, $conf->currency) . ($usehtml ? "<br>\n" : "\n");
    if (!empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) {
        $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER;
        if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) {
            $usehtml += 1;
        }
    }
    $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
    $mail->errors_to = $errorsto;
    // Send or not email
    if ($mode == 'confirm') {
        $result = $mail->sendfile();
        if (!$result) {
            print "Error sending email " . $mail->error . "\n";
            dol_syslog("Error sending email " . $mail->error . "\n");
        }
    } else {
        print "No email sent (test mode)\n";
        dol_syslog("No email sent (test mode)");
        $mail->dump_mail();
        $result = 1;
    }
    if ($result) {
        return 1;
    } else {
        return -1;
    }
}
예제 #24
0
/**
 * Function to build a compiled PDF
 *
 * @param	DoliDB		$db						Database handler
 * @param	Translate	$langs					Object langs
 * @param	Conf		$conf					Object conf
 * @param	string		$diroutputpdf			Dir to output file
 * @param	string		$newlangid				Lang id
 * @param 	array		$filter					Array with filters
 * @param 	date		$dateafterdate			Invoice after date
 * @param 	date 		$datebeforedate			Invoice before date
 * @param 	date		$paymentdateafter		Payment after date (must includes hour)
 * @param 	date		$paymentdatebefore		Payment before date (must includes hour)
 * @param	int			$usestdout				Add information onto standard output
 * @param	int			$regenerate				''=Use existing PDF files, 'nameofpdf'=Regenerate all PDF files using the template
 * @param	string		$filesuffix				Suffix to add into file name of generated PDF
 * @param	string		$paymentbankid			Only if payment on this bank account id
 * @param	array		$thirdpartiesid			List of thirdparties id when using filter excludethirdpartiesid	or onlythirdpartiesid
 * @param	string		$fileprefix				Prefix to add into filename of generated PDF
 * @return	int									Error code
 */
function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filter, $dateafterdate, $datebeforedate, $paymentdateafter, $paymentdatebefore, $usestdout, $regenerate = 0, $filesuffix = '', $paymentbankid = '', $thirdpartiesid = '', $fileprefix = 'mergedpdf')
{
    $sql = "SELECT DISTINCT f.rowid, f.facnumber";
    $sql .= " FROM " . MAIN_DB_PREFIX . "facture as f";
    $sqlwhere = '';
    $sqlorder = '';
    if (in_array('all', $filter)) {
        $sqlorder = " ORDER BY f.facnumber ASC";
    }
    if (in_array('date', $filter)) {
        if (empty($sqlwhere)) {
            $sqlwhere = ' WHERE ';
        } else {
            $sqlwhere .= " AND";
        }
        $sqlwhere .= " f.fk_statut > 0";
        $sqlwhere .= " AND f.datef >= '" . $db->idate($dateafterdate) . "'";
        $sqlwhere .= " AND f.datef <= '" . $db->idate($datebeforedate) . "'";
        $sqlorder = " ORDER BY f.datef ASC";
    }
    if (in_array('nopayment', $filter)) {
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "paiement_facture as pf ON f.rowid = pf.fk_facture";
        if (empty($sqlwhere)) {
            $sqlwhere = ' WHERE ';
        } else {
            $sqlwhere .= " AND";
        }
        $sqlwhere .= " f.fk_statut > 0";
        $sqlwhere .= " AND pf.fk_paiement IS NULL";
    }
    if (in_array('payments', $filter) || in_array('bank', $filter)) {
        $sql .= ", " . MAIN_DB_PREFIX . "paiement_facture as pf, " . MAIN_DB_PREFIX . "paiement as p";
        if (in_array('bank', $filter)) {
            $sql .= ", " . MAIN_DB_PREFIX . "bank as b";
        }
        if (empty($sqlwhere)) {
            $sqlwhere = ' WHERE ';
        } else {
            $sqlwhere .= " AND";
        }
        $sqlwhere .= " f.fk_statut > 0";
        $sqlwhere .= " AND f.rowid = pf.fk_facture";
        $sqlwhere .= " AND pf.fk_paiement = p.rowid";
        if (in_array('payments', $filter)) {
            $sqlwhere .= " AND p.datep >= '" . $db->idate($paymentdateafter) . "'";
            $sqlwhere .= " AND p.datep <= '" . $db->idate($paymentdatebefore) . "'";
        }
        if (in_array('bank', $filter)) {
            $sqlwhere .= " AND p.fk_bank = b.rowid";
            $sqlwhere .= " AND b.fk_account = " . $paymentbankid;
        }
        $sqlorder = " ORDER BY p.datep ASC";
    }
    if (in_array('nodeposit', $filter)) {
        if (empty($sqlwhere)) {
            $sqlwhere = ' WHERE ';
        } else {
            $sqlwhere .= " AND";
        }
        $sqlwhere .= ' type <> 3';
    }
    if (in_array('noreplacement', $filter)) {
        if (empty($sqlwhere)) {
            $sqlwhere = ' WHERE ';
        } else {
            $sqlwhere .= " AND";
        }
        $sqlwhere .= ' type <> 1';
    }
    if (in_array('nocreditnote', $filter)) {
        if (empty($sqlwhere)) {
            $sqlwhere = ' WHERE ';
        } else {
            $sqlwhere .= " AND";
        }
        $sqlwhere .= ' type <> 2';
    }
    if (in_array('excludethirdparties', $filter) && is_array($thirdpartiesid)) {
        if (empty($sqlwhere)) {
            $sqlwhere = ' WHERE ';
        } else {
            $sqlwhere .= " AND";
        }
        $sqlwhere .= ' f.fk_soc NOT IN (' . join(',', $thirdpartiesid) . ')';
    }
    if (in_array('onlythirdparties', $filter) && is_array($thirdpartiesid)) {
        if (empty($sqlwhere)) {
            $sqlwhere = ' WHERE ';
        } else {
            $sqlwhere .= " AND";
        }
        $sqlwhere .= ' f.fk_soc IN (' . join(',', $thirdpartiesid) . ')';
    }
    if ($sqlwhere) {
        $sql .= $sqlwhere;
    }
    if ($sqlorder) {
        $sql .= $sqlorder;
    }
    //print $sql; exit;
    dol_syslog("scripts/invoices/rebuild_merge.php:", LOG_DEBUG);
    if ($usestdout) {
        print '--- start' . "\n";
    }
    // Start of transaction
    //$db->begin();
    $error = 0;
    $result = 0;
    $files = array();
    // liste les fichiers
    dol_syslog("scripts/invoices/rebuild_merge.php", LOG_DEBUG);
    if ($resql = $db->query($sql)) {
        $num = $db->num_rows($resql);
        $cpt = 0;
        $oldemail = '';
        $message = '';
        $total = '';
        if ($num) {
            // First loop on each resultset to build PDF
            // -----------------------------------------
            while ($cpt < $num) {
                $obj = $db->fetch_object($resql);
                $fac = new Facture($db);
                $result = $fac->fetch($obj->rowid);
                if ($result > 0) {
                    $outputlangs = $langs;
                    if (!empty($newlangid)) {
                        if ($outputlangs->defaultlang != $newlangid) {
                            $outputlangs = new Translate("", $conf);
                            $outputlangs->setDefaultLang($newlangid);
                        }
                    }
                    $filename = $conf->facture->dir_output . '/' . $fac->ref . '/' . $fac->ref . '.pdf';
                    if ($regenerate || !dol_is_file($filename)) {
                        if ($usestdout) {
                            print "Build PDF for invoice " . $obj->facnumber . " - Lang = " . $outputlangs->defaultlang . "\n";
                        }
                        $result = $fac->generateDocument($regenerate ? $regenerate : $fac->modelpdf, $outputlangs);
                    } else {
                        if ($usestdout) {
                            print "PDF for invoice " . $obj->facnumber . " already exists\n";
                        }
                    }
                    // Add file into files array
                    $files[] = $filename;
                }
                if ($result <= 0) {
                    $error++;
                    if ($usestdout) {
                        print "Error: Failed to build PDF for invoice " . ($fac->ref ? $fac->ref : ' id ' . $obj->rowid) . "\n";
                    } else {
                        dol_syslog("Failed to build PDF for invoice " . ($fac->ref ? $fac->ref : ' id ' . $obj->rowid), LOG_ERR);
                    }
                }
                $cpt++;
            }
            // Define format of output PDF
            $formatarray = pdf_getFormat($langs);
            $page_largeur = $formatarray['width'];
            $page_hauteur = $formatarray['height'];
            $format = array($page_largeur, $page_hauteur);
            if ($usestdout) {
                print "Using output PDF format " . join('x', $format) . "\n";
            } else {
                dol_syslog("Using output PDF format " . join('x', $format), LOG_ERR);
            }
            // Now, build a merged files with all files in $files array
            //---------------------------------------------------------
            // Create empty PDF
            $pdf = pdf_getInstance($format);
            if (class_exists('TCPDF')) {
                $pdf->setPrintHeader(false);
                $pdf->setPrintFooter(false);
            }
            $pdf->SetFont(pdf_getPDFFont($langs));
            if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) {
                $pdf->SetCompression(false);
            }
            //$pdf->SetCompression(false);
            // Add all others
            foreach ($files as $file) {
                if ($usestdout) {
                    print "Merge PDF file for invoice " . $file . "\n";
                } else {
                    dol_syslog("Merge PDF file for invoice " . $file);
                }
                // Charge un document PDF depuis un fichier.
                $pagecount = $pdf->setSourceFile($file);
                for ($i = 1; $i <= $pagecount; $i++) {
                    $tplidx = $pdf->importPage($i);
                    $s = $pdf->getTemplatesize($tplidx);
                    $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
                    $pdf->useTemplate($tplidx);
                }
            }
            // Create output dir if not exists
            dol_mkdir($diroutputpdf);
            // Save merged file
            $filename = $fileprefix;
            if (empty($filename)) {
                $filename = 'mergedpdf';
            }
            if (!empty($filesuffix)) {
                $filename .= '_' . $filesuffix;
            }
            $file = $diroutputpdf . '/' . $filename . '.pdf';
            if (!$error && $pagecount) {
                $pdf->Output($file, 'F');
                if (!empty($conf->global->MAIN_UMASK)) {
                    @chmod($file, octdec($conf->global->MAIN_UMASK));
                }
            }
            if ($usestdout) {
                if (!$error) {
                    print "Merged PDF has been built in " . $file . "\n";
                } else {
                    print "Can't build PDF " . $file . "\n";
                }
            }
            $result = 1;
        } else {
            if ($usestdout) {
                print "No invoices found for criteria.\n";
            } else {
                dol_syslog("No invoices found for criteria");
            }
            $result = 0;
        }
    } else {
        dol_print_error($db);
        dol_syslog("scripts/invoices/rebuild_merge.php: Error");
        $error++;
    }
    if ($error) {
        return -1;
    } else {
        return $result;
    }
}
예제 #25
0
파일: card.php 프로젝트: ADDAdev/Dolibarr
    }
}
if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->facture->paiement) {
    $db->begin();
    $object->fetch($id);
    if ($object->valide() > 0) {
        $db->commit();
        // Loop on each invoice linked to this payment to rebuild PDF
        $factures = array();
        foreach ($factures as $id) {
            $fac = new Facture($db);
            $fac->fetch($id);
            $outputlangs = $langs;
            if (!empty($_REQUEST['lang_id'])) {
                $outputlangs = new Translate("", $conf);
                $outputlangs->setDefaultLang($_REQUEST['lang_id']);
            }
            if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
                $fac->generateDocument($fac->modelpdf, $outputlangs);
            }
        }
        header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $object->id);
        exit;
    } else {
        $langs->load("errors");
        setEventMessage($langs->trans($object->error), 'errors');
        $db->rollback();
    }
}
if ($action == 'setnum_paiement' && !empty($_POST['num_paiement'])) {
    $object->fetch($id);
function _getOutPutLangs(&$object)
{
    global $conf;
    $object->fetch_thirdparty();
    $outputlangs = new Translate('', $conf);
    $langcode = !empty($object->thirdparty->country_code) ? $object->thirdparty->country_code : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
    $outputlangs->setDefaultLang($langcode);
    return $outputlangs;
}
예제 #27
0
             $object->fetch_thirdparty(GETPOST('socid', 'int'));
         } else {
             unset($object->thirdparty);
         }
     }
 }
 // Build doc
 if ($action == 'builddoc' && $user->rights->projet->creer) {
     // Save last template used to generate document
     if (GETPOST('model')) {
         $object->setDocModel($user, GETPOST('model', 'alpha'));
     }
     $outputlangs = $langs;
     if (GETPOST('lang_id')) {
         $outputlangs = new Translate("", $conf);
         $outputlangs->setDefaultLang(GETPOST('lang_id'));
     }
     $result = $object->generateDocument($object->modelpdf, $outputlangs);
     if ($result <= 0) {
         setEventMessages($object->error, $object->errors, 'errors');
         $action = '';
     }
 }
 // Delete file in doc form
 if ($action == 'remove_file' && $user->rights->projet->creer) {
     require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
     if ($object->id > 0) {
         $langs->load("other");
         $upload_dir = $conf->projet->dir_output . "/";
         $urlfile = GETPOST('urlfile', 'alpha');
         $file = $upload_dir . '/' . $filetodelete;
 /**
  * @param   array         $parameters     Hook metadatas (context, etc...)
  * @param   Commande    $object        The object to process
  * @param   string          $action        Current action (if set). Generally create or edit or null
  * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
  * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
  */
 public function formConfirm(array $parameters, Commande $object, &$action, HookManager $hookmanager)
 {
     global $langs, $db, $conf;
     $langs->load('importorderlines@importorderlines');
     if ($object->statut >= 1) {
         return 0;
     }
     require __DIR__ . '/Utils.php';
     if ($action == 'import') {
         $this->resprints = Utils::uploadForm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ImportOrderLines'), $langs->trans('ConfirmCloneOrder', $object->ref), 'confirm_import', $langs->trans('SelectFileToImport'));
     } elseif ($action == 'confirm_import') {
         try {
             if (!isset($_FILES['uploadfile'])) {
                 throw new Exception($langs->trans('UploadFileError'));
             }
             $file = $_FILES['uploadfile'];
             if (!is_uploaded_file($file['tmp_name'])) {
                 throw new Exception($langs->trans('UploadFileError'));
             }
             if ($file['error'] != UPLOAD_ERR_OK) {
                 throw new Exception($langs->trans('UploadFileError'), $file['error']);
             }
             require __DIR__ . '/../lib/phpoffice/phpexcel/Classes/PHPExcel.php';
             //Supported PHPExcel File readers to ensure we deal with a Spreadsheet.
             $supported_filereaders = array('CSV', 'Excel2007', 'Excel5', 'OOCalc', 'Excel2003XML');
             if (!in_array(PHPExcel_IOFactory::identify($file['tmp_name']), $supported_filereaders)) {
                 throw new Exception($langs->trans('UploadFileErrorUnsupportedFormat'));
             }
             try {
                 $excelfd = PHPExcel_IOFactory::load($file['tmp_name']);
             } catch (PHPExcel_Reader_Exception $e) {
                 throw new Exception($e->getMessage());
             }
             $activesheet = $excelfd->getActiveSheet();
             //Check of the format
             $a1 = $activesheet->getCell('A1')->getValue() == $langs->transnoentities('Ref');
             $b1 = $activesheet->getCell('B1')->getValue() == $langs->transnoentities('Label');
             $c1 = $activesheet->getCell('C1')->getValue() == $langs->transnoentities('Qty');
             if (!$a1 || !$b1 || !$c1) {
                 throw new Exception($langs->trans('UploadFileErrorFormat'));
             }
             $maxrow = $activesheet->getHighestRow();
             for ($i = 2; $i <= $maxrow; $i++) {
                 $qty = (int) $activesheet->getCellByColumnAndRow(2, $i)->getValue();
                 if ($qty > 0) {
                     $ref = $activesheet->getCellByColumnAndRow(0, $i)->getValue();
                     $prod = new Product($db);
                     if ($prod->fetch('', $ref) <= 0) {
                         throw new Exception($langs->trans('ErrorProductNotFound', $ref));
                     }
                     Utils::addOrderLine($object, $prod, $qty);
                     unset($prod);
                 }
             }
         } catch (Exception $e) {
             $message = $e->getMessage();
             setEventMessage($e->getMessage(), 'errors');
             if ($e->getCode()) {
                 $message .= '. Error code: ' . $e->getCode();
             }
             dol_syslog('[importorderlines] ' . $message, LOG_DEBUG);
             return -1;
         }
         //Delete temporary file
         unlink($file['tmp_name']);
         //Reload the object with new lines
         $object->fetch($object->id);
         if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
             // Define output language
             $outputlangs = $langs;
             $newlang = GETPOST('lang_id', 'alpha');
             if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) {
                 $newlang = $object->thirdparty->default_lang;
             }
             if (!empty($newlang)) {
                 $outputlangs = new Translate("", $conf);
                 $outputlangs->setDefaultLang($newlang);
             }
             // PDF
             $hidedetails = !empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0;
             $hidedesc = !empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0;
             $hideref = !empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0;
             commande_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
         }
     }
     return 0;
 }
예제 #29
0
	$delivery->fetch($_REQUEST['id']);

	if ($_REQUEST['model'])
	{
		$delivery->setDocModel($user, $_REQUEST['model']);
	}

	// Define output language
	$outputlangs = $langs;
	$newlang='';
	if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id'];
	if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$delivery->client->default_lang;
	if (! empty($newlang))
	{
		$outputlangs = new Translate("",$conf);
		$outputlangs->setDefaultLang($newlang);
	}

	$result=delivery_order_pdf_create($db, $delivery,$_REQUEST['model'],$outputlangs);
	if ($result <= 0)
	{
		dol_print_error($db,$result);
		exit;
	}
}


/*
 *	View
 */
 /**
  *	Close the commercial proposal
  *
  *	@param      User	$user		Object user that close
  *	@param      int		$statut		Statut
  *	@param      string	$note		Comment
  *	@return     int         		<0 if KO, >0 if OK
  */
 function cloture($user, $statut, $note)
 {
     global $langs, $conf;
     $this->statut = $statut;
     $error = 0;
     $now = dol_now();
     $this->db->begin();
     $sql = "UPDATE " . MAIN_DB_PREFIX . "propal";
     $sql .= " SET fk_statut = " . $statut . ", note_private = '" . $this->db->escape($note) . "', date_cloture='" . $this->db->idate($now) . "', fk_user_cloture=" . $user->id;
     $sql .= " WHERE rowid = " . $this->id;
     $resql = $this->db->query($sql);
     if ($resql) {
         if ($statut == 2) {
             // The connected company is classified as a client
             $soc = new Societe($this->db);
             $soc->id = $this->socid;
             $result = $soc->set_as_client();
             if ($result < 0) {
                 $this->error = $this->db->error();
                 $this->db->rollback();
                 return -2;
             }
             if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
                 // Define output language
                 $outputlangs = $langs;
                 if (!empty($conf->global->MAIN_MULTILANGS)) {
                     $outputlangs = new Translate("", $conf);
                     $newlang = GETPOST('lang_id') ? GETPOST('lang_id') : $this->client->default_lang;
                     $outputlangs->setDefaultLang($newlang);
                 }
                 //$ret=$object->fetch($id);    // Reload to get new records
                 propale_pdf_create($this->db, $this, $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL ? $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL : $this->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
             }
             // Appel des triggers
             include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
             $interface = new Interfaces($this->db);
             $result = $interface->run_triggers('PROPAL_CLOSE_SIGNED', $this, $user, $langs, $conf);
             if ($result < 0) {
                 $error++;
                 $this->errors = $interface->errors;
             }
             // Fin appel triggers
         } else {
             if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
                 // Define output language
                 $outputlangs = $langs;
                 if (!empty($conf->global->MAIN_MULTILANGS)) {
                     $outputlangs = new Translate("", $conf);
                     $newlang = GETPOST('lang_id') ? GETPOST('lang_id') : $this->client->default_lang;
                     $outputlangs->setDefaultLang($newlang);
                 }
                 //$ret=$object->fetch($id);    // Reload to get new records
                 propale_pdf_create($this->db, $this, $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED ? $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED : $this->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
             }
             // Appel des triggers
             include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
             $interface = new Interfaces($this->db);
             $result = $interface->run_triggers('PROPAL_CLOSE_REFUSED', $this, $user, $langs, $conf);
             if ($result < 0) {
                 $error++;
                 $this->errors = $interface->errors;
             }
             // Fin appel triggers
         }
         $this->db->commit();
         return 1;
     } else {
         $this->error = $this->db->error();
         $this->db->rollback();
         return -1;
     }
 }