Esempio n. 1
0
	/**
     *      Write the object to document file to disk
     *      @param      socid
     *      @param      catid
     *      @param      outputlangs     Lang object for output language
     *      @return     int             1=OK, 0=KO
	 */
	function write_file($socid = 0, $catid = 0, $outputlangs='')
	{
		global $user,$conf,$langs;

		if (! is_object($outputlangs)) $outputlangs=$langs;
		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
		if (!class_exists('TCPDF')) $outputlangs->charset_output='ISO-8859-1';

		$outputlangs->load("main");
		$outputlangs->load("dict");
		$outputlangs->load("companies");
		$outputlangs->load("bills");
		$outputlangs->load("products");

        $dir = $conf->agenda->dir_temp."/";
		$file = $dir . "actions-".$this->month."-".$this->year.".pdf";

		if (! file_exists($dir))
		{
			if (create_exdir($dir) < 0)
			{
				$this->error=$langs->trans("ErrorCanNotCreateDir",$dir);
				return 0;
			}
		}

		if (file_exists($dir))
		{
            $pdf=pdf_getInstance($this->format);

            if (class_exists('TCPDF'))
            {
                $pdf->setPrintHeader(false);
                $pdf->setPrintFooter(false);
            }
            $pdf->SetFont(pdf_getPDFFont($outputlangs));

			$pdf->Open();
			$pagenb=0;
			$pdf->SetDrawColor(128,128,128);
			$pdf->SetFillColor(220,220,220);

			$pdf->SetTitle($outputlangs->convToOutputCharset($this->title));
			$pdf->SetSubject($outputlangs->convToOutputCharset($this->subject));
			$pdf->SetCreator("Dolibarr ".DOL_VERSION);
			$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
			$pdf->SetKeywords($outputlangs->convToOutputCharset($this->title." ".$this->subject));

			$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
			$pdf->SetAutoPageBreak(1,0);

			$nbpage = $this->_pages($pdf, $outputlangs);

			$pdf->AliasNbPages();
			$pdf->Close();

			$pdf->Output($file,'F');
			if (! empty($conf->global->MAIN_UMASK))
			@chmod($file, octdec($conf->global->MAIN_UMASK));

			return 1;
		}
	}
Esempio n. 2
0
	/**
	 *    \brief      Ajoute destinataires dans table des cibles
	 *    \param      mailing_id    Id of emailing
	 *    \param      filterarray   Requete sql de selection des destinataires
	 *    \return     int           < 0 si erreur, nb ajout si ok
	 */
	function add_to_target($mailing_id,$filtersarray=array())
	{
		global $conf,$langs,$_FILES;

		require_once(DOL_DOCUMENT_ROOT."/lib/files.lib.php");

		// For compatibility with Unix, MS-Dos or Macintosh
		ini_set('auto_detect_line_endings', true);

		$cibles = array();

		$upload_dir=$conf->mailing->dir_temp;

		if (create_exdir($upload_dir) >= 0)
		{
			$resupload = dol_move_uploaded_file($_FILES['username']['tmp_name'], $upload_dir . "/" . $_FILES['username']['name'], 1, 0, $_FILES['username']['error']);
			if (is_numeric($resupload) && $resupload > 0)
			{
				$cpt=0;

				//$mesg = '<div class="ok">'.$langs->trans("FileTransferComplete").'</div>';
				//print_r($_FILES);
				$file=$upload_dir . "/" . $_FILES['username']['name'];
				$handle = @fopen($file, "r");
				if ($handle)
				{
					$i = 0;
		            $j = 0;

            		$old = '';
					while (!feof($handle))
					{
						$cpt++;
				        $buffer = trim(fgets($handle));
			        	$tab=explode(';',$buffer,4);
				        $email=$tab[0];
				        $name=$tab[1];
				        $firstname=$tab[2];
				        $other=$tab[3];
				        if (! empty($buffer))
				        {
			        		//print 'xx'.dol_strlen($buffer).empty($buffer)."<br>\n";
				        	$id=$cpt;
					        if (isValidEMail($email))
					        {
		   						if ($old <> $email)
								{
									$cibles[$j] = array(
					                    			'email' => $email,
					                    			'name' => $name,
					                    			'firstname' => $firstname,
													'other' => $other,
                                                    'source_url' => '',
                                                    'source_id' => '',
                                                    'source_type' => 'file'
									);
									$old = $email;
									$j++;
								}
					        }
					        else
					        {
					        	$i++;
					        	$langs->load("errors");
					        	$this->error = $langs->trans("ErrorFoundBadEmailInFile",$i,$cpt,$email);
					        }
				        }
				    }
				    fclose($handle);

				    if ($i > 0)
				    {
				    	return -$i;
				    }
				}
				else
				{
					$this->error = $langs->trans("ErrorFaildToOpenFile");
					return -1;
				}

				dol_syslog(get_class($this)."::add_to_target mailing ".$cpt." targets found");
			}
			else
			{
				$langs->load("errors");
				if ($resupload < 0)	// Unknown error
				{
					$this->error = '<div class="error">'.$langs->trans("ErrorFileNotUploaded").'</div>';
				}
				else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload))	// Files infected by a virus
				{
					$this->error = '<div class="error">'.$langs->trans("ErrorFileIsInfectedWithAVirus").'</div>';
				}
				else	// Known error
				{
					$this->error = '<div class="error">'.$langs->trans($resupload).'</div>';
				}
			}
		}

		ini_set('auto_detect_line_endings', false);

		return parent::add_to_target($mailing_id, $cibles);
	}
Esempio n. 3
0
	/**
	 *      \brief      Build export file
	 *      \param      user                User that export
	 *      \param      model               Export format
	 *      \param      datatoexport        Name of dataset to export
	 *      \param      array_selected      Filter on array of fields to export
	 *      \param		sqlquery = ''		if set, transmit a sql query instead of building it from arrays
	 *      \remarks    Les tableaux array_export_xxx sont deja chargees pour le bon datatoexport
	 *                  aussi le parametre datatoexport est inutilise
	 */
	function build_file($user, $model, $datatoexport, $array_selected, $sqlquery = '')
 	{
		global $conf,$langs;

		$indice=0;
		asort($array_selected);

		dol_syslog("Export::build_file $model, $datatoexport, $array_selected");

		// Creation de la classe d'export du model ExportXXX
		$dir = DOL_DOCUMENT_ROOT . "/includes/modules/export/";
		$file = "export_".$model.".modules.php";
		$classname = "Export".$model;
		require_once($dir.$file);
		$objmodel = new $classname($db);

		if ($sqlquery) $sql = $sqlquery;
        else $sql=$this->build_sql($indice,$array_selected);

		// Run the sql
		$this->sqlusedforexport=$sql;
		dol_syslog("Export::build_file sql=".$sql);
		$resql = $this->db->query($sql);
		if ($resql)
		{
			//$this->array_export_label[$indice]
			$filename="export_".$datatoexport;
			$filename.='.'.$objmodel->getDriverExtension();
			$dirname=$conf->export->dir_temp.'/'.$user->id;

			$outputlangs=$langs;	// Lang for output

			// Open file
			create_exdir($dirname);
			$result=$objmodel->open_file($dirname."/".$filename, $outputlangs);

			if ($result >= 0)
			{
				// Genere en-tete
				$objmodel->write_header($outputlangs);

				// Genere ligne de titre
				$objmodel->write_title($this->array_export_fields[$indice],$array_selected,$outputlangs);

				while ($objp = $this->db->fetch_object($resql))
				{
					$var=!$var;

					// Process special operations
					if (! empty($this->array_export_special[$indice]))
					{
						foreach ($this->array_export_special[$indice] as $key => $value)
						{
							if (! array_key_exists($key, $array_selected)) continue;		// Field not selected
							// Operation NULLIFNEG
							if ($this->array_export_special[$indice][$key]=='NULLIFNEG')
							{
								//$alias=$this->array_export_alias[$indice][$key];
								$alias=str_replace(array('.', '-'),'_',$key);
								if ($objp->$alias < 0) $objp->$alias='';
							}
							// Operation ZEROIFNEG
							if ($this->array_export_special[$indice][$key]=='ZEROIFNEG')
							{
								//$alias=$this->array_export_alias[$indice][$key];
								$alias=str_replace(array('.', '-'),'_',$key);
								if ($objp->$alias < 0) $objp->$alias='0';
							}
						}
					}
					// end of special operation processing

					$objmodel->write_record($array_selected,$objp,$outputlangs);
				}

				// Genere en-tete
				$objmodel->write_footer($outputlangs);

				// Close file
				$objmodel->close_file();
			}
			else
			{
				$this->error=$objmodel->error;
				dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
				return -1;
			}
		}
		else
		{
			$this->error=$this->db->error()." - sql=".$sql;
			dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
			return -1;
		}
	}
Esempio n. 4
0
         $langs->load("errors");
         $message .= '<div class="error">' . $langs->trans("ErrorLoginAlreadyExists", $edituser->login) . '</div>';
     } else {
         $message .= '<div class="error">' . $edituser->error . '</div>';
     }
 }
 if ($ret >= 0 && !count($edituser->errors)) {
     if (GETPOST('deletephoto') && $edituser->photo) {
         $fileimg = $conf->user->dir_output . '/' . get_exdir($edituser->id, 2, 0, 1) . '/logos/' . $edituser->photo;
         $dirthumbs = $conf->user->dir_output . '/' . get_exdir($edituser->id, 2, 0, 1) . '/logos/thumbs';
         dol_delete_file($fileimg);
         dol_delete_dir_recursive($dirthumbs);
     }
     if (isset($_FILES['photo']['tmp_name']) && trim($_FILES['photo']['tmp_name'])) {
         $dir = $conf->user->dir_output . '/' . get_exdir($edituser->id, 2, 0, 1);
         create_exdir($dir);
         if (@is_dir($dir)) {
             $newfile = $dir . '/' . dol_sanitizeFileName($_FILES['photo']['name']);
             $result = dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1, 0, $_FILES['photo']['error']);
             if (!$result > 0) {
                 $message .= '<div class="error">' . $langs->trans("ErrorFailedToSaveFile") . '</div>';
             } else {
                 // Create small thumbs for company (Ratio is near 16/9)
                 // Used on logon for example
                 $imgThumbSmall = vignette($newfile, $maxwidthsmall, $maxheightsmall, '_small', $quality);
                 // Create mini thumbs for company (Ratio is near 16/9)
                 // Used on menu or for setup page for example
                 $imgThumbMini = vignette($newfile, $maxwidthmini, $maxheightmini, '_mini', $quality);
             }
         }
     }
Esempio n. 5
0
	/**
	 *		\brief      Function to build PDF on disk, then output on HTTP strem.
	 *		\param	    arrayofmembers	Array of members informations
	 *		\param		outputlangs		Lang object for output language
	 *		\return	    int     		1=ok, 0=ko
	 */
	function write_file($arrayofmembers,$outputlangs)
	{
		global $user,$conf,$langs,$mysoc,$_Avery_Labels;

		// Choose type (CARD by default)
		$this->code=empty($conf->global->ADHERENT_CARD_TYPE)?'CARD':$conf->global->ADHERENT_CARD_TYPE;
		$this->Tformat = $_Avery_Labels[$this->code];
		if (empty($this->Tformat)) { dol_print_error('','ErrorBadTypeForCard'.$this->code); exit; }
		$this->type = 'pdf';
		$this->format = $this->Tformat['paper-size'];

		if (! is_object($outputlangs)) $outputlangs=$langs;
		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
		if (!class_exists('TCPDF')) $outputlangs->charset_output='ISO-8859-1';

		$outputlangs->load("main");
		$outputlangs->load("dict");
		$outputlangs->load("companies");
		$outputlangs->load("members");
		$outputlangs->load("admin");


		$dir = $conf->adherent->dir_temp;
		$file = $dir . "/tmpcards.pdf";

		if (! file_exists($dir))
		{
			if (create_exdir($dir) < 0)
			{
				$this->error=$langs->trans("ErrorCanNotCreateDir",$dir);
				return 0;
			}
		}

        $pdf=pdf_getInstance($this->format,$this->Tformat['metric']);

        if (class_exists('TCPDF'))
        {
            $pdf->setPrintHeader(false);
            $pdf->setPrintFooter(false);
        }
        $pdf->SetFont(pdf_getPDFFont($outputlangs));

		$pdf->SetTitle($outputlangs->transnoentities('MembersCards'));
		$pdf->SetSubject($outputlangs->transnoentities("MembersCards"));
		$pdf->SetCreator("Dolibarr ".DOL_VERSION);
		$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
		$pdf->SetKeyWords($outputlangs->transnoentities('MembersCards')." ".$outputlangs->transnoentities("Foundation")." ".$outputlangs->convToOutputCharset($mysoc->name));
		if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);

		$pdf->SetMargins(0,0);
		$pdf->SetAutoPageBreak(false);

		$this->_Metric_Doc = $this->Tformat['metric'];
		// Permet de commencer l'impression de l'etiquette desiree dans le cas ou la page a deja servie
		$posX=1;
		$posY=1;
		if ($posX > 0) $posX--; else $posX=0;
		if ($posY > 0) $posY--; else $posY=0;
		$this->_COUNTX = $posX;
		$this->_COUNTY = $posY;
		$this->_Set_Format($pdf, $this->Tformat);


		$pdf->Open();
		$pdf->AddPage();


		// Add each record
		foreach($arrayofmembers as $val)
		{
			// imprime le texte specifique sur la carte
			$this->Add_PDF_card($pdf,$val['textleft'],$val['textheader'],$val['textfooter'],$langs,$val['textright'],$val['id'],$val['photo']);
		}

		//$pdf->SetXY(10, 295);
		//$pdf->Cell($this->_Width, $this->_Line_Height, 'XXX',0,1,'C');


		// Output to file
		$pdf->Output($file,'F');

		if (! empty($conf->global->MAIN_UMASK))
			@chmod($file, octdec($conf->global->MAIN_UMASK));



		// Output to http stream
		clearstatcache();

		$attachment=true;
		if (! empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS)) $attachment=false;
		$filename='tmpcards.pdf';
		$type=dol_mimetype($filename);

		if ($encoding)   header('Content-Encoding: '.$encoding);
		if ($type)       header('Content-Type: '.$type);
		if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"');
		else header('Content-Disposition: inline; filename="'.$filename.'"');

		// Ajout directives pour resoudre bug IE
		header('Cache-Control: Public, must-revalidate');
		header('Pragma: public');

		readfile($file);

		return 1;
	}
Esempio n. 6
0
$upload_dir = $conf->ecm->dir_output.'/'.$relativepath;



/*******************************************************************
* ACTIONS
*
* Put here all code to do according to value of "action" parameter
********************************************************************/

