protected function invalidateUserCacheByUserId($userId)
 {
     if (empty($userId) or !is_numeric($userId)) {
         throw new InvalidArgumentException("\$userId have to be non zero integer");
     }
     if ($this->memcache != null) {
         $this->memcache->invalidateCacheByTag(self::USER_TAG . $userId);
     }
     $hookParams = array('userId' => $userId);
     HookManager::callHook("ClearUserCache", $hookParams);
 }
 /**
  * Load all plugin that have been loaded to the queue
  */
 public function load()
 {
     $this->buildAllowanceTables($this->pluginsToLoad);
     foreach ($this->pluginsToLoad as $packageName => $plugins) {
         foreach ($plugins as $pluginName) {
             $this->usePlugin($packageName, $pluginName);
         }
         HookManager::callHook("AfterThisPluginTreeInit");
         HookManager::unRegisterHook("AfterThisPluginTreeInit");
     }
     $this->customConfigs = new Config();
 }
 /**
  * Login user of given user id
  * 
  * @param integer $userId
  * @param boolean $writeCookie
  *
  * @return User
  */
 public function doLogin($userId, $additionalCredentials = array(), $writeCookie = false)
 {
     if (empty($userId) or !is_numeric($userId)) {
         throw new InvalidArgumentException("\$userId have to be non zero integer!");
     }
     $usr = $this->um->getUserById($userId);
     $this->checkIfLoginIsAllowed($usr);
     $hookParams = array("user" => $usr, "additionalCredentials" => $additionalCredentials);
     HookManager::callHook("OnUserLogin", $hookParams);
     $this->saveUserIdInSession($usr);
     $this->updateUserLastLoginDateAndIP($usr);
     if ($writeCookie) {
         $this->writeLoginCookie($usr);
     }
     return $usr;
 }
Example #4
0
 public static function getModuleExecList($hookname = null)
 {
     $ModuleExecList = array();
     if (is_null($hookname)) {
         $hookArr = self::getHookexecuteList();
     } elseif (is_array($hookname)) {
         $hookArr = $hookname;
     } elseif (strlen($hookname) > 0) {
         $hookArr = array($hookname);
     }
     $moduleArr = array();
     foreach ($hookArr as $hookname) {
         $ModuleList = HookManager::getHookModuleExecList($hookname);
         if ($ModuleList && count($ModuleList) > 0) {
             foreach ($ModuleList as $moduleObj) {
                 if (array_key_exists($moduleObj['id_module'], $moduleArr)) {
                     continue;
                 }
                 $moduleArr[$moduleObj['id_module']] = 1;
                 $ModuleExecList[] = $moduleObj;
             }
         }
     }
     return $ModuleExecList;
 }
 /**
  *	Function to build pdf onto disk
  *
  *	@param		Object		$object			Object expedition to generate (or id if old method)
  *	@param		Translate	$outputlangs		Lang output object
  *  @param		string		$srctemplatepath	Full path of source filename for generator using a template file
  *  @param		int			$hidedetails		Do not show line details
  *  @param		int			$hidedesc			Do not show desc
  *  @param		int			$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, $hookmanager;
     $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 (!empty($conf->global->MAIN_USE_FPDF)) {
         $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 (dol_mkdir($dir) < 0) {
                 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
                 return 0;
             }
         }
         if (file_exists($dir)) {
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action);
             // Note that $action and $object may have been modified by some hooks
             $nblignes = count($object->lines);
             $pdf = pdf_getInstance($this->format);
             $default_font_size = pdf_getPDFFontSize($outputlangs);
             $heightforinfotot = 0;
             // Height reserved to output the info and total part
             $heightforfreetext = isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5;
             // Height reserved to output the free text on last page
             $heightforfooter = $this->marge_basse + 8;
             // Height reserved to output the footer (value include bottom margin)
             $pdf->SetAutoPageBreak(1, 0);
             if (class_exists('TCPDF')) {
                 $pdf->setPrintHeader(false);
                 $pdf->setPrintFooter(false);
             }
             $pdf->SetFont(pdf_getPDFFont($outputlangs));
             // Set path to the background PDF File
             if (empty($conf->global->MAIN_DISABLE_FPDI) && !empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) {
                 $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output . '/' . $conf->global->MAIN_ADD_PDF_BACKGROUND);
                 $tplidx = $pdf->importPage(1);
             }
             $pdf->Open();
             $pagenb = 0;
             $pdf->SetDrawColor(128, 128, 128);
             if (method_exists($pdf, 'AliasNbPages')) {
                 $pdf->AliasNbPages();
             }
             $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
             $pdf->SetSubject($outputlangs->transnoentities("Shipment"));
             $pdf->SetCreator("Dolibarr " . DOL_VERSION);
             $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
             $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref) . " " . $outputlangs->transnoentities("Shipment"));
             if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
                 $pdf->SetCompression(false);
             }
             $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);
             // Left, Top, Right
             // New page
             $pdf->AddPage();
             if (!empty($tplidx)) {
                 $pdf->useTemplate($tplidx);
             }
             $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 = empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10;
             $tab_height = 130;
             $tab_height_newpage = 150;
             // Incoterm
             $height_incoterms = 0;
             if ($conf->incoterm->enabled) {
                 $desc_incoterms = $object->getIncotermsForPDF();
                 if ($desc_incoterms) {
                     $tab_top = 88;
                     $pdf->SetFont('', '', $default_font_size - 1);
                     $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
                     $nexY = $pdf->GetY();
                     $height_incoterms = $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_incoterms + 1);
                     $tab_top = $nexY + 6;
                     $height_incoterms += 4;
                 }
             }
             if (!empty($object->note_public) || !empty($object->tracking_number)) {
                 $tab_top = 88 + $height_incoterms;
                 $tab_top_alt = $tab_top;
                 $pdf->SetFont('', 'B', $default_font_size - 2);
                 $pdf->writeHTMLCell(60, 4, $this->posxdesc - 1, $tab_top - 1, $outputlangs->transnoentities("TrackingNumber") . " : " . $object->tracking_number, 0, 1, false, true, 'L');
                 $tab_top_alt = $pdf->GetY();
                 //$tab_top_alt += 1;
                 // Tracking number
                 if (!empty($object->tracking_number)) {
                     $object->GetUrlTrackingStatus($object->tracking_number);
                     if (!empty($object->tracking_url)) {
                         if ($object->shipping_method_id > 0) {
                             // Get code using getLabelFromKey
                             $code = $outputlangs->getLabelFromKey($this->db, $object->shipping_method_id, 'c_shipment_mode', 'rowid', 'code');
                             $label = '';
                             if ($object->tracking_url != $object->tracking_number) {
                                 $label .= $outputlangs->trans("LinkToTrackYourPackage") . "<br>";
                             }
                             $label .= $outputlangs->trans("SendingMethod") . ": " . $outputlangs->trans("SendingMethod" . strtoupper($code));
                             //var_dump($object->tracking_url != $object->tracking_number);exit;
                             if ($object->tracking_url != $object->tracking_number) {
                                 $label .= " : ";
                                 $label .= $object->tracking_url;
                             }
                             $pdf->SetFont('', 'B', $default_font_size - 2);
                             $pdf->writeHTMLCell(60, 4, $this->posxdesc - 1, $tab_top_alt, $label, 0, 1, false, true, 'L');
                             $tab_top_alt = $pdf->GetY();
                         }
                     }
                 }
                 // Notes
                 if (!empty($object->note_public)) {
                     $pdf->SetFont('', '', $default_font_size - 1);
                     // Dans boucle pour gerer multi-page
                     $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top_alt, dol_htmlentitiesbr($object->note_public), 0, 1);
                 }
                 $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;
             $num = count($object->lines);
             // Loop on each lines
             for ($i = 0; $i < $num; $i++) {
                 $curY = $nexY;
                 $pdf->SetFont('', '', $default_font_size - 1);
                 // Into loop to work with multipage
                 $pdf->SetTextColor(0, 0, 0);
                 $pdf->setTopMargin($tab_top_newpage);
                 $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot);
                 // The only function to edit the bottom margin of current page to set it.
                 $pageposbefore = $pdf->getPage();
                 // Description de la ligne produit
                 pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxqtyordered - 10, 3, $this->posxdesc, $curY, 0, 1);
                 $nexY = $pdf->GetY();
                 $pageposafter = $pdf->getPage();
                 $pdf->setPage($pageposbefore);
                 $pdf->setTopMargin($this->marge_haute);
                 $pdf->setPageOrientation('', 1, 0);
                 // The only function to edit the bottom margin of current page to set it.
                 // We suppose that a too long description is moved completely on next page
                 if ($pageposafter > $pageposbefore) {
                     $pdf->setPage($pageposafter);
                     $curY = $tab_top_newpage;
                 }
                 $pdf->SetFont('', '', $default_font_size - 1);
                 // On repositionne la police par defaut
                 $pdf->SetXY($this->posxqtyordered, $curY);
                 $pdf->MultiCell($this->posxqtytoship - $this->posxqtyordered, 3, $object->lines[$i]->qty_asked, '', 'C');
                 $pdf->SetXY($this->posxqtytoship, $curY);
                 $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxqtytoship, 3, $object->lines[$i]->qty_shipped, '', 'C');
                 // Add line
                 if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < $nblignes - 1) {
                     $pdf->setPage($pageposafter);
                     $pdf->SetLineStyle(array('dash' => '1,1', 'color' => array(210, 210, 210)));
                     //$pdf->SetDrawColor(190,190,200);
                     $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1);
                     $pdf->SetLineStyle(array('dash' => 0));
                 }
                 $nexY += 2;
                 // Passe espace entre les lignes
                 // Detect if some page were added automatically and output _tableau for past pages
                 while ($pagenb < $pageposafter) {
                     $pdf->setPage($pagenb);
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     $pagenb++;
                     $pdf->setPage($pagenb);
                     $pdf->setPageOrientation('', 1, 0);
                     // The only function to edit the bottom margin of current page to set it.
                 }
                 if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) {
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     // New page
                     $pdf->AddPage();
                     if (!empty($tplidx)) {
                         $pdf->useTemplate($tplidx);
                     }
                     $pagenb++;
                 }
             }
             // Show square
             if ($pagenb == 1) {
                 $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter - $heightforfreetext - $heightforinfotot, 0, $outputlangs, 0, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforfooter - $heightforfreetext - $heightforinfotot + 1;
             } else {
                 $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter - $heightforfreetext - $heightforinfotot, 0, $outputlangs, 1, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforfooter - $heightforfreetext - $heightforinfotot + 1;
             }
             // Pied de page
             $this->_pagefoot($pdf, $object, $outputlangs);
             if (method_exists($pdf, 'AliasNbPages')) {
                 $pdf->AliasNbPages();
             }
             $pdf->Close();
             $pdf->Output($file, 'F');
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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
 }
 /**
  *	Function to build a document on disk using the generic odt module.
  *
  *	@param		Propale		$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
  *  @param		int			$hidedetails		Do not show line details
  *  @param		int			$hidedesc			Do not show desc
  *  @param		int			$hideref			Do not show ref
  *	@return		int         					1 if OK, <=0 if KO
  */
 function write_file($object, $outputlangs, $srctemplatepath, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
 {
     global $user, $langs, $conf, $mysoc, $hookmanager;
     if (empty($srctemplatepath)) {
         dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
         return -1;
     }
     // Add odtgeneration hook
     if (!is_object($hookmanager)) {
         include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
         $hookmanager = new HookManager($this->db);
     }
     $hookmanager->initHooks(array('odtgeneration'));
     global $action;
     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("bills");
     if ($conf->supplier_proposal->dir_output) {
         // If $object is id instead of object
         if (!is_object($object)) {
             $id = $object;
             $object = new SupplierProposal($this->db);
             $result = $object->fetch($id);
             if ($result < 0) {
                 dol_print_error($this->db, $object->error);
                 return -1;
             }
         }
         $dir = $conf->supplier_proposal->dir_output;
         $objectref = dol_sanitizeFileName($object->ref);
         if (!preg_match('/specimen/i', $objectref)) {
             $dir .= "/" . $objectref;
         }
         $file = $dir . "/" . $objectref . ".odt";
         if (!file_exists($dir)) {
             if (dol_mkdir($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('/\\.od(t|s)/i', '', $newfile);
             $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
             $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
             $newfiletmp = $objectref . '_' . $newfiletmp;
             // Get extension (ods or odt)
             $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
             if (!empty($conf->global->MAIN_DOC_USE_TIMING)) {
                 $filename = $newfiletmp . '.' . dol_print_date(dol_now(), '%Y%m%d%H%M%S') . '.' . $newfileformat;
             } else {
                 $filename = $newfiletmp . '.' . $newfileformat;
             }
             $file = $dir . '/' . $filename;
             //print "newdir=".$dir;
             //print "newfile=".$newfile;
             //print "file=".$file;
             //print "conf->propal->dir_temp=".$conf->propal->dir_temp;
             dol_mkdir($conf->supplier_proposal->dir_temp);
             // If BILLING contact defined on invoice, we use it
             $usecontact = false;
             $arrayidcontact = $object->getIdContact('external', 'BILLING');
             if (count($arrayidcontact) > 0) {
                 $usecontact = true;
                 $result = $object->fetch_contact($arrayidcontact[0]);
             }
             // Recipient name
             if (!empty($usecontact)) {
                 // On peut utiliser le nom de la societe du contact
                 if (!empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) {
                     $socobject = $object->contact;
                 } else {
                     $socobject = $object->client;
                 }
             } else {
                 $socobject = $object->client;
             }
             // Make substitution
             $substitutionarray = array('__FROM_NAME__' => $this->emetteur->name, '__FROM_EMAIL__' => $this->emetteur->email, '__TOTAL_TTC__' => $object->total_ttc, '__TOTAL_HT__' => $object->total_ht, '__TOTAL_VAT__' => $object->total_vat);
             complete_substitutions_array($substitutionarray, $langs, $object);
             // Call the ODTSubstitution hook
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$substitutionarray);
             $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             // Line of free text
             $newfreetext = '';
             $paramfreetext = 'SUPPLIER_PROPOSAL_FREE_TEXT';
             if (!empty($conf->global->{$paramfreetext})) {
                 $newfreetext = make_substitutions($conf->global->{$paramfreetext}, $substitutionarray);
             }
             // Open and load template
             require_once ODTPHP_PATH . 'odf.php';
             try {
                 $odfHandler = new odf($srctemplatepath, array('PATH_TO_TMP' => $conf->supplier_proposal->dir_temp, 'ZIP_PROXY' => 'PclZipProxy', 'DELIMITER_LEFT' => '{', 'DELIMITER_RIGHT' => '}'));
             } catch (Exception $e) {
                 $this->error = $e->getMessage();
                 return -1;
             }
             // After construction $odfHandler->contentXml contains content and
             // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
             // [!-- BEGIN lines --]*[!-- END lines --]
             //print html_entity_decode($odfHandler->__toString());
             //print exit;
             // Make substitutions into odt of freetext
             try {
                 $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
             } catch (OdfException $e) {
             }
             // Make substitutions into odt
             $array_user = $this->get_substitutionarray_user($user, $outputlangs);
             $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs);
             $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs);
             $array_objet = $this->get_substitutionarray_object($object, $outputlangs);
             $array_other = $this->get_substitutionarray_other($outputlangs);
             $tmparray = array_merge($array_user, $array_soc, $array_thirdparty, $array_objet, $array_other);
             complete_substitutions_array($tmparray, $outputlangs, $object);
             // Call the ODTSubstitution hook
             $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
             $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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) {
                 }
             }
             // Replace tags of lines
             try {
                 $listlines = $odfHandler->setSegment('lines');
                 foreach ($object->lines as $line) {
                     $tmparray = $this->get_substitutionarray_lines($line, $outputlangs);
                     complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
                     // Call the ODTSubstitutionLine hook
                     $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray, 'line' => $line);
                     $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action);
                     // Note that $action and $object may have been modified by some hooks
                     foreach ($tmparray as $key => $val) {
                         try {
                             $listlines->setVars($key, $val, true, 'UTF-8');
                         } catch (OdfException $e) {
                         } catch (SegmentException $e) {
                         }
                     }
                     $listlines->merge();
                 }
                 $odfHandler->mergeSegment($listlines);
             } catch (OdfException $e) {
                 $this->error = $e->getMessage();
                 dol_syslog($this->error, LOG_WARNING);
                 return -1;
             }
             // Replace labels translated
             $tmparray = $outputlangs->get_translations_for_substitutions();
             foreach ($tmparray as $key => $value) {
                 try {
                     $odfHandler->setVars($key, $value, true, 'UTF-8');
                 } catch (OdfException $e) {
                 }
             }
             // Call the beforeODTSave hook
             $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
             $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             // Write new file
             if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
                 try {
                     $odfHandler->exportAsAttachedPDF($file);
                 } catch (Exception $e) {
                     $this->error = $e->getMessage();
                     return -1;
                 }
             } else {
                 try {
                     $odfHandler->saveToDisk($file);
                 } catch (Exception $e) {
                     $this->error = $e->getMessage();
                     return -1;
                 }
             }
             $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
             $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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;
 }
Example #7
0
// Get object canvas (By default, this is not defined, so standard usage of dolibarr)
$object->getCanvas($socid);
$canvas = $object->canvas?$object->canvas:GETPOST("canvas");
if (! empty($canvas))
{
    require_once(DOL_DOCUMENT_ROOT."/core/class/canvas.class.php");
    $objcanvas = new Canvas($db, $action);
    $objcanvas->getCanvas('thirdparty', 'card', $canvas);
}

// Security check
$result = restrictedArea($user, 'societe', $socid, '&societe', '', 'fk_soc', 'rowid', $objcanvas);

// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
include_once(DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php');
$hookmanager=new HookManager($db);
$hookmanager->initHooks(array('thirdpartycard'));


/*
 * Actions
 */

$parameters=array('id'=>$socid, 'objcanvas'=>$objcanvas);
$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
$error=$hookmanager->error; $errors=array_merge($errors, (array) $hookmanager->errors);

if (empty($reshook))
{
    if (GETPOST('getcustomercode'))
    {
Example #8
0
 /**
  *  Function to build pdf onto disk
  *
  *  @param		Object		$object				Object to generate
  *  @param		Translate	$outputlangs		Lang output object
  *  @param		string		$srctemplatepath	Full path of source filename for generator using a template file
  *  @param		int			$hidedetails		Do not show line details
  *  @param		int			$hidedesc			Do not show desc
  *  @param		int			$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, $mysoc, $hookmanager;
     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 (!empty($conf->global->MAIN_USE_FPDF)) {
         $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) {
         $object->fetch_thirdparty();
         // Definition of $dir and $file
         if ($object->specimen) {
             $dir = $conf->expedition->dir_output . "/receipt";
             $file = $dir . "/SPECIMEN.pdf";
         } else {
             $objectref = dol_sanitizeFileName($object->ref);
             $dir = $conf->expedition->dir_output . "/receipt/" . $objectref;
             $file = $dir . "/" . $objectref . ".pdf";
         }
         if (!file_exists($dir)) {
             if (dol_mkdir($dir) < 0) {
                 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
                 return 0;
             }
         }
         if (file_exists($dir)) {
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action);
             // Note that $action and $object may have been modified by some hooks
             $nblines = count($object->lines);
             // Create pdf instance
             $pdf = pdf_getInstance($this->format);
             $default_font_size = pdf_getPDFFontSize($outputlangs);
             // Must be after pdf_getInstance
             $heightforinfotot = 30;
             // Height reserved to output the info and total part
             $heightforfreetext = isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5;
             // Height reserved to output the free text on last page
             $heightforfooter = $this->marge_basse + 8;
             // Height reserved to output the footer (value include bottom margin)
             $pdf->SetAutoPageBreak(1, 0);
             if (class_exists('TCPDF')) {
                 $pdf->setPrintHeader(false);
                 $pdf->setPrintFooter(false);
             }
             $pdf->SetFont(pdf_getPDFFont($outputlangs));
             // Set path to the background PDF File
             if (empty($conf->global->MAIN_DISABLE_FPDI) && !empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) {
                 $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output . '/' . $conf->global->MAIN_ADD_PDF_BACKGROUND);
                 $tplidx = $pdf->importPage(1);
             }
             // We get the shipment that is the origin of delivery receipt
             $expedition = new Expedition($this->db);
             $result = $expedition->fetch($object->origin_id);
             // Now we get the order that is origin of shipment
             $commande = new Commande($this->db);
             if ($expedition->origin == 'commande') {
                 $commande->fetch($expedition->origin_id);
             }
             $object->commande = $commande;
             // We set order of shipment onto delivery.
             $object->commande->loadExpeditions();
             $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 (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
                 $pdf->SetCompression(false);
             }
             $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);
             // Left, Top, Right
             /*
             // Positionne $this->atleastonediscount si on a au moins une remise
             for ($i = 0 ; $i < $nblines ; $i++)
             {
              	if ($object->lines[$i]->remise_percent)
              	{
              		$this->atleastonediscount++;
              	}
             }
              				if (empty($this->atleastonediscount))
             {
             	$this->posxpicture+=($this->postotalht - $this->posxdiscount);
             	$this->posxtva+=($this->postotalht - $this->posxdiscount);
             	$this->posxup+=($this->postotalht - $this->posxdiscount);
             	$this->posxqty+=($this->postotalht - $this->posxdiscount);
             	$this->posxdiscount+=($this->postotalht - $this->posxdiscount);
             	//$this->postotalht;
             }
             */
             // New page
             $pdf->AddPage();
             if (!empty($tplidx)) {
                 $pdf->useTemplate($tplidx);
             }
             $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 = empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10;
             $tab_height = 130;
             $tab_height_newpage = 150;
             // Affiche notes
             if (!empty($object->note_public)) {
                 $tab_top = 88;
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($object->note_public), 0, 1);
                 $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 < $nblines; $i++) {
                 $curY = $nexY;
                 $pdf->SetFont('', '', $default_font_size - 1);
                 // Into loop to work with multipage
                 $pdf->SetTextColor(0, 0, 0);
                 $pdf->setTopMargin($tab_top_newpage);
                 $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot);
                 // The only function to edit the bottom margin of current page to set it.
                 $pageposbefore = $pdf->getPage();
                 // Description of product line
                 $curX = $this->posxdesc - 1;
                 $showpricebeforepagebreak = 1;
                 $pdf->startTransaction();
                 pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxcomm - $curX, 3, $curX, $curY, $hideref, $hidedesc);
                 $pageposafter = $pdf->getPage();
                 if ($pageposafter > $pageposbefore) {
                     $pdf->rollbackTransaction(true);
                     $pageposafter = $pageposbefore;
                     //print $pageposafter.'-'.$pageposbefore;exit;
                     $pdf->setPageOrientation('', 1, $heightforfooter);
                     // The only function to edit the bottom margin of current page to set it.
                     pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxcomm - $curX, 4, $curX, $curY, $hideref, $hidedesc);
                     $posyafter = $pdf->GetY();
                     if ($posyafter > $this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)) {
                         if ($i == $nblines - 1) {
                             $pdf->AddPage('', '', true);
                             if (!empty($tplidx)) {
                                 $pdf->useTemplate($tplidx);
                             }
                             if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                                 $this->_pagehead($pdf, $object, 0, $outputlangs);
                             }
                             $pdf->setPage($pageposafter + 1);
                         }
                     } else {
                         // We found a page break
                         $showpricebeforepagebreak = 0;
                     }
                 } else {
                     $pdf->commitTransaction();
                 }
                 $nexY = $pdf->GetY();
                 $pageposafter = $pdf->getPage();
                 $pdf->setPage($pageposbefore);
                 $pdf->setTopMargin($this->marge_haute);
                 $pdf->setPageOrientation('', 1, 0);
                 // The only function to edit the bottom margin of current page to set it.
                 // We suppose that a too long description is moved completely on next page
                 if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
                     $pdf->setPage($pageposafter);
                     $curY = $tab_top_newpage;
                 }
                 $pdf->SetFont('', '', $default_font_size - 1);
                 // On repositionne la police par defaut
                 /*
                 // TVA
                 $pdf->SetXY($this->posxcomm, $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
                 //$qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails);
                 $pdf->SetXY($this->posxqty, $curY);
                 $pdf->MultiCell($this->posxremainingqty - $this->posxqty, 3, $object->lines[$i]->qty_shipped, 0, 'R');
                 // Remaining to ship
                 $pdf->SetXY($this->posxremainingqty, $curY);
                 $qtyRemaining = $object->lines[$i]->qty_asked - $object->commande->expeditions[$object->lines[$i]->fk_origin_line];
                 $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxremainingqty, 3, $qtyRemaining, 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;
                 */
                 // Add line
                 if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < $nblines - 1) {
                     $pdf->setPage($pageposafter);
                     $pdf->SetLineStyle(array('dash' => '1,1', 'color' => array(210, 210, 210)));
                     //$pdf->SetDrawColor(190,190,200);
                     $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1);
                     $pdf->SetLineStyle(array('dash' => 0));
                 }
                 $nexY += 2;
                 // Passe espace entre les lignes
                 // Detect if some page were added automatically and output _tableau for past pages
                 while ($pagenb < $pageposafter) {
                     $pdf->setPage($pagenb);
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     $pagenb++;
                     $pdf->setPage($pagenb);
                     $pdf->setPageOrientation('', 1, 0);
                     // The only function to edit the bottom margin of current page to set it.
                     if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                         $this->_pagehead($pdf, $object, 0, $outputlangs);
                     }
                 }
                 if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) {
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     // New page
                     $pdf->AddPage();
                     if (!empty($tplidx)) {
                         $pdf->useTemplate($tplidx);
                     }
                     $pagenb++;
                     if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                         $this->_pagehead($pdf, $object, 0, $outputlangs);
                     }
                 }
             }
             // Show square
             if ($pagenb == 1) {
                 $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
             } else {
                 $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
             }
             // Affiche zone infos
             $this->_tableau_info($pdf, $object, $bottomlasttab, $outputlangs);
             // Pied de page
             $this->_pagefoot($pdf, $object, $outputlangs);
             if (method_exists($pdf, 'AliasNbPages')) {
                 $pdf->AliasNbPages();
             }
             // Check product remaining to be delivered
             // TODO doit etre modifie
             //$waitingDelivery = $object->getRemainingDelivered();
             /*
             				$waitingDelivery='';
             
             				if (is_array($waitingDelivery) & !empty($waitingDelivery))
             				{
             					$pdf->AddPage();
             
             					$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
                 				$num = count($header);
                					for($i = 0; $i < $num; $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,1);
             
             							$pdf->AddPage('P', 'A4');
             
             							$pdf->SetFont('','', $default_font_size - 1);
             							$this->_pagehead($pdf, $object, 0, $outputlangs);
             
             							$pdf-> SetY(40);
             
             							$num = count($header);
             							for($i = 0; $i < $num; $i++)
             							{
             								$pdf->Cell($w[$i],7,$header[$i],1,0,'C');
             							}
             
             							$pdf->Ln();
             						}
             					}
             
             					$this->_pagefoot($pdf,$object,$outputlangs);
             
             					if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();
             				}*/
             $pdf->Close();
             $pdf->Output($file, 'F');
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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;
 }