// Upload file
if (GETPOST("sendit") && ! empty($conf->global->MAIN_UPLOAD_DOC))
{
	require_once(DOL_DOCUMENT_ROOT."/lib/files.lib.php");

	if (create_exdir($upload_dir) >= 0)
	{
		$resupload = dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_dir . "/" . $_FILES['userfile']['name'],0,0,$_FILES['userfile']['error']);
		if (is_numeric($resupload) && $resupload > 0)
		{
		    $result=$ecmdir->changeNbOfFiles('+');
	    }
	    else
	    {
   			$langs->load("errors");
			if ($resupload < 0)	// Unknown error
			{
				$mesg = '<div class="error">'.$langs->trans("ErrorFileNotUploaded").'</div>';
			}
			else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload))	// Files infected by a virus
			{
Esempio n. 7
0
		$mesg=$langs->trans("ErrorFieldRequired",$langs->transnoentities("File"));
		$error++;
	}
	else
	{
		if (! preg_match('/\.tgz/i',$original_file))
		{
			$mesg=$langs->trans("ErrorFileMustBeADolibarrPackage");
			$error++;
		}
	}

	if (! $error)
	{
		@dol_delete_dir_recursive($conf->admin->dir_temp.'/'.$original_file);
		create_exdir($conf->admin->dir_temp.'/'.$original_file);

		$result=dol_move_uploaded_file($_FILES["fileinstall"]["tmp_name"],$newfile,1,0,$_FILES['fileinstall']['error']);
		if ($result > 0)
		{
			//dol_uncompress($newfile);
		}
	}
}


/*
 * View
 */

$wikihelp='EN:Installation_-_Upgrade|FR:Installation_-_Mise_à_jour|ES:Instalaci&omodulon_-_Actualizaci&omodulon';
    /**
     *	Create a withdraw
     *	@param 	banque	code of bank
     *	@param	guichet	code of banck office
     *	@param	mode	real=do action, simu=test only
     *	@return	int		<0 if KO, nbre of invoice withdrawed if OK
     */
    function Create($banque=0, $guichet=0, $mode='real')
    {
        global $conf,$langs;

        dol_syslog("BonPrelevement::Create banque=$banque guichet=$guichet");

        require_once (DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php");
        require_once (DOL_DOCUMENT_ROOT."/societe/class/societe.class.php");

        $error = 0;

        $datetimeprev = time();

        $month = strftime("%m", $datetimeprev);
        $year = strftime("%Y", $datetimeprev);

        $puser = new User($this->db, $conf->global->PRELEVEMENT_USER);

        /*
         * Read invoices
         */
        $factures = array();
        $factures_prev = array();
        $factures_result = array();

        if (! $error)
        {
            $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc";
            $sql.= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib";
            $sql.= ", pfd.amount";
            $sql.= ", s.nom";
            $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
            $sql.= ", ".MAIN_DB_PREFIX."societe as s";
            $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
            if ($banque == 1 || $agence ==1) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr";
            $sql.= " WHERE f.rowid = pfd.fk_facture";
            $sql.= " AND f.entity = ".$conf->entity;
            $sql.= " AND s.rowid = f.fk_soc";
            if ($banque == 1 || $agence ==1) $sql.= " AND s.rowid = sr.fk_soc";
            $sql.= " AND f.fk_statut = 1";
            $sql.= " AND f.paye = 0";
            $sql.= " AND pfd.traite = 0";
            $sql.= " AND f.total_ttc > 0";
            if ($banque == 1) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'";
            if ($agence == 1) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'";

            dol_syslog("Bon-Prelevement::Create sql=".$sql, LOG_DEBUG);
            $resql = $this->db->query($sql);
            if ($resql)
            {
                $num = $this->db->num_rows($resql);
                $i = 0;

                while ($i < $num)
                {
                    $row = $this->db->fetch_row($resql);
                    $factures[$i] = $row;
                    $i++;
                }
                $this->db->free($resql);
                dol_syslog($i." invoices to withdraw");
            }
            else
            {
                $error = 1;
                dol_syslog("Erreur -1");
                dol_syslog($this->db->error());
            }
        }

        if (! $error)
        {
            // Check RIB
        	$i = 0;
            dol_syslog("Start RIB check");

            if (sizeof($factures) > 0)
            {
                foreach ($factures as $fac)
                {
                    $fact = new Facture($this->db);

                    if ($fact->fetch($fac[0]) >= 0)
                    {
                        $soc = new Societe($this->db);
                        if ($soc->fetch($fact->socid) >= 0)
                        {
                            if ($soc->verif_rib() == 1)
                            {
                                $factures_prev[$i] = $fac;
                                /* second tableau necessaire pour bon-prelevement */
                                $factures_prev_id[$i] = $fac[0];
                                $i++;
                            }
                            else
                            {
                                dol_syslog("Error on third party bank number RIB/IBAN $fact->socid $soc->nom", LOG_ERR);
                                $facture_errors[$fac[0]]="Error on third party bank number RIB/IBAN $fact->socid $soc->nom";
                            }
                        }
                        else
                        {
                            dol_syslog("Failed to read company", LOG_ERR);
                        }
                    }
                    else
                    {
                        dol_syslog("Failed to read invoice", LOG_ERR);
                    }
                }
            }
            else
            {
                dol_syslog("No invoice to process");
            }
        }

		$ok=0;

        // Withdraw invoices in factures_prev array
        $out=sizeof($factures_prev)." invoices will be withdrawn.";
		//print $out."\n";
		dol_syslog($out);


		if (sizeof($factures_prev) > 0)
		{
			if ($mode=='real')
			{
				$ok=1;
			}
			else
			{
				print $langs->trans("ModeWarning"); //"Option for real mode was not set, we stop after this simulation\n";
			}
		}


        if ($ok)
        {
			/*
			 * We are in real mode.
			 * We create withdraw receipt and build withdraw into disk
			 */
            $this->db->begin();

            /*
             * Traitements
             *
             */
            if (!$error)
            {
                $ref = "T".substr($year,-2).$month;

                $sql = "SELECT count(*)";
                $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons";
                $sql.= " WHERE ref LIKE '".$ref."%'";
                $sql.= " AND entity = ".$conf->entity;

            	dol_syslog("Bon-Prelevement::Create sql=".$sql, LOG_DEBUG);
                $resql = $this->db->query($sql);

                if ($resql)
                {
                    $row = $this->db->fetch_row($resql);
                }
                else
                {
                    $error++;
                    dol_syslog("Erreur recherche reference");
                }

                $ref = $ref . substr("00".($row[0]+1), -2);

                $filebonprev = $ref;

                // Create withdraw receipt in database
                $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons (";
                $sql.= " ref, entity, datec";
                $sql.= ") VALUES (";
                $sql.= "'".$ref."'";
                $sql.= ", ".$conf->entity;
                $sql.= ", '".$this->db->idate(mktime())."'";
                $sql.= ")";

            	dol_syslog("Bon-Prelevement::Create sql=".$sql, LOG_DEBUG);
                $resql = $this->db->query($sql);

                if ($resql)
                {
                    $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons");

                    $dir=$conf->prelevement->dir_output.'/receipts';
                    $file=$filebonprev;
                    if (! is_dir($dir)) create_exdir($dir);

                    $bonprev = new BonPrelevement($this->db, $dir."/".$file);
                    $bonprev->id = $prev_id;
                }
                else
                {
                    $error++;
                    dol_syslog("Erreur creation du bon de prelevement");
                }
            }

            /*
             * Creation process
             *
             */
			if (!$error)
			{
				if (sizeof($factures_prev) > 0)
				{
					foreach ($factures_prev as $fac)
					{
						// Fetch invoice
						$fact = new Facture($this->db);
						$fact->fetch($fac[0]);
						/*
						 * Add standing order
						 *
						 *
						 * $fac[3] : banque
						 * $fac[4] : guichet
						 * $fac[5] : number
						 * $fac[6] : cle rib
						 * $fac[7] : amount
						 * $fac[8] : client nom
						 * $fac[2] : client id
						 */
						$ri = $bonprev->AddFacture($fac[0], $fac[2], $fac[8], $fac[7],
						$fac[3], $fac[4], $fac[5], $fac[6]);
						if ($ri <> 0)
						{
							$error++;
						}

						/*
						 * Update orders
						 *
						 */
						$sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande";
						$sql.= " SET traite = 1";
						$sql.= ", date_traite = ".$this->db->idate(mktime());
						$sql.= ", fk_prelevement_bons = ".$prev_id;
						$sql.= " WHERE rowid = ".$fac[1];

						dol_syslog("Bon-Prelevement::Create sql=".$sql, LOG_DEBUG);
						if ($this->db->query($sql))
						{

						}
						else
						{
							$error++;
							dol_syslog("Erreur mise a jour des demandes");
							dol_syslog($this->db->error());
						}

					}

				}

			}

			if (!$error)
			{
				/*
				 * Withdraw receipt
				 */

				dol_syslog("Debut prelevement - Nombre de factures ".sizeof($factures_prev));

				if (sizeof($factures_prev) > 0)
				{
					$bonprev->date_echeance = $datetimeprev;
					$bonprev->reference_remise = $ref;

					$bonprev->numero_national_emetteur    = $conf->global->PRELEVEMENT_NUMERO_NATIONAL_EMETTEUR;
					$bonprev->raison_sociale              = $conf->global->PRELEVEMENT_RAISON_SOCIALE;

					$bonprev->emetteur_code_banque 		  = $conf->global->PRELEVEMENT_CODE_BANQUE;
					$bonprev->emetteur_code_guichet       = $conf->global->PRELEVEMENT_CODE_GUICHET;
					$bonprev->emetteur_numero_compte      = $conf->global->PRELEVEMENT_NUMERO_COMPTE;
					$bonprev->emetteur_number_key		  = $conf->global->PRELEVEMENT_NUMBER_KEY;

					$bonprev->factures = $factures_prev_id;

					//Build file
					$bonprev->generate();
				}
				dol_syslog( $filebonprev ) ;
				dol_syslog("Fin prelevement");
			}

			/*
			 * Update total
			 *
			 */

			$sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
			$sql.= " SET amount = ".price2num($bonprev->total);
			$sql.= " WHERE rowid = ".$prev_id;
			$sql.= " AND entity = ".$conf->entity;

			dol_syslog("Bon-Prelevement::Create sql=".$sql, LOG_DEBUG);
			$resql=$this->db->query($sql);
			if (! $resql)
			{
				$error++;
				dol_syslog("Erreur mise a jour du total - $sql");
			}

			/*
			 * Rollback or Commit
			 *
			 */
			if (!$error)
			{
				$this->db->commit();
			}
			else
			{
				$this->db->rollback();
				dol_syslog("Error",LOG_ERROR);
			}

			return sizeof($factures_prev);
		}
		else
		{
			return 0;
		}
	}
Esempio n. 9
0
	/**
	 *      Create record into database
	 *      @param      user        User that create
	 *      @return     int         <0 if KO, >0 if OK
	 */
	function create($user)
	{
		global $conf, $langs;

		$now=dol_now();

		// Clean parameters
		$this->label=dol_sanitizeFileName(trim($this->label));
		$this->fk_parent=trim($this->fk_parent);
		$this->description=trim($this->description);
		if (! $this->cachenbofdoc) $this->cachenbofdoc=0;
		$this->date_c=$now;
		$this->fk_user_c=$user->id;
		if ($this->fk_parent <= 0) $this->fk_parent=0;


		// Check if same directory does not exists with this name
		$relativepath=$this->label;
		if ($this->fk_parent)
		{
			$parent = new ECMDirectory($this->db);
			$parent->fetch($this->fk_parent);
			$relativepath=$parent->getRelativePath().$relativepath;
		}
		$relativepath=preg_replace('/([\/])+/i','/',$relativepath);	// Avoid duplicate / or \
		//print $relativepath.'<br>';

		$cat = new ECMDirectory($this->db);
		$cate_arbo = $cat->get_full_arbo(1);
		$pathfound=0;
		foreach ($cate_arbo as $key => $categ)
		{
			$path=str_replace($this->forbiddenchars,'_',$categ['fulllabel']);
			//print $path.'<br>';
			if ($path == $relativepath)
			{
				$pathfound=1;
				break;
			}
		}

		if ($pathfound)
		{
			$this->error="ErrorDirAlreadyExists";
			dol_syslog("EcmDirectories::create ".$this->error, LOG_WARNING);
			return -1;
		}
		else
		{
			$this->db->begin();

			// Insert request
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."ecm_directories(";
			$sql.= "label,";
			$sql.= "entity,";
			$sql.= "fk_parent,";
			$sql.= "description,";
			$sql.= "cachenbofdoc,";
			$sql.= "date_c,";
			$sql.= "fk_user_c";
			$sql.= ") VALUES (";
			$sql.= " '".$this->db->escape($this->label)."',";
			$sql.= " '".$conf->entity."',";
			$sql.= " '".$this->fk_parent."',";
			$sql.= " '".$this->db->escape($this->description)."',";
			$sql.= " ".($this->cachenbofdoc).",";
			$sql.= " '".$this->db->idate($this->date_c)."',";
			$sql.= " '".$this->fk_user_c."'";
			$sql.= ")";

			dol_syslog("EcmDirectories::create sql=".$sql, LOG_DEBUG);
			$resql=$this->db->query($sql);
			if ($resql)
			{
				$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."ecm_directories");

				$dir=$conf->ecm->dir_output.'/'.$this->getRelativePath();
				$result=create_exdir($dir);

				// Appel des triggers
				include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
				$interface=new Interfaces($this->db);
				$result=$interface->run_triggers('MYECMDIR_CREATE',$this,$user,$langs,$conf);
				if ($result < 0) { $error++; $this->errors=$interface->errors; }
				// Fin appel triggers

				if (! $error)
				{
					$this->db->commit();
					return $this->id;
				}
				else
				{
					$this->db->rollback();
					return -1;
				}
			}
			else
			{
				$this->error="Error ".$this->db->lasterror();
				dol_syslog("EcmDirectories::create ".$this->error, LOG_ERR);
				$this->db->rollback();
				return -1;
			}
		}
	}
Esempio n. 10
0
	/**
	 *		Creation d'un icone de couleur
	 *		@param	color		Couleur de l'image
	 *		@param	module  Nom du module
	 *		@param	name	  Nom de l'image
	 *		@param	x       Largeur de l'image en pixels
	 *		@param	y       Hauteur de l'image en pixels
	 */
	function CreateColorIcon($color,$module,$name,$x='12',$y='12')
	{
		global $conf;

		$file = $conf->$module->dir_temp.'/'.$name.'.png';

		// On cree le repertoire contenant les icones
		if (! file_exists($conf->$module->dir_temp))
		{
			create_exdir($conf->$module->dir_temp);
		}

		// On cree l'image en vraies couleurs
		$image = imagecreatetruecolor($x,$y);

		$color = substr($color,1,6);

		$rouge = hexdec(substr($color,0,2)); //conversion du canal rouge
		$vert  = hexdec(substr($color,2,2)); //conversion du canal vert
		$bleu  = hexdec(substr($color,4,2)); //conversion du canal bleu

		$couleur = imagecolorallocate($image,$rouge,$vert,$bleu);
		//print $rouge.$vert.$bleu;
		imagefill($image,0,0,$couleur); //on remplit l'image
		// On cree la couleur et on l'attribue a une variable pour ne pas la perdre
		ImagePng($image,$file); //renvoie une image sous format png
		ImageDestroy($image);
	}
	/**
	 *		\brief      Fonction generant le document sur le disque
	 *		\param	    object			Objet expedition a generer (ou id si ancienne methode)
	 *		\param		outputlangs		Lang output object
	 * 	 	\return	    int     		1=ok, 0=ko
	 */
	function write_file(&$object, $outputlangs)
	{
		global $user,$conf,$langs,$mysoc;
		$default_font_size = pdf_getPDFFontSize($outputlangs);

		$object->fetch_thirdparty();

		if (! is_object($outputlangs)) $outputlangs=$langs;
		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
		if (!class_exists('TCPDF')) $outputlangs->charset_output='ISO-8859-1';

		$outputlangs->load("main");
		$outputlangs->load("dict");
		$outputlangs->load("companies");
		$outputlangs->load("bills");
		$outputlangs->load("products");
		$outputlangs->load("propal");
		$outputlangs->load("sendings");
		$outputlangs->load("deliveries");

		//Generation de la fiche
		$this->expe = $object;

		//Verification de la configuration
		if ($conf->expedition->dir_output)
		{
			$object->fetch_thirdparty();

			$origin = $object->origin;

			//Creation de l expediteur
			$this->expediteur = $mysoc;

			//Creation du destinataire
			$idcontact = $object->$origin->getIdContact('external','SHIPPING');
            $this->destinataire = new Contact($this->db);
			if ($idcontact[0]) $this->destinataire->fetch($idcontact[0]);

			//Creation du livreur
			$idcontact = $object->$origin->getIdContact('internal','LIVREUR');
			$this->livreur = new User($this->db);
			if ($idcontact[0]) $this->livreur->fetch($idcontact[0]);


			// Definition de $dir et $file
			if ($object->specimen)
			{
				$dir = $conf->expedition->dir_output."/sending";
				$file = $dir . "/SPECIMEN.pdf";
			}
			else
			{
				$expref = dol_sanitizeFileName($object->ref);
				$dir = $conf->expedition->dir_output . "/sending/" . $expref;
				$file = $dir . "/" . $expref . ".pdf";
			}

			if (! file_exists($dir))
			{
				if (create_exdir($dir) < 0)
				{
					$this->error=$outputlangs->transnoentities("ErrorCanNotCreateDir",$dir);
					return 0;
				}
			}

			//Si le dossier existe
			if (file_exists($dir))
			{
                $pdf=pdf_getInstance($this->format,'mm','l');

			    if (class_exists('TCPDF'))
                {
                    $pdf->setPrintHeader(false);
                    $pdf->setPrintFooter(false);
                }
                $pdf->SetFont(pdf_getPDFFont($outputlangs));

				$pdf->Open();
				$pagenb=0;
				$pdf->SetDrawColor(128,128,128);

				//Generation de l entete du fichier
				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
				$pdf->SetSubject($outputlangs->transnoentities("Sending"));
				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Sending"));
				if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);

				$pdf->SetMargins(10, 10, 10);
				$pdf->SetAutoPageBreak(1,0);

				$pdf->SetFont('','', $default_font_size - 3);

				// New page
				$pdf->AddPage();
				$pagenb++;
				$this->_pagehead($pdf, $this->expe, $outputlangs);
				$pdf->SetFont('','', $default_font_size - 3);
				$pdf->MultiCell(0, 3, '');		// Set interline to 3
				$pdf->SetTextColor(0,0,0);

				//Initialisation des coordonnees
				$tab_top = 53;
				$tab_height = 70;
				$pdf->SetFillColor(240,240,240);
				$pdf->SetTextColor(0,0,0);
				$pdf->SetFont('','',  $default_font_size - 3);
				$pdf->SetXY (10, $tab_top + 5 );
				$iniY = $pdf->GetY();
				$curY = $pdf->GetY();
				$nexY = $pdf->GetY();
				//Generation du tableau
				$this->_tableau($pdf, $tab_top, $tab_height, $nexY, $outputlangs);

				$nblignes = sizeof($object->lines);

				for ($i = 0 ; $i < $nblignes ; $i++)
				{
					// Description de la ligne produit

					//Creation des cases a cocher
					$pdf->rect(10+3, $curY+1, 3, 3);
					$pdf->rect(20+3, $curY+1, 3, 3);
					//Insertion de la reference du produit
					$pdf->SetXY (30, $curY+1 );
					$pdf->SetFont('','B', $default_font_size - 3);
					$pdf->MultiCell(24, 3, $outputlangs->convToOutputCharset($object->lines[$i]->ref), 0, 'L', 0);
					//Insertion du libelle
					$pdf->SetFont('','', $default_font_size - 3);
					$pdf->SetXY (50, $curY+1 );
                    //$libelleproduitservice=pdf_getlinedesc($object->$origin,$i,$outputlangs);
					$libelleproduitservice = pdf_writelinedesc($pdf,$object->$origin,$i,$outputlangs,90,3,50,$curY+1,1);
					//$pdf->writeHTMLCell(90, 3, 50, $curY+1, $outputlangs->convToOutputCharset($libelleproduitservice), 0, 'L', 0);
					//Insertion de la quantite commandee
					$pdf->SetFont('','', $default_font_size - 3);
					$pdf->SetXY (140, $curY+1 );
					$pdf->MultiCell(30, 3, $object->lines[$i]->qty_asked, 0, 'C', 0);
					//Insertion de la quantite a envoyer
					$pdf->SetFont('','', $default_font_size - 3);
					$pdf->SetXY (170, $curY+1 );
					$pdf->MultiCell(30, 3, $object->lines[$i]->qty_shipped, 0, 'C', 0);

					//Generation de la page 2
					$curY += (dol_nboflines_bis($libelleproduitservice,0,$outputlangs->charset_output)*3+1);
					$nexY = $curY;
					if ($nexY > ($tab_top+$tab_height-10) && $i < $nblignes - 1)
					{
						$this->_tableau($pdf, $tab_top, $tab_height, $nexY, $outputlangs);
						$this->_pagefoot($pdf, $object, $outputlangs);
						$pdf->AliasNbPages();

						$curY = $iniY;

						// New page
						$pdf->AddPage();
						$pagenb++;
						$this->_pagehead($pdf, $this->expe, $outputlangs);
						$pdf->MultiCell(0, 3, '');		// Set interline to 3
						$pdf->SetTextColor(0,0,0);
						$pdf->SetFont('','', $default_font_size - 3);
					}
				}
				//Insertion du pied de page
				$this->_pagefoot($pdf, $object, $outputlangs);

				$pdf->AliasNbPages();

				$pdf->Close();

				$pdf->Output($file,'F');
                if (! empty($conf->global->MAIN_UMASK))
                    @chmod($file, octdec($conf->global->MAIN_UMASK));

				return 1;
			}
			else
			{
				$this->error=$outputlangs->transnoentities("ErrorCanNotCreateDir",$dir);
				return 0;
			}
		}
		else
		{
			$this->error=$outputlangs->transnoentities("ErrorConstantNotDefined","EXP_OUTPUTDIR");
			return 0;
		}
		$this->error=$outputlangs->transnoentities("ErrorUnknown");
		return 0;   // Erreur par defaut

	}
	/**
	 *	Function to build a document on disk using the generic odt module.
	 *	@param	    object				Object source to build document
	 *	@param		outputlangs			Lang output object
	 * 	@param		srctemplatepath	Full path of source filename for generator using a template file
	 *	@return	    int         		1 if OK, <=0 if KO
	 */
	function write_file($object,$outputlangs,$srctemplatepath)
	{
		global $user,$langs,$conf,$mysoc;

		if (empty($srctemplatepath))
		{
			dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
			return -1;
		}

		if (! is_object($outputlangs)) $outputlangs=$langs;
		$sav_charset_output=$outputlangs->charset_output;
		$outputlangs->charset_output='UTF-8';

		$outputlangs->load("main");
		$outputlangs->load("dict");
		$outputlangs->load("companies");
		$outputlangs->load("projects");

		if ($conf->societe->dir_output)
		{
			// If $object is id instead of object
			if (! is_object($object))
			{
				$id = $object;
				$object = new Societe($this->db);
				$object->fetch($id);

				if ($result < 0)
				{
					dol_print_error($db,$object->error);
					return -1;
				}
			}

			$objectref = dol_sanitizeFileName($object->id);
			$dir = $conf->societe->dir_output;
			if (! preg_match('/specimen/i',$objectref)) $dir.= "/" . $objectref;
			$file = $dir . "/" . $objectref . ".odt";

			if (! file_exists($dir))
			{
				if (create_exdir($dir) < 0)
				{
					$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
					return -1;
				}
			}

			if (file_exists($dir))
			{
				//print "srctemplatepath=".$srctemplatepath;	// Src filename
				$newfile=basename($srctemplatepath);
				$newfiletmp=preg_replace('/\.odt/i','',$newfile);
				$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
				//print "newdir=".$dir;
				//print "newfile=".$newfile;
				//print "file=".$file;
				//print "conf->societe->dir_temp=".$conf->societe->dir_temp;

				create_exdir($conf->societe->dir_temp);

				// Open and load template
				require_once(DOL_DOCUMENT_ROOT.'/includes/odtphp/odf.php');
				$odfHandler = new odf($srctemplatepath, array(
						'PATH_TO_TMP'	  => $conf->societe->dir_temp,
						'ZIP_PROXY'		  => 'PclZipProxy',	// PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
						'DELIMITER_LEFT'  => '{',
						'DELIMITER_RIGHT' => '}')
				);

				//print $odfHandler->__toString()."\n";

				// Make substitutions into odt of user info
			    $tmparray=$this->get_substitutionarray_user($user,$outputlangs);
                //var_dump($tmparray); exit;
                foreach($tmparray as $key=>$value)
                {
                    try {
                        if (preg_match('/logo$/',$key)) // Image
                        {
                            //var_dump($value);exit;
                            if (file_exists($value)) $odfHandler->setImage($key, $value);
                            else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
                        }
                        else    // Text
                        {
                            //print $key.' '.$value;exit;
                            $odfHandler->setVars($key, $value, true, 'UTF-8');
                        }
                    }
                    catch(OdfException $e)
                    {
                    }
                }
                // Make substitutions into odt of mysoc info
                $tmparray=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
				//var_dump($tmparray); exit;
				foreach($tmparray as $key=>$value)
				{
					try {
						if (preg_match('/logo$/',$key))	// Image
						{
							//var_dump($value);exit;
							if (file_exists($value)) $odfHandler->setImage($key, $value);
							else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
						}
						else	// Text
						{
							$odfHandler->setVars($key, $value, true, 'UTF-8');
						}
					}
					catch(OdfException $e)
					{
					}
				}
                // Make substitutions into odt of thirdparty + external modules
				$tmparray=$this->get_substitutionarray_thirdparty($object,$outputlangs);
                complete_substitutions_array($tmparray, $langs, $object);
                //var_dump($object->id); exit;
				foreach($tmparray as $key=>$value)
				{
					try {
						if (preg_match('/logo$/',$key))	// Image
						{
							if (file_exists($value)) $odfHandler->setImage($key, $value);
							else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
						}
						else	// Text
						{
							$odfHandler->setVars($key, $value, true, 'UTF-8');
						}
					}
					catch(OdfException $e)
					{
					}
				}

				// Write new file
				//$result=$odfHandler->exportAsAttachedFile('toto');
				$odfHandler->saveToDisk($file);

				if (! empty($conf->global->MAIN_UMASK))
				@chmod($file, octdec($conf->global->MAIN_UMASK));

				$odfHandler=null;	// Destroy object

				return 1;   // Success
			}
			else
			{
				$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
				return -1;
			}
		}

		return -1;
	}
Esempio n. 13
0
 /**
  * 	\brief		Dump a LDAP message to ldapinput.in file
  *	\param		dn			DN entry key
  *	\param		info		Attributes array
  *	\return		int			<0 if KO, >0 if OK
  */
 function dump($dn, $info)
 {
     global $conf;
     // Create content
     $content = $this->dump_content($dn, $info);
     //Create file
     $result = create_exdir($conf->ldap->dir_temp);
     $file = $conf->ldap->dir_temp . '/ldapinput.in';
     $fp = fopen($file, "w");
     if ($fp) {
         fputs($fp, $content);
         fclose($fp);
         if (!empty($conf->global->MAIN_UMASK)) {
             @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
         }
         return 1;
     } else {
         return -1;
     }
 }
Esempio n. 14
0
			$dir[2] = "$main_data_dir/propale";
			$dir[3] = "$main_data_dir/mycompany";
			$dir[4] = "$main_data_dir/ficheinter";
			$dir[5] = "$main_data_dir/produit";
			$dir[6] = "$main_data_dir/rapport";

			// Boucle sur chaque repertoire de dir[] pour les creer s'ils nexistent pas
			for ($i = 0 ; $i < sizeof($dir) ; $i++)
			{
				if (is_dir($dir[$i]))
				{
					dolibarr_install_syslog("etape1: Directory '".$dir[$i]."' exists");
				}
				else
				{
					if (create_exdir($dir[$i]) < 0)
					{
						print "<tr><td>";
						print "Failed to create directory: ".$dir[$i];
						print '</td><td>';
						print $langs->trans("Error");
						print "</td></tr>";
						$error++;
					}
					else
					{
						dolibarr_install_syslog("etape1: Directory '".$dir[$i]."' created");
					}
				}
			}
			if ($error)
Esempio n. 15
0
    /**
     *      Function called when module is enabled.
     *      The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database.
     *      It also creates data directories.
     *      @return     int             1 if OK, 0 if KO
     */
	function init($options='')
	{
		global $conf;

		// We disable this to prevent pb of modules not correctly disabled
		//$this->remove($options);

		require_once(DOL_DOCUMENT_ROOT.'/lib/files.lib.php');
		$dirodt=DOL_DATA_ROOT.'/doctemplates/thirdparties';
		create_exdir($dirodt);
		dol_copy(DOL_DOCUMENT_ROOT.'/install/doctemplates/thirdparties/template_thirdparty.odt',$dirodt.'/template_thirdparty.odt',0,0);

		$sql = array();

		return $this->_init($sql,$options);
	}
Esempio n. 16
0
 /**
  *    \brief      Deplace fichier uploade sous le nom $files dans le repertoire sdir
  *    \param      sdir        Repertoire destination finale
  *    \param      $file       Nom du fichier uploade
  *    \param      maxWidth    Largeur maximum que dois faire la miniature (160 par defaut)
  *    \param      maxHeight   Hauteur maximum que dois faire la miniature (120 par defaut)
  */
 function add_photo($sdir, $file, $maxWidth = 160, $maxHeight = 120)
 {
     require_once DOL_DOCUMENT_ROOT . "/lib/files.lib.php";
     $dir = $sdir . '/' . get_exdir($this->id, 2) . $this->id . "/";
     $dir .= "photos/";
     if (!file_exists($dir)) {
         create_exdir($dir);
     }
     if (file_exists($dir)) {
         $originImage = $dir . $file['name'];
         // Cree fichier en taille origine
         $result = dol_move_uploaded_file($file['tmp_name'], $originImage, 1, 0, 0);
         if (file_exists($originImage)) {
             // Cree fichier en taille vignette
             $this->add_thumb($originImage, $maxWidth, $maxHeight);
         }
     }
 }