Example #9
0
 /**
  *  Function to build pdf onto disk
  *
  *  @param		Object			$object				Object to generate
  *  @param		Translate		$outputlangs		Lang output object
  *  @param		string			$srctemplatepath	Full path of source filename for generator using a template file
  *  @param		int				$hidedetails		Do not show line details
  *  @param		int				$hidedesc			Do not show desc
  *  @param		int				$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, $mysoc, $db, $hookmanager;
     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 (!empty($conf->global->MAIN_USE_FPDF)) {
         $outputlangs->charset_output = 'ISO-8859-1';
     }
     $outputlangs->load("main");
     $outputlangs->load("dict");
     $outputlangs->load("companies");
     $outputlangs->load("interventions");
     if ($conf->ficheinter->dir_output) {
         $object->fetch_thirdparty();
         // Definition of $dir and $file
         if ($object->specimen) {
             $dir = $conf->ficheinter->dir_output;
             $file = $dir . "/SPECIMEN.pdf";
         } else {
             $objectref = dol_sanitizeFileName($object->ref);
             $dir = $conf->ficheinter->dir_output . "/" . $objectref;
             $file = $dir . "/" . $objectref . ".pdf";
         }
         if (!file_exists($dir)) {
             if (dol_mkdir($dir) < 0) {
                 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
                 return 0;
             }
         }
         if (file_exists($dir)) {
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action);
             // Note that $action and $object may have been modified by some hooks
             $nblignes = count($object->lines);
             // Create pdf instance
             $pdf = pdf_getInstance($this->format);
             $default_font_size = pdf_getPDFFontSize($outputlangs);
             // Must be after pdf_getInstance
             $heightforinfotot = 50;
             // Height reserved to output the info and total part
             $heightforfreetext = isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5;
             // Height reserved to output the free text on last page
             $heightforfooter = $this->marge_basse + 8;
             // Height reserved to output the footer (value include bottom margin)
             $pdf->SetAutoPageBreak(1, 0);
             if (class_exists('TCPDF')) {
                 $pdf->setPrintHeader(false);
                 $pdf->setPrintFooter(false);
             }
             $pdf->SetFont(pdf_getPDFFont($outputlangs));
             // Set path to the background PDF File
             if (empty($conf->global->MAIN_DISABLE_FPDI) && !empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) {
                 $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output . '/' . $conf->global->MAIN_ADD_PDF_BACKGROUND);
                 $tplidx = $pdf->importPage(1);
             }
             $pdf->Open();
             $pagenb = 0;
             $pdf->SetDrawColor(128, 128, 128);
             $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
             $pdf->SetSubject($outputlangs->transnoentities("InterventionCard"));
             $pdf->SetCreator("Dolibarr " . DOL_VERSION);
             $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
             $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref) . " " . $outputlangs->transnoentities("InterventionCard"));
             if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
                 $pdf->SetCompression(false);
             }
             $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);
             // Left, Top, Right
             // New page
             $pdf->AddPage();
             if (!empty($tplidx)) {
                 $pdf->useTemplate($tplidx);
             }
             $pagenb++;
             $this->_pagehead($pdf, $object, 1, $outputlangs);
             $pdf->SetFont('', '', $default_font_size - 1);
             $pdf->SetTextColor(0, 0, 0);
             $tab_top = 90;
             $tab_top_newpage = empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10;
             $tab_height = 130;
             $tab_height_newpage = 150;
             // Affiche notes
             $notetoshow = empty($object->note_public) ? '' : $object->note_public;
             if ($notetoshow) {
                 $tab_top = 88;
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1);
                 $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;
             $pdf->SetXY($this->marge_gauche, $tab_top);
             $pdf->MultiCell(190, 5, $outputlangs->transnoentities("Description"), 0, 'L', 0);
             $pdf->line($this->marge_gauche, $tab_top + 5, $this->page_largeur - $this->marge_droite, $tab_top + 5);
             $pdf->SetFont('', '', $default_font_size - 1);
             $pdf->SetXY($this->marge_gauche, $tab_top + 5);
             $text = $object->description;
             if ($object->duree > 0) {
                 $totaltime = convertSecondToTime($object->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY);
                 $text .= ($text ? ' - ' : '') . $langs->trans("Total") . ": " . $totaltime;
             }
             $desc = dol_htmlentitiesbr($text, 1);
             //print $outputlangs->convToOutputCharset($desc); exit;
             $pdf->writeHTMLCell(180, 3, 10, $tab_top + 5, $outputlangs->convToOutputCharset($desc), 0, 1);
             $nexY = $pdf->GetY();
             $pdf->line($this->marge_gauche, $nexY, $this->page_largeur - $this->marge_droite, $nexY);
             $nblines = count($object->lines);
             // Loop on each lines
             for ($i = 0; $i < $nblines; $i++) {
                 $objectligne = $object->lines[$i];
                 $valide = empty($objectligne->id) ? 0 : $objectligne->fetch($objectligne->id);
                 if ($valide > 0 || $object->specimen) {
                     $curY = $nexY;
                     $pdf->SetFont('', '', $default_font_size - 1);
                     // Into loop to work with multipage
                     $pdf->SetTextColor(0, 0, 0);
                     $pdf->setTopMargin($tab_top_newpage);
                     $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot);
                     // The only function to edit the bottom margin of current page to set it.
                     $pageposbefore = $pdf->getPage();
                     // Description of product line
                     $curX = $this->posxdesc - 1;
                     // Description of product line
                     $txt = $outputlangs->transnoentities("Date") . " : " . dol_print_date($objectligne->datei, 'dayhour', false, $outputlangs, true);
                     if ($objectligne->duration > 0) {
                         $txt .= " - " . $outputlangs->transnoentities("Duration") . " : " . convertSecondToTime($objectligne->duration);
                     }
                     $txt = '<strong>' . dol_htmlentitiesbr($txt, 1, $outputlangs->charset_output) . '</strong>';
                     $desc = dol_htmlentitiesbr($objectligne->desc, 1);
                     $pdf->startTransaction();
                     $pdf->writeHTMLCell(0, 0, $curX, $curY + 1, dol_concatdesc($txt, $desc), 0, 1, 0);
                     $pageposafter = $pdf->getPage();
                     if ($pageposafter > $pageposbefore) {
                         $pdf->rollbackTransaction(true);
                         $pageposafter = $pageposbefore;
                         //print $pageposafter.'-'.$pageposbefore;exit;
                         $pdf->setPageOrientation('', 1, $heightforfooter);
                         // The only function to edit the bottom margin of current page to set it.
                         $pdf->writeHTMLCell(0, 0, $curX, $curY, $txt . '<br>' . $desc, LR, 1, 0);
                         $pageposafter = $pdf->getPage();
                         $posyafter = $pdf->GetY();
                         //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit;
                         if ($posyafter > $this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)) {
                             if ($i == $nblines - 1) {
                                 $pdf->AddPage('', '', true);
                                 if (!empty($tplidx)) {
                                     $pdf->useTemplate($tplidx);
                                 }
                                 if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                                     $this->_pagehead($pdf, $object, 0, $outputlangs);
                                 }
                                 $pdf->setPage($pageposafter + 1);
                             }
                         }
                     } else {
                         $pdf->commitTransaction();
                     }
                     $nexY = $pdf->GetY();
                     $pageposafter = $pdf->getPage();
                     $pdf->setPage($pageposbefore);
                     $pdf->setTopMargin($this->marge_haute);
                     $pdf->setPageOrientation('', 1, 0);
                     // The only function to edit the bottom margin of current page to set it.
                     // We suppose that a too long description is moved completely on next page
                     if ($pageposafter > $pageposbefore) {
                         $pdf->setPage($pageposafter);
                         $curY = $tab_top_newpage;
                     }
                     $pdf->SetFont('', '', $default_font_size - 1);
                     // On repositionne la police par defaut
                     // Detect if some page were added automatically and output _tableau for past pages
                     while ($pagenb < $pageposafter) {
                         $pdf->setPage($pagenb);
                         if ($pagenb == 1) {
                             $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                         } else {
                             $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                         }
                         $this->_pagefoot($pdf, $object, $outputlangs, 1);
                         $pagenb++;
                         $pdf->setPage($pagenb);
                         $pdf->setPageOrientation('', 1, 0);
                         // The only function to edit the bottom margin of current page to set it.
                         if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                             $this->_pagehead($pdf, $object, 0, $outputlangs);
                         }
                     }
                     if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) {
                         if ($pagenb == 1) {
                             $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                         } else {
                             $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                         }
                         $this->_pagefoot($pdf, $object, $outputlangs, 1);
                         // New page
                         $pdf->AddPage();
                         if (!empty($tplidx)) {
                             $pdf->useTemplate($tplidx);
                         }
                         $pagenb++;
                         if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                             $this->_pagehead($pdf, $object, 0, $outputlangs);
                         }
                     }
                 }
             }
             // Show square
             if ($pagenb == 1) {
                 $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
             } else {
                 $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
             }
             $this->_pagefoot($pdf, $object, $outputlangs);
             if (method_exists($pdf, 'AliasNbPages')) {
                 $pdf->AliasNbPages();
             }
             $pdf->Close();
             $pdf->Output($file, 'F');
             // Add pdfgeneration hook
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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", "FICHEINTER_OUTPUTDIR");
         return 0;
     }
     $this->error = $langs->trans("ErrorUnknown");
     return 0;
     // Erreur par defaut
 }
 /**
  *	Fonction generant le projet sur le disque
  *
  *	@param	Project		$object   		Object project a generer
  *	@param	Translate	$outputlangs	Lang output object
  *	@return	int         				1 if OK, <=0 if KO
  */
 function write_file($object, $outputlangs)
 {
     global $user, $langs, $conf;
     $formproject = new FormProjets($this->db);
     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 (!empty($conf->global->MAIN_USE_FPDF)) {
         $outputlangs->charset_output = 'ISO-8859-1';
     }
     $outputlangs->load("main");
     $outputlangs->load("dict");
     $outputlangs->load("companies");
     $outputlangs->load("projects");
     if ($conf->projet->dir_output) {
         //$nblignes = count($object->lines);  // This is set later with array of tasks
         $objectref = dol_sanitizeFileName($object->ref);
         $dir = $conf->projet->dir_output;
         if (!preg_match('/specimen/i', $objectref)) {
             $dir .= "/" . $objectref;
         }
         $file = $dir . "/" . $objectref . ".pdf";
         if (!file_exists($dir)) {
             if (dol_mkdir($dir) < 0) {
                 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
                 return 0;
             }
         }
         if (file_exists($dir)) {
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action);
             // Note that $action and $object may have been modified by some hooks
             $pdf = pdf_getInstance($this->format);
             $default_font_size = pdf_getPDFFontSize($outputlangs);
             // Must be after pdf_getInstance
             $heightforinfotot = 50;
             // Height reserved to output the info and total part
             $heightforfreetext = isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5;
             // Height reserved to output the free text on last page
             $heightforfooter = $this->marge_basse + 8;
             // Height reserved to output the footer (value include bottom margin)
             $pdf->SetAutoPageBreak(1, 0);
             if (class_exists('TCPDF')) {
                 $pdf->setPrintHeader(false);
                 $pdf->setPrintFooter(false);
             }
             $pdf->SetFont(pdf_getPDFFont($outputlangs));
             // Complete object by loading several other informations
             $task = new Task($this->db);
             $tasksarray = $task->getTasksArray(0, 0, $object->id);
             $object->lines = $tasksarray;
             $nblignes = count($object->lines);
             $pdf->Open();
             $pagenb = 0;
             $pdf->SetDrawColor(128, 128, 128);
             $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
             $pdf->SetSubject($outputlangs->transnoentities("Project"));
             $pdf->SetCreator("Dolibarr " . DOL_VERSION);
             $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
             $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref) . " " . $outputlangs->transnoentities("Project"));
             if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
                 $pdf->SetCompression(false);
             }
             $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);
             // Left, Top, Right
             // 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 = 50;
             $tab_height = 200;
             $tab_top_newpage = 40;
             $tab_height_newpage = 210;
             // Affiche notes
             if (!empty($object->note_public)) {
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->writeHTMLCell(190, 3, $this->posxref - 1, $tab_top - 2, dol_htmlentitiesbr($object->note_public), 0, 1);
                 $nexY = $pdf->GetY();
                 $height_note = $nexY - ($tab_top - 2);
                 // Rect prend une longueur en 3eme param
                 $pdf->SetDrawColor(192, 192, 192);
                 $pdf->Rect($this->marge_gauche, $tab_top - 3, $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;
             $listofreferent = array('propal' => array('name' => "Proposals", 'title' => "ListProposalsAssociatedProject", 'class' => 'Propal', 'table' => 'propal', 'datefieldname' => 'datep', 'test' => $conf->propal->enabled && $user->rights->propale->lire), 'order' => array('name' => "CustomersOrders", 'title' => "ListOrdersAssociatedProject", 'class' => 'Commande', 'table' => 'commande', 'datefieldname' => 'date_commande', 'test' => $conf->commande->enabled && $user->rights->commande->lire), 'invoice' => array('name' => "CustomersInvoices", 'title' => "ListInvoicesAssociatedProject", 'class' => 'Facture', 'margin' => 'add', 'table' => 'facture', 'datefieldname' => 'datef', 'test' => $conf->facture->enabled && $user->rights->facture->lire), 'invoice_predefined' => array('name' => "PredefinedInvoices", 'title' => "ListPredefinedInvoicesAssociatedProject", 'class' => 'FactureRec', 'table' => 'facture_rec', 'datefieldname' => 'datec', 'test' => $conf->facture->enabled && $user->rights->facture->lire), 'order_supplier' => array('name' => "SuppliersOrders", 'title' => "ListSupplierOrdersAssociatedProject", 'class' => 'CommandeFournisseur', 'table' => 'commande_fournisseur', 'datefieldname' => 'date_commande', 'test' => $conf->fournisseur->enabled && $user->rights->fournisseur->commande->lire), 'invoice_supplier' => array('name' => "BillsSuppliers", 'title' => "ListSupplierInvoicesAssociatedProject", 'class' => 'FactureFournisseur', 'margin' => 'minus', 'table' => 'facture_fourn', 'datefieldname' => 'datef', 'test' => $conf->fournisseur->enabled && $user->rights->fournisseur->facture->lire), 'contract' => array('name' => "Contracts", 'title' => "ListContractAssociatedProject", 'class' => 'Contrat', 'table' => 'contrat', 'datefieldname' => 'date_contrat', 'test' => $conf->contrat->enabled && $user->rights->contrat->lire), 'intervention' => array('name' => "Interventions", 'title' => "ListFichinterAssociatedProject", 'class' => 'Fichinter', 'table' => 'fichinter', 'datefieldname' => 'date_valid', 'disableamount' => 1, 'test' => $conf->ficheinter->enabled && $user->rights->ficheinter->lire), 'trip' => array('name' => "TripsAndExpenses", 'title' => "ListTripAssociatedProject", 'class' => 'Deplacement', 'table' => 'deplacement', 'datefieldname' => 'dated', 'margin' => 'minus', 'disableamount' => 1, 'test' => $conf->deplacement->enabled && $user->rights->deplacement->lire), 'agenda' => array('name' => "Agenda", 'title' => "ListActionsAssociatedProject", 'class' => 'ActionComm', 'table' => 'actioncomm', 'datefieldname' => 'datep', 'disableamount' => 1, 'test' => $conf->agenda->enabled && $user->rights->agenda->allactions->lire));
             foreach ($listofreferent as $key => $value) {
                 $title = $value['title'];
                 $classname = $value['class'];
                 $tablename = $value['table'];
                 $datefieldname = $value['datefieldname'];
                 $qualified = $value['test'];
                 if ($qualified) {
                     $elementarray = $object->get_element_list($key, $tablename, $datefieldname, $dates, $datee);
                     $num = count($elementarray);
                     if ($num > 0) {
                         $nexY = $pdf->GetY() + 5;
                         $curY = $nexY;
                         $pdf->SetXY($this->posxref, $curY);
                         $pdf->MultiCell($this->posxstatut - $this->posxref, 3, $outputlangs->transnoentities($title), 0, 'L');
                         $selectList = $formproject->select_element($tablename, $project->thirdparty->id);
                         $nexY = $pdf->GetY() + 1;
                         $curY = $nexY;
                         $pdf->SetXY($this->posxref, $curY);
                         $pdf->MultiCell($this->posxdate - $this->posxref, 3, $outputlangs->transnoentities("Ref"), 1, 'L');
                         $pdf->SetXY($this->posxdate, $curY);
                         $pdf->MultiCell($this->posxsociety - $this->posxdate, 3, $outputlangs->transnoentities("Date"), 1, 'C');
                         $pdf->SetXY($this->posxsociety, $curY);
                         $pdf->MultiCell($this->posxamountht - $this->posxsociety, 3, $outputlangs->transnoentities("ThirdParty"), 1, 'L');
                         if (empty($value['disableamount'])) {
                             $pdf->SetXY($this->posxamountht, $curY);
                             $pdf->MultiCell($this->posxamountttc - $this->posxamountht, 3, $outputlangs->transnoentities("AmountHT"), 1, 'R');
                             $pdf->SetXY($this->posxamountttc, $curY);
                             $pdf->MultiCell($this->posxstatut - $this->posxamountttc, 3, $outputlangs->transnoentities("AmountTTC"), 1, 'R');
                         } else {
                             $pdf->SetXY($this->posxamountht, $curY);
                             $pdf->MultiCell($this->posxstatut - $this->posxamountht, 3, "", 1, 'R');
                         }
                         $pdf->SetXY($this->posxstatut, $curY);
                         $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxstatut, 3, $outputlangs->transnoentities("Statut"), 1, 'R');
                         if (is_array($elementarray) && count($elementarray) > 0) {
                             $nexY = $pdf->GetY();
                             $curY = $nexY;
                             $total_ht = 0;
                             $total_ttc = 0;
                             $num = count($elementarray);
                             for ($i = 0; $i < $num; $i++) {
                                 $element = new $classname($this->db);
                                 $element->fetch($elementarray[$i]);
                                 $element->fetch_thirdparty();
                                 // print $classname;
                                 $qualifiedfortotal = true;
                                 if ($key == 'invoice') {
                                     if ($element->close_code == 'replaced') {
                                         $qualifiedfortotal = false;
                                     }
                                     // Replacement invoice
                                 }
                                 $pdf->SetXY($this->posxref, $curY);
                                 $pdf->MultiCell($this->posxdate - $this->posxref, 3, $element->ref, 1, 'L');
                                 // Date
                                 if ($tablename == 'commande_fournisseur' || $tablename == 'supplier_order') {
                                     $date = $element->date_commande;
                                 } else {
                                     $date = $element->date;
                                     if (empty($date)) {
                                         $date = $element->datep;
                                     }
                                     if (empty($date)) {
                                         $date = $element->date_contrat;
                                     }
                                     if (empty($date)) {
                                         $date = $element->datev;
                                     }
                                     // Fiche inter
                                 }
                                 $pdf->SetXY($this->posxdate, $curY);
                                 $pdf->MultiCell($this->posxsociety - $this->posxdate, 3, dol_print_date($date, 'day'), 1, 'C');
                                 $pdf->SetXY($this->posxsociety, $curY);
                                 if (is_object($element->thirdparty)) {
                                     $pdf->MultiCell($this->posxamountht - $this->posxsociety, 3, $element->thirdparty->name, 1, 'L');
                                 }
                                 // Amount without tax
                                 if (empty($value['disableamount'])) {
                                     $pdf->SetXY($this->posxamountht, $curY);
                                     $pdf->MultiCell($this->posxamountttc - $this->posxamountht, 3, isset($element->total_ht) ? price($element->total_ht) : '&nbsp;', 1, 'R');
                                     $pdf->SetXY($this->posxamountttc, $curY);
                                     $pdf->MultiCell($this->posxstatut - $this->posxamountttc, 3, isset($element->total_ttc) ? price($element->total_ttc) : '&nbsp;', 1, 'R');
                                 } else {
                                     $pdf->SetXY($this->posxamountht, $curY);
                                     $pdf->MultiCell($this->posxstatut - $this->posxamountht, 3, "", 1, 'R');
                                 }
                                 // Status
                                 if ($element instanceof CommonInvoice) {
                                     // This applies for Facture and FactureFournisseur
                                     $outputstatut = $element->getLibStatut(1, $element->getSommePaiement());
                                 } else {
                                     $outputstatut = $element->getLibStatut(1);
                                 }
                                 $pdf->SetXY($this->posxstatut, $curY);
                                 $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxstatut, 3, $outputstatut, 1, 'R', false, 1, '', '', true, 0, true);
                                 if ($qualifiedfortotal) {
                                     $total_ht = $total_ht + $element->total_ht;
                                     $total_ttc = $total_ttc + $element->total_ttc;
                                 }
                                 $nexY = $pdf->GetY();
                                 $curY = $nexY;
                             }
                             if (empty($value['disableamount'])) {
                                 $curY = $nexY;
                                 $pdf->SetXY($this->posxref, $curY);
                                 $pdf->MultiCell($this->posxamountttc - $this->posxref, 3, "TOTAL", 1, 'L');
                                 $pdf->SetXY($this->posxamountht, $curY);
                                 $pdf->MultiCell($this->posxamountttc - $this->posxamountht, 3, isset($element->total_ht) ? price($total_ht) : '&nbsp;', 1, 'R');
                                 $pdf->SetXY($this->posxamountttc, $curY);
                                 $pdf->MultiCell($this->posxstatut - $this->posxamountttc, 3, isset($element->total_ttc) ? price($total_ttc) : '&nbsp;', 1, 'R');
                                 $pdf->SetXY($this->posxstatut, $curY);
                                 $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxstatut, 3, $outputlangs->transnoentities("Nb") . " " . $num, 1, 'L');
                             }
                             $nexY = $pdf->GetY() + 5;
                             $curY = $nexY;
                         }
                     }
                 }
             }
             /*
              * Pied de page
              */
             $this->_pagefoot($pdf, $object, $outputlangs);
             if (method_exists($pdf, 'AliasNbPages')) {
                 $pdf->AliasNbPages();
             }
             $pdf->Close();
             $pdf->Output($file, 'F');
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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;
 }
 /**
  *	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;
 }
Example #12
0
require_once DOL_DOCUMENT_ROOT . "/core/class/html.formother.class.php";
require_once DOL_DOCUMENT_ROOT . "/core/class/extrafields.class.php";
$langs->load("mails");
if (!$user->rights->mailing->lire || empty($conf->global->EXTERNAL_USERS_ARE_AUTHORIZED) && $user->societe_id > 0) {
    accessforbidden();
}
$id = GETPOST('mailid', 'int') ? GETPOST('mailid', 'int') : GETPOST('id', 'int');
$action = GETPOST('action', 'alpha');
$confirm = GETPOST('confirm', 'alpha');
$urlfrom = GETPOST('urlfrom');
$object = new Mailing($db);
$result = $object->fetch($id);
$extrafields = new ExtraFields($db);
// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
$hookmanager = new HookManager($db);
$hookmanager->initHooks(array('mailingcard'));
// Tableau des substitutions possibles
$object->substitutionarray = array('__ID__' => 'IdRecord', '__CAMPAGNEID__' => 'IdCampagne', '__EMAIL__' => 'EMail', '__LASTNAME__' => 'Lastname', '__FIRSTNAME__' => 'Firstname', '__MAILTOEMAIL__' => 'MailtoEmail', '__OTHER1__' => 'Other1', '__OTHER2__' => 'Other2', '__OTHER3__' => 'Other3', '__OTHER4__' => 'Other4', '__OTHER5__' => 'Other5', '__SIGNATURE__' => 'Signature', '__PERSONALIZED__' => 'Personalized');
if ($conf->global->MAILING_EMAIL_UNSUBSCRIBE) {
    $object->substitutionarray = array_merge($object->substitutionarray, array('__CHECK_READ__' => 'CheckMail', '__UNSUBSCRIBE__' => 'Unsubscribe'));
}
$object->substitutionarrayfortest = array('__ID__' => 'TESTIdRecord', '__CAMPAGNEID' => 'TESTIdCampagne', '__EMAIL__' => 'TESTEMail', '__LASTNAME__' => 'TESTLastname', '__FIRSTNAME__' => 'TESTFirstname', '__MAILTOEMAIL__' => 'TESTMailtoEmail', '__OTHER1__' => 'TESTOther1', '__OTHER2__' => 'TESTOther2', '__OTHER3__' => 'TESTOther3', '__OTHER4__' => 'TESTOther4', '__OTHER5__' => 'TESTOther5', '__SIGNATURE__' => 'TESTSignature', '__PERSONALIZED__' => 'TESTPersonalized');
if ($conf->global->MAILING_EMAIL_UNSUBSCRIBE) {
    $object->substitutionarrayfortest = array_merge($object->substitutionarrayfortest, array('__CHECK_READ__' => 'TESTCheckMail', '__UNSUBSCRIBE__' => 'TESTUnsubscribe'));
}
/*
 * Actions
 */
$parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action);
Example #13
0
<?php

require_once STINGLE_PATH . "configs/config.inc.php";
require_once SITE_CONFIGS_PATH . "config.inc.php";
require_once STINGLE_PATH . "init/init.php";
HookManager::callHook("BeforeController");
HookManager::callHook("Controller");
HookManager::callHook("AfterController");
HookManager::callHook("InitEnd");
Example #14
0
 /**
  * Register plugin hooks
  * 
  * @throws RuntimeException
  */
 private function registerHooks()
 {
     if (isset($this->config->Hooks)) {
         foreach (get_object_vars($this->config->Hooks) as $hookName => $hookMethod) {
             if ($this->packageManager->isHookRegistrationIsAllowed($hookMethod, $this->packageName, $this->pluginName)) {
                 $hookMethodName = "hook{$hookMethod}";
                 $hook = new Hook($hookName, $hookMethodName, $this);
                 if (HookManager::isHookRegistered($hook)) {
                     throw new RuntimeException("Hook {$hookMethod} is already registered.");
                 }
                 if (method_exists($this, $hookMethodName)) {
                     HookManager::registerHook($hook);
                 } else {
                     throw new RuntimeException("Hook method of plugin {$this->pluginName} in package {$this->packageName} for hook {$hookName} -> {$hookMethodName} doesn't exists!");
                 }
             }
         }
     }
 }