Esempio n. 17
0
	/**
	 *	Fonction generant le bon de livraison sur le disque
	 *	@param	    object   		Object livraison a generer
	 *	@param		outputlangs		Lang output object
	 *	@return	    int         	1 if OK, <=0 if KO
	 */
	function write_file($object,$outputlangs)
	{
		global $user,$langs,$conf;
		$default_font_size = pdf_getPDFFontSize($outputlangs);

		if (! is_object($outputlangs)) $outputlangs=$langs;
		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
		if (!class_exists('TCPDF')) $outputlangs->charset_output='ISO-8859-1';

		$outputlangs->load("main");
		$outputlangs->load("dict");
		$outputlangs->load("companies");
		$outputlangs->load("bills");
		$outputlangs->load("products");
		$outputlangs->load("deliveries");
		$outputlangs->load("sendings");

		if ($conf->expedition->dir_output."/receipt")
		{
			$object->fetch_thirdparty();

			$nblines = sizeof($object->lines);

			$objectref = dol_sanitizeFileName($object->ref);
			$dir = $conf->expedition->dir_output."/receipt";
			if (! preg_match('/specimen/i',$objectref)) $dir.= "/" . $objectref;
			$file = $dir . "/" . $objectref . ".pdf";

			if (! file_exists($dir))
			{
				if (create_exdir($dir) < 0)
				{
					$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
					return 0;
				}
			}

			if (file_exists($dir))
			{
                $pdf=pdf_getInstance($this->format);

                if (class_exists('TCPDF'))
                {
                    $pdf->setPrintHeader(false);
                    $pdf->setPrintFooter(false);
                }
                $pdf->SetFont(pdf_getPDFFont($outputlangs));

				// Complete object by loading several other informations
				$expedition=new Expedition($this->db);
				$result = $expedition->fetch($object->expedition_id);

				$commande = new Commande($this->db);
				if ($expedition->origin == 'commande')
				{
					$commande->fetch($expedition->origin_id);
				}
				$object->commande=$commande;


				$pdf->Open();
				$pagenb=0;
				$pdf->SetDrawColor(128,128,128);

				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
				$pdf->SetSubject($outputlangs->transnoentities("DeliveryOrder"));
				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("DeliveryOrder"));
				if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);

				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
				$pdf->SetAutoPageBreak(1,0);

				/*
				 // Positionne $this->atleastonediscount si on a au moins une remise
				 for ($i = 0 ; $i < $nblignes ; $i++)
				 {
				 if ($object->lines[$i]->remise_percent)
				 {
				 $this->atleastonediscount++;
				 }
				 }
				 */

				// New page
				$pdf->AddPage();
				$pagenb++;
				$this->_pagehead($pdf, $object, 1, $outputlangs);
				$pdf->SetFont('','', $default_font_size - 1);
				$pdf->MultiCell(0, 3, '');		// Set interline to 3
				$pdf->SetTextColor(0,0,0);

				$tab_top = 90;
				$tab_top_newpage = 50;
				$tab_height = 110;
				$tab_height_newpage = 150;

				// Affiche notes
				if (! empty($object->note_public))
				{
					$tab_top = 88;

					$pdf->SetFont('','', $default_font_size - 1);   // Dans boucle pour gerer multi-page
					$pdf->SetXY ($this->posxdesc-1, $tab_top);
					$pdf->MultiCell(190, 3, $outputlangs->convToOutputCharset($object->note_public), 0, 'L');
					$nexY = $pdf->GetY();
					$height_note=$nexY-$tab_top;

					// Rect prend une longueur en 3eme param
					$pdf->SetDrawColor(192,192,192);
					$pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1);

					$tab_height = $tab_height - $height_note;
					$tab_top = $nexY+6;
				}
				else
				{
					$height_note=0;
				}

				$iniY = $tab_top + 7;
				$curY = $tab_top + 7;
				$nexY = $tab_top + 7;

				// Boucle sur les lignes
				for ($i = 0 ; $i < $nblines ; $i++)
				{
					$curY = $nexY;

                    $pdf->SetFont('','', $default_font_size - 1);   // Dans boucle pour gerer multi-page

                    // Description de la ligne produit
					//$libelleproduitservice=pdf_getlinedesc($object,$i,$outputlangs);
					pdf_writelinedesc($pdf,$object,$i,$outputlangs,108,3,$this->posxdesc-1,$curY);
					//$pdf->writeHTMLCell(108, 3, $this->posxdesc-1, $curY, $outputlangs->convToOutputCharset($libelleproduitservice), 0, 1);

					$pdf->SetFont('','', $default_font_size - 1);   // On repositionne la police par defaut
					$nexY = $pdf->GetY();

					/*
					 // TVA
					 $pdf->SetXY ($this->posxtva, $curY);
					 $pdf->MultiCell(10, 4, ($object->lines[$i]->tva_tx < 0 ? '*':'').abs($object->lines[$i]->tva_tx), 0, 'R');

					 // Prix unitaire HT avant remise
					 $pdf->SetXY ($this->posxup, $curY);
					 $pdf->MultiCell(20, 4, price($object->lines[$i]->subprice), 0, 'R', 0);
					 */
					// Quantity
					$pdf->SetXY ($this->posxqty, $curY);
					$pdf->MultiCell(30, 3, $object->lines[$i]->qty_shipped, 0, 'R');
					/*
					 // Remise sur ligne
					 $pdf->SetXY ($this->posxdiscount, $curY);
					 if ($object->lines[$i]->remise_percent)
					 {
					 $pdf->MultiCell(14, 3, $object->lines[$i]->remise_percent."%", 0, 'R');
					 }

					 // Total HT ligne
					 $pdf->SetXY ($this->postotalht, $curY);
					 $total = price($object->lines[$i]->price * $object->lines[$i]->qty);
					 $pdf->MultiCell(23, 3, $total, 0, 'R', 0);

					 // Collecte des totaux par valeur de tva
					 // dans le tableau tva["taux"]=total_tva
					 $tvaligne=$object->lines[$i]->price * $object->lines[$i]->qty;
					 if ($object->remise_percent) $tvaligne-=($tvaligne*$object->remise_percent)/100;
					 $this->tva[ (string)$object->lines[$i]->tva_tx ] += $tvaligne;
					 */
					$nexY+=2;    // Passe espace entre les lignes

					// Cherche nombre de lignes a venir pour savoir si place suffisante
					if ($i < ($nblines - 1) && empty($hidedesc))	// If it's not last line
					{
						//on recupere la description du produit suivant
						$follow_descproduitservice = $object->lines[$i+1]->desc;
						//on compte le nombre de ligne afin de verifier la place disponible (largeur de ligne 52 caracteres)
						$nblineFollowDesc = (dol_nboflines_bis($follow_descproduitservice,52,$outputlangs->charset_output)*4);
					}
					else	// If it's last line
					{
						$nblineFollowDesc = 0;
					}

					// Test if a new page is required
					if ($pagenb == 1)
					{
						$tab_top_in_current_page=$tab_top;
						$tab_height_in_current_page=$tab_height;
					}
					else
					{
						$tab_top_in_current_page=$tab_top_newpage;
						$tab_height_in_current_page=$tab_height_newpage;
					}
					if (($nexY+$nblineFollowDesc) > ($tab_top_in_current_page+$tab_height_in_current_page) && $i < ($nblignes - 1))
					{
						if ($pagenb == 1)
						{
							$this->_tableau($pdf, $tab_top, $tab_height + 20, $nexY, $outputlangs);
						}
						else
						{
							$this->_tableau($pdf, $tab_top_newpage, $tab_height_newpage, $nexY, $outputlangs);
						}

						$this->_pagefoot($pdf, $object, $outputlangs);

						// New page
						$pdf->AddPage();
						$pagenb++;
						$this->_pagehead($pdf, $object, 0, $outputlangs);
						$pdf->SetFont('','', $default_font_size - 1);
						$pdf->MultiCell(0, 3, '');		// Set interline to 3
						$pdf->SetTextColor(0,0,0);

						$nexY = $tab_top_newpage + 7;
					}
				}

				// Show square
				if ($pagenb == 1)
				{
					$this->_tableau($pdf, $tab_top, $tab_height, $nexY, $outputlangs);
					$bottomlasttab=$tab_top + $tab_height + 1;
				}
				else
				{
					$this->_tableau($pdf, $tab_top_newpage, $tab_height_newpage, $nexY, $outputlangs);
					$bottomlasttab=$tab_top_newpage + $tab_height_newpage + 1;
				}


				/*
				 * Pied de page
				 */
				$this->_pagefoot($pdf,$object,$outputlangs);

				// Check product remaining to be delivered
				// TODO doit etre modifie
				//$waitingDelivery = $object->getRemainingDelivered();

				if (is_array($waitingDelivery) & !empty($waitingDelivery))
				{
					$pdf->AddPage('P', 'A4');

					$this->_pagehead($pdf, $object, 1, $outputlangs);
					$pdf-> SetY(90);

					$w=array(40,100,50);
					$header=array($outputlangs->transnoentities('Reference'),
								  $outputlangs->transnoentities('Label'),
								  $outputlangs->transnoentities('Qty')
								  );

    				// Header
   					for($i=0;$i<count($header);$i++)
   					{
   						$pdf->Cell($w[$i],7,$header[$i],1,0,'C');
   					}

			    	$pdf->Ln();

			    	// Data
					foreach($waitingDelivery as $value)
					{
						$pdf->Cell($w[0], 6, $value['ref'], 1, 0, 'L');
						$pdf->Cell($w[1], 6, $value['label'], 1, 0, 'L');
						$pdf->Cell($w[2], 6, $value['qty'], 1, 1, 'R');

						if ($pdf->GetY() > 250)
						{
							$this->_pagefoot($pdf,$object,$outputlangs);

							$pdf->AddPage('P', 'A4');

							$pdf->SetFont('','', $default_font_size - 1);
							$this->_pagehead($pdf, $object, 0, $outputlangs);

							$pdf-> SetY(40);

							for($i=0;$i<count($header);$i++)
							{
								$pdf->Cell($w[$i],7,$header[$i],1,0,'C');
							}

							$pdf->Ln();
						}
					}

					$this->_pagefoot($pdf,$object,$outputlangs);

				}

				$pdf->AliasNbPages();

				$pdf->Close();

				$pdf->Output($file,'F');
				if (! empty($conf->global->MAIN_UMASK))
				@chmod($file, octdec($conf->global->MAIN_UMASK));

				return 1;   // Pas d'erreur
			}
			else
			{
				$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
				return 0;
			}
		}

		$this->error=$langs->transnoentities("ErrorConstantNotDefined","LIVRAISON_OUTPUTDIR");
		return 0;
	}
Esempio n. 18
0
	/**
	 *  Deplace fichier recupere sur internet (utilise pour interface avec OSC)
	 *  @param      sdir        		Repertoire destination finale
	 *  @param      $files      		url de l'image
	 *	@author	  Jean Heimburger	june 2007
	 */
	function add_photo_web($sdir, $file)
	{
		$dir = $sdir .'/'. get_exdir($this->id,2) . $this->id ."/";
		$dir .= "photos/";

		$dir_osencoded=dol_osencode($dir);
		if (! file_exists($dir_osencoded))
		{
			dol_syslog("Product Create ".$dir);
			create_exdir($dir);
		}

		if (file_exists($dir_osencoded))
		{
			// Cree fichier en taille vignette
			// \todo A faire

			// Cree fichier en taille origine
			$content = @file_get_contents($file);
			if( $content)
			{
				$nom = basename($file);
				$im = fopen(dol_osencode($dir.$nom),'wb');
				fwrite($im, $content);
				fclose($im);
			}
		}
	}
Esempio n. 19
0
	/**
     *  Function to build pdf onto disk
     *  @param      object          Id of object to generate
     *  @param      outputlangs     Lang output object
     *  @param      srctemplatepath Full path of source filename for generator using a template file
     *  @param      hidedetails     Do not show line details
     *  @param      hidedesc        Do not show desc
     *  @param      hideref         Do not show ref
     *  @return     int             1=OK, 0=KO
	 */
	function write_file($object,$outputlangs,$srctemplatepath='',$hidedetails=0,$hidedesc=0,$hideref=0)
	{
		global $user,$conf,$langs,$mysoc;

		if (! is_object($outputlangs)) $outputlangs=$langs;
		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
		if (!class_exists('TCPDF')) $outputlangs->charset_output='ISO-8859-1';

		$outputlangs->load("main");
		$outputlangs->load("dict");
		$outputlangs->load("companies");
		$outputlangs->load("bills");
		$outputlangs->load("products");
        $outputlangs->load("orders");

		$default_font_size = pdf_getPDFFontSize($outputlangs);

		if ($conf->commande->dir_output)
		{
			// Definition of $dir and $file
			if ($object->specimen)
			{
				$dir = $conf->commande->dir_output;
				$file = $dir . "/SPECIMEN.pdf";
			}
			else
			{
				$objectref = dol_sanitizeFileName($object->ref);
				$dir = $conf->commande->dir_output . "/" . $objectref;
				$file = $dir . "/" . $objectref . ".pdf";
			}

			if (! file_exists($dir))
			{
				if (create_exdir($dir) < 0)
				{
					$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
					return 0;
				}
			}

			if (file_exists($dir))
			{
                $pdf=pdf_getInstance($this->format);

                if (class_exists('TCPDF'))
                {
                    $pdf->setPrintHeader(false);
                    $pdf->setPrintFooter(false);
                }
                $pdf->SetFont(pdf_getPDFFont($outputlangs));

				$pdf->Open();
				$pagenb=0;
				$pdf->SetDrawColor(128,128,128);

				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
				$pdf->SetSubject($outputlangs->transnoentities("Order"));
				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Order"));
				if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);

				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
				$pdf->SetAutoPageBreak(1,0);

				// New page
				$pdf->AddPage();
				$pagenb++;
				$this->_pagehead($pdf, $object, 1, $outputlangs);
				$pdf->SetFont('','', $default_font_size - 1);
				$pdf->MultiCell(0, 3, '');		// Set interline to 3
				$pdf->SetTextColor(0,0,0);


				$tab_top = 100;
				$tab_height = 140;

				$pdf->SetFillColor(220,220,220);

				$pdf->SetTextColor(0,0,0);
				$pdf->SetFont('','', $default_font_size - 1);

				$pdf->SetXY (10, $tab_top + 10 );

				$iniY = $pdf->GetY();
				$curY = $pdf->GetY();
				$nexY = $pdf->GetY();
				$nblignes = sizeof($object->lines);

				for ($i = 0 ; $i < $nblignes ; $i++)
				{
					$curY = $nexY;

					$pdf->SetFont('','', $default_font_size - 1);   // Dans boucle pour gerer multi-page

					// Description de la ligne produit
					pdf_writelinedesc($pdf,$object,$i,$outputlangs,100,3,30,$curY,1,$hidedesc);
					//$pdf->writeHTMLCell(100, 3, 30, $curY, $outputlangs->convToOutputCharset($libelleproduitservice), 0, 1);

					$pdf->SetFont('','', $default_font_size - 1);   // On repositionne la police par defaut
					$nexY = $pdf->GetY();

					$ref = pdf_getlineref($object, $i, $outputlangs);
					$pdf->SetXY (10, $curY);
					$pdf->MultiCell(20, 3, $ref, 0, 'C');

					$vat_rate = pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails);
					$pdf->SetXY (133, $curY);
					$pdf->MultiCell(12, 3, $vat_rate, 0, 'C');

					$qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails);
					$pdf->SetXY (145, $curY);
					$pdf->MultiCell(10, 3, $qty, 0, 'C');

					$up_excl_tax = pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails);
					$pdf->SetXY (156, $curY);
					$pdf->MultiCell(18, 3, $up_excl_tax, 0, 'R', 0);

					$total_excl_tax = pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails);
					$pdf->SetXY (174, $curY);
					$pdf->MultiCell(26, 3, $total_excl_tax, 0, 'R', 0);

					$nexY+=2;    // Passe espace entre les lignes

					// cherche nombre de lignes a venir pour savoir si place suffisante
					if ($i < ($nblignes - 1) && empty($hidedesc))	// If it's not last line
					{
						//on recupere la description du produit suivant
						$follow_descproduitservice = $object->lines[$i+1]->desc;
						//on compte le nombre de ligne afin de verifier la place disponible (largeur de ligne 52 caracteres)
						$nblineFollowDesc = (dol_nboflines_bis($follow_descproduitservice,52,$outputlangs->charset_output)*4);
					}
					else	// If it's last line
					{
						$nblineFollowDesc = 0;
					}

					if (($nexY+$nblineFollowDesc) > ($tab_top+$tab_height) && $i < ($nblignes - 1))
					{
						$this->_tableau($pdf, $tab_top, $tab_height, $nexY, $outputlangs);

						// New page
						$pdf->AddPage();
						$pagenb++;
						$this->_pagehead($pdf, $object, 0, $outputlangs);
						$pdf->SetFont('','', $default_font_size - 1);
						$pdf->MultiCell(0, 3, '');		// Set interline to 3
						$pdf->SetTextColor(0,0,0);

						$nexY = $tab_top + 8;
					}
				}

				$this->_tableau($pdf, $tab_top, $tab_height, $nexY, $outputlangs);

				$bottomlasttab=$tab_top + $tab_height + 1;

				// Affiche zone infos
				$this->_tableau_info($pdf, $object, $bottomlasttab, $outputlangs);

				// Affiche zone totaux
				$tab2_top = 241;
				$tab2_lh = 4;

				$pdf->SetFont('','', $default_font_size);

				$pdf->SetXY (132, $tab2_top + 0);
				$pdf->MultiCell(42, $tab2_lh, $langs->transnoentities("TotalHT"), 0, 'R', 0);

				$pdf->SetXY (132, $tab2_top + $tab2_lh);
				$pdf->MultiCell(42, $tab2_lh, $langs->transnoentities("TotalVAT"), 0, 'R', 0);

				$pdf->SetXY (132, $tab2_top + ($tab2_lh*2));
				$pdf->MultiCell(42, $tab2_lh, $langs->transnoentities("TotalTTC"), 1, 'R', 1);

				$pdf->SetXY (174, $tab2_top + 0);
				$pdf->MultiCell(26, $tab2_lh, price($object->total_ht), 0, 'R', 0);

				$pdf->SetXY (174, $tab2_top + $tab2_lh);
				$pdf->MultiCell(26, $tab2_lh, price($object->total_tva), 0, 'R', 0);

				$pdf->SetXY (174, $tab2_top + ($tab2_lh*2));
				$pdf->MultiCell(26, $tab2_lh, price($object->total_ttc), 1, 'R', 1);

				// Pied de page
				$this->_pagefoot($pdf,$object,$outputlangs);
				$pdf->AliasNbPages();

				$pdf->Close();

				$pdf->Output($file,'F');
				if (! empty($conf->global->MAIN_UMASK))
					@chmod($file, octdec($conf->global->MAIN_UMASK));

				return 1;
			}
		}
		else
		{
			$this->error=$langs->transnoentities("ErrorConstantNotDefined","COMMANDE_OUTPUTDIR");
			return 0;
		}

		$this->error=$langs->transnoentities("ErrorUnknown");
		return 0;   // Erreur par defaut
	}
    /**
     *  Create directories required by module
     *  @return     int     Nb of errors (0 if OK)
     */
    function create_dirs()
    {
        global $langs, $conf;

        $err=0;

        if (is_array($this->dirs))
        {
            foreach ($this->dirs as $key => $value)
            {
                $addtodatabase=0;

                if (! is_array($value)) $dir=$value;    // Default simple mode
                else {
                    $constname = $this->const_name."_DIR_";
                    $dir       = $this->dirs[$key][1];
                    $addtodatabase = empty($this->dirs[$key][2])?'':$this->dirs[$key][2]; // Create constante in llx_const
                    $subname   = empty($this->dirs[$key][3])?'':strtoupper($this->dirs[$key][3]); // Add submodule name (ex: $conf->module->submodule->dir_output)
                    $forcename = empty($this->dirs[$key][4])?'':strtoupper($this->dirs[$key][4]); // Change the module name if different

                    if ($forcename) $constname = 'MAIN_MODULE_'.$forcename."_DIR_";
                    if ($subname)   $constname = $constname.$subname."_";

                    $name      = $constname.strtoupper($this->dirs[$key][0]);
                }

                // Define directory full path ($dir must start with "/")
                if (empty($conf->global->MAIN_MODULE_MULTICOMPANY) || $conf->entity == 1) $fulldir = DOL_DATA_ROOT.$dir;
                else $fulldir = DOL_DATA_ROOT."/".$conf->entity.$dir;
                // Create dir if it does not exists
                if ($fulldir && ! file_exists($fulldir))
                {
                    if (create_exdir($fulldir) < 0)
                    {
                        $this->error = $langs->trans("ErrorCanNotCreateDir",$fulldir);
                        dol_syslog(get_class($this)."::_init ".$this->error, LOG_ERR);
                        $err++;
                    }
                }

                // Define the constant in database if requested (not the default mode)
                if ($addtodatabase)
                {
                    $result = $this->insert_dirs($name,$dir);
                    if ($result) $err++;
                }
            }
        }

        return $err;
    }
Esempio n. 21
0
	/**
	 *  Fonction appelee lors de l'activation du module. Insere en base les constantes, boites, permissions du module.
	 *  Definit egalement les repertoires de donnees a creer pour ce module.
	 *	@param		options		Options when enabling module
	 */
	function init($options='')
	{
		global $conf;

		// Remove permissions and default values
		$this->remove($options);

		require_once(DOL_DOCUMENT_ROOT.'/lib/files.lib.php');
		$dirodt=DOL_DATA_ROOT.'/doctemplates/invoices';
		create_exdir($dirodt);
		dol_copy(DOL_DOCUMENT_ROOT.'/install/doctemplates/invoices/template_invoice.odt',$dirodt.'/template_invoice.odt',0,0);

		$sql = array(
			 "DELETE FROM ".MAIN_DB_PREFIX."document_model WHERE nom = '".$this->const[0][2]."' AND entity = ".$conf->entity,
			 "INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity) VALUES('".$this->const[0][2]."','invoice',".$conf->entity.")",
		);

		return $this->_init($sql,$options);
	}