Example #15
0
 /**
  *  Build document onto disk
  *
  *  @param	Object		$object         Object invoice to build (or id if old method)
  *  @param  Translate	$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 (!empty($conf->global->MAIN_USE_FPDF)) {
         $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 (dol_mkdir($dir) < 0) {
                 $this->error = $langs->trans("ErrorCanNotCreateDir", $dir);
                 return 0;
             }
         }
         if (file_exists($dir)) {
             $nblignes = count($object->lines);
             $pdf = pdf_getInstance($this->format);
             if (class_exists('TCPDF')) {
                 $pdf->setPrintHeader(false);
                 $pdf->setPrintFooter(false);
             }
             $pdf->SetFont(pdf_getPDFFont($outputlangs));
             // Set path to the background PDF File
             if (empty($conf->global->MAIN_DISABLE_FPDI) && !empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) {
                 $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output . '/' . $conf->global->MAIN_ADD_PDF_BACKGROUND);
                 $tplidx = $pdf->importPage(1);
             }
             $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();
             if (!empty($tplidx)) {
                 $pdf->useTemplate($tplidx);
             }
             $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->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($object->note_public), 0, 1);
                 $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 & 0x1) == 0x1) {
                     $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)) {
                     //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;
                     // Et si on affiche dates de validite, on ajoute encore une ligne
                     if ($object->lines[$i]->date_start && $object->lines[$i]->date_end) {
                         $nblineFollowDesc += 4;
                     }
                 } else {
                     $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();
                     if (!empty($tplidx)) {
                         $pdf->useTemplate($tplidx);
                     }
                     $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);
             $amount_credit_notes_included = 0;
             $amount_deposits_included = 0;
             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');
             // Actions on extra fields (by external module or standard code)
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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
 }
Example #16
0
 /**
  *	Fonction to generate document on disk
  *
  *	@param	RemiseCheque	$object			Object RemiseCheque			
  *	@param	string			$_dir			Directory
  *	@param	string			$number			Number
  *	@param	Translate		$outputlangs	Lang output object
  *	@return	int     						1=ok, 0=ko
  */
 function write_file($object, $_dir, $number, $outputlangs)
 {
     global $user, $conf, $langs, $hookmanager;
     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 (!empty($conf->global->MAIN_USE_FPDF)) {
         $outputlangs->charset_output = 'ISO-8859-1';
     }
     $outputlangs->load("main");
     $outputlangs->load("companies");
     $outputlangs->load("bills");
     $outputlangs->load("products");
     $outputlangs->load("compta");
     $dir = $_dir . "/" . get_exdir($number, 0, 1, 0, $object, 'cheque') . $number;
     if (!is_dir($dir)) {
         $result = dol_mkdir($dir);
         if ($result < 0) {
             $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
             return -1;
         }
     }
     $file = $dir . "/bordereau-" . $number . ".pdf";
     // Add pdfgeneration hook
     if (!is_object($hookmanager)) {
         include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
         $hookmanager = new HookManager($this->db);
     }
     $hookmanager->initHooks(array('pdfgeneration'));
     $parameters = array('file' => $file, 'outputlangs' => $outputlangs);
     global $action;
     $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action);
     // Note that $action and $object may have been modified by some hooks
     // Create PDF instance
     $pdf = pdf_getInstance($this->format);
     $heightforinfotot = 50;
     // Height reserved to output the info and total part
     $heightforfreetext = isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5;
     // Height reserved to output the free text on last page
     $heightforfooter = $this->marge_basse + 8;
     // Height reserved to output the footer (value include bottom margin)
     $pdf->SetAutoPageBreak(1, 0);
     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->transnoentities("CheckReceipt") . " " . $number);
     $pdf->SetSubject($outputlangs->transnoentities("CheckReceipt"));
     $pdf->SetCreator("Dolibarr " . DOL_VERSION);
     $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
     $pdf->SetKeyWords($outputlangs->transnoentities("CheckReceipt") . " " . $number);
     if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
         $pdf->SetCompression(false);
     }
     $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);
     // Left, Top, Right
     $nboflines = count($this->lines);
     // Define nb of page
     $pages = intval($nboflines / $this->line_per_page);
     if ($nboflines % $this->line_per_page > 0) {
         $pages++;
     }
     if ($pages == 0) {
         // force to build at least one page if report has no lines
         $pages = 1;
     }
     $pdf->AddPage();
     $pagenb++;
     $this->Header($pdf, $pagenb, $pages, $outputlangs);
     $this->Body($pdf, $pagenb, $pages, $outputlangs);
     // Pied de page
     $this->_pagefoot($pdf, '', $outputlangs);
     if (method_exists($pdf, 'AliasNbPages')) {
         $pdf->AliasNbPages();
     }
     $pdf->Close();
     $pdf->Output($file, 'F');
     // Add pdfgeneration hook
     if (!is_object($hookmanager)) {
         include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
         $hookmanager = new HookManager($this->db);
     }
     $hookmanager->initHooks(array('pdfgeneration'));
     $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
     global $action;
     $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action);
     // Note that $action and $object may have been modified by some hooks
     if (!empty($conf->global->MAIN_UMASK)) {
         @chmod($file, octdec($conf->global->MAIN_UMASK));
     }
     $outputlangs->charset_output = $sav_charset_output;
     return 1;
     // Pas d'erreur
 }
Example #17
0
 /**
  *	Fonction generant le projet sur le disque
  *
  *	@param	Project		$object   		Object project a generer
  *	@param	Translate	$outputlangs	Lang output object
  *	@return	int         				1 if OK, <=0 if KO
  */
 function write_file($object, $outputlangs)
 {
     global $conf, $hookmanager, $langs, $user;
     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 (!empty($conf->global->MAIN_USE_FPDF)) {
         $outputlangs->charset_output = 'ISO-8859-1';
     }
     $outputlangs->load("main");
     $outputlangs->load("dict");
     $outputlangs->load("companies");
     $outputlangs->load("projects");
     if ($conf->projet->dir_output) {
         //$nblignes = count($object->lines);  // This is set later with array of tasks
         $objectref = dol_sanitizeFileName($object->ref);
         $dir = $conf->projet->dir_output;
         if (!preg_match('/specimen/i', $objectref)) {
             $dir .= "/" . $objectref;
         }
         $file = $dir . "/" . $objectref . ".pdf";
         if (!file_exists($dir)) {
             if (dol_mkdir($dir) < 0) {
                 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
                 return 0;
             }
         }
         if (file_exists($dir)) {
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action);
             // Note that $action and $object may have been modified by some hooks
             $pdf = pdf_getInstance($this->format);
             $default_font_size = pdf_getPDFFontSize($outputlangs);
             // Must be after pdf_getInstance
             $heightforinfotot = 50;
             // Height reserved to output the info and total part
             $heightforfreetext = isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5;
             // Height reserved to output the free text on last page
             $heightforfooter = $this->marge_basse + 8;
             // Height reserved to output the footer (value include bottom margin)
             $pdf->SetAutoPageBreak(1, 0);
             if (class_exists('TCPDF')) {
                 $pdf->setPrintHeader(false);
                 $pdf->setPrintFooter(false);
             }
             $pdf->SetFont(pdf_getPDFFont($outputlangs));
             // Complete object by loading several other informations
             $task = new Task($this->db);
             $tasksarray = $task->getTasksArray(0, 0, $object->id);
             if (!$object->id > 0) {
                 $tasksarray = array_slice($tasksarray, 0, min(5, count($tasksarray)));
             }
             $object->lines = $tasksarray;
             $nblignes = count($object->lines);
             $pdf->Open();
             $pagenb = 0;
             $pdf->SetDrawColor(128, 128, 128);
             $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
             $pdf->SetSubject($outputlangs->transnoentities("Project"));
             $pdf->SetCreator("Dolibarr " . DOL_VERSION);
             $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
             $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref) . " " . $outputlangs->transnoentities("Project"));
             if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
                 $pdf->SetCompression(false);
             }
             $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);
             // Left, Top, Right
             // 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 = 50;
             $tab_height = 200;
             $tab_top_newpage = 40;
             $tab_height_newpage = 210;
             // Affiche notes
             if (!empty($object->note_public)) {
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->writeHTMLCell(190, 3, $this->posxref - 1, $tab_top - 2, dol_htmlentitiesbr($object->note_public), 0, 1);
                 $nexY = $pdf->GetY();
                 $height_note = $nexY - ($tab_top - 2);
                 // Rect prend une longueur en 3eme param
                 $pdf->SetDrawColor(192, 192, 192);
                 $pdf->Rect($this->marge_gauche, $tab_top - 3, $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;
                 // Description of ligne
                 $ref = $object->lines[$i]->ref;
                 $libelleline = $object->lines[$i]->label;
                 $progress = $object->lines[$i]->progress . '%';
                 $datestart = dol_print_date($object->lines[$i]->date_start, 'day');
                 $dateend = dol_print_date($object->lines[$i]->date_end, 'day');
                 $planned_workload = convertSecondToTime($object->lines[$i]->planned_workload, 'allhourmin');
                 $pdf->SetFont('', '', $default_font_size - 1);
                 // Dans boucle pour gerer multi-page
                 $pdf->SetXY($this->posxref, $curY);
                 $pdf->MultiCell($this->posxlabel - $this->posxref, 3, $outputlangs->convToOutputCharset($ref), 0, 'L');
                 $pdf->SetXY($this->posxlabel, $curY);
                 $pdf->MultiCell($this->posxworkload - $this->posxlabel, 3, $outputlangs->convToOutputCharset($libelleline), 0, 'L');
                 $pdf->SetXY($this->posxworkload, $curY);
                 $pdf->MultiCell($this->posxprogress - $this->posxworkload, 3, $planned_workload, 0, 'R');
                 $pdf->SetXY($this->posxprogress, $curY);
                 $pdf->MultiCell($this->posxdatestart - $this->posxprogress, 3, $progress, 0, 'R');
                 $pdf->SetXY($this->posxdatestart, $curY);
                 $pdf->MultiCell($this->posxdateend - $this->posxdatestart, 3, $datestart, 0, 'C');
                 $pdf->SetXY($this->posxdateend, $curY);
                 $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxdateend, 3, $dateend, 0, 'C');
                 $pageposafter = $pdf->getPage();
                 $pdf->SetFont('', '', $default_font_size - 1);
                 // On repositionne la police par defaut
                 $nexY = $pdf->GetY();
                 // Add line
                 if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < $nblignes - 1) {
                     $pdf->setPage($pageposafter);
                     $pdf->SetLineStyle(array('dash' => '1,1', 'color' => array(80, 80, 80)));
                     //$pdf->SetDrawColor(190,190,200);
                     $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1);
                     $pdf->SetLineStyle(array('dash' => 0));
                 }
                 $nexY += 2;
                 // Passe espace entre les lignes
                 // Detect if some page were added automatically and output _tableau for past pages
                 while ($pagenb < $pageposafter) {
                     $pdf->setPage($pagenb);
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     $pagenb++;
                     $pdf->setPage($pagenb);
                     $pdf->setPageOrientation('', 1, 0);
                     // The only function to edit the bottom margin of current page to set it.
                 }
                 if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) {
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     // New page
                     $pdf->AddPage();
                     if (!empty($tplidx)) {
                         $pdf->useTemplate($tplidx);
                     }
                     $pagenb++;
                 }
             }
             // Show square
             if ($pagenb == 1) {
                 $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
             } else {
                 $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
             }
             /*
              * Pied de page
              */
             $this->_pagefoot($pdf, $object, $outputlangs);
             if (method_exists($pdf, 'AliasNbPages')) {
                 $pdf->AliasNbPages();
             }
             $pdf->Close();
             $pdf->Output($file, 'F');
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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;
 }
 /**
  *  Function to build pdf onto disk
  *
  *  @param		Object		$object				Object to generate
  *  @param		Translate	$outputlangs		Lang output object
  *  @param		string		$srctemplatepath	Full path of source filename for generator using a template file
  *  @param		int			$hidedetails		Do not show line details
  *  @param		int			$hidedesc			Do not show desc
  *  @param		int			$hideref			Do not show ref
  *  @param		object		$hookmanager		Hookmanager object
  *  @return     int         	    			1=OK, 0=KO
  */
 function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0, $hookmanager = false)
 {
     global $user, $langs, $conf, $mysoc, $db;
     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 (!empty($conf->global->MAIN_USE_FPDF)) {
         $outputlangs->charset_output = 'ISO-8859-1';
     }
     $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 (dol_mkdir($dir) < 0) {
                 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
                 return 0;
             }
         }
         if (file_exists($dir)) {
             $nblignes = count($object->lines);
             $pdf = pdf_getInstance($this->format);
             $default_font_size = pdf_getPDFFontSize($outputlangs);
             // Must be after pdf_getInstance
             $heightforinfotot = 50;
             // Height reserved to output the info and total part
             $heightforfreetext = isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5;
             // Height reserved to output the free text on last page
             $heightforfooter = $this->marge_basse + 8;
             // Height reserved to output the footer (value include bottom margin)
             $pdf->SetAutoPageBreak(1, 0);
             if (class_exists('TCPDF')) {
                 $pdf->setPrintHeader(false);
                 $pdf->setPrintFooter(false);
             }
             $pdf->SetFont(pdf_getPDFFont($outputlangs));
             // Set path to the background PDF File
             if (empty($conf->global->MAIN_DISABLE_FPDI) && !empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) {
                 $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output . '/' . $conf->global->MAIN_ADD_PDF_BACKGROUND);
                 $tplidx = $pdf->importPage(1);
             }
             $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 (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
                 $pdf->SetCompression(false);
             }
             $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);
             // Left, Top, Right
             // 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();
             if (!empty($tplidx)) {
                 $pdf->useTemplate($tplidx);
             }
             $pagenb++;
             $this->_pagehead($pdf, $object, 1, $outputlangs, $hookmanager);
             $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 = empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10;
             $tab_height = 130;
             $tab_height_newpage = 150;
             // Affiche notes
             if (!empty($object->note_public)) {
                 $tab_top = 88;
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($object->note_public), 0, 1);
                 $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);
                 // Into loop to work with multipage
                 $pdf->SetTextColor(0, 0, 0);
                 $pdf->setTopMargin($tab_top_newpage);
                 $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot);
                 // The only function to edit the bottom margin of current page to set it.
                 $pageposbefore = $pdf->getPage();
                 // Description of product line
                 $curX = $this->posxdesc - 1;
                 $showpricebeforepagebreak = 1;
                 $pdf->startTransaction();
                 pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxtva - $curX, 3, $curX, $curY, $hideref, $hidedesc, 0, $hookmanager);
                 $pageposafter = $pdf->getPage();
                 if ($pageposafter > $pageposbefore) {
                     $pdf->rollbackTransaction(true);
                     $pageposafter = $pageposbefore;
                     //print $pageposafter.'-'.$pageposbefore;exit;
                     $pdf->setPageOrientation('', 1, $heightforfooter);
                     // The only function to edit the bottom margin of current page to set it.
                     pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxtva - $curX, 4, $curX, $curY, $hideref, $hidedesc, 0, $hookmanager);
                     $pageposafter = $pdf->getPage();
                     $posyafter = $pdf->GetY();
                     //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit;
                     if ($posyafter > $this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)) {
                         if ($i == $nblignes - 1) {
                             $pdf->AddPage('', '', true);
                             if (!empty($tplidx)) {
                                 $pdf->useTemplate($tplidx);
                             }
                             if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                                 $this->_pagehead($pdf, $object, 0, $outputlangs, $hookmanager);
                             }
                             $pdf->setPage($pagenb + 1);
                         }
                     } else {
                         // We found a page break
                         $showpricebeforepagebreak = 0;
                     }
                 } else {
                     $pdf->commitTransaction();
                 }
                 $nexY = $pdf->GetY();
                 $pageposafter = $pdf->getPage();
                 $pdf->setPage($pageposbefore);
                 $pdf->setTopMargin($this->marge_haute);
                 $pdf->setPageOrientation('', 1, 0);
                 // The only function to edit the bottom margin of current page to set it.
                 // We suppose that a too long description is moved completely on next page
                 if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
                     $pdf->setPage($pageposafter);
                     $curY = $tab_top_newpage;
                 }
                 $pdf->SetFont('', '', $default_font_size - 1);
                 // On repositionne la police par defaut
                 // VAT Rate
                 if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) {
                     $vat_rate = pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails, $hookmanager);
                     $pdf->SetXY($this->posxtva, $curY);
                     $pdf->MultiCell($this->posxup - $this->posxtva - 1, 3, $vat_rate, 0, 'R');
                 }
                 // Unit price before discount
                 $up_excl_tax = pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails, $hookmanager);
                 $pdf->SetXY($this->posxup, $curY);
                 $pdf->MultiCell($this->posxqty - $this->posxup - 1, 3, $up_excl_tax, 0, 'R', 0);
                 // Quantity
                 $qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails, $hookmanager);
                 $pdf->SetXY($this->posxqty, $curY);
                 $pdf->MultiCell($this->posxdiscount - $this->posxqty - 1, 3, $qty, 0, 'R');
                 // Enough for 6 chars
                 // Discount on line
                 if ($object->lines[$i]->remise_percent) {
                     $pdf->SetXY($this->posxdiscount - 2, $curY);
                     $remise_percent = pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails, $hookmanager);
                     $pdf->MultiCell($this->postotalht - $this->posxdiscount + 2, 3, $remise_percent, 0, 'R');
                 }
                 // Total HT line
                 $total_excl_tax = pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails, $hookmanager);
                 $pdf->SetXY($this->postotalht, $curY);
                 $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalht, 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;
                 $localtax1_rate = $object->lines[$i]->localtax1_tx;
                 $localtax2_rate = $object->lines[$i]->localtax2_tx;
                 $localtax1_type = $object->lines[$i]->localtax1_type;
                 $localtax2_type = $object->lines[$i]->localtax2_type;
                 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;
                 // TODO : store local taxes types into object lines and remove this
                 $localtax1_array = getLocalTaxesFromRate($vatrate, 1, $mysoc);
                 $localtax2_array = getLocalTaxesFromRate($vatrate, 2, $mysoc);
                 if (!isset($localtax1_type)) {
                     $localtax1_type = $localtax1_array[0];
                 }
                 if (!isset($localtax2_type)) {
                     $localtax2_type = $localtax2_array[0];
                 }
                 //end TODO
                 // retrieve global local tax
                 if ($localtax1_type == '7') {
                     $localtax1_rate = $localtax1_array[1];
                 }
                 if ($localtax2_type == '7') {
                     $localtax2_rate = $localtax2_array[1];
                 }
                 if ($localtax1_type && ($localtax1ligne != 0 || $localtax1_type == '7')) {
                     $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne;
                 }
                 if ($localtax2_type && ($localtax2ligne != 0 || $localtax2_type == '7')) {
                     $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne;
                 }
                 if (($object->lines[$i]->info_bits & 0x1) == 0x1) {
                     $vatrate .= '*';
                 }
                 if (!isset($this->tva[$vatrate])) {
                     $this->tva[$vatrate] = '';
                 }
                 $this->tva[$vatrate] += $tvaligne;
                 // Add line
                 if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < $nblignes - 1) {
                     $pdf->SetLineStyle(array('dash' => '1,1', 'color' => array(210, 210, 210)));
                     //$pdf->SetDrawColor(190,190,200);
                     $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1);
                     $pdf->SetLineStyle(array('dash' => 0));
                 }
                 $nexY += 2;
                 // Passe espace entre les lignes
                 // Detect if some page were added automatically and output _tableau for past pages
                 while ($pagenb < $pageposafter) {
                     $pdf->setPage($pagenb);
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     $pagenb++;
                     $pdf->setPage($pagenb);
                     $pdf->setPageOrientation('', 1, 0);
                     // The only function to edit the bottom margin of current page to set it.
                     if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                         $this->_pagehead($pdf, $object, 0, $outputlangs, $hookmanager);
                     }
                 }
                 if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) {
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     // New page
                     $pdf->AddPage();
                     if (!empty($tplidx)) {
                         $pdf->useTemplate($tplidx);
                     }
                     $pagenb++;
                     if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                         $this->_pagehead($pdf, $object, 0, $outputlangs, $hookmanager);
                     }
                 }
             }
             // Show square
             if ($pagenb == 1) {
                 $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
             } else {
                 $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 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');
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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", "FAC_OUTPUTDIR");
         return 0;
     }
     $this->error = $langs->trans("ErrorUnknown");
     return 0;
     // Erreur par defaut
 }