Esempio n. 22
0
		{
            print "Merge PDF file for invoice ".$file."\n";

			// 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
		create_exdir($diroutputpdf);

		// Save merged file
		$filename='mergedpdf';

		if (! empty($option)) $filename.='_'.$option;

		if ($pagecount)
		{
			$file=$diroutputpdf.'/'.$filename.'.pdf';
			$pdf->Output($file,'F');
			if (! empty($conf->global->MAIN_UMASK))
				@chmod($file, octdec($conf->global->MAIN_UMASK));
		}

		print "Merged PDF has been built in ".$file."\n";
Esempio n. 23
0
	/**
	 *		\brief      Save an image file on disk (with no output)
	 *		\param   	$code			Value to encode
	 *		\param   	$encoding		Mode of encoding
	 *		\param   	$readable		Code can be read
	 */
	function writeBarCode($code,$encoding,$readable='Y')
	{
		global $conf,$filebarcode;

		create_exdir($conf->barcode->dir_temp);

		$file=$conf->barcode->dir_temp.'/barcode_'.$code.'_'.$encoding.'.png';

		$filebarcode=$file;	// global var to be used in barcode_outimage called by barcode_print in buildBarCode

		$result=$this->buildBarCode($code,$encoding,$readable);

		return $result;
	}
Esempio n. 24
0
 /**
  *		Export events from database into a cal file.
  *		@param		format			'vcal', 'ical/ics', 'rss'
  *		@param		type			'event' or 'journal'
  *		@param		cachedelay		Do not rebuild file if date older than cachedelay seconds
  *		@param		filename		Force filename
  *		@param		filters			Array of filters
  *		@return     int     		<0 if error, nb of events in new file if ok
  */
 function build_exportfile($format, $type, $cachedelay, $filename, $filters)
 {
     global $conf, $langs, $dolibarr_main_url_root, $mysoc;
     require_once DOL_DOCUMENT_ROOT . "/lib/xcal.lib.php";
     require_once DOL_DOCUMENT_ROOT . "/lib/date.lib.php";
     dol_syslog("ActionComm::build_exportfile Build export file format=" . $format . ", type=" . $type . ", cachedelay=" . $cachedelay . ", filename=" . $filename . ", filters size=" . sizeof($filters), LOG_DEBUG);
     // Check parameters
     if (empty($format)) {
         return -1;
     }
     // Clean parameters
     if (!$filename) {
         $extension = 'vcs';
         if ($format == 'ical') {
             $extension = 'ics';
         }
         $filename = $format . '.' . $extension;
     }
     // Create dir and define output file (definitive and temporary)
     $result = create_exdir($conf->agenda->dir_temp);
     $outputfile = $conf->agenda->dir_temp . '/' . $filename;
     $result = 0;
     $buildfile = true;
     $login = '';
     $logina = '';
     $logind = '';
     $logint = '';
     $now = dol_now();
     if ($cachedelay) {
         $nowgmt = dol_now();
         include_once DOL_DOCUMENT_ROOT . '/lib/files.lib.php';
         if (dol_filemtime($outputfile) > $nowgmt - $cachedelay) {
             dol_syslog("ActionComm::build_exportfile file " . $outputfile . " is not older than now - cachedelay (" . $nowgmt . " - " . $cachedelay . "). Build is canceled");
             $buildfile = false;
         }
     }
     if ($buildfile) {
         // Build event array
         $eventarray = array();
         $sql = "SELECT a.id,";
         $sql .= " a.datep,";
         // Start
         $sql .= " a.datep2,";
         // End
         $sql .= " a.durationp,";
         $sql .= " a.datec, a.tms as datem,";
         $sql .= " a.note, a.label, a.fk_action as type_id,";
         $sql .= " a.fk_soc,";
         $sql .= " a.fk_user_author, a.fk_user_mod,";
         $sql .= " a.fk_user_action, a.fk_user_done,";
         $sql .= " a.fk_contact, a.percent as percentage,";
         $sql .= " a.fk_element, a.elementtype,";
         $sql .= " a.priority, a.fulldayevent, a.location,";
         $sql .= " u.firstname, u.name,";
         $sql .= " s.nom as socname,";
         $sql .= " c.id as type_id, c.code as type_code, c.libelle";
         $sql .= " FROM (" . MAIN_DB_PREFIX . "c_actioncomm as c, " . MAIN_DB_PREFIX . "actioncomm as a)";
         $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "user as u on u.rowid = a.fk_user_author";
         $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s on s.rowid = a.fk_soc AND s.entity IN (0, " . $conf->entity . ")";
         $sql .= " WHERE a.fk_action=c.id";
         $sql .= " AND a.entity = " . $conf->entity;
         foreach ($filters as $key => $value) {
             if ($key == 'notolderthan') {
                 $sql .= " AND a.datep >= '" . $this->db->idate($now - $value * 24 * 60 * 60) . "'";
             }
             if ($key == 'year') {
                 $sql .= " AND a.datep BETWEEN '" . $this->db->idate(dol_get_first_day($value, 1)) . "' AND '" . $this->db->idate(dol_get_last_day($value, 12)) . "'";
             }
             if ($key == 'id') {
                 $sql .= " AND a.id=" . (is_numeric($value) ? $value : 0);
             }
             if ($key == 'idfrom') {
                 $sql .= " AND a.id >= " . (is_numeric($value) ? $value : 0);
             }
             if ($key == 'idto') {
                 $sql .= " AND a.id <= " . (is_numeric($value) ? $value : 0);
             }
             if ($key == 'login') {
                 $login = $value;
                 $userforfilter = new User($this->db);
                 $result = $userforfilter->fetch('', $value);
                 $sql .= " AND (";
                 $sql .= " a.fk_user_author = " . $userforfilter->id;
                 $sql .= " OR a.fk_user_action = " . $userforfilter->id;
                 $sql .= " OR a.fk_user_done = " . $userforfilter->id;
                 $sql .= ")";
             }
             if ($key == 'logina') {
                 $logina = $value;
                 $userforfilter = new User($this->db);
                 $result = $userforfilter->fetch('', $value);
                 $sql .= " AND a.fk_user_author = " . $userforfilter->id;
             }
             if ($key == 'logint') {
                 $logint = $value;
                 $userforfilter = new User($this->db);
                 $result = $userforfilter->fetch('', $value);
                 $sql .= " AND a.fk_user_action = " . $userforfilter->id;
             }
             if ($key == 'logind') {
                 $logind = $value;
                 $userforfilter = new User($this->db);
                 $result = $userforfilter->fetch('', $value);
                 $sql .= " AND a.fk_user_done = " . $userforfilter->id;
             }
         }
         $sql .= " AND a.datep IS NOT NULL";
         // To exclude corrupted events and avoid errors in lightning/sunbird import
         $sql .= " ORDER by datep";
         //print $sql;exit;
         dol_syslog("ActionComm::build_exportfile select events sql=" . $sql);
         $resql = $this->db->query($sql);
         if ($resql) {
             // Note: Output of sql request is encoded in $conf->file->character_set_client
             while ($obj = $this->db->fetch_object($resql)) {
                 $qualified = true;
                 // 'eid','startdate','duration','enddate','title','summary','category','email','url','desc','author'
                 $event = array();
                 $event['uid'] = 'dolibarragenda-' . $this->db->database_name . '-' . $obj->id . "@" . $_SERVER["SERVER_NAME"];
                 $event['type'] = $type;
                 //$datestart=$obj->datea?$obj->datea:$obj->datep;
                 //$dateend=$obj->datea2?$obj->datea2:$obj->datep2;
                 //$duration=$obj->durationa?$obj->durationa:$obj->durationp;
                 $datestart = $this->db->jdate($obj->datep);
                 //print $datestart.'x'; exit;
                 $dateend = $this->db->jdate($obj->datep2);
                 $duration = $obj->durationp;
                 $event['summary'] = $langs->convToOutputCharset($obj->label . ($obj->socname ? " (" . $obj->socname . ")" : ""));
                 $event['desc'] = $langs->convToOutputCharset($obj->note);
                 $event['startdate'] = $datestart;
                 $event['duration'] = $duration;
                 // Not required with type 'journal'
                 $event['enddate'] = $dateend;
                 // Not required with type 'journal'
                 $event['author'] = $obj->firstname . ($obj->name ? " " . $obj->name : "");
                 $event['priority'] = $obj->priority;
                 $event['fulldayevent'] = $obj->fulldayevent;
                 $event['location'] = $langs->convToOutputCharset($obj->location);
                 $event['transparency'] = 'TRANSPARENT';
                 // OPAQUE (busy) or TRANSPARENT (not busy)
                 $event['category'] = $langs->convToOutputCharset($obj->libelle);
                 // libelle type action
                 $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', $dolibarr_main_url_root);
                 $url = $urlwithouturlroot . DOL_URL_ROOT . '/comm/action/fiche.php?id=' . $obj->id;
                 $event['url'] = $url;
                 $event['created'] = $this->db->jdate($obj->datec);
                 $event['modified'] = $this->db->jdate($obj->datem);
                 if ($qualified && $datestart) {
                     $eventarray[$datestart] = $event;
                 }
             }
         } else {
             $this->error = $this->db->lasterror();
             dol_syslog("ActionComm::build_exportfile " . $this->db->lasterror(), LOG_ERR);
             return -1;
         }
         $langs->load("agenda");
         // Define title and desc
         $more = '';
         if ($login) {
             $more = $langs->transnoentities("User") . ' ' . $langs->convToOutputCharset($login);
         }
         if ($logina) {
             $more = $langs->transnoentities("ActionsAskedBy") . ' ' . $langs->convToOutputCharset($logina);
         }
         if ($logint) {
             $more = $langs->transnoentities("ActionsToDoBy") . ' ' . $langs->convToOutputCharset($logint);
         }
         if ($logind) {
             $more = $langs->transnoentities("ActionsDoneBy") . ' ' . $langs->convToOutputCharset($logind);
         }
         if ($more) {
             $title = $langs->convToOutputCharset('Dolibarr actions ' . $mysoc->name) . ' - ' . $more;
             $desc = $more;
             $desc .= $langs->convToOutputCharset(' (' . $mysoc->name . ' - built by Dolibarr)');
         } else {
             $title = $langs->convToOutputCharset('Dolibarr actions ' . $mysoc->name);
             $desc = $langs->transnoentities('ListOfActions');
             $desc .= $langs->convToOutputCharset(' (' . $mysoc->name . ' - built by Dolibarr)');
         }
         // Create temp file
         $outputfiletmp = tempnam($conf->agenda->dir_temp, 'tmp');
         // Temporary file (allow call of function by different threads
         @chmod($outputfiletmp, octdec($conf->global->MAIN_UMASK));
         // Write file
         if ($format == 'vcal') {
             $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
         }
         if ($format == 'ical') {
             $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
         }
         if ($format == 'rss') {
             $result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp);
         }
         if ($result >= 0) {
             if (rename($outputfiletmp, $outputfile)) {
                 $result = 1;
             } else {
                 dol_syslog("ActionComm::build_exportfile failed to rename " . $outputfiletmp . " to " . $outputfile, LOG_ERR);
                 dol_delete_file($outputfiletmp, 0, 1);
                 $result = -1;
             }
         } else {
             dol_syslog("ActionComm::build_exportfile build_xxxfile function fails to for format=" . $format . " outputfiletmp=" . $outputfile, LOG_ERR);
             dol_delete_file($outputfiletmp, 0, 1);
             $langs->load("errors");
             $this->error = $langs->trans("ErrorFailToCreateFile", $outputfile);
         }
     }
     return $result;
 }
 /**
  *	Function to build a document on disk using the generic odt module.
  *
  *	@param	Societe		$object				Object source to build document
  *	@param	Translate	$outputlangs		Lang output object
  * 	@param	string		$srctemplatepath	Full path of source filename for generator using a template file
  *	@return	int         					1 if OK, <=0 if KO
  */
 function write_file($object, $outputlangs, $srctemplatepath)
 {
     global $user, $langs, $conf, $mysoc;
     if (empty($srctemplatepath)) {
         dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
         return -1;
     }
     if (!is_object($outputlangs)) {
         $outputlangs = $langs;
     }
     $sav_charset_output = $outputlangs->charset_output;
     $outputlangs->charset_output = 'UTF-8';
     $outputlangs->load("main");
     $outputlangs->load("dict");
     $outputlangs->load("companies");
     $outputlangs->load("projects");
     if ($conf->contrat->dir_output) {
         $soc = new Societe($this->db);
         $soc->fetch($object->socid);
         $dir = $conf->contrat->dir_output;
         $objectref = dol_sanitizeFileName($object->ref);
         if (!preg_match('/specimen/i', $objectref)) {
             $dir .= "/" . $objectref;
         }
         if (!file_exists($dir)) {
             if (create_exdir($dir) < 0) {
                 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
                 return -1;
             }
         }
         if (file_exists($dir)) {
             //print "srctemplatepath=".$srctemplatepath;	// Src filename
             $newfile = basename($srctemplatepath);
             $newfiletmp = preg_replace('/\\.odt/i', '', $newfile);
             $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
             $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
             $file = $dir . '/' . $newfiletmp . '.' . dol_print_date(dol_now(), '%Y%m%d%H%M%S') . '.odt';
             //print "newdir=".$dir;
             //print "newfile=".$newfile;
             //print "file=".$file;
             //print "conf->societe->dir_temp=".$conf->societe->dir_temp;
             create_exdir($conf->contrat->dir_temp);
             // If BILLING contact defined on invoice, we use it
             $usecontact = false;
             $arrayidcontact = $object->getIdContact('external', 'SALESREPSIGN');
             if (count($arrayidcontact) > 0) {
                 $usecontact = true;
                 $result = $soc->fetch_contact($arrayidcontact[0]);
             }
             // Recipient name
             if (!empty($usecontact)) {
                 // On peut utiliser le nom de la societe du contact
                 if ($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) {
                     $socobject = $object->contact;
                 } else {
                     $socobject = $soc->client;
                 }
             } else {
                 $socobject = $soc->client;
             }
             // Make substitution
             $substitutionarray = array('__FROM_NAME__' => $this->emetteur->nom, '__FROM_EMAIL__' => $this->emetteur->email, '__TOTAL_TTC__' => $object->total_ttc, '__TOTAL_HT__' => $object->total_ht, '__TOTAL_VAT__' => $object->total_vat, 'date' => dol_print_date($object->date_contrat, "%d %b %Y"));
             complete_substitutions_array($substitutionarray, $langs, $object);
             // Open and load template
             require_once ODTPHP_PATH . 'odf.php';
             $odfHandler = new odf($srctemplatepath, array('PATH_TO_TMP' => $conf->contrat->dir_temp, 'ZIP_PROXY' => 'PclZipProxy', 'DELIMITER_LEFT' => '{', 'DELIMITER_RIGHT' => '}'));
             //print $odfHandler->__toString()."\n";
             //
             foreach ($substitutionarray as $key => $value) {
                 try {
                     if (preg_match('/logo$/', $key)) {
                         //var_dump($value);exit;
                         if (file_exists($value)) {
                             $odfHandler->setImage($key, $value);
                         } else {
                             $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
                         }
                     } else {
                         //print $key.' '.$value;exit;
                         $odfHandler->setVars($key, $value, true, 'UTF-8');
                     }
                 } catch (OdfException $e) {
                 }
             }
             // Make substitutions into odt of user info
             $tmparray = $this->get_substitutionarray_user($user, $outputlangs);
             //var_dump($tmparray); exit;
             foreach ($tmparray as $key => $value) {
                 try {
                     if (preg_match('/logo$/', $key)) {
                         //var_dump($value);exit;
                         if (file_exists($value)) {
                             $odfHandler->setImage($key, $value);
                         } else {
                             $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
                         }
                     } else {
                         //print $key.' '.$value;exit;
                         $odfHandler->setVars($key, $value, true, 'UTF-8');
                     }
                 } catch (OdfException $e) {
                 }
             }
             // Make substitutions into odt of mysoc info
             $tmparray = $this->get_substitutionarray_mysoc($mysoc, $outputlangs);
             //var_dump($tmparray); exit;
             foreach ($tmparray as $key => $value) {
                 try {
                     if (preg_match('/logo$/', $key)) {
                         //var_dump($value);exit;
                         if (file_exists($value)) {
                             $odfHandler->setImage($key, $value);
                         } else {
                             $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
                         }
                     } else {
                         $odfHandler->setVars($key, $value, true, 'UTF-8');
                     }
                 } catch (OdfException $e) {
                 }
             }
             // Make substitutions into odt of thirdparty + external modules
             $tmparray = $this->get_substitutionarray_thirdparty($soc, $outputlangs);
             //complete_substitutions_array($tmparray, $langs, $object);
             //var_dump($object->id); exit;
             foreach ($tmparray as $key => $value) {
                 try {
                     if (preg_match('/logo$/', $key)) {
                         if (file_exists($value)) {
                             $odfHandler->setImage($key, $value);
                         } else {
                             $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
                         }
                     } else {
                         $odfHandler->setVars($key, $value, true, 'UTF-8');
                     }
                 } catch (OdfException $e) {
                 }
             }
             // Get extra fields for contractid
             include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
             $hookmanager = new HookManager($this->db);
             $hookmanager->callHooks(array('contrat_extrafields'));
             $parameters = array('id' => $object->id);
             $values = $hookmanager->executeHooks('getFields', $parameters, $object, GETPOST('action'));
             // Note that $action and $object may have been modified by hook
             if (is_array($values)) {
                 foreach ($values as $key => $value) {
                     try {
                         if (preg_match("/^options_/", $key)) {
                             $var = substr($key, 8, strlen($key));
                             // retire options_
                             $odfHandler->setVars($var, $values[$key], true, 'UTF-8');
                         }
                     } catch (OdfException $e) {
                     }
                 }
             }
             // Get extra fields for socid
             include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
             $hookmanager = new HookManager($this->db);
             $hookmanager->callHooks(array('thirdparty_extrafields'));
             $parameters = array('id' => $soc->id);
             $values = $hookmanager->executeHooks('getFields', $parameters, $soc, GETPOST('action'));
             // Note that $action and $object may have been modified by hook
             if (is_array($values)) {
                 foreach ($values as $key => $value) {
                     try {
                         if (preg_match("/^options_/", $key)) {
                             $var = substr($key, 8, strlen($key));
                             // retire options_
                             $odfHandler->setVars($var, $values[$key], true, 'UTF-8');
                         }
                     } catch (OdfException $e) {
                     }
                 }
             }
             // Write new file
             //$result=$odfHandler->exportAsAttachedFile('toto');
             $odfHandler->saveToDisk($file);
             if (!empty($conf->global->MAIN_UMASK)) {
                 @chmod($file, octdec($conf->global->MAIN_UMASK));
             }
             $odfHandler = null;
             // Destroy object
             return 1;
             // Success
         } else {
             $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
             return -1;
         }
     }
     return -1;
 }
	/**
     *  Function to build pdf onto disk
     *  @param      object          Id of object to generate
     *  @param      outputlangs     Lang output object
     *  @param      srctemplatepath Full path of source filename for generator using a template file
     *  @param      hidedetails     Do not show line details
     *  @param      hidedesc        Do not show desc
     *  @param      hideref         Do not show ref
     *  @return     int             1=OK, 0=KO
	 */
	function write_file($object,$outputlangs,$srctemplatepath='',$hidedetails=0,$hidedesc=0,$hideref=0)
	{
		global $user,$langs,$conf;
		$default_font_size = pdf_getPDFFontSize($outputlangs);

		if (! is_object($outputlangs)) $outputlangs=$langs;
		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
		$sav_charset_output=$outputlangs->charset_output;
		if (!class_exists('TCPDF')) $outputlangs->charset_output='ISO-8859-1';

		$outputlangs->load("main");
		$outputlangs->load("dict");
		$outputlangs->load("companies");
		$outputlangs->load("bills");
		$outputlangs->load("propal");
		$outputlangs->load("products");

		if ($conf->propale->dir_output)
		{
			$object->fetch_thirdparty();

			$deja_regle = "";

			// Definition de $dir et $file
			if ($object->specimen)
			{
				$dir = $conf->propale->dir_output;
				$file = $dir . "/SPECIMEN.pdf";
			}
			else
			{
				$objectref = dol_sanitizeFileName($object->ref);
				$dir = $conf->propale->dir_output . "/" . $objectref;
				$file = $dir . "/" . $objectref . ".pdf";
			}

			if (! file_exists($dir))
			{
				if (create_exdir($dir) < 0)
				{
					$this->error=$langs->trans("ErrorCanNotCreateDir",$dir);
					return 0;
				}
			}

			if (file_exists($dir))
			{
				$nblignes = sizeof($object->lines);

				// Create pdf instance
                $pdf=pdf_getInstance($this->format);

                if (class_exists('TCPDF'))
                {
                    $pdf->setPrintHeader(false);
                    $pdf->setPrintFooter(false);
                }
                $pdf->SetFont(pdf_getPDFFont($outputlangs));

				$pdf->Open();
				$pagenb=0;
				$pdf->SetDrawColor(128,128,128);

				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
				$pdf->SetSubject($outputlangs->transnoentities("CommercialProposal"));
				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("CommercialProposal"));
				if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);

				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
				$pdf->SetAutoPageBreak(1,0);

				// Positionne $this->atleastonediscount si on a au moins une remise
				for ($i = 0 ; $i < $nblignes ; $i++)
				{
					if ($object->lines[$i]->remise_percent)
					{
						$this->atleastonediscount++;
					}
				}

				// New page
				$pdf->AddPage();
				$pagenb++;
				$this->_pagehead($pdf, $object, 1, $outputlangs);
				$pdf->SetFont('','', $default_font_size - 1);
				$pdf->MultiCell(0, 4, '');		// Set interline to 4
				$pdf->SetTextColor(0,0,0);

				$tab_top = 90;
				$tab_top_middlepage = 50;
				$tab_top_newpage = 50;
				$tab_height = 130;
				$tab_height_middlepage = 200;
				$tab_height_endpage = 170;

				// Affiche notes
				if (! empty($object->note_public))
				{
					$tab_top = 88;

					$pdf->SetFont('','', $default_font_size - 1);   // Dans boucle pour gerer multi-page
					$pdf->SetXY ($this->posxdesc-1, $tab_top);
					$pdf->MultiCell(190, 4, $outputlangs->convToOutputCharset($object->note_public), 0, 'L');
					$nexY = $pdf->GetY();
					$height_note=$nexY-$tab_top;

					// Rect prend une longueur en 3eme param
					$pdf->SetDrawColor(192,192,192);
					$pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1);

					$tab_height = $tab_height - $height_note;
					$tab_top = $nexY+6;
				}
				else
				{
					$height_note=0;
				}

				$iniY = $tab_top + 7;
				$curY = $tab_top + 7;
				$nexY = $tab_top + 7;

				// Loop on each lines
				for ($i = 0 ; $i < $nblignes ; $i++)
				{
					$curY = $nexY;

					$pdf->SetFont('','', $default_font_size - 1);   // Dans boucle pour gerer multi-page

					// Description de la ligne produit
					$curX = $this->posxdesc-1;
					pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxtva-$curX,4,$curX,$curY,$hideref,$hidedesc);

					$pdf->SetFont('','', $default_font_size - 1);   // On repositionne la police par defaut
					$nexY = $pdf->GetY();

					// TVA
					if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT))
					{
						$vat_rate = pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails);
						$pdf->SetXY ($this->posxtva, $curY);
						$pdf->MultiCell($this->posxup-$this->posxtva-1, 4, $vat_rate, 0, 'R');
					}

					// Prix unitaire HT avant remise
					$up_excl_tax = pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails);
					$pdf->SetXY ($this->posxup, $curY);
					$pdf->MultiCell($this->posxqty-$this->posxup-1, 4, $up_excl_tax, 0, 'R', 0);

					// Quantity
					$qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails);
					$pdf->SetXY ($this->posxqty, $curY);
					$pdf->MultiCell($this->posxdiscount-$this->posxqty-1, 4, $qty, 0, 'R');

					// Remise sur ligne
					$pdf->SetXY ($this->posxdiscount, $curY);
					if ($object->lines[$i]->remise_percent)
					{
						$remise_percent = pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails);
						$pdf->MultiCell($this->postotalht-$this->posxdiscount-1, 4, $remise_percent, 0, 'R');
					}

					// Total HT ligne
					$total_excl_tax = pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails);
					$pdf->SetXY ($this->postotalht, $curY);
					$pdf->MultiCell(26, 4, $total_excl_tax, 0, 'R', 0);

					// Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva
					$tvaligne=$object->lines[$i]->total_tva;
					$localtax1ligne=$object->lines[$i]->total_localtax1;
					$localtax2ligne=$object->lines[$i]->total_localtax2;

					if ($object->remise_percent) $tvaligne-=($tvaligne*$object->remise_percent)/100;
					if ($object->remise_percent) $localtax1ligne-=($localtax1ligne*$object->remise_percent)/100;
					if ($object->remise_percent) $localtax2ligne-=($localtax2ligne*$object->remise_percent)/100;

					$vatrate=(string) $object->lines[$i]->tva_tx;
					$localtax1rate=(string) $object->lines[$i]->localtax1_tx;
					$localtax2rate=(string) $object->lines[$i]->localtax2_tx;

					if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate.='*';

					$this->tva[$vatrate] += $tvaligne;
					$this->localtax1[$localtax1rate]+=$localtax1ligne;
					$this->localtax2[$localtax2rate]+=$localtax2ligne;

					$nexY+=2;    // Passe espace entre les lignes

					// Cherche nombre de lignes a venir pour savoir si place suffisante
					if ($i < ($nblignes - 1) && empty($hidedesc))	// If it's not last line
					{
						//on recupere la description du produit suivant
						$follow_descproduitservice = $object->lines[$i+1]->desc;
						//on compte le nombre de ligne afin de verifier la place disponible (largeur de ligne 52 caracteres)
						$nblineFollowDesc = (dol_nboflines_bis($follow_descproduitservice,52,$outputlangs->charset_output)*4);
					}
					else	// If it's last line
					{
						$nblineFollowDesc = 0;
					}

					// Test if a new page is required
					if ($pagenb == 1)
					{
						$tab_top_in_current_page=$tab_top;
						$tab_height_in_current_page=$tab_height;
					}
					else
					{
						$tab_top_in_current_page=$tab_top_newpage;
						$tab_height_in_current_page=$tab_height_middlepage;
					}
					if (($nexY+$nblineFollowDesc) > ($tab_top_in_current_page+$tab_height_in_current_page) && $i < ($nblignes - 1))
					{
						if ($pagenb == 1)
						{
							$this->_tableau($pdf, $tab_top, $tab_height + 20, $nexY, $outputlangs);
						}
						else
						{
							$this->_tableau($pdf, $tab_top_newpage, $tab_height_middlepage, $nexY, $outputlangs);
						}

						$this->_pagefoot($pdf,$object,$outputlangs);

						// New page
						$pdf->AddPage();
						$pagenb++;
						$this->_pagehead($pdf, $object, 0, $outputlangs);
						$pdf->SetFont('','', $default_font_size - 1);
						$pdf->MultiCell(0, 3, '');		// Set interline to 3
						$pdf->SetTextColor(0,0,0);

						$nexY = $tab_top_newpage + 7;
					}

				}

				// Show square
				if ($pagenb == 1)
				{
					$this->_tableau($pdf, $tab_top, $tab_height, $nexY, $outputlangs);
					$bottomlasttab=$tab_top + $tab_height + 1;
				}
				else
				{
					$this->_tableau($pdf, $tab_top_newpage, $tab_height_endpage, $nexY, $outputlangs);
					$bottomlasttab=$tab_top_newpage + $tab_height_endpage + 1;
				}

				// Affiche zone infos
				$posy=$this->_tableau_info($pdf, $object, $bottomlasttab, $outputlangs);

				// Affiche zone totaux
				$posy=$this->_tableau_tot($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs);

				// Affiche zone versements
				if ($deja_regle)
				{
					$posy=$this->_tableau_versements($pdf, $object, $posy, $outputlangs);
				}

				// Pied de page
				$this->_pagefoot($pdf,$object,$outputlangs);
				$pdf->AliasNbPages();

				$pdf->Close();

				$pdf->Output($file,'F');
				if (! empty($conf->global->MAIN_UMASK))
				@chmod($file, octdec($conf->global->MAIN_UMASK));

				// Add external file
				//$pdfConcat = new concat_pdf();
				//$pdfConcat->setFiles(array($file, DOL_DOCUMENT_ROOT."/includes/modules/propale/morefile.pdf"));
				//$pdfConcat->concat();
				//$pdf->AliasNbPages();
				//$pdfConcat->Output($file,'F');

				$outputlangs->charset_output=$sav_charset_output;
				return 1;   // Pas d'erreur
			}
			else
			{
				$this->error=$langs->trans("ErrorCanNotCreateDir",$dir);
				return 0;
			}
		}
		else
		{
			$this->error=$langs->trans("ErrorConstantNotDefined","PROP_OUTPUTDIR");
			return 0;
		}

		$this->error=$langs->trans("ErrorUnknown");
		return 0;   // Erreur par defaut
	}
	/**
	 *		\brief      Fonction generant le document sur le disque
	 *		\param	    object			Objet expedition a generer (ou id si ancienne methode)
	 *		\param		outputlangs		Lang output object
	 * 	 	\return	    int     		1=ok, 0=ko
	 */
	function write_file(&$object, $outputlangs)
	{
		global $user,$conf,$langs;
		$default_font_size = pdf_getPDFFontSize($outputlangs);

		$object->fetch_thirdparty();

		if (! is_object($outputlangs)) $outputlangs=$langs;
		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
		if (!class_exists('TCPDF')) $outputlangs->charset_output='ISO-8859-1';

		$outputlangs->load("main");
		$outputlangs->load("dict");
		$outputlangs->load("companies");
		$outputlangs->load("bills");
		$outputlangs->load("products");
		$outputlangs->load("propal");
		$outputlangs->load("deliveries");
        $outputlangs->load("sendings");

		if ($conf->expedition->dir_output)
		{
			// Definition de $dir et $file
			if ($object->specimen)
			{
				$dir = $conf->expedition->dir_output."/sending";
				$file = $dir . "/SPECIMEN.pdf";
			}
			else
			{
				$expref = dol_sanitizeFileName($object->ref);
				$dir = $conf->expedition->dir_output."/sending/" . $expref;
				$file = $dir . "/" . $expref . ".pdf";
			}

			if (! file_exists($dir))
			{
				if (create_exdir($dir) < 0)
				{
					$this->error=$outputlangs->transnoentities("ErrorCanNotCreateDir",$dir);
					return 0;
				}
			}

			if (file_exists($dir))
			{
                $pdf=pdf_getInstance($this->format);

                if (class_exists('TCPDF'))
                {
                    $pdf->setPrintHeader(false);
                    $pdf->setPrintFooter(false);
                }
                $pdf->SetFont(pdf_getPDFFont($outputlangs));

				$pdf->Open();
				$pagenb=0;
				$pdf->SetDrawColor(128,128,128);

				$pdf->AliasNbPages();

				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
				$pdf->SetSubject($outputlangs->transnoentities("Sending"));
				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
				$pdf->SetKeyWords($outputlangs->convToOutputCharset($fac->ref)." ".$outputlangs->transnoentities("Sending"));
				if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);

				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
				$pdf->SetAutoPageBreak(1,0);

				// New page
				$pdf->AddPage();
				$pagenb++;
				$this->_pagehead($pdf, $object, 1, $outputlangs);
				$pdf->SetFont('','', $default_font_size - 1);
				$pdf->MultiCell(0, 3, '');		// Set interline to 3
				$pdf->SetTextColor(0,0,0);

				$tab_top = 90;
				$tab_height = 170;
				
				if (! empty($object->note_public) || ! empty($object->tracking_number))
				{
					$tab_top = 88;
					
					// Tracking number
					if (! empty($object->tracking_number))
					{
						$object->GetUrlTrackingStatus($object->tracking_number);
						if (! empty($object->tracking_url))
						{
							if ($object->expedition_method_id > 0)
							{
								// Get code using getLabelFromKey
								$code=$outputlangs->getLabelFromKey($this->db,$object->expedition_method_id,'c_shipment_mode','rowid','code');
								$label=$outputlangs->trans("LinkToTrackYourPackage")."<br>";
								$label.=$outputlangs->trans("SendingMethod".strtoupper($code))." :";
								$pdf->SetFont('','B', $default_font_size - 2);
								$pdf->writeHTMLCell(60, 4, $this->posxdesc-1, $tab_top-1, $label." ".$object->tracking_url, 0, 1, false, true, 'L');
							}
						}
					}

					// Affiche notes
					if (! empty($object->note_public))
					{
						$pdf->SetFont('','', $default_font_size - 1);   // Dans boucle pour gerer multi-page
						$pdf->SetXY ($this->posxdesc-1, $tab_top);
						$pdf->MultiCell(190, 3, $outputlangs->convToOutputCharset($object->note_public), 0, 'L');
					}
					
					$nexY = $pdf->GetY();
					$height_note=$nexY-$tab_top;

					// Rect prend une longueur en 3eme param
					$pdf->SetDrawColor(192,192,192);
					$pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1);
					
					$tab_height = $tab_height - $height_note;
					$tab_top = $nexY+6;
				}
				else
				{
					$height_note=0;
				}
				
				$this->_tableau($pdf, $tab_top, $tab_height, $nexY, $outputlangs);

				$nexY = $tab_top + 7;

				for ($i = 0 ; $i < sizeof($object->lines) ; $i++)
				{
					$curY = $nexY;

					$pdf->SetFont('','', $default_font_size - 1);   // Dans boucle pour gerer multi-page

					// Description de la ligne produit
					pdf_writelinedesc($pdf,$object,$i,$outputlangs,150,3,$this->posxdesc,$curY,0,1);

					$pdf->SetFont('','', $default_font_size - 1);   // On repositionne la police par defaut
					$nexY = $pdf->GetY();

					$pdf->SetXY ($this->posxqtyordered+5, $curY);
					$pdf->MultiCell(30, 3, $object->lines[$i]->qty_asked,'','C');

					$pdf->SetXY ($this->posxqtytoship+5, $curY);
					$pdf->MultiCell(30, 3, $object->lines[$i]->qty_shipped,'','C');

					$nexY+=2;    // Passe espace entre les lignes
				}


				// Pied de page
				$this->_pagefoot($pdf,$object,$outputlangs);
				$pdf->AliasNbPages();

				$pdf->Close();

				$pdf->Output($file,'F');
				if (! empty($conf->global->MAIN_UMASK))
				@chmod($file, octdec($conf->global->MAIN_UMASK));

				return 1;
			}
			else
			{
				$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
				return 0;
			}
		}
		else
		{
			$this->error=$langs->transnoentities("ErrorConstantNotDefined","EXP_OUTPUTDIR");
			return 0;
		}
		$this->error=$langs->transnoentities("ErrorUnknown");
		return 0;   // Erreur par defaut
	}
Esempio n. 28
0
    /**
     *  Write the object to document file to disk
     *	@param	    don	            Donation object
     *  @param      outputlangs     Lang object for output language
     *	@return	    int             >0 if OK, <0 if KO
     */
    function write_file($don,$outputlangs)
    {
		global $user,$conf,$langs,$mysoc;

		$now=gmmktime();

		if (! is_object($outputlangs)) $outputlangs=$langs;

		$outputlangs->load("main");
		$outputlangs->load("dict");
		$outputlangs->load("companies");
		$outputlangs->load("bills");
		$outputlangs->load("products");

        if ($conf->don->dir_output)
        {
			// Definition de l'objet $don (pour compatibilite ascendante)
        	if (! is_object($don))
        	{
	            $id = $don;
	            $don = new Don($this->db);
	            $ret=$don->fetch($id);
			}

			// Definition de $dir et $file
			if ($don->specimen)
			{
				$dir = $conf->don->dir_output;
				$file = $dir . "/SPECIMEN.html";
			}
			else
			{
				$donref = dol_sanitizeFileName($don->ref);
				$dir = $conf->don->dir_output . "/" . get_exdir($donref,2);
				$file = $dir . "/" . $donref . ".html";
			}

	        if (! file_exists($dir))
	        {
	            if (create_exdir($dir) < 0)
	            {
	                $this->error=$langs->trans("ErrorCanNotCreateDir",$dir);
	                return -1;
	            }
	        }

            if (file_exists($dir))
            {
		        // Defini contenu
		        $donmodel=DOL_DOCUMENT_ROOT ."/includes/modules/dons/html_cerfafr.html";
		        $html = implode('', file($donmodel));
		        $html = str_replace('__REF__',$id,$html);
		        $html = str_replace('__DATE__',dol_print_date($don->date,'day',false,$outputlangs),$html);
		        $html = str_replace('__IP__',$user->ip,$html);
		        $html = str_replace('__AMOUNT__',$don->amount,$html);
		        $html = str_replace('__CURRENCY__',$outputlangs->transnoentitiesnoconv("Currency".$conf->monnaie),$html);
		        $html = str_replace('__CURRENCYCODE__',$conf->monnaie,$html);
		        $html = str_replace('__MAIN_INFO_SOCIETE_NOM__',$mysoc->name,$html);
		        $html = str_replace('__MAIN_INFO_SOCIETE_ADRESSE__',$mysoc->address,$html);
		        $html = str_replace('__MAIN_INFO_SOCIETE_CP__',$mysoc->zip,$html);
		        $html = str_replace('__MAIN_INFO_SOCIETE_VILLE__',$mysoc->town,$html);
		        $html = str_replace('__DONATOR_NAME__',$don->nom,$html);
		        $html = str_replace('__DONATOR_ADDRESS__',$don->adresse,$html);
		        $html = str_replace('__DONATOR_ZIP__',$don->cp,$html);
		        $html = str_replace('__DONATOR_TOWN__',$don->ville,$html);
		        $html = str_replace('__PAYMENTMODE_LIB__ ',$don->modepaiement,$html);
		        $html = str_replace('__NOW__',dol_print_date($now,'',false,$outputlangs),$html);

		        // Sauve fichier sur disque
		        dol_syslog("html_cerfafr::write_file $file");
		        $handle=fopen($file,"w");
		        fwrite($handle,$html);
		        fclose($handle);
				if (! empty($conf->global->MAIN_UMASK))
					@chmod($file, octdec($conf->global->MAIN_UMASK));

		        return 1;
            }
            else
            {
                $this->error=$langs->trans("ErrorCanNotCreateDir",$dir);
                return 0;
            }
	    }
        else
        {
            $this->error=$langs->trans("ErrorConstantNotDefined","DON_OUTPUTDIR");
            return 0;
		}
        $this->error=$langs->trans("ErrorUnknown");
        return 0;   // Erreur par defaut

    }