Example #19
0
	/**
	 *	Update a record into database
	 *
	 *	@param	int		$id         Id of product
	 *	@param  User	$user       Object user making update
	 *	@param	int		$notrigger	Disable triggers
	 *	@return int         		1 if OK, -1 if ref already exists, -2 if other error
	 */
	function update($id, $user, $notrigger=false)
	{
		global $langs, $conf;

		$error=0;

		$this->db->begin();

		// Verification parametres
		if (! $this->libelle) $this->libelle = 'MISSING LABEL';

		// Clean parameters
		$this->ref = dol_string_nospecial(trim($this->ref));
		$this->libelle = trim($this->libelle);
		$this->description = trim($this->description);
		$this->note = trim($this->note);
		$this->weight = price2num($this->weight);
		$this->weight_units = trim($this->weight_units);
		$this->length = price2num($this->length);
		$this->length_units = trim($this->length_units);
		$this->surface = price2num($this->surface);
		$this->surface_units = trim($this->surface_units);
		$this->volume = price2num($this->volume);
		$this->volume_units = trim($this->volume_units);
		if (empty($this->tva_tx))    			$this->tva_tx = 0;
		if (empty($this->tva_npr))    			$this->tva_npr = 0;
		//Local taxes
		if (empty($this->localtax1_tx))			$this->localtax1_tx = 0;
		if (empty($this->localtax2_tx))			$this->localtax2_tx = 0;

		if (empty($this->finished))  			$this->finished = 0;
        if (empty($this->country_id))           $this->country_id = 0;

		$this->accountancy_code_buy = trim($this->accountancy_code_buy);
		$this->accountancy_code_sell= trim($this->accountancy_code_sell);

		$sql = "UPDATE ".MAIN_DB_PREFIX."product";
		$sql.= " SET label = '" . $this->db->escape($this->libelle) ."'";
		$sql.= ",ref = '" . $this->ref ."'";
		$sql.= ",tva_tx = " . $this->tva_tx;
		$sql.= ",recuperableonly = " . $this->tva_npr;

		//Local taxes
		$sql.= ",localtax1_tx = " . $this->localtax1_tx;
		$sql.= ",localtax2_tx = " . $this->localtax2_tx;

		$sql.= ",tosell = " . $this->status;
		$sql.= ",tobuy = " . $this->status_buy;
		$sql.= ",finished = " . ($this->finished<0 ? "null" : $this->finished);
		$sql.= ",weight = " . ($this->weight!='' ? "'".$this->weight."'" : 'null');
		$sql.= ",weight_units = " . ($this->weight_units!='' ? "'".$this->weight_units."'": 'null');
		$sql.= ",length = " . ($this->length!='' ? "'".$this->length."'" : 'null');
		$sql.= ",length_units = " . ($this->length_units!='' ? "'".$this->length_units."'" : 'null');
		$sql.= ",surface = " . ($this->surface!='' ? "'".$this->surface."'" : 'null');
		$sql.= ",surface_units = " . ($this->surface_units!='' ? "'".$this->surface_units."'" : 'null');
		$sql.= ",volume = " . ($this->volume!='' ? "'".$this->volume."'" : 'null');
		$sql.= ",volume_units = " . ($this->volume_units!='' ? "'".$this->volume_units."'" : 'null');
		$sql.= ",seuil_stock_alerte = " . ((isset($this->seuil_stock_alerte) && $this->seuil_stock_alerte != '') ? "'".$this->seuil_stock_alerte."'" : "null");
		$sql.= ",description = '" . $this->db->escape($this->description) ."'";
        $sql.= ",customcode = '" .        $this->db->escape($this->customcode) ."'";
        $sql.= ",fk_country = " . ($this->country_id > 0 ? $this->country_id : 'null');
        $sql.= ",note = '" .        $this->db->escape($this->note) ."'";
		$sql.= ",duration = '" . $this->duration_value . $this->duration_unit ."'";
		$sql.= ",accountancy_code_buy = '" . $this->accountancy_code_buy."'";
		$sql.= ",accountancy_code_sell= '" . $this->accountancy_code_sell."'";
		$sql.= " WHERE rowid = " . $id;

		dol_syslog(get_class($this)."update sql=".$sql);
		$resql=$this->db->query($sql);
		if ($resql)
		{
			$this->id = $id;

			// Multilangs
			if($conf->global->MAIN_MULTILANGS)
			{
				if ( $this->setMultiLangs() < 0)
				{
					$this->error=$langs->trans("Error")." : ".$this->db->error()." - ".$sql;
					return -2;
				}
			}

			// Actions on extra fields (by external module or standard code)
			include_once(DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php');
			$hookmanager=new HookManager($this->db);
			$hookmanager->initHooks(array('productdao'));
			$parameters=array('id'=>$this->id);
			$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
			if (empty($reshook))
			{
			    $result=$this->insertExtraFields();
			    if ($result < 0)
			    {
			        $error++;
			    }
			}
			else if ($reshook < 0) $error++;

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

			if (! $error && (is_object($this->oldcopy) && $this->oldcopy->ref != $this->ref))
			{
				// We remove directory
				if ($conf->product->dir_output)
				{
					$olddir = $conf->product->dir_output . "/" . dol_sanitizeFileName($this->oldcopy->ref);
					$newdir = $conf->product->dir_output . "/" . dol_sanitizeFileName($this->ref);
					if (file_exists($olddir))
					{
						$res=@dol_move($olddir, $newdir);
						if (! $res)
						{
							$this->error='ErrorFailToMoveDir';
							$error++;
						}
					}
				}
			}

			if (! $error)
			{
				$this->db->commit();
				return 1;
			}
			else
			{
				$this->db->rollback();
				return -$error;
			}
		}
		else
		{
			if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
			{
				$this->error=$langs->trans("Error")." : ".$langs->trans("ErrorProductAlreadyExists",$this->ref);
				return -1;
			}
			else
			{
				$this->error=$langs->trans("Error")." : ".$this->db->error()." - ".$sql;
				return -2;
			}
		}
	}
$date_end = dol_mktime(23, 59, 59, $_REQUEST["date_endmonth"], $_REQUEST["date_endday"], $_REQUEST["date_endyear"]);
$date_starty = dol_mktime(0, 0, 0, $_REQUEST["date_start_delymonth"], $_REQUEST["date_start_delyday"], $_REQUEST["date_start_delyyear"]);
// Date for local PHP server
$date_endy = dol_mktime(23, 59, 59, $_REQUEST["date_end_delymonth"], $_REQUEST["date_end_delyday"], $_REQUEST["date_end_delyyear"]);
if ($action == 'create') {
    if (is_array($selected) == false) {
        $error++;
        setEventMessages($langs->trans('Error_OrderNotChecked'), null, 'errors');
    } else {
        $origin = GETPOST('origin');
        $originid = GETPOST('originid');
    }
}
// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
$hookmanager = new HookManager($db);
$hookmanager->initHooks(array('orderstoinvoice'));
/*
 * Actions
 */
if (($action == 'create' || $action == 'add') && !$error) {
    require_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
    require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
    require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
    require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
    if (!empty($conf->projet->enabled)) {
        require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
    }
    $langs->load('bills');
    $langs->load('products');
    $langs->load('main');
Example #21
0
                if (!empty($file['precompileCode'])) {
                    $fileContents .= $file['precompileCode'] . "\n\n";
                }
                $fileContents .= $content . "\n\n";
                if (!empty($file['postcompileCode'])) {
                    $fileContents .= $file['postcompileCode'] . "\n\n";
                }
            }
            file_put_contents($classesCacheFilename, $fileContents);
        }
    }
}
// Request Parser
HookManager::callHook("BeforeRequestParser");
HookManager::callHook("BeforeRequestParserStep2");
HookManager::callHook("RequestParser");
HookManager::callHook("AfterRequestParser");
HookManager::callHook("BeforeController");
HookManager::callHook("Controller");
HookManager::callHook("AfterController");
//$time = microtime(true);
HookManager::callHook("BeforeOutput");
HookManager::callHook("Output");
HookManager::callHook("AfterOutput");
if (ConfigManager::getGlobalConfig()->Stingle->BootCompiler === true) {
    if (!file_exists($configCacheFilename) and !$isGetConfigFromCache) {
        file_put_contents($configCacheFilename, serialize(ConfigManager::mergeConfigs(ConfigManager::getGlobalConfig(), ConfigManager::getCache())));
    }
}
//echo "out - " . (microtime(true) - $time) . "<br>";
// Finish
Example #22
0
 /**
  * Send mail that was prepared by constructor
  *
  * @return    boolean     True if mail sent, false otherwise
  */
 function sendfile()
 {
     global $conf, $db;
     $errorlevel = error_reporting();
     error_reporting($errorlevel ^ E_WARNING);
     // Desactive warnings
     $res = false;
     if (empty($conf->global->MAIN_DISABLE_ALL_MAILS)) {
         require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
         $hookmanager = new HookManager($db);
         $hookmanager->initHooks(array('maildao'));
         $reshook = $hookmanager->executeHooks('doactions', $parameters, $this, $action);
         // Note that $action and $object may have been modified by some hooks
         if (!empty($reshook)) {
             $this->error = "Error in hook maildao doactions " . $reshook;
             dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
             return $reshook;
         }
         // Action according to choosed sending method
         if ($conf->global->MAIN_MAIL_SENDMODE == 'mail') {
             // Use mail php function (default PHP method)
             // ------------------------------------------
             dol_syslog("CMailFile::sendfile addr_to=" . $this->addr_to . ", subject=" . $this->subject, LOG_DEBUG);
             dol_syslog("CMailFile::sendfile header=\n" . $this->headers, LOG_DEBUG);
             //dol_syslog("CMailFile::sendfile message=\n".$message);
             // If Windows, sendmail_from must be defined
             if (isset($_SERVER["WINDIR"])) {
                 if (empty($this->addr_from)) {
                     $this->addr_from = '*****@*****.**';
                 }
                 @ini_set('sendmail_from', $this->getValidAddress($this->addr_from, 2));
             }
             // Forcage parametres
             if (!empty($conf->global->MAIN_MAIL_SMTP_SERVER)) {
                 ini_set('SMTP', $conf->global->MAIN_MAIL_SMTP_SERVER);
             }
             if (!empty($conf->global->MAIN_MAIL_SMTP_PORT)) {
                 ini_set('smtp_port', $conf->global->MAIN_MAIL_SMTP_PORT);
             }
             $dest = $this->getValidAddress($this->addr_to, 2);
             if (!$dest) {
                 $this->error = "Failed to send mail with php mail to HOST=" . ini_get('SMTP') . ", PORT=" . ini_get('smtp_port') . "<br>Recipient address '{$dest}' invalid";
                 dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
             } else {
                 dol_syslog("CMailFile::sendfile: mail start HOST=" . ini_get('SMTP') . ", PORT=" . ini_get('smtp_port'), LOG_DEBUG);
                 $bounce = '';
                 // By default
                 if (!empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F)) {
                     // le "Return-Path" (retour des messages bounced) dans les header ne fonctionne pas avec tous les MTA
                     // Le forcage de la valeure grace à l'option -f de sendmail est donc possible si la constante MAIN_MAIL_ALLOW_SENDMAIL_F est definie.
                     // La variable definie pose des pb avec certains sendmail securisee (option -f refusee car dangereuse)
                     $bounce .= ($bounce ? ' ' : '') . (!empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f' . $this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO, 2) : ($this->addr_from != '' ? '-f' . $this->getValidAddress($this->addr_from, 2) : ''));
                 }
                 if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) {
                     $bounce .= ($bounce ? ' ' : '') . '-ba';
                 }
                 $this->message = stripslashes($this->message);
                 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
                     $this->dump_mail();
                 }
                 if (!empty($bounce)) {
                     $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $bounce);
                 } else {
                     $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers);
                 }
                 if (!$res) {
                     $this->error = "Failed to send mail with php mail";
                     $linuxlike = 1;
                     if (preg_match('/^win/i', PHP_OS)) {
                         $linuxlike = 0;
                     }
                     if (preg_match('/^mac/i', PHP_OS)) {
                         $linuxlike = 0;
                     }
                     if (!$linuxlike) {
                         $this->error .= " to HOST=" . ini_get('SMTP') . ", PORT=" . ini_get('smtp_port');
                         // This values are value used only for non linuxlike systems
                     }
                     $this->error .= ".<br>Check your server logs and your firewalls setup";
                     dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
                 } else {
                     dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
                 }
             }
             if (isset($_SERVER["WINDIR"])) {
                 @ini_restore('sendmail_from');
             }
             // Forcage parametres
             if (!empty($conf->global->MAIN_MAIL_SMTP_SERVER)) {
                 ini_restore('SMTP');
             }
             if (!empty($conf->global->MAIN_MAIL_SMTP_PORT)) {
                 ini_restore('smtp_port');
             }
         } else {
             if ($conf->global->MAIN_MAIL_SENDMODE == 'smtps') {
                 // Use SMTPS library
                 // ------------------------------------------
                 $this->smtps->setTransportType(0);
                 // Only this method is coded in SMTPs library
                 // Forcage parametres
                 if (empty($conf->global->MAIN_MAIL_SMTP_SERVER)) {
                     $conf->global->MAIN_MAIL_SMTP_SERVER = ini_get('SMTP');
                 }
                 if (empty($conf->global->MAIN_MAIL_SMTP_PORT)) {
                     $conf->global->MAIN_MAIL_SMTP_PORT = ini_get('smtp_port');
                 }
                 // If we use SSL/TLS
                 $server = $conf->global->MAIN_MAIL_SMTP_SERVER;
                 if (!empty($conf->global->MAIN_MAIL_EMAIL_TLS) && function_exists('openssl_open')) {
                     $server = 'ssl://' . $server;
                 }
                 $this->smtps->setHost($server);
                 $this->smtps->setPort($conf->global->MAIN_MAIL_SMTP_PORT);
                 // 25, 465...;
                 if (!empty($conf->global->MAIN_MAIL_SMTPS_ID)) {
                     $this->smtps->setID($conf->global->MAIN_MAIL_SMTPS_ID);
                 }
                 if (!empty($conf->global->MAIN_MAIL_SMTPS_PW)) {
                     $this->smtps->setPW($conf->global->MAIN_MAIL_SMTPS_PW);
                 }
                 //$smtps->_msgReplyTo  = '*****@*****.**';
                 $res = true;
                 $from = $this->smtps->getFrom('org');
                 if (!$from) {
                     $this->error = "Failed to send mail with smtps lib to HOST=" . $server . ", PORT=" . $conf->global->MAIN_MAIL_SMTP_PORT . "<br>Sender address '{$from}' invalid";
                     dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
                     $res = false;
                 }
                 $dest = $this->smtps->getTo();
                 if (!$dest) {
                     $this->error = "Failed to send mail with smtps lib to HOST=" . $server . ", PORT=" . $conf->global->MAIN_MAIL_SMTP_PORT . "<br>Recipient address '{$dest}' invalid";
                     dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
                     $res = false;
                 }
                 if ($res) {
                     if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
                         $this->smtps->setDebug(true);
                     }
                     $result = $this->smtps->sendMsg();
                     //print $result;
                     if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
                         $this->dump_mail();
                     }
                     $result = $this->smtps->getErrors();
                     if (empty($this->error) && empty($result)) {
                         $res = true;
                     } else {
                         if (empty($this->error)) {
                             $this->error = $result;
                         }
                         dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
                         $res = false;
                     }
                 }
             } else {
                 // Send mail method not correctly defined
                 // --------------------------------------
                 return 'Bad value for MAIN_MAIL_SENDMODE constant';
             }
         }
     } else {
         $this->error = 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
         dol_syslog("CMailFile::sendfile: " . $this->error, LOG_WARNING);
     }
     error_reporting($errorlevel);
     // Reactive niveau erreur origine
     return $res;
 }
Example #23
0
	/**
	 *    Delete a third party from database and all its dependencies (contacts, rib...)
	 *
	 *    @param	int		$id     Id of third party to delete
	 *    @return	int				<0 if KO, 0 if nothing done, >0 if OK
	 */
	function delete($id) {
		global $user, $langs, $conf;
		require_once(DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php");

		dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
		$error = 0;

		// Test if child exists
		//$objectisused = $this->isObjectUsed($this->rowid); // TODO A reactivier
		if (empty($objectisused)) {


			require_once(DOL_DOCUMENT_ROOT . "/categories/class/categorie.class.php");
			$static_cat = new Categorie($this->db);
			$toute_categs = array();

			// Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
			if ($this->client || $this->prospect) {
				$toute_categs ['societe'] = $static_cat->containing($this->id, 2);
			}
			if ($this->fournisseur) {
				$toute_categs ['fournisseur'] = $static_cat->containing($this->id, 1);
			}

			// Remove each "Categorie"
			foreach ($toute_categs as $type => $categs_type) {
				foreach ($categs_type as $cat) {
					$cat->del_type($this, $type);
				}
			}

			return parent::delete();

			// TODO Supprimer les contacts
			// Remove contacts
			if (!$error) {
				$sql = "DELETE FROM " . MAIN_DB_PREFIX . "socpeople";
				$sql.= " WHERE fk_soc = " . $id;
				dol_syslog(get_class($this) . "::delete sql=" . $sql, LOG_DEBUG);
				if (!$this->db->query($sql)) {
					$error++;
					$this->error .= $this->db->lasterror();
					dol_syslog(get_class($this) . "::delete erreur -1 " . $this->error, LOG_ERR);
				}
			}

			// Update link in member table
			if (!$error) {
				$sql = "UPDATE " . MAIN_DB_PREFIX . "adherent";
				$sql.= " SET fk_soc = NULL WHERE fk_soc = " . $id;
				dol_syslog(get_class($this) . "::delete sql=" . $sql, LOG_DEBUG);
				if (!$this->db->query($sql)) {
					$error++;
					$this->error .= $this->db->lasterror();
					dol_syslog(get_class($this) . "::delete erreur -1 " . $this->error, LOG_ERR);
				}
			}

			// Remove ban
			if (!$error) {
				$sql = "DELETE FROM " . MAIN_DB_PREFIX . "societe_rib";
				$sql.= " WHERE fk_soc = " . $id;
				dol_syslog(get_class($this) . "::Delete sql=" . $sql, LOG_DEBUG);
				if (!$this->db->query($sql)) {
					$error++;
					$this->error = $this->db->lasterror();
					dol_syslog(get_class($this) . "::Delete erreur -2 " . $this->error, LOG_ERR);
				}
			}

			// Removed extrafields
			//$result=$this->deleteExtraFields($this);
			//if ($result < 0) $error++;

			if (!$error) {
				// Additionnal action by hooks
				include_once(DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php');
				$hookmanager = new HookManager($this->db);
				$hookmanager->initHooks(array('thirdparty_extrafields'));
				$parameters = array();
				$action = 'delete';
				$reshook = $hookmanager->executeHooks('deleteThirdparty', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
				if (!empty($hookmanager->error)) {
					$error++;
					$this->error = $hookmanager->error;
				}
			}

			// Remove third party
			if (!$error) {
				$sql = "DELETE FROM " . MAIN_DB_PREFIX . "societe";
				$sql.= " WHERE rowid = " . $id;
				dol_syslog(get_class($this) . "::delete sql=" . $sql, LOG_DEBUG);
				if (!$this->db->query($sql)) {
					$error++;
					$this->error = $this->db->lasterror();
					dol_syslog(get_class($this) . "::delete erreur -3 " . $this->error, LOG_ERR);
				}
			}

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

			if (!$error) {
				$this->db->commit();

				// Delete directory
				$docdir = $conf->societe->multidir_output[$this->entity] . "/" . $id;
				if (file_exists($docdir)) {
					dol_delete_dir_recursive($docdir);
				}

				return 1;
			} else {
				$this->db->rollback();
				return -1;
			}
		}
	}
 /**
  *	Function to build a document on disk using the generic odt module.
  *
  *	@param	Project		$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, $hookmanager;
     if (empty($srctemplatepath)) {
         dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
         return -1;
     }
     // Add odtgeneration hook
     if (!is_object($hookmanager)) {
         include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
         $hookmanager = new HookManager($this->db);
     }
     $hookmanager->initHooks(array('odtgeneration'));
     global $action;
     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->projet->dir_output) {
         // If $object is id instead of object
         if (!is_object($object)) {
             $id = $object;
             $object = new Project($this->db);
             $result = $object->fetch($id);
             if ($result < 0) {
                 dol_print_error($this->db, $object->error);
                 return -1;
             }
         }
         $dir = $conf->projet->dir_output;
         $objectref = dol_sanitizeFileName($object->ref);
         if (!preg_match('/specimen/i', $objectref)) {
             $dir .= "/" . $objectref;
         }
         $file = $dir . "/" . $objectref . ".odt";
         if (!file_exists($dir)) {
             if (dol_mkdir($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('/\\.od(t|s)/i', '', $newfile);
             $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
             $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
             $newfiletmp = $objectref . '_' . $newfiletmp;
             //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
             // Get extension (ods or odt)
             $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
             if (!empty($conf->global->MAIN_DOC_USE_TIMING)) {
                 $filename = $newfiletmp . '.' . dol_print_date(dol_now(), '%Y%m%d%H%M%S') . '.' . $newfileformat;
             } else {
                 $filename = $newfiletmp . '.' . $newfileformat;
             }
             $file = $dir . '/' . $filename;
             //print "newdir=".$dir;
             //print "newfile=".$newfile;
             //print "file=".$file;
             //print "conf->societe->dir_temp=".$conf->societe->dir_temp;
             dol_mkdir($conf->projet->dir_temp);
             $socobject = $object->thirdparty;
             // Make substitution
             $substitutionarray = array('__FROM_NAME__' => $this->emetteur->nom, '__FROM_EMAIL__' => $this->emetteur->email);
             complete_substitutions_array($substitutionarray, $langs, $object);
             // Open and load template
             require_once ODTPHP_PATH . 'odf.php';
             try {
                 $odfHandler = new odf($srctemplatepath, array('PATH_TO_TMP' => $conf->projet->dir_temp, 'ZIP_PROXY' => 'PclZipProxy', 'DELIMITER_LEFT' => '{', 'DELIMITER_RIGHT' => '}'));
             } catch (Exception $e) {
                 $this->error = $e->getMessage();
                 return -1;
             }
             // After construction $odfHandler->contentXml contains content and
             // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
             // [!-- BEGIN lines --]*[!-- END lines --]
             //print html_entity_decode($odfHandler->__toString());
             //print exit;
             // Make substitutions into odt of user info
             $tmparray = $this->get_substitutionarray_user($user, $outputlangs);
             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 mysoc
             $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
             $tmparray = $this->get_substitutionarray_thirdparty($socobject, $outputlangs);
             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) {
                 }
             }
             // Replace tags of object + external modules
             $tmparray = $this->get_substitutionarray_object($object, $outputlangs);
             complete_substitutions_array($tmparray, $outputlangs, $object);
             // Call the ODTSubstitution hook
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
             $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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) {
                 }
             }
             // Replace tags of lines for tasks
             try {
                 $listlines = $odfHandler->setSegment('tasks');
                 $taskstatic = new Task($this->db);
                 // Security check
                 $socid = 0;
                 if (!empty($object->fk_soc)) {
                     $socid = $object->fk_soc;
                 }
                 $tasksarray = $taskstatic->getTasksArray(0, 0, $object->id, $socid, 0);
                 foreach ($tasksarray as $task) {
                     $tmparray = $this->get_substitutionarray_tasks($task, $outputlangs);
                     //complete_substitutions_array($tmparray, $outputlangs, $object, $task, "completesubstitutionarray_lines");
                     foreach ($tmparray as $key => $val) {
                         try {
                             $listlines->setVars($key, $val, true, 'UTF-8');
                         } catch (OdfException $e) {
                         } catch (SegmentException $e) {
                         }
                     }
                     $taskobj = new Task($this->db);
                     $taskobj->fetch($task->id);
                     // Replace tags of lines for contacts task
                     $sourcearray = array('internal', 'external');
                     $contact_arrray = array();
                     foreach ($sourcearray as $source) {
                         $contact_temp = $taskobj->liste_contact(-1, $source);
                         if (is_array($contact_temp) && count($contact_temp) > 0) {
                             $contact_arrray = array_merge($contact_arrray, $contact_temp);
                         }
                     }
                     if (is_array($contact_arrray) && count($contact_arrray) > 0) {
                         $listlinestaskres = $listlines->__get('tasksressources');
                         foreach ($contact_arrray as $contact) {
                             if ($contact['source'] == 'internal') {
                                 $objectdetail = new User($this->db);
                                 $objectdetail->fetch($contact['id']);
                                 $contact['socname'] = $mysoc->name;
                             } elseif ($contact['source'] == 'external') {
                                 $objectdetail = new Contact($this->db);
                                 $objectdetail->fetch($contact['id']);
                                 $soc = new Societe($this->db);
                                 $soc->fetch($contact['socid']);
                                 $contact['socname'] = $soc->name;
                             }
                             $contact['fullname'] = $objectdetail->getFullName($outputlangs, 1);
                             $tmparray = $this->get_substitutionarray_tasksressource($contact, $outputlangs);
                             foreach ($tmparray as $key => $val) {
                                 try {
                                     $listlinestaskres->setVars($key, $val, true, 'UTF-8');
                                 } catch (OdfException $e) {
                                 } catch (SegmentException $e) {
                                 }
                             }
                             $listlinestaskres->merge();
                         }
                     }
                     //Time ressources
                     $sql = "SELECT t.rowid, t.task_date, t.task_duration, t.fk_user, t.note";
                     $sql .= ", u.lastname, u.firstname";
                     $sql .= " FROM " . MAIN_DB_PREFIX . "projet_task_time as t";
                     $sql .= " , " . MAIN_DB_PREFIX . "user as u";
                     $sql .= " WHERE t.fk_task =" . $task->id;
                     $sql .= " AND t.fk_user = u.rowid";
                     $sql .= " ORDER BY t.task_date DESC";
                     $resql = $this->db->query($sql);
                     if ($resql) {
                         $num = $this->db->num_rows($resql);
                         $i = 0;
                         $tasks = array();
                         $listlinestasktime = $listlines->__get('taskstimes');
                         while ($i < $num) {
                             $row = $this->db->fetch_array($resql);
                             if (!empty($row['fk_user'])) {
                                 $objectdetail = new User($this->db);
                                 $objectdetail->fetch($row['fk_user']);
                                 $row['fullcivname'] = $objectdetail->getFullName($outputlangs, 1);
                             } else {
                                 $row['fullcivname'] = '';
                             }
                             $tmparray = $this->get_substitutionarray_taskstime($row, $outputlangs);
                             foreach ($tmparray as $key => $val) {
                                 try {
                                     $listlinestasktime->setVars($key, $val, true, 'UTF-8');
                                 } catch (OdfException $e) {
                                 } catch (SegmentException $e) {
                                 }
                             }
                             $listlinestasktime->merge();
                             $i++;
                         }
                         $this->db->free($resql);
                     }
                     // Replace tags of project files
                     $listtasksfiles = $listlines->__get('tasksfiles');
                     $upload_dir = $conf->projet->dir_output . '/' . dol_sanitizeFileName($object->ref) . '/' . dol_sanitizeFileName($task->ref);
                     $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\\.meta|_preview\\.png)$', 'name', SORT_ASC, 1);
                     foreach ($filearray as $filedetail) {
                         $tmparray = $this->get_substitutionarray_task_file($filedetail, $outputlangs);
                         //dol_syslog(get_class($this).'::main $tmparray'.var_export($tmparray,true));
                         foreach ($tmparray as $key => $val) {
                             try {
                                 $listtasksfiles->setVars($key, $val, true, 'UTF-8');
                             } catch (OdfException $e) {
                             } catch (SegmentException $e) {
                             }
                         }
                         $listtasksfiles->merge();
                     }
                     $listlines->merge();
                 }
                 $odfHandler->mergeSegment($listlines);
             } catch (OdfException $e) {
                 $this->error = $e->getMessage();
                 dol_syslog($this->error, LOG_WARNING);
                 return -1;
             }
             // Replace tags of project files
             try {
                 $listlines = $odfHandler->setSegment('projectfiles');
                 $upload_dir = $conf->projet->dir_output . '/' . dol_sanitizeFileName($object->ref);
                 $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\\.meta|_preview\\.png)$', 'name', SORT_ASC, 1);
                 foreach ($filearray as $filedetail) {
                     //dol_syslog(get_class($this).'::main $filedetail'.var_export($filedetail,true));
                     $tmparray = $this->get_substitutionarray_project_file($filedetail, $outputlangs);
                     foreach ($tmparray as $key => $val) {
                         try {
                             $listlines->setVars($key, $val, true, 'UTF-8');
                         } catch (OdfException $e) {
                         } catch (SegmentException $e) {
                         }
                     }
                     $listlines->merge();
                 }
                 $odfHandler->mergeSegment($listlines);
             } catch (OdfException $e) {
                 $this->error = $e->getMessage();
                 dol_syslog($this->error, LOG_WARNING);
                 return -1;
             }
             // Replace tags of lines for contacts
             $sourcearray = array('internal', 'external');
             $contact_arrray = array();
             foreach ($sourcearray as $source) {
                 $contact_temp = $object->liste_contact(-1, $source);
                 if (is_array($contact_temp) && count($contact_temp) > 0) {
                     $contact_arrray = array_merge($contact_arrray, $contact_temp);
                 }
             }
             if (is_array($contact_arrray) && count($contact_arrray) > 0) {
                 try {
                     $listlines = $odfHandler->setSegment('projectcontacts');
                     foreach ($contact_arrray as $contact) {
                         if ($contact['source'] == 'internal') {
                             $objectdetail = new User($this->db);
                             $objectdetail->fetch($contact['id']);
                             $contact['socname'] = $mysoc->name;
                         } elseif ($contact['source'] == 'external') {
                             $objectdetail = new Contact($this->db);
                             $objectdetail->fetch($contact['id']);
                             $soc = new Societe($this->db);
                             $soc->fetch($contact['socid']);
                             $contact['socname'] = $soc->name;
                         }
                         $contact['fullname'] = $objectdetail->getFullName($outputlangs, 1);
                         $tmparray = $this->get_substitutionarray_project_contacts($contact, $outputlangs);
                         foreach ($tmparray as $key => $val) {
                             try {
                                 $listlines->setVars($key, $val, true, 'UTF-8');
                             } catch (OdfException $e) {
                             } catch (SegmentException $e) {
                             }
                         }
                         $listlines->merge();
                     }
                     $odfHandler->mergeSegment($listlines);
                 } catch (OdfException $e) {
                     $this->error = $e->getMessage();
                     dol_syslog($this->error, LOG_WARNING);
                     return -1;
                 }
             }
             //List of referent
             $listofreferent = array('propal' => array('title' => "ListProposalsAssociatedProject", 'class' => 'Propal', 'table' => 'propal', 'test' => $conf->propal->enabled && $user->rights->propale->lire), 'order' => array('title' => "ListOrdersAssociatedProject", 'class' => 'Commande', 'table' => 'commande', 'test' => $conf->commande->enabled && $user->rights->commande->lire), 'invoice' => array('title' => "ListInvoicesAssociatedProject", 'class' => 'Facture', 'table' => 'facture', 'test' => $conf->facture->enabled && $user->rights->facture->lire), 'invoice_predefined' => array('title' => "ListPredefinedInvoicesAssociatedProject", 'class' => 'FactureRec', 'table' => 'facture_rec', 'test' => $conf->facture->enabled && $user->rights->facture->lire), 'order_supplier' => array('title' => "ListSupplierOrdersAssociatedProject", 'table' => 'commande_fournisseur', 'class' => 'CommandeFournisseur', 'test' => $conf->fournisseur->enabled && $user->rights->fournisseur->commande->lire), 'invoice_supplier' => array('title' => "ListSupplierInvoicesAssociatedProject", 'table' => 'facture_fourn', 'class' => 'FactureFournisseur', 'test' => $conf->fournisseur->enabled && $user->rights->fournisseur->facture->lire), 'contract' => array('title' => "ListContractAssociatedProject", 'class' => 'Contrat', 'table' => 'contrat', 'test' => $conf->contrat->enabled && $user->rights->contrat->lire), 'intervention' => array('title' => "ListFichinterAssociatedProject", 'class' => 'Fichinter', 'table' => 'fichinter', 'disableamount' => 1, 'test' => $conf->ficheinter->enabled && $user->rights->ficheinter->lire), 'trip' => array('title' => "ListTripAssociatedProject", 'class' => 'Deplacement', 'table' => 'deplacement', 'disableamount' => 1, 'test' => $conf->deplacement->enabled && $user->rights->deplacement->lire), 'agenda' => array('title' => "ListActionsAssociatedProject", 'class' => 'ActionComm', 'table' => 'actioncomm', 'disableamount' => 1, 'test' => $conf->agenda->enabled && $user->rights->agenda->allactions->lire));
             //Insert reference
             try {
                 $listlines = $odfHandler->setSegment('projectrefs');
                 foreach ($listofreferent as $keyref => $valueref) {
                     $title = $valueref['title'];
                     $tablename = $valueref['table'];
                     $classname = $valueref['class'];
                     $qualified = $valueref['test'];
                     if ($qualified) {
                         $elementarray = $object->get_element_list($keyref, $tablename);
                         if (count($elementarray) > 0 && is_array($elementarray)) {
                             $var = true;
                             $total_ht = 0;
                             $total_ttc = 0;
                             $num = count($elementarray);
                             for ($i = 0; $i < $num; $i++) {
                                 $ref_array = array();
                                 $ref_array['type'] = $langs->trans($classname);
                                 $element = new $classname($this->db);
                                 $element->fetch($elementarray[$i]);
                                 $element->fetch_thirdparty();
                                 //Ref object
                                 $ref_array['ref'] = $element->ref;
                                 //Date object
                                 $dateref = $element->date;
                                 if (empty($dateref)) {
                                     $dateref = $element->datep;
                                 }
                                 if (empty($dateref)) {
                                     $dateref = $element->date_contrat;
                                 }
                                 $ref_array['date'] = $dateref;
                                 //Soc object
                                 if (is_object($element->thirdparty)) {
                                     $ref_array['socname'] = $element->thirdparty->name;
                                 } else {
                                     $ref_array['socname'] = '';
                                 }
                                 //Amount object
                                 if (empty($valueref['disableamount'])) {
                                     if (!empty($element->total_ht)) {
                                         $ref_array['amountht'] = $element->total_ht;
                                         $ref_array['amountttc'] = $element->total_ttc;
                                     } else {
                                         $ref_array['amountht'] = 0;
                                         $ref_array['amountttc'] = 0;
                                     }
                                 } else {
                                     $ref_array['amountht'] = '';
                                     $ref_array['amountttc'] = '';
                                 }
                                 $ref_array['status'] = $element->getLibStatut(0);
                                 $tmparray = $this->get_substitutionarray_project_reference($ref_array, $outputlangs);
                                 foreach ($tmparray as $key => $val) {
                                     try {
                                         $listlines->setVars($key, $val, true, 'UTF-8');
                                     } catch (OdfException $e) {
                                     } catch (SegmentException $e) {
                                     }
                                 }
                                 $listlines->merge();
                             }
                         }
                     }
                     $odfHandler->mergeSegment($listlines);
                 }
             } catch (OdfException $e) {
                 $this->error = $e->getMessage();
                 dol_syslog($this->error, LOG_WARNING);
                 return -1;
             }
             // Replace labels translated
             $tmparray = $outputlangs->get_translations_for_substitutions();
             foreach ($tmparray as $key => $value) {
                 try {
                     $odfHandler->setVars($key, $value, true, 'UTF-8');
                 } catch (OdfException $e) {
                 }
             }
             // Call the beforeODTSave hook
             $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             // Write new file
             if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
                 try {
                     $odfHandler->exportAsAttachedPDF($file);
                 } catch (Exception $e) {
                     $this->error = $e->getMessage();
                     return -1;
                 }
             } else {
                 try {
                     $odfHandler->saveToDisk($file);
                 } catch (Exception $e) {
                     $this->error = $e->getMessage();
                     return -1;
                 }
             }
             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;
 }
Example #25
0
Debug::setMode($config->Debug->enabled);
SiteMode::set($config->SiteMode->mode);
// Register User Hooks
if (isset($config->Hooks)) {
    foreach (get_object_vars($config->Hooks) as $hookName => $funcName) {
        if (is_object($funcName)) {
            foreach (get_object_vars($funcName) as $regFuncName) {
                HookManager::registerHook(new Hook($hookName, $regFuncName));
            }
        } else {
            HookManager::registerHook(new Hook($hookName, $funcName));
        }
    }
}
// Init packages/plugins
HookManager::callHook("BeforePackagesLoad");
foreach (get_object_vars($config->Packages) as $package) {
    $package = get_object_vars($package);
    if (!isset($package[1])) {
        $package[1] = array();
    }
    Reg::get('packageMgr')->addPackage($package[0], $package[1]);
}
Reg::get('packageMgr')->load();
HookManager::callHook("AfterPackagesLoad");
// Request Parser
HookManager::callHook("BeforeRequestParser");
HookManager::callHook("BeforeRequestParserStep2");
HookManager::callHook("RequestParser");
HookManager::callHook("AfterRequestParser");
Example #26
0
 /**
  *	Function to build pdf onto disk
  *
  *	@param		Object		$object			Object expedition to generate (or id if old method)
  *	@param		Translate	$outputlangs		Lang output object
  *  @param		string		$srctemplatepath	Full path of source filename for generator using a template file
  *  @param		int			$hidedetails		Do not show line details
  *  @param		int			$hidedesc			Do not show desc
  *  @param		int			$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, $hookmanager;
     $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 (!empty($conf->global->MAIN_USE_FPDF)) {
         $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) {
         $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 (!empty($idcontact[0])) {
             $this->destinataire->fetch($idcontact[0]);
         }
         //Creation du livreur
         $idcontact = $object->{$origin}->getIdContact('internal', 'LIVREUR');
         $this->livreur = new User($this->db);
         if (!empty($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 (dol_mkdir($dir) < 0) {
                 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
                 return 0;
             }
         }
         if (file_exists($dir)) {
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action);
             // Note that $action and $object may have been modified by some hooks
             $nblignes = count($object->lines);
             $pdf = pdf_getInstance($this->format, 'mm', 'l');
             $default_font_size = pdf_getPDFFontSize($outputlangs);
             $heightforinfotot = 0;
             // Height reserved to output the info and total part
             $heightforfreetext = isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5;
             // Height reserved to output the free text on last page
             $heightforfooter = $this->marge_basse + 8;
             // Height reserved to output the footer (value include bottom margin)
             $pdf->SetAutoPageBreak(1, 0);
             if (class_exists('TCPDF')) {
                 $pdf->setPrintHeader(false);
                 $pdf->setPrintFooter(false);
             }
             $pdf->SetFont(pdf_getPDFFont($outputlangs));
             // Set path to the background PDF File
             if (empty($conf->global->MAIN_DISABLE_FPDI) && !empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) {
                 $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output . '/' . $conf->global->MAIN_ADD_PDF_BACKGROUND);
                 $tplidx = $pdf->importPage(1);
             }
             $pdf->Open();
             $pagenb = 0;
             $pdf->SetDrawColor(128, 128, 128);
             if (method_exists($pdf, 'AliasNbPages')) {
                 $pdf->AliasNbPages();
             }
             $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
             $pdf->SetSubject($outputlangs->transnoentities("Shipment"));
             $pdf->SetCreator("Dolibarr " . DOL_VERSION);
             $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
             $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref) . " " . $outputlangs->transnoentities("Shipment"));
             if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
                 $pdf->SetCompression(false);
             }
             $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);
             // Left, Top, Right
             // New page
             $pdf->AddPage();
             $pagenb++;
             $this->_pagehead($pdf, $object, 1, $outputlangs);
             $pdf->SetFont('', '', $default_font_size - 3);
             $pdf->MultiCell(0, 3, '');
             // Set interline to 3
             $pdf->SetTextColor(0, 0, 0);
             $tab_top = 52;
             $tab_top_newpage = empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10;
             $tab_height = $this->page_hauteur - $tab_top - $heightforfooter;
             $tab_height_newpage = $this->page_hauteur - $tab_top_newpage - $heightforfooter;
             // Affiche notes
             if (!empty($object->note_public)) {
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->writeHTMLCell(190, 3, $this->marge_gauche, $tab_top, dol_htmlentitiesbr($object->note_public), 0, 1);
                 $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;
             }
             $pdf->SetFillColor(240, 240, 240);
             $pdf->SetTextColor(0, 0, 0);
             $pdf->SetXY(10, $tab_top + 5);
             $iniY = $tab_top + 7;
             $curY = $tab_top + 7;
             $nexY = $tab_top + 7;
             $num = count($object->lines);
             // Loop on each lines
             for ($i = 0; $i < $num; $i++) {
                 $curY = $nexY;
                 $pdf->SetFont('', '', $default_font_size - 3);
                 $pdf->SetTextColor(0, 0, 0);
                 $pdf->setTopMargin($tab_top_newpage);
                 $pdf->setPageOrientation('', 1, $heightforfooter);
                 // The only function to edit the bottom margin of current page to set it.
                 $pageposbefore = $pdf->getPage();
                 // Description de la ligne produit
                 $libelleproduitservice = pdf_writelinedesc($pdf, $object, $i, $outputlangs, 90, 3, 50, $curY, 0, 1);
                 $nexY = $pdf->GetY();
                 $pageposafter = $pdf->getPage();
                 $pdf->setPage($pageposbefore);
                 $pdf->setTopMargin($this->marge_haute);
                 $pdf->setPageOrientation('', 1, 0);
                 // The only function to edit the bottom margin of current page to set it.
                 // We suppose that a too long description is moved completely on next page
                 if ($pageposafter > $pageposbefore) {
                     $pdf->setPage($pageposafter);
                     $curY = $tab_top_newpage;
                 }
                 $pdf->SetFont('', '', $default_font_size - 3);
                 //Creation des cases a cocher
                 $pdf->Rect(10 + 3, $curY, 3, 3);
                 $pdf->Rect(20 + 3, $curY, 3, 3);
                 //Insertion de la reference du produit
                 $pdf->SetXY(30, $curY);
                 $pdf->SetFont('', 'B', $default_font_size - 3);
                 $pdf->MultiCell(24, 3, $outputlangs->convToOutputCharset($object->lines[$i]->ref), 0, 'L', 0);
                 $pdf->SetXY(140, $curY);
                 $pdf->MultiCell(30, 3, $object->lines[$i]->qty_asked, 0, 'C', 0);
                 $pdf->SetXY(170, $curY);
                 $pdf->MultiCell(30, 3, $object->lines[$i]->qty_shipped, 0, 'C', 0);
                 // Add line
                 if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < $nblignes - 1) {
                     $pdf->setPage($pageposafter);
                     $pdf->SetLineStyle(array('dash' => '1,1', 'color' => array(60, 60, 60)));
                     //$pdf->SetDrawColor(190,190,200);
                     $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1);
                     $pdf->SetLineStyle(array('dash' => 0));
                 }
                 $nexY += 2;
                 // Passe espace entre les lignes
                 // Detect if some page were added automatically and output _tableau for past pages
                 while ($pagenb < $pageposafter) {
                     $pdf->setPage($pagenb);
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage - 1, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     $pagenb++;
                     $pdf->setPage($pagenb);
                     $pdf->setPageOrientation('', 1, 0);
                     // The only function to edit the bottom margin of current page to set it.
                 }
                 if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) {
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage - 1, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     // New page
                     $pdf->AddPage();
                     $pagenb++;
                 }
             }
             // Show square
             if ($pagenb == 1) {
                 $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
             } else {
                 $this->_tableau($pdf, $tab_top_newpage - 1, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
             }
             // Pied de page
             $this->_pagefoot($pdf, $object, $outputlangs);
             if (method_exists($pdf, 'AliasNbPages')) {
                 $pdf->AliasNbPages();
             }
             $pdf->Close();
             $pdf->Output($file, 'F');
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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 pdf onto disk
  *
  *  @param		Object		$object				Object to generate
  *  @param		Translate	$outputlangs		Lang output object
  *  @param		string		$srctemplatepath	Full path of source filename for generator using a template file
  *  @param		int			$hidedetails		Do not show line details
  *  @param		int			$hidedesc			Do not show desc
  *  @param		int			$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, $mysoc, $db, $hookmanager;
     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 (!empty($conf->global->MAIN_USE_FPDF)) {
         $outputlangs->charset_output = 'ISO-8859-1';
     }
     $outputlangs->load("main");
     $outputlangs->load("dict");
     $outputlangs->load("trips");
     $outputlangs->load("project");
     $nblignes = count($object->lines);
     if ($conf->expensereport->dir_output) {
         // Definition of $dir and $file
         if ($object->specimen) {
             $dir = $conf->expensereport->dir_output;
             $file = $dir . "/SPECIMEN.pdf";
         } else {
             $objectref = dol_sanitizeFileName($object->ref);
             $dir = $conf->expensereport->dir_output . "/" . $objectref;
             $file = $dir . "/" . $objectref . ".pdf";
         }
         if (!file_exists($dir)) {
             if (dol_mkdir($dir) < 0) {
                 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
                 return 0;
             }
         }
         if (isset($object->lignes) && !isset($object->lines)) {
             $object->lines = $object->lignes;
         }
         if (file_exists($dir)) {
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action);
             // Note that $action and $object may have been modified by some hooks
             // Create pdf instance
             $pdf = pdf_getInstance($this->format);
             $default_font_size = pdf_getPDFFontSize($outputlangs);
             // Must be after pdf_getInstance
             $heightforinfotot = 50;
             // Height reserved to output the info and total part
             $heightforfreetext = isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5;
             // Height reserved to output the free text on last page
             $heightforfooter = $this->marge_basse + 8;
             // Height reserved to output the footer (value include bottom margin)
             $pdf->SetAutoPageBreak(1, 0);
             if (class_exists('TCPDF')) {
                 $pdf->setPrintHeader(false);
                 $pdf->setPrintFooter(false);
             }
             $pdf->SetFont(pdf_getPDFFont($outputlangs));
             // Set path to the background PDF File
             if (empty($conf->global->MAIN_DISABLE_FPDI) && !empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) {
                 $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output . '/' . $conf->global->MAIN_ADD_PDF_BACKGROUND);
                 $tplidx = $pdf->importPage(1);
             }
             $pdf->Open();
             $pagenb = 0;
             $pdf->SetDrawColor(128, 128, 128);
             $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref_number));
             $pdf->SetSubject($outputlangs->transnoentities("Trips"));
             $pdf->SetCreator("Dolibarr " . DOL_VERSION);
             $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
             $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref) . " " . $outputlangs->transnoentities("Trips"));
             if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
                 $pdf->SetCompression(false);
             }
             $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);
             // Left, Top, Right
             // 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();
             if (!empty($tplidx)) {
                 $pdf->useTemplate($tplidx);
             }
             $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 = 95;
             $tab_top_newpage = empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 95 : 10;
             $tab_height = 110;
             $tab_height_newpage = 110;
             // Show notes
             $notetoshow = empty($object->note_public) ? '' : $object->note_public;
             if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) {
                 // Get first sale rep
                 if (is_object($object->thirdparty)) {
                     $salereparray = $object->thirdparty->getSalesRepresentatives($user);
                     $salerepobj = new User($this->db);
                     $salerepobj->fetch($salereparray[0]['id']);
                     if (!empty($salerepobj->signature)) {
                         $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature);
                     }
                 }
             }
             if ($notetoshow) {
                 $tab_top = 95;
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->writeHTMLCell(190, 3, $this->posxpiece - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1);
                 $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++) {
                 $piece_comptable = $i + 1;
                 $curY = $nexY;
                 $pdf->SetFont('', '', $default_font_size - 1);
                 // Into loop to work with multipage
                 $pdf->SetTextColor(0, 0, 0);
                 $pdf->setTopMargin($tab_top_newpage);
                 $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot);
                 // The only function to edit the bottom margin of current page to set it.
                 $pageposbefore = $pdf->getPage();
                 // Description of product line
                 $curX = $this->posxdesc - 1;
                 $showpricebeforepagebreak = 1;
                 // Accountancy piece
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->writeHTMLCell($this->posxcomment - $this->posxpiece - 1, 3, $this->posxpiece - 1, $curY, $piece_comptable, 0, 1);
                 // Comments
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->SetXY($this->posxcomment, $curY);
                 $pdf->writeHTMLCell($this->posxdate - $this->posxdesc - 1, 3, $this->posxdesc - 1, $curY, $object->lines[$i]->comments, 0, 1);
                 //nexY
                 $nexY = $pdf->GetY();
                 $pageposafter = $pdf->getPage();
                 $pdf->setPage($pageposbefore);
                 $pdf->setTopMargin($this->marge_haute);
                 $pdf->setPageOrientation('', 1, 0);
                 // The only function to edit the bottom margin of current page to set it.
                 // Date
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->SetXY($this->posxdate, $curY);
                 $pdf->MultiCell($this->posxtype - $this->posxdate - 1, 3, dol_print_date($object->lines[$i]->date, "day", false, $outpulangs), 0, 'C');
                 // Type
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->SetXY($this->posxtype, $curY);
                 $pdf->MultiCell($this->posxprojet - $this->posxtype - 1, 3, $outputlangs->transnoentities($object->lines[$i]->type_fees_code), 0, 'C');
                 // Project
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->SetXY($this->posxprojet, $curY);
                 $pdf->MultiCell($this->posxtva - $this->posxprojet - 1, 3, $object->lines[$i]->projet_ref, 0, 'C');
                 // VAT Rate
                 if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) {
                     $vat_rate = pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails);
                     $pdf->SetFont('', '', $default_font_size - 1);
                     $pdf->SetXY($this->posxtva, $curY);
                     $pdf->MultiCell($this->posxup - $this->posxtva - 1, 3, $vat_rate, 0, 'R');
                 }
                 // Unit price
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->SetXY($this->posxup, $curY);
                 $pdf->MultiCell($this->posxqty - $this->posxup - 1, 3, price($object->lines[$i]->value_unit), 0, 'R');
                 // Quantity
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->SetXY($this->posxqty, $curY);
                 $pdf->MultiCell($this->postotalttc - $this->posxqty, 3, $object->lines[$i]->qty, 0, 'C');
                 // Total with all taxes
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->SetXY($this->postotalttc - 1, $curY);
                 $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalttc, 3, price($object->lines[$i]->total_ttc), 0, 'R');
                 $nexY += 5;
                 // Cherche nombre de lignes a venir pour savoir si place suffisante
                 if ($i < $nblignes - 1) {
                     //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;
                     // Et si on affiche dates de validite, on ajoute encore une ligne
                     if ($object->lines[$i]->date_start && $object->lines[$i]->date_end) {
                         $nblineFollowDesc += 4;
                     }
                 } else {
                     $nblineFollowDesc = 0;
                 }
                 $nexY += 2;
                 // Passe espace entre les lignes
                 // Detect if some page were added automatically and output _tableau for past pages
                 while ($pagenb < $pageposafter) {
                     $pdf->setPage($pagenb);
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     $pagenb++;
                     $pdf->setPage($pagenb);
                     $pdf->setPageOrientation('', 1, 0);
                     // The only function to edit the bottom margin of current page to set it.
                     if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                         $this->_pagehead($pdf, $object, 0, $outputlangs);
                     }
                 }
                 if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) {
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     // New page
                     $pdf->AddPage();
                     if (!empty($tplidx)) {
                         $pdf->useTemplate($tplidx);
                     }
                     $pagenb++;
                     if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                         $this->_pagehead($pdf, $object, 0, $outputlangs);
                     }
                 }
             }
             // Show square
             if ($pagenb == 1) {
                 $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
             } else {
                 $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
             }
             // Show total area box
             $posy = $bottomlasttab + 5;
             //$nexY+95;
             $pdf->SetXY(100, $posy);
             $pdf->MultiCell(60, 5, $outputlangs->transnoentities("TotalHT"), 1, 'L');
             $pdf->SetXY(160, $posy);
             $pdf->MultiCell($this->page_largeur - $this->marge_gauche - 160, 5, price($object->total_ht), 1, 'R');
             $pdf->SetFillColor(248, 248, 248);
             if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) {
                 $posy += 5;
                 $pdf->SetXY(100, $posy);
                 $pdf->SetTextColor(0, 0, 60);
                 $pdf->MultiCell(60, 5, $outputlangs->transnoentities("TotalVAT"), 1, 'L');
                 $pdf->SetXY(160, $posy);
                 $pdf->MultiCell($this->page_largeur - $this->marge_gauche - 160, 5, price($object->total_tva), 1, 'R');
             }
             $posy += 5;
             $pdf->SetXY(100, $posy);
             $pdf->SetFont('', 'B', 10);
             $pdf->SetTextColor(0, 0, 60);
             $pdf->MultiCell(60, 5, $outputlangs->transnoentities("TotalTTC"), 1, 'L');
             $pdf->SetXY(160, $posy);
             $pdf->MultiCell($this->page_largeur - $this->marge_gauche - 160, 5, price($object->total_ttc), 1, 'R');
             // Pied de page
             $this->_pagefoot($pdf, $object, $outputlangs);
             if (method_exists($pdf, 'AliasNbPages')) {
                 $pdf->AliasNbPages();
             }
             $pdf->Close();
             $pdf->Output($file, 'F');
             // Add pdfgeneration hook
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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", "EXPENSEREPORT_OUTPUTDIR");
         return 0;
     }
     $this->error = $langs->trans("ErrorUnknown");
     return 0;
     // Erreur par defaut
 }
Example #28
0
 /**
  * Register plugin hooks
  * 
  * @throws RuntimeException
  */
 private function registerHooks()
 {
     if (isset($this->config->Hooks)) {
         foreach (get_object_vars($this->config->Hooks) as $hookName => $hookMethod) {
             if ($this->packageManager->isHookRegistrationIsAllowed($hookMethod, $this->packageName, $this->pluginName)) {
                 $hookMethodName = "hook{$hookMethod}";
                 $hook = new Hook($hookName, $hookMethodName, $this);
                 if (HookManager::isHookRegistered($hook)) {
                     throw new RuntimeException("Hook {$hookMethod} is already registered.");
                 }
                 if (method_exists($this, $hookMethodName)) {
                     // Check if there is hook registered on $hookName with same method name and replace it
                     $isReplacedHook = false;
                     if (HookManager::isAnyHooksRegistered($hookName)) {
                         $registeredHooks = HookManager::getRegisteredHooks($hookName);
                         foreach ($registeredHooks as $registeredHook) {
                             if ($registeredHook->getMethod() == $hookMethodName) {
                                 HookManager::replaceHook($registeredHook, $hook);
                                 $isReplacedHook = true;
                                 break;
                             }
                         }
                     }
                     if (!$isReplacedHook) {
                         // Register hook if it is not replaced
                         HookManager::registerHook($hook);
                     }
                 } else {
                     throw new RuntimeException("Hook method of plugin {$this->pluginName} in package {$this->packageName} for hook {$hookName} -> {$hookMethodName} doesn't exists!");
                 }
             }
         }
     }
 }
 /**
  *  Function to build pdf onto disk
  *
  *  @param		Object		$object				Object to generate
  *  @param		Translate	$outputlangs		Lang output object
  *  @param		string		$srctemplatepath	Full path of source filename for generator using a template file
  *  @param		int			$hidedetails		Do not show line details
  *  @param		int			$hidedesc			Do not show desc
  *  @param		int			$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, $mysoc, $db, $hookmanager;
     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 (!empty($conf->global->MAIN_USE_FPDF)) {
         $outputlangs->charset_output = 'ISO-8859-1';
     }
     $outputlangs->load("main");
     $outputlangs->load("dict");
     $outputlangs->load("companies");
     $outputlangs->load("bills");
     $outputlangs->load("products");
     $nblignes = count($object->lines);
     // Loop on each lines to detect if there is at least one image to show
     $realpatharray = array();
     if (!empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE)) {
         for ($i = 0; $i < $nblignes; $i++) {
             if (empty($object->lines[$i]->fk_product)) {
                 continue;
             }
             $objphoto = new Product($this->db);
             $objphoto->fetch($object->lines[$i]->fk_product);
             $pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product') . $object->lines[$i]->fk_product . "/photos/";
             $dir = $conf->product->dir_output . '/' . $pdir;
             $realpath = '';
             foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) {
                 $filename = $obj['photo'];
                 //if ($obj['photo_vignette']) $filename='thumbs/'.$obj['photo_vignette'];
                 $realpath = $dir . $filename;
                 break;
             }
             if ($realpath) {
                 $realpatharray[$i] = $realpath;
             }
         }
     }
     if (count($realpatharray) == 0) {
         $this->posxpicture = $this->posxtva;
     }
     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 (dol_mkdir($dir) < 0) {
                 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
                 return 0;
             }
         }
         if (file_exists($dir)) {
             // Add pdfgeneration hook
             if (!is_object($hookmanager)) {
                 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
                 $hookmanager = new HookManager($this->db);
             }
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action);
             // Note that $action and $object may have been modified by some hooks
             // Set nblignes with the new facture lines content after hook
             $nblignes = count($object->lines);
             // Create pdf instance
             $pdf = pdf_getInstance($this->format);
             $default_font_size = pdf_getPDFFontSize($outputlangs);
             // Must be after pdf_getInstance
             $heightforinfotot = 50;
             // Height reserved to output the info and total part
             $heightforfreetext = isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5;
             // Height reserved to output the free text on last page
             $heightforfooter = $this->marge_basse + 8;
             // Height reserved to output the footer (value include bottom margin)
             $pdf->SetAutoPageBreak(1, 0);
             if (class_exists('TCPDF')) {
                 $pdf->setPrintHeader(false);
                 $pdf->setPrintFooter(false);
             }
             $pdf->SetFont(pdf_getPDFFont($outputlangs));
             // Set path to the background PDF File
             if (empty($conf->global->MAIN_DISABLE_FPDI) && !empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) {
                 $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output . '/' . $conf->global->MAIN_ADD_PDF_BACKGROUND);
                 $tplidx = $pdf->importPage(1);
             }
             $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 (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
                 $pdf->SetCompression(false);
             }
             $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);
             // Left, Top, Right
             // Positionne $this->atleastonediscount si on a au moins une remise
             for ($i = 0; $i < $nblignes; $i++) {
                 if ($object->lines[$i]->remise_percent) {
                     $this->atleastonediscount++;
                 }
             }
             if (empty($this->atleastonediscount) && empty($conf->global->PRODUCT_USE_UNITS)) {
                 $this->posxpicture += $this->postotalht - $this->posxdiscount;
                 $this->posxtva += $this->postotalht - $this->posxdiscount;
                 $this->posxup += $this->postotalht - $this->posxdiscount;
                 $this->posxqty += $this->postotalht - $this->posxdiscount;
                 $this->posxdiscount += $this->postotalht - $this->posxdiscount;
                 //$this->postotalht;
             }
             // Situation invoice handling
             if ($object->situation_cycle_ref) {
                 $this->situationinvoice = True;
                 $progress_width = 14;
                 $this->posxtva -= $progress_width;
                 $this->posxup -= $progress_width;
                 $this->posxqty -= $progress_width;
                 $this->posxdiscount -= $progress_width;
                 $this->posxprogress -= $progress_width;
             }
             // New page
             $pdf->AddPage();
             if (!empty($tplidx)) {
                 $pdf->useTemplate($tplidx);
             }
             $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 = empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10;
             $tab_height = 130;
             $tab_height_newpage = 150;
             // Incoterm
             $height_incoterms = 0;
             if ($conf->incoterm->enabled) {
                 $desc_incoterms = $object->getIncotermsForPDF();
                 if ($desc_incoterms) {
                     $tab_top = 88;
                     $pdf->SetFont('', '', $default_font_size - 1);
                     $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
                     $nexY = $pdf->GetY();
                     $height_incoterms = $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_incoterms + 1);
                     $tab_top = $nexY + 6;
                     $height_incoterms += 4;
                 }
             }
             // Affiche notes
             $notetoshow = empty($object->note_public) ? '' : $object->note_public;
             if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) {
                 // Get first sale rep
                 if (is_object($object->thirdparty)) {
                     $salereparray = $object->thirdparty->getSalesRepresentatives($user);
                     $salerepobj = new User($this->db);
                     $salerepobj->fetch($salereparray[0]['id']);
                     if (!empty($salerepobj->signature)) {
                         $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature);
                     }
                 }
             }
             if ($notetoshow) {
                 $tab_top = 88 + $height_incoterms;
                 $pdf->SetFont('', '', $default_font_size - 1);
                 $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1);
                 $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);
                 // Into loop to work with multipage
                 $pdf->SetTextColor(0, 0, 0);
                 // Define size of image if we need it
                 $imglinesize = array();
                 if (!empty($realpatharray[$i])) {
                     $imglinesize = pdf_getSizeForImage($realpatharray[$i]);
                 }
                 $pdf->setTopMargin($tab_top_newpage);
                 $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot);
                 // The only function to edit the bottom margin of current page to set it.
                 $pageposbefore = $pdf->getPage();
                 $showpricebeforepagebreak = 1;
                 $posYAfterImage = 0;
                 $posYAfterDescription = 0;
                 // We start with Photo of product line
                 if (isset($imglinesize['width']) && isset($imglinesize['height']) && $curY + $imglinesize['height'] > $this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)) {
                     $pdf->AddPage('', '', true);
                     if (!empty($tplidx)) {
                         $pdf->useTemplate($tplidx);
                     }
                     if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                         $this->_pagehead($pdf, $object, 0, $outputlangs);
                     }
                     $pdf->setPage($pageposbefore + 1);
                     $curY = $tab_top_newpage;
                     $showpricebeforepagebreak = 0;
                 }
                 if (isset($imglinesize['width']) && isset($imglinesize['height'])) {
                     $curX = $this->posxpicture - 1;
                     $pdf->Image($realpatharray[$i], $curX + ($this->posxtva - $this->posxpicture - $imglinesize['width']) / 2, $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300);
                     // Use 300 dpi
                     // $pdf->Image does not increase value return by getY, so we save it manually
                     $posYAfterImage = $curY + $imglinesize['height'];
                 }
                 // Description of product line
                 $curX = $this->posxdesc - 1;
                 $pdf->startTransaction();
                 pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxpicture - $curX, 3, $curX, $curY, $hideref, $hidedesc);
                 $pageposafter = $pdf->getPage();
                 if ($pageposafter > $pageposbefore) {
                     $pdf->rollbackTransaction(true);
                     $pageposafter = $pageposbefore;
                     //print $pageposafter.'-'.$pageposbefore;exit;
                     $pdf->setPageOrientation('', 1, $heightforfooter);
                     // The only function to edit the bottom margin of current page to set it.
                     pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxpicture - $curX, 3, $curX, $curY, $hideref, $hidedesc);
                     $pageposafter = $pdf->getPage();
                     $posyafter = $pdf->GetY();
                     //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit;
                     if ($posyafter > $this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)) {
                         if ($i == $nblignes - 1) {
                             $pdf->AddPage('', '', true);
                             if (!empty($tplidx)) {
                                 $pdf->useTemplate($tplidx);
                             }
                             if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                                 $this->_pagehead($pdf, $object, 0, $outputlangs);
                             }
                             $pdf->setPage($pageposafter + 1);
                         }
                     } else {
                         // We found a page break
                         $showpricebeforepagebreak = 0;
                     }
                 } else {
                     $pdf->commitTransaction();
                 }
                 $posYAfterDescription = $pdf->GetY();
                 $nexY = $pdf->GetY();
                 $pageposafter = $pdf->getPage();
                 $pdf->setPage($pageposbefore);
                 $pdf->setTopMargin($this->marge_haute);
                 $pdf->setPageOrientation('', 1, 0);
                 // The only function to edit the bottom margin of current page to set it.
                 // We suppose that a too long description or photo were moved completely on next page
                 if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
                     $pdf->setPage($pageposafter);
                     $curY = $tab_top_newpage;
                 }
                 $pdf->SetFont('', '', $default_font_size - 1);
                 // On repositionne la police par defaut
                 // VAT Rate
                 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 - 0.8, 3, $vat_rate, 0, 'R');
                 }
                 // Unit price before discount
                 $up_excl_tax = pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails);
                 $pdf->SetXY($this->posxup, $curY);
                 $pdf->MultiCell($this->posxqty - $this->posxup - 0.8, 3, $up_excl_tax, 0, 'R', 0);
                 // Quantity
                 $qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails);
                 $pdf->SetXY($this->posxqty, $curY);
                 // Enough for 6 chars
                 if ($conf->global->PRODUCT_USE_UNITS) {
                     $pdf->MultiCell($this->posxunit - $this->posxqty - 0.8, 4, $qty, 0, 'R');
                 } else {
                     $pdf->MultiCell($this->posxdiscount - $this->posxqty - 0.8, 4, $qty, 0, 'R');
                 }
                 // Unit
                 if ($conf->global->PRODUCT_USE_UNITS) {
                     $unit = pdf_getlineunit($object, $i, $outputlangs, $hidedetails, $hookmanager);
                     $pdf->SetXY($this->posxunit, $curY);
                     $pdf->MultiCell($this->posxdiscount - $this->posxunit - 0.8, 4, $unit, 0, 'L');
                 }
                 // Discount on line
                 if ($object->lines[$i]->remise_percent) {
                     $pdf->SetXY($this->posxdiscount - 2, $curY);
                     $remise_percent = pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails);
                     $pdf->MultiCell($this->posxprogress - $this->posxdiscount + 2, 3, $remise_percent, 0, 'R');
                 }
                 if ($this->situationinvoice) {
                     // Situation progress
                     $progress = pdf_getlineprogress($object, $i, $outputlangs, $hidedetails);
                     $pdf->SetXY($this->posxprogress, $curY);
                     $pdf->MultiCell($this->postotalht - $this->posxprogress, 3, $progress, 0, 'R');
                 }
                 // Total HT line
                 $total_excl_tax = pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails);
                 $pdf->SetXY($this->postotalht, $curY);
                 $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalht, 3, $total_excl_tax, 0, 'R', 0);
                 // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva
                 $prev_progress = $object->lines[$i]->get_prev_progress();
                 if ($prev_progress > 0) {
                     if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) {
                         $tvaligne = $object->lines[$i]->multicurrency_total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent;
                     } else {
                         $tvaligne = $object->lines[$i]->total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent;
                     }
                 } else {
                     if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) {
                         $tvaligne = $object->lines[$i]->multicurrency_total_tva;
                     } else {
                         $tvaligne = $object->lines[$i]->total_tva;
                     }
                 }
                 $localtax1ligne = $object->lines[$i]->total_localtax1;
                 $localtax2ligne = $object->lines[$i]->total_localtax2;
                 $localtax1_rate = $object->lines[$i]->localtax1_tx;
                 $localtax2_rate = $object->lines[$i]->localtax2_tx;
                 $localtax1_type = $object->lines[$i]->localtax1_type;
                 $localtax2_type = $object->lines[$i]->localtax2_type;
                 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;
                 // Retrieve type from database for backward compatibility with old records
                 if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') && (!empty($localtax1_rate) || !empty($localtax2_rate))) {
                     $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc);
                     $localtax1_type = $localtaxtmp_array[0];
                     $localtax2_type = $localtaxtmp_array[2];
                 }
                 // retrieve global local tax
                 if ($localtax1_type && $localtax1ligne != 0) {
                     $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne;
                 }
                 if ($localtax2_type && $localtax2ligne != 0) {
                     $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne;
                 }
                 if (($object->lines[$i]->info_bits & 0x1) == 0x1) {
                     $vatrate .= '*';
                 }
                 if (!isset($this->tva[$vatrate])) {
                     $this->tva[$vatrate] = '';
                 }
                 $this->tva[$vatrate] += $tvaligne;
                 if ($posYAfterImage > $posYAfterDescription) {
                     $nexY = $posYAfterImage;
                 }
                 // Add line
                 if ($conf->global->MAIN_PDF_DASH_BETWEEN_LINES && $i < $nblignes - 1) {
                     $pdf->setPage($pageposafter);
                     $pdf->SetLineStyle(array('dash' => '1,1', 'color' => array(80, 80, 80)));
                     //$pdf->SetDrawColor(190,190,200);
                     $pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1);
                     $pdf->SetLineStyle(array('dash' => 0));
                 }
                 $nexY += 2;
                 // Passe espace entre les lignes
                 // Detect if some page were added automatically and output _tableau for past pages
                 while ($pagenb < $pageposafter) {
                     $pdf->setPage($pagenb);
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1, $object->multicurrency_code);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     $pagenb++;
                     $pdf->setPage($pagenb);
                     $pdf->setPageOrientation('', 1, 0);
                     // The only function to edit the bottom margin of current page to set it.
                     if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                         $this->_pagehead($pdf, $object, 0, $outputlangs);
                     }
                 }
                 if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) {
                     if ($pagenb == 1) {
                         $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1, $object->multicurrency_code);
                     } else {
                         $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code);
                     }
                     $this->_pagefoot($pdf, $object, $outputlangs, 1);
                     // New page
                     $pdf->AddPage();
                     if (!empty($tplidx)) {
                         $pdf->useTemplate($tplidx);
                     }
                     $pagenb++;
                     if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
                         $this->_pagehead($pdf, $object, 0, $outputlangs);
                     }
                 }
             }
             // Show square
             if ($pagenb == 1) {
                 $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0, $object->multicurrency_code);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
             } else {
                 $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0, $object->multicurrency_code);
                 $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 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);
             if (method_exists($pdf, 'AliasNbPages')) {
                 $pdf->AliasNbPages();
             }
             $pdf->Close();
             $pdf->Output($file, 'F');
             // Add pdfgeneration hook
             $hookmanager->initHooks(array('pdfgeneration'));
             $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
             global $action;
             $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action);
             // Note that $action and $object may have been modified by some hooks
             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", "FAC_OUTPUTDIR");
         return 0;
     }
     $this->error = $langs->trans("ErrorUnknown");
     return 0;
     // Erreur par defaut
 }
Example #30
0
 /**
  *  Load an object from an order and create a new invoice into database
  *
  *  @param      Object			$object         	Object source
  *  @return     int             					<0 if KO, 0 if nothing done, 1 if OK
  */
 function createFromOrder($object)
 {
     global $conf, $user, $langs;
     $error = 0;
     // Closed order
     $this->date = dol_now();
     $this->source = 0;
     $num = count($object->lines);
     for ($i = 0; $i < $num; $i++) {
         $line = new FactureLigne($this->db);
         $line->libelle = $object->lines[$i]->libelle;
         $line->desc = $object->lines[$i]->desc;
         //$line->price			= $object->lines[$i]->price;
         $line->subprice = $object->lines[$i]->subprice;
         $line->total_ht = $object->lines[$i]->total_ht;
         $line->total_tva = $object->lines[$i]->total_tva;
         $line->total_ttc = $object->lines[$i]->total_ttc;
         $line->tva_tx = $object->lines[$i]->tva_tx;
         $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
         $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
         $line->qty = $object->lines[$i]->qty;
         $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
         $line->remise_percent = $object->lines[$i]->remise_percent;
         $line->fk_product = $object->lines[$i]->fk_product;
         $line->info_bits = $object->lines[$i]->info_bits;
         $line->product_type = $object->lines[$i]->product_type;
         $line->rang = $object->lines[$i]->rang;
         $line->special_code = $object->lines[$i]->special_code;
         $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
         $this->lines[$i] = $line;
     }
     $this->socid = $object->socid;
     $this->fk_project = $object->fk_project;
     $this->cond_reglement_id = $object->cond_reglement_id;
     $this->mode_reglement_id = $object->mode_reglement_id;
     $this->availability_id = $object->availability_id;
     $this->demand_reason_id = $object->demand_reason_id;
     $this->date_livraison = $object->date_livraison;
     $this->fk_delivery_address = $object->fk_delivery_address;
     $this->contact_id = $object->contactid;
     $this->ref_client = $object->ref_client;
     $this->note = $object->note;
     $this->note_public = $object->note_public;
     $this->origin = $object->element;
     $this->origin_id = $object->id;
     // Possibility to add external linked objects with hooks
     $this->linked_objects[$this->origin] = $this->origin_id;
     if (is_array($object->other_linked_objects) && !empty($object->other_linked_objects)) {
         $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
     }
     $ret = $this->create($user);
     if ($ret > 0) {
         // Actions hooked (by external module)
         include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
         $hookmanager = new HookManager($this->db);
         $hookmanager->initHooks(array('invoicedao'));
         $parameters = array('objFrom' => $object);
         $action = '';
         $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action);
         // Note that $action and $object may have been modified by some hooks
         if ($reshook < 0) {
             $error++;
         }
         if (!$error) {
             return 1;
         } else {
             return -1;
         }
     } else {
         return -1;
     }
 }