Esempio n. 29
0
	/**
     *      Write the invoice as a document onto disk
     *      @param      object          Object invoice to build (or id if old method)
     *      @param      outputlangs     Lang object for output language
     *      @return     int             1=OK, 0=KO
	 */
	function write_file($object,$outputlangs='')
	{
		global $user,$langs,$conf,$mysoc;

		if (! is_object($outputlangs)) $outputlangs=$langs;
		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
		if (!class_exists('TCPDF')) $outputlangs->charset_output='ISO-8859-1';

		$outputlangs->load("main");
		$outputlangs->load("dict");
		$outputlangs->load("companies");
		$outputlangs->load("bills");
		$outputlangs->load("products");

		$default_font_size = pdf_getPDFFontSize($outputlangs);

		if ($conf->fournisseur->dir_output.'/facture')
		{
			$object->fetch_thirdparty();

			$deja_regle = $object->getSommePaiement();
            //$amount_credit_notes_included = $object->getSumCreditNotesUsed();
            //$amount_deposits_included = $object->getSumDepositsUsed();

			// Definition de $dir et $file
			if ($object->specimen)
			{
				$dir = $conf->fournisseur->facture->dir_output;
				$file = $dir . "/SPECIMEN.pdf";
			}
			else
			{
				$objectref = dol_sanitizeFileName($object->ref);
                $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2).$objectref;
				$file = $dir . "/" . $objectref . ".pdf";
			}

			if (! file_exists($dir))
			{
				if (create_exdir($dir) < 0)
				{
					$this->error=$langs->trans("ErrorCanNotCreateDir",$dir);
					return 0;
				}

			}

			if (file_exists($dir))
			{
				$nblignes = sizeof($object->lines);

                $pdf=pdf_getInstance($this->format);

                if (class_exists('TCPDF'))
                {
                    $pdf->setPrintHeader(false);
                    $pdf->setPrintFooter(false);
                }
                $pdf->SetFont(pdf_getPDFFont($outputlangs));

				$pdf->Open();
				$pagenb=0;
				$pdf->SetDrawColor(128,128,128);

				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
				$pdf->SetSubject($outputlangs->transnoentities("Invoice"));
				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Order"));
				if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);

				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
				$pdf->SetAutoPageBreak(1,0);

			    // Positionne $this->atleastonediscount si on a au moins une remise
                for ($i = 0 ; $i < $nblignes ; $i++)
                {
                    if ($object->lines[$i]->remise_percent)
                    {
                        $this->atleastonediscount++;
                    }
                }

                // New page
				$pdf->AddPage();
				$pagenb++;
				$this->_pagehead($pdf, $object, 1, $outputlangs);
				$pdf->SetFont('','', $default_font_size - 1);
				$pdf->MultiCell(0, 3, '');		// Set interline to 3
				$pdf->SetTextColor(0,0,0);

				$tab_top = 90;
				$tab_top_newpage = 50;
				$tab_height = 110;
				$tab_height_newpage = 150;

				// Affiche notes
				if (! empty($object->note_public))
				{
					$tab_top = 88;

					$pdf->SetFont('','', $default_font_size - 1);   // Dans boucle pour gerer multi-page
					$pdf->SetXY ($this->posxdesc-1, $tab_top);
					$pdf->MultiCell(190, 3, $outputlangs->convToOutputCharset($object->note_public), 0, 'L');
					$nexY = $pdf->GetY();
					$height_note=$nexY-$tab_top;

					// Rect prend une longueur en 3eme param
					$pdf->SetDrawColor(192,192,192);
					$pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1);

					$tab_height = $tab_height - $height_note;
					$tab_top = $nexY+6;
				}
				else
				{
					$height_note=0;
				}

				$iniY = $tab_top + 7;
				$curY = $tab_top + 7;
				$nexY = $tab_top + 7;

				// Boucle sur les lignes
				for ($i = 0 ; $i < $nblignes ; $i++)
				{
					$curY = $nexY;

                    $pdf->SetFont('','', $default_font_size - 1);   // Dans boucle pour gerer multi-page

                    // Description of product line
                    $pdf->SetFont('','', $default_font_size - 1);   // Into loop to work with multipage
                    $curX = $this->posxdesc-1;
                    pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxtva-$curX,3,$curX,$curY,0,0,1);

					$pdf->SetFont('','', $default_font_size - 1);   // On repositionne la police par defaut
					$nexY = $pdf->GetY();

					// VAT rate
                    if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT))
                    {
    					$vat_rate = pdf_getlinevatrate($object, $i, $outputlangs);
                        $pdf->SetXY ($this->posxtva, $curY);
	       				$pdf->MultiCell($this->posxup-$this->posxtva-1, 3, $vat_rate, 0, 'R');
                    }

					// Unit price before discount
					$pdf->SetXY ($this->posxup, $curY);
					$pdf->MultiCell($this->posxqty-$this->posxup-1, 3, price($object->lines[$i]->pu_ht), 0, 'R', 0);

					// Quantity
					$pdf->SetXY ($this->posxqty, $curY);
					$pdf->MultiCell($this->posxdiscount-$this->posxqty-1, 3, $object->lines[$i]->qty, 0, 'R');

					// Discount on line
					$pdf->SetXY ($this->posxdiscount, $curY);
					if ($object->lines[$i]->remise_percent)
					{
						$pdf->MultiCell($this->postotalht-$this->posxdiscount-1, 3, $object->lines[$i]->remise_percent."%", 0, 'R');
					}

					// Total HT line
                    $total_excl_tax = pdf_getlinetotalexcltax($object, $i, $outputlangs);
                    $pdf->SetXY ($this->postotalht, $curY);
                    $pdf->MultiCell(26, 3, $total_excl_tax, 0, 'R', 0);

					// Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva
					$tvaligne=$object->lines[$i]->total_tva;

					$localtax1ligne=$object->lines[$i]->total_localtax1;
					$localtax2ligne=$object->lines[$i]->total_localtax2;

					if ($object->remise_percent) $tvaligne-=($tvaligne*$object->remise_percent)/100;

					$vatrate=(string) $object->lines[$i]->tva_tx;
					$localtax1rate=(string) $object->lines[$i]->localtax1_tx;
					$localtax2rate=(string) $object->lines[$i]->localtax2_tx;

					if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate.='*';
					$this->tva[$vatrate] += $tvaligne;
					$this->localtax1[$localtax1rate]+=$localtax1ligne;
					$this->localtax2[$localtax2rate]+=$localtax2ligne;

					$nexY+=2;    // Passe espace entre les lignes

					// Test if a new page is required
					if ($pagenb == 1)
					{
						$tab_top_in_current_page=$tab_top;
						$tab_height_in_current_page=$tab_height;
					}
					else
					{
						$tab_top_in_current_page=$tab_top_newpage;
						$tab_height_in_current_page=$tab_height_newpage;
					}
					if (($nexY+$nblineFollowDesc) > ($tab_top_in_current_page+$tab_height_in_current_page) && $i < ($nblignes - 1))
					{
						if ($pagenb == 1)
						{
							$this->_tableau($pdf, $tab_top, $tab_height + 20, $nexY, $outputlangs);
						}
						else
						{
							$this->_tableau($pdf, $tab_top_newpage, $tab_height_newpage, $nexY, $outputlangs);
						}

						$this->_pagefoot($pdf, $object, $outputlangs);

						// New page
						$pdf->AddPage();
						$pagenb++;
						$this->_pagehead($pdf, $object, 0, $outputlangs);
						$pdf->SetFont('','', $default_font_size - 1);
						$pdf->MultiCell(0, 3, '');		// Set interline to 3
						$pdf->SetTextColor(0,0,0);

						$nexY = $tab_top_newpage + 7;
					}

				}

				// Show square
				if ($pagenb == 1)
				{
					$this->_tableau($pdf, $tab_top, $tab_height, $nexY, $outputlangs);
					$bottomlasttab=$tab_top + $tab_height + 1;
				}
				else
				{
					$this->_tableau($pdf, $tab_top_newpage, $tab_height_newpage, $nexY, $outputlangs);
					$bottomlasttab=$tab_top_newpage + $tab_height_newpage + 1;
				}

				// Affiche zone totaux
				$posy=$this->_tableau_tot($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs);

				if ($deja_regle || $amount_credit_notes_included || $amount_deposits_included)
				{
					$posy=$this->_tableau_versements($pdf, $object, $posy, $outputlangs);
				}

				// Pied de page
				$this->_pagefoot($pdf, $object, $outputlangs);
				$pdf->AliasNbPages();

				$pdf->Close();

				$pdf->Output($file,'F');
				if (! empty($conf->global->MAIN_UMASK))
				@chmod($file, octdec($conf->global->MAIN_UMASK));

				return 1;   // Pas d'erreur
			}
			else
			{
				$this->error=$langs->trans("ErrorCanNotCreateDir",$dir);
				return 0;
			}
		}
		else
		{
			$this->error=$langs->trans("ErrorConstantNotDefined","SUPPLIER_OUTPUTDIR");
			return 0;
		}
		$this->error=$langs->trans("ErrorUnknown");
		return 0;   // Erreur par defaut
	}
Esempio n. 30
0
	/**
     *  Function to build pdf onto disk
     *  @param      object          Id of object to generate
     *  @param      outputlangs     Lang output object
     *  @param      srctemplatepath Full path of source filename for generator using a template file
     *  @param      hidedetails     Do not show line details
     *  @param      hidedesc        Do not show desc
     *  @param      hideref         Do not show ref
     *  @return     int             1=OK, 0=KO
	 */
	function write_file($object,$outputlangs,$srctemplatepath='',$hidedetails=0,$hidedesc=0,$hideref=0)
	{
		global $user,$langs,$conf;

		if (! is_object($outputlangs)) $outputlangs=$langs;
		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
		if (!class_exists('TCPDF')) $outputlangs->charset_output='ISO-8859-1';

		$default_font_size = pdf_getPDFFontSize($outputlangs);

		$outputlangs->load("main");
		$outputlangs->load("dict");
		$outputlangs->load("companies");
		$outputlangs->load("bills");
		$outputlangs->load("products");

		if ($conf->facture->dir_output)
		{
			$object->fetch_thirdparty();

			$deja_regle = $object->getSommePaiement();
			$amount_credit_notes_included = $object->getSumCreditNotesUsed();
			$amount_deposits_included = $object->getSumDepositsUsed();

			// Definition of $dir and $file
			if ($object->specimen)
			{
				$dir = $conf->facture->dir_output;
				$file = $dir . "/SPECIMEN.pdf";
			}
			else
			{
				$objectref = dol_sanitizeFileName($object->ref);
				$dir = $conf->facture->dir_output . "/" . $objectref;
				$file = $dir . "/" . $objectref . ".pdf";
			}

			if (! file_exists($dir))
			{
				if (create_exdir($dir) < 0)
				{
					$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
					return 0;
				}
			}

			if (file_exists($dir))
			{
                $pdf=pdf_getInstance($this->format);

                if (class_exists('TCPDF'))
                {
                    $pdf->setPrintHeader(false);
                    $pdf->setPrintFooter(false);
                }
                $pdf->SetFont(pdf_getPDFFont($outputlangs));

				$pdf->Open();
				$pagenb=0;
				$pdf->SetDrawColor(128,128,128);

				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
				$pdf->SetSubject($outputlangs->transnoentities("Invoice"));
				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Invoice"));
				if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);

				$pdf->SetMargins(10, 10, 10);
				$pdf->SetAutoPageBreak(1,0);

				// New page
				$pdf->AddPage();
				$pagenb++;
				$this->_pagehead($pdf, $object, 1, $outputlangs);
				$pdf->SetFont('','', $default_font_size - 1);
				$pdf->MultiCell(0, 3, '');		// Set interline to 3
				$pdf->SetTextColor(0,0,0);

				$tab_top = $this->marges['h']+90;
				$tab_height = 110;

				$pdf->SetFillColor(220,220,220);
				$pdf->SetFont('','', $default_font_size - 1);
				$pdf->SetXY ($this->marges['g'], $tab_top + $this->marges['g'] );

				$iniY = $pdf->GetY();
				$curY = $pdf->GetY();
				$nexY = $pdf->GetY();
				$nblignes = sizeof($object->lines);

				// Loop on each lines
				for ($i = 0 ; $i < $nblignes ; $i++)
				{
					$curY = $nexY;

					// Description of product line
                    pdf_writelinedesc($pdf,$object,$i,$outputlangs,108,3,$this->posxdesc-1,$curY+1,$hideref,$hidedesc);

					$nexY = $pdf->GetY();

					// TVA
					if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT))
					{
						if ($this->franchise!=1)
						{
							$vat_rate = pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails);
							$pdf->SetXY ($this->marges['g']+118, $curY);
							$pdf->MultiCell(12, 3, $vat_rate, 0, 'R');
						}
					}

					// Prix unitaire HT avant remise
					$up_excl_tax = pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails);
					$pdf->SetXY ($this->marges['g']+132, $curY);
					$pdf->MultiCell(16, 3, $up_excl_tax, 0, 'R', 0);

					// Quantity
					$qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails);
					$pdf->SetXY ($this->marges['g']+150, $curY);
					$pdf->MultiCell(10, 3, $qty, 0, 'R');

					// Remise sur ligne
					$pdf->SetXY ($this->marges['g']+160, $curY);
					if ($object->lines[$i]->remise_percent) {
						$remise_percent = pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails);
						$pdf->MultiCell(14, 3, $remise_percent, 0, 'R');
					}

					// Total HT
					$total_excl_tax = pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails);
					$pdf->SetXY ($this->marges['g']+168, $curY);
					$pdf->MultiCell(21, 3, $total_excl_tax, 0, 'R', 0);


					if ($nexY > 200 && $i < $nblignes - 1)
					{
						$this->_tableau($pdf, $tab_top, $tab_height, $nexY, $object, $outputlangs);
						$nexY = $iniY;

						// New page
						$pdf->AddPage();
						$pagenb++;
						$this->_pagehead($pdf, $object, 0, $outputlangs);
						$pdf->SetFont('','', $default_font_size - 1);
						$pdf->MultiCell(0, 3, '');		// Set interline to 3
						$pdf->SetTextColor(0,0,0);
					}

				}
				$posy=$this->_tableau($pdf, $tab_top, $tab_height, $nexY, $object, $outputlangs);
				$bottomlasttab=$tab_top + $tab_height + 1;

				// Affiche zone infos
				$posy=$this->_tableau_info($pdf, $object, $bottomlasttab, $outputlangs);

				// Affiche zone totaux
				$posy=$this->_tableau_tot($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs);

				// Affiche zone versements
				if ($deja_regle || $amount_credit_notes_included || $amount_deposits_included)
				{
					$posy=$this->_tableau_versements($pdf, $object, $posy, $outputlangs);
				}

				// Pied de page
				$this->_pagefoot($pdf, $object, $outputlangs);
				$pdf->AliasNbPages();

				$pdf->Close();

				$pdf->Output($file,'F');
				if (! empty($conf->global->MAIN_UMASK))
				@chmod($file, octdec($conf->global->MAIN_UMASK));

				return 1;   // Pas d'erreur
			}
			else
			{
				$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
				return 0;
			}
		}
		else
		{
			$this->error=$langs->transnoentities("ErrorConstantNotDefined","FAC_OUTPUTDIR");
			return 0;
		}
		$this->error=$langs->transnoentities("ErrorUnknown");
		return 0;   // Erreur par defaut
	}