Exemplo n.º 1
0
 /**
  *      Return a string to show the box with list of available documents for object.
  *      This also set the property $this->numoffiles
  *
  *      @param      string				$modulepart         Module the files are related to ('propal', 'facture', 'facture_fourn', 'mymodule', 'mymodule_temp', ...)
  *      @param      string				$modulesubdir       Existing (so sanitized) sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
  *      @param      string				$filedir            Directory to scan
  *      @param      string				$urlsource          Url of origin page (for return)
  *      @param      int					$genallowed         Generation is allowed (1/0 or array list of templates)
  *      @param      int					$delallowed         Remove is allowed (1/0)
  *      @param      string				$modelselected      Model to preselect by default
  *      @param      string				$allowgenifempty	Allow generation even if list of template ($genallowed) is empty (show however a warning)
  *      @param      string				$forcenomultilang	Do not show language option (even if MAIN_MULTILANGS defined)
  *      @param      int					$iconPDF            Deprecated, see getDocumentsLink
  * 		@param		int					$maxfilenamelength	Max length for filename shown
  * 		@param		string				$noform				Do not output html form tags
  * 		@param		string				$param				More param on http links
  * 		@param		string				$title				Title to show on top of form
  * 		@param		string				$buttonlabel		Label on submit button
  * 		@param		string				$codelang			Default language code to use on lang combo box if multilang is enabled
  * 		@param		string				$morepicto			Add more HTML content into cell with picto
  * 		@return		string              					Output string with HTML array of documents (might be empty string)
  */
 function showdocuments($modulepart, $modulesubdir, $filedir, $urlsource, $genallowed, $delallowed = 0, $modelselected = '', $allowgenifempty = 1, $forcenomultilang = 0, $iconPDF = 0, $maxfilenamelength = 28, $noform = 0, $param = '', $title = '', $buttonlabel = '', $codelang = '', $morepicto = '')
 {
     // Deprecation warning
     if (0 !== $iconPDF) {
         dol_syslog(__METHOD__ . ": passing iconPDF parameter is deprecated", LOG_WARNING);
     }
     global $langs, $conf, $user, $hookmanager;
     global $form, $bc;
     if (!is_object($form)) {
         $form = new Form($this->db);
     }
     include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
     // For backward compatibility
     if (!empty($iconPDF)) {
         return $this->getDocumentsLink($modulepart, $modulesubdir, $filedir);
     }
     $printer = 0;
     if (in_array($modulepart, array('facture', 'supplier_proposal', 'propal', 'proposal', 'order', 'commande', 'expedition', 'commande_fournisseur'))) {
         $printer = !empty($user->rights->printing->read) && !empty($conf->printing->enabled) ? true : false;
     }
     $hookmanager->initHooks(array('formfile'));
     $forname = 'builddoc';
     $out = '';
     $var = true;
     $headershown = 0;
     $showempty = 0;
     $i = 0;
     $titletoshow = $langs->trans("Documents");
     if (!empty($title)) {
         $titletoshow = $title;
     }
     $out .= "\n" . '<!-- Start show_document -->' . "\n";
     //print 'filedir='.$filedir;
     // Show table
     if ($genallowed) {
         $modellist = array();
         if ($modulepart == 'company') {
             $showempty = 1;
             if (is_array($genallowed)) {
                 $modellist = $genallowed;
             } else {
                 include_once DOL_DOCUMENT_ROOT . '/core/modules/societe/modules_societe.class.php';
                 $modellist = ModeleThirdPartyDoc::liste_modeles($this->db);
             }
         } else {
             if ($modulepart == 'propal') {
                 if (is_array($genallowed)) {
                     $modellist = $genallowed;
                 } else {
                     include_once DOL_DOCUMENT_ROOT . '/core/modules/propale/modules_propale.php';
                     $modellist = ModelePDFPropales::liste_modeles($this->db);
                 }
             } else {
                 if ($modulepart == 'supplier_proposal') {
                     if (is_array($genallowed)) {
                         $modellist = $genallowed;
                     } else {
                         include_once DOL_DOCUMENT_ROOT . '/core/modules/supplier_proposal/modules_supplier_proposal.php';
                         $modellist = ModelePDFSupplierProposal::liste_modeles($this->db);
                     }
                 } else {
                     if ($modulepart == 'commande') {
                         if (is_array($genallowed)) {
                             $modellist = $genallowed;
                         } else {
                             include_once DOL_DOCUMENT_ROOT . '/core/modules/commande/modules_commande.php';
                             $modellist = ModelePDFCommandes::liste_modeles($this->db);
                         }
                     } elseif ($modulepart == 'expedition') {
                         if (is_array($genallowed)) {
                             $modellist = $genallowed;
                         } else {
                             include_once DOL_DOCUMENT_ROOT . '/core/modules/expedition/modules_expedition.php';
                             $modellist = ModelePDFExpedition::liste_modeles($this->db);
                         }
                     } elseif ($modulepart == 'livraison') {
                         if (is_array($genallowed)) {
                             $modellist = $genallowed;
                         } else {
                             include_once DOL_DOCUMENT_ROOT . '/core/modules/livraison/modules_livraison.php';
                             $modellist = ModelePDFDeliveryOrder::liste_modeles($this->db);
                         }
                     } else {
                         if ($modulepart == 'ficheinter') {
                             if (is_array($genallowed)) {
                                 $modellist = $genallowed;
                             } else {
                                 include_once DOL_DOCUMENT_ROOT . '/core/modules/fichinter/modules_fichinter.php';
                                 $modellist = ModelePDFFicheinter::liste_modeles($this->db);
                             }
                         } elseif ($modulepart == 'facture') {
                             if (is_array($genallowed)) {
                                 $modellist = $genallowed;
                             } else {
                                 include_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
                                 $modellist = ModelePDFFactures::liste_modeles($this->db);
                             }
                         } elseif ($modulepart == 'contract') {
                             if (is_array($genallowed)) {
                                 $modellist = $genallowed;
                             } else {
                                 include_once DOL_DOCUMENT_ROOT . '/core/modules/contract/modules_contract.php';
                                 $modellist = ModelePDFContract::liste_modeles($this->db);
                             }
                         } elseif ($modulepart == 'project') {
                             if (is_array($genallowed)) {
                                 $modellist = $genallowed;
                             } else {
                                 include_once DOL_DOCUMENT_ROOT . '/core/modules/project/modules_project.php';
                                 $modellist = ModelePDFProjects::liste_modeles($this->db);
                             }
                         } elseif ($modulepart == 'project_task') {
                             if (is_array($genallowed)) {
                                 $modellist = $genallowed;
                             } else {
                                 include_once DOL_DOCUMENT_ROOT . '/core/modules/project/task/modules_task.php';
                                 $modellist = ModelePDFTask::liste_modeles($this->db);
                             }
                         } elseif ($modulepart == 'export') {
                             if (is_array($genallowed)) {
                                 $modellist = $genallowed;
                             } else {
                                 include_once DOL_DOCUMENT_ROOT . '/core/modules/export/modules_export.php';
                                 $modellist = ModeleExports::liste_modeles($this->db);
                             }
                         } else {
                             if ($modulepart == 'commande_fournisseur') {
                                 if (is_array($genallowed)) {
                                     $modellist = $genallowed;
                                 } else {
                                     include_once DOL_DOCUMENT_ROOT . '/core/modules/supplier_order/modules_commandefournisseur.php';
                                     $modellist = ModelePDFSuppliersOrders::liste_modeles($this->db);
                                 }
                             } else {
                                 if ($modulepart == 'facture_fournisseur') {
                                     if (is_array($genallowed)) {
                                         $modellist = $genallowed;
                                     } else {
                                         include_once DOL_DOCUMENT_ROOT . '/core/modules/supplier_invoice/modules_facturefournisseur.php';
                                         $modellist = ModelePDFSuppliersInvoices::liste_modeles($this->db);
                                     }
                                 } else {
                                     if ($modulepart == 'remisecheque') {
                                         if (is_array($genallowed)) {
                                             $modellist = $genallowed;
                                         } else {
                                             include_once DOL_DOCUMENT_ROOT . '/core/modules/cheque/pdf/modules_chequereceipts.php';
                                             $modellist = ModeleChequeReceipts::liste_modeles($this->db);
                                         }
                                     } elseif ($modulepart == 'donation') {
                                         if (is_array($genallowed)) {
                                             $modellist = $genallowed;
                                         } else {
                                             include_once DOL_DOCUMENT_ROOT . '/core/modules/dons/modules_don.php';
                                             $modellist = ModeleDon::liste_modeles($this->db);
                                         }
                                     } else {
                                         if ($modulepart == 'unpaid') {
                                             $modellist = '';
                                         } else {
                                             if ($modulepart != 'agenda') {
                                                 // For normalized standard modules
                                                 $file = dol_buildpath('/core/modules/' . $modulepart . '/modules_' . $modulepart . '.php', 0);
                                                 if (file_exists($file)) {
                                                     $res = (include_once $file);
                                                 } else {
                                                     $file = dol_buildpath('/' . $modulepart . '/core/modules/' . $modulepart . '/modules_' . $modulepart . '.php', 0);
                                                     $res = (include_once $file);
                                                 }
                                                 $class = 'Modele' . ucfirst($modulepart);
                                                 if (class_exists($class)) {
                                                     $modellist = call_user_func($class . '::liste_modeles', $this->db);
                                                 } else {
                                                     dol_print_error($this->db, 'Bad value for modulepart');
                                                     return -1;
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $headershown = 1;
         $buttonlabeltoshow = $buttonlabel;
         if (empty($buttonlabel)) {
             $buttonlabel = $langs->trans('Generate');
         }
         if (empty($noform)) {
             $out .= '<form action="' . $urlsource . (empty($conf->global->MAIN_JUMP_TAG) ? '' : '#builddoc') . '" name="' . $forname . '" id="' . $forname . '_form" method="post">';
         }
         $out .= '<input type="hidden" name="action" value="builddoc">';
         $out .= '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
         $out .= load_fiche_titre($titletoshow, '', '');
         $out .= '<table class="liste formdoc noborder" summary="listofdocumentstable" width="100%">';
         $out .= '<tr class="liste_titre">';
         // Model
         if (!empty($modellist)) {
             $out .= '<th align="center" class="formdoc liste_titre maxwidthonsmartphone">';
             $out .= '<span class="hideonsmartphone">' . $langs->trans('Model') . ' </span>';
             if (is_array($modellist) && count($modellist) == 1) {
                 $arraykeys = array_keys($modellist);
                 $modelselected = $arraykeys[0];
             }
             $out .= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', '');
             $out .= '</th>';
         } else {
             $out .= '<th align="left" class="formdoc liste_titre">';
             $out .= $langs->trans("Files");
             $out .= '</th>';
         }
         // Language code (if multilang)
         $out .= '<th align="center" class="formdoc liste_titre maxwidthonsmartphone">';
         if (($allowgenifempty || is_array($modellist) && count($modellist) > 0) && $conf->global->MAIN_MULTILANGS && !$forcenomultilang && (!empty($modellist) || $showempty)) {
             include_once DOL_DOCUMENT_ROOT . '/core/class/html.formadmin.class.php';
             $formadmin = new FormAdmin($this->db);
             $defaultlang = $codelang ? $codelang : $langs->getDefaultLang();
             $morecss = 'maxwidth150';
             if (!empty($conf->browser->phone)) {
                 $morecss = 'maxwidth100';
             }
             $out .= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss);
         } else {
             $out .= '&nbsp;';
         }
         $out .= '</th>';
         // Button
         $addcolumforpicto = $delallowed || $printer || $morepicto;
         $out .= '<th align="center" colspan="' . ($addcolumforpicto ? '2' : '1') . '" class="formdocbutton liste_titre maxwidthonsmartphone">';
         $genbutton = '<input class="button" id="' . $forname . '_generatebutton" name="' . $forname . '_generatebutton"';
         $genbutton .= ' type="submit" value="' . $buttonlabel . '"';
         if (!$allowgenifempty && !is_array($modellist) && empty($modellist)) {
             $genbutton .= ' disabled';
         }
         $genbutton .= '>';
         if ($allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') {
             $langs->load("errors");
             $genbutton .= ' ' . img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
         }
         if (!$allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') {
             $genbutton = '';
         }
         if (empty($modellist) && !$showempty && $modulepart != 'unpaid') {
             $genbutton = '';
         }
         $out .= $genbutton;
         $out .= '</th>';
         if (!empty($hookmanager->hooks['formfile'])) {
             foreach ($hookmanager->hooks['formfile'] as $module) {
                 if (method_exists($module, 'formBuilddocLineOptions')) {
                     $out .= '<th></th>';
                 }
             }
         }
         $out .= '</tr>';
         // Execute hooks
         $parameters = array('socid' => isset($GLOBALS['socid']) ? $GLOBALS['socid'] : '', 'id' => isset($GLOBALS['id']) ? $GLOBALS['id'] : '', 'modulepart' => $modulepart);
         if (is_object($hookmanager)) {
             $reshook = $hookmanager->executeHooks('formBuilddocOptions', $parameters, $GLOBALS['object']);
             $out .= $hookmanager->resPrint;
         }
     }
     // Get list of files
     if (!empty($filedir)) {
         $file_list = dol_dir_list($filedir, 'files', 0, '', '(\\.meta|_preview\\.png)$', 'date', SORT_DESC);
         // Affiche en-tete tableau si non deja affiche
         if (!empty($file_list) && !$headershown) {
             $headershown = 1;
             $out .= '<div class="titre">' . $titletoshow . '</div>';
             $out .= '<table class="border" summary="listofdocumentstable" width="100%">';
         }
         // Loop on each file found
         if (is_array($file_list)) {
             foreach ($file_list as $file) {
                 $var = !$var;
                 // Define relative path for download link (depends on module)
                 $relativepath = $file["name"];
                 // Cas general
                 if ($modulesubdir) {
                     $relativepath = $modulesubdir . "/" . $file["name"];
                 }
                 // Cas propal, facture...
                 if ($modulepart == 'export') {
                     $relativepath = $file["name"];
                 }
                 // Other case
                 $out .= "<tr " . $bc[$var] . ">";
                 $documenturl = DOL_URL_ROOT . '/document.php';
                 if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) {
                     $documenturl = $conf->global->DOL_URL_ROOT_DOCUMENT_PHP;
                 }
                 // Show file name with link to download
                 $out .= '<td class="nowrap">';
                 $out .= '<a data-ajax="false" href="' . $documenturl . '?modulepart=' . $modulepart . '&amp;file=' . urlencode($relativepath) . '"';
                 $mime = dol_mimetype($relativepath, '', 0);
                 if (preg_match('/text/', $mime)) {
                     $out .= ' target="_blank"';
                 }
                 $out .= ' target="_blank">';
                 $out .= img_mime($file["name"], $langs->trans("File") . ': ' . $file["name"]) . ' ' . dol_trunc($file["name"], $maxfilenamelength);
                 $out .= '</a>' . "\n";
                 $out .= '</td>';
                 // Show file size
                 $size = !empty($file['size']) ? $file['size'] : dol_filesize($filedir . "/" . $file["name"]);
                 $out .= '<td align="right" class="nowrap">' . dol_print_size($size) . '</td>';
                 // Show file date
                 $date = !empty($file['date']) ? $file['date'] : dol_filemtime($filedir . "/" . $file["name"]);
                 $out .= '<td align="right" class="nowrap">' . dol_print_date($date, 'dayhour', 'tzuser') . '</td>';
                 if ($delallowed || $printer || $morepicto) {
                     $out .= '<td align="right">';
                     if ($delallowed) {
                         $out .= '<a href="' . $urlsource . (strpos($urlsource, '?') ? '&amp;' : '?') . 'action=remove_file&amp;file=' . urlencode($relativepath);
                         $out .= $param ? '&amp;' . $param : '';
                         //$out.= '&modulepart='.$modulepart; // TODO obsolete ?
                         //$out.= '&urlsource='.urlencode($urlsource); // TODO obsolete ?
                         $out .= '">' . img_picto($langs->trans("Delete"), 'delete.png') . '</a>';
                         //$out.='</td>';
                     }
                     if ($printer) {
                         //$out.= '<td align="right">';
                         $out .= '&nbsp;<a href="' . $urlsource . (strpos($urlsource, '?') ? '&amp;' : '?') . 'action=print_file&amp;printer=' . $modulepart . '&amp;file=' . urlencode($relativepath);
                         $out .= $param ? '&amp;' . $param : '';
                         $out .= '">' . img_picto($langs->trans("PrintFile", $relativepath), 'printer.png') . '</a>';
                     }
                     if ($morepicto) {
                         $morepicto = preg_replace('/__FILENAMEURLENCODED__/', urlencode($relativepath), $morepicto);
                         $out .= $morepicto;
                     }
                     $out .= '</td>';
                 }
                 if (is_object($hookmanager)) {
                     $parameters = array('socid' => isset($GLOBALS['socid']) ? $GLOBALS['socid'] : '', 'id' => isset($GLOBALS['id']) ? $GLOBALS['id'] : '', 'modulepart' => $modulepart, 'relativepath' => $relativepath);
                     $res = $hookmanager->executeHooks('formBuilddocLineOptions', $parameters, $file);
                     if (empty($res)) {
                         $out .= $hookmanager->resPrint;
                         // Complete line
                         $out .= '</tr>';
                     } else {
                         $out = $hookmanager->resPrint;
                     }
                     // Replace line
                 }
             }
             if (count($file_list) == 0 && $headershown) {
                 $out .= '<tr ' . $bc[0] . '><td colspan="3">' . $langs->trans("None") . '</td></tr>';
             }
             $this->numoffiles++;
         }
     }
     if ($headershown) {
         // Affiche pied du tableau
         $out .= "</table>\n";
         if ($genallowed) {
             if (empty($noform)) {
                 $out .= '</form>' . "\n";
             }
         }
     }
     $out .= '<!-- End show_document -->' . "\n";
     //return ($i?$i:$headershown);
     return $out;
 }
Exemplo n.º 2
0
 /**
  * 	Parse rss URL
  *
  * 	@param	string	$urlRSS		Url to parse
  * 	@param	int		$maxNb		Max nb of records to get (0 for no limit)
  * 	@param	int		$cachedelay	0=No cache, nb of seconds we accept cache files (cachedir must also be defined)
  * 	@param	string	$cachedir	Directory where to save cache file
  *	@return	int					<0 if KO, >0 if OK
  */
 public function parser($urlRSS, $maxNb = 0, $cachedelay = 60, $cachedir = '')
 {
     global $conf;
     include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
     $rss = '';
     $str = '';
     // This will contain content of feed
     // Check parameters
     if (!dol_is_url($urlRSS)) {
         $this->error = "ErrorBadUrl";
         return -1;
     }
     $this->_urlRSS = $urlRSS;
     $newpathofdestfile = $cachedir . '/' . dol_hash($this->_urlRSS, 3);
     // Force md5 hash (does not contains special chars)
     $newmask = '0644';
     //dol_syslog("RssPArser::parser parse url=".$urlRSS." => cache file=".$newpathofdestfile);
     $nowgmt = dol_now();
     // Search into cache
     $foundintocache = 0;
     if ($cachedelay > 0 && $cachedir) {
         $filedate = dol_filemtime($newpathofdestfile);
         if ($filedate >= $nowgmt - $cachedelay) {
             //dol_syslog("RssParser::parser cache file ".$newpathofdestfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we use it.");
             $foundintocache = 1;
             $this->_lastfetchdate = $filedate;
         } else {
             dol_syslog(get_class($this) . "::parser cache file " . $newpathofdestfile . " is not found or older than now - cachedelay (" . $nowgmt . " - " . $cachedelay . ") so we can't use it.");
         }
     }
     // Load file into $str
     if ($foundintocache) {
         $str = file_get_contents($newpathofdestfile);
     } else {
         try {
             ini_set("user_agent", "Dolibarr ERP-CRM RSS reader");
             ini_set("max_execution_time", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
             ini_set("default_socket_timeout", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
             $opts = array('http' => array('method' => "GET"));
             if (!empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) {
                 $opts['http']['timeout'] = $conf->global->MAIN_USE_CONNECT_TIMEOUT;
             }
             if (!empty($conf->global->MAIN_PROXY_USE)) {
                 $opts['http']['proxy'] = 'tcp://' . $conf->global->MAIN_PROXY_HOST . ':' . $conf->global->MAIN_PROXY_PORT;
             }
             //var_dump($opts);exit;
             $context = stream_context_create($opts);
             $str = file_get_contents($this->_urlRSS, false, $context);
         } catch (Exception $e) {
             print 'Error retrieving URL ' . $this->urlRSS . ' - ' . $e->getMessage();
         }
     }
     if ($str !== false) {
         // Convert $str into xml
         if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
             //print 'xx'.LIBXML_NOCDATA;
             libxml_use_internal_errors(false);
             $rss = simplexml_load_string($str, "SimpleXMLElement", LIBXML_NOCDATA);
         } else {
             $xmlparser = xml_parser_create('');
             if (!is_resource($xmlparser)) {
                 $this->error = "ErrorFailedToCreateParser";
                 return -1;
             }
             xml_set_object($xmlparser, $this);
             xml_set_element_handler($xmlparser, 'feed_start_element', 'feed_end_element');
             xml_set_character_data_handler($xmlparser, 'feed_cdata');
             $status = xml_parse($xmlparser, $str);
             xml_parser_free($xmlparser);
             $rss = $this;
             //var_dump($rss->_format);exit;
         }
     }
     // If $rss loaded
     if ($rss) {
         // Save file into cache
         if (empty($foundintocache) && $cachedir) {
             dol_syslog(get_class($this) . "::parser cache file " . $newpathofdestfile . " is saved onto disk.");
             if (!dol_is_dir($cachedir)) {
                 dol_mkdir($cachedir);
             }
             $fp = fopen($newpathofdestfile, 'w');
             fwrite($fp, $str);
             fclose($fp);
             if (!empty($conf->global->MAIN_UMASK)) {
                 $newmask = $conf->global->MAIN_UMASK;
             }
             @chmod($newpathofdestfile, octdec($newmask));
             $this->_lastfetchdate = $nowgmt;
         }
         unset($str);
         // Free memory
         if (empty($rss->_format)) {
             $rss->_format = 'rss';
             if (empty($rss->channel)) {
                 $rss->_format = 'atom';
             }
         }
         $items = array();
         // Save description entries
         if ($rss->_format == 'rss') {
             //var_dump($rss);
             if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
                 if (!empty($rss->channel->language)) {
                     $this->_language = (string) $rss->channel->language;
                 }
                 if (!empty($rss->channel->generator)) {
                     $this->_generator = (string) $rss->channel->generator;
                 }
                 if (!empty($rss->channel->copyright)) {
                     $this->_copyright = (string) $rss->channel->copyright;
                 }
                 if (!empty($rss->channel->lastbuilddate)) {
                     $this->_lastbuilddate = (string) $rss->channel->lastbuilddate;
                 }
                 if (!empty($rss->channel->image->url[0])) {
                     $this->_imageurl = (string) $rss->channel->image->url[0];
                 }
                 if (!empty($rss->channel->link)) {
                     $this->_link = (string) $rss->channel->link;
                 }
                 if (!empty($rss->channel->title)) {
                     $this->_title = (string) $rss->channel->title;
                 }
                 if (!empty($rss->channel->description)) {
                     $this->_description = (string) $rss->channel->description;
                 }
             } else {
                 //var_dump($rss->channel);
                 if (!empty($rss->channel['language'])) {
                     $this->_language = (string) $rss->channel['language'];
                 }
                 if (!empty($rss->channel['generator'])) {
                     $this->_generator = (string) $rss->channel['generator'];
                 }
                 if (!empty($rss->channel['copyright'])) {
                     $this->_copyright = (string) $rss->channel['copyright'];
                 }
                 if (!empty($rss->channel['lastbuilddate'])) {
                     $this->_lastbuilddate = (string) $rss->channel['lastbuilddate'];
                 }
                 if (!empty($rss->image['url'])) {
                     $this->_imageurl = (string) $rss->image['url'];
                 }
                 if (!empty($rss->channel['link'])) {
                     $this->_link = (string) $rss->channel['link'];
                 }
                 if (!empty($rss->channel['title'])) {
                     $this->_title = (string) $rss->channel['title'];
                 }
                 if (!empty($rss->channel['description'])) {
                     $this->_description = (string) $rss->channel['description'];
                 }
             }
             if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
                 $items = $rss->channel->item;
             } else {
                 $items = $rss->items;
             }
             // With xmlparse
             //var_dump($items);exit;
         } else {
             if ($rss->_format == 'atom') {
                 //var_dump($rss);
                 if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
                     if (!empty($rss->generator)) {
                         $this->_generator = (string) $rss->generator;
                     }
                     if (!empty($rss->lastbuilddate)) {
                         $this->_lastbuilddate = (string) $rss->modified;
                     }
                     if (!empty($rss->link->href)) {
                         $this->_link = (string) $rss->link->href;
                     }
                     if (!empty($rss->title)) {
                         $this->_title = (string) $rss->title;
                     }
                     if (!empty($rss->description)) {
                         $this->_description = (string) $rss->description;
                     }
                 } else {
                     //if (!empty($rss->channel['rss_language']))      $this->_language = (string) $rss->channel['rss_language'];
                     if (!empty($rss->channel['generator'])) {
                         $this->_generator = (string) $rss->channel['generator'];
                     }
                     //if (!empty($rss->channel['rss_copyright']))     $this->_copyright = (string) $rss->channel['rss_copyright'];
                     if (!empty($rss->channel['modified'])) {
                         $this->_lastbuilddate = (string) $rss->channel['modified'];
                     }
                     //if (!empty($rss->image['rss_url']))             $this->_imageurl = (string) $rss->image['rss_url'];
                     if (!empty($rss->channel['link'])) {
                         $this->_link = (string) $rss->channel['link'];
                     }
                     if (!empty($rss->channel['title'])) {
                         $this->_title = (string) $rss->channel['title'];
                     }
                     //if (!empty($rss->channel['rss_description']))   $this->_description = (string) $rss->channel['rss_description'];
                 }
                 if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
                     $tmprss = xml2php($rss);
                     $items = $tmprss['entry'];
                 } else {
                     $items = $rss->items;
                 }
                 // With xmlparse
                 //var_dump($items);exit;
             }
         }
         $i = 0;
         // Loop on each record
         if (is_array($items)) {
             foreach ($items as $item) {
                 //var_dump($item);exit;
                 if ($rss->_format == 'rss') {
                     if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
                         $itemLink = (string) $item->link;
                         $itemTitle = (string) $item->title;
                         $itemDescription = (string) $item->description;
                         $itemPubDate = (string) $item->pubDate;
                         $itemId = '';
                         $itemAuthor = '';
                     } else {
                         $itemLink = (string) $item['link'];
                         $itemTitle = (string) $item['title'];
                         $itemDescription = (string) $item['description'];
                         $itemPubDate = (string) $item['pubdate'];
                         $itemId = (string) $item['guid'];
                         $itemAuthor = (string) $item['author'];
                     }
                     // Loop on each category
                     $itemCategory = array();
                     if (is_array($item->category)) {
                         foreach ($item->category as $cat) {
                             $itemCategory[] = (string) $cat;
                         }
                     }
                 } else {
                     if ($rss->_format == 'atom') {
                         if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
                             $itemLink = isset($item['link']['href']) ? (string) $item['link']['href'] : '';
                             $itemTitle = (string) $item['title'];
                             $itemDescription = (string) $item['summary'];
                             $itemPubDate = (string) $item['created'];
                             $itemId = (string) $item['id'];
                             $itemAuthor = (string) ($item['author'] ? $item['author'] : $item['author_name']);
                         } else {
                             $itemLink = isset($item['link']['href']) ? (string) $item['link']['href'] : '';
                             $itemTitle = (string) $item['title'];
                             $itemDescription = (string) $item['summary'];
                             $itemPubDate = (string) $item['created'];
                             $itemId = (string) $item['id'];
                             $itemAuthor = (string) ($item['author'] ? $item['author'] : $item['author_name']);
                         }
                     } else {
                         print 'ErrorBadFeedFormat';
                     }
                 }
                 // Add record to result array
                 $this->_rssarray[$i] = array('link' => $itemLink, 'title' => $itemTitle, 'description' => $itemDescription, 'pubDate' => $itemPubDate, 'category' => $itemCategory, 'id' => $itemId, 'author' => $itemAuthor);
                 //var_dump($this->_rssarray);
                 $i++;
                 if ($i > $maxNb) {
                     break;
                 }
                 // We get all records we want
             }
         }
         return 1;
     } else {
         $this->error = 'ErrorFailedToLoadRSSFile';
         return -1;
     }
 }
Exemplo n.º 3
0
 // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
 $fileimage = $file . '_preview.png';
 // If PDF has 1 page
 $fileimagebis = $file . '_preview-0.pdf.png';
 // If PDF has more than one page
 $relativepathimage = $relativepath . '_preview.png';
 $var = true;
 // Si fichier PDF existe
 if (file_exists($file)) {
     $encfile = urlencode($file);
     print '<table class="nobordernopadding" width="100%">';
     print '<tr class="liste_titre"><td colspan="4">' . $langs->trans("Documents") . '</td></tr>';
     print '<tr ' . $bc[$var] . '><td>' . $langs->trans("Proposal") . ' PDF</td>';
     print '<td><a data-ajax="false" href="' . DOL_URL_ROOT . '/document.php?modulepart=propal&file=' . urlencode($relativepath) . '">' . $object->ref . '.pdf</a></td>';
     print '<td align="right">' . dol_print_size(dol_filesize($file)) . '</td>';
     print '<td align="right">' . dol_print_date(dol_filemtime($file), 'dayhour') . '</td>';
     print '</tr>';
     print "</table>\n";
     // Conversion du PDF en image png si fichier png non existant
     if (!file_exists($fileimage) && !file_exists($fileimagebis) || filemtime($fileimage) < filemtime($file)) {
         if (class_exists("Imagick")) {
             $ret = dol_convert_file($file, 'png', $fileimage);
             if ($ret < 0) {
                 $error++;
             }
         } else {
             $langs->load("errors");
             print '<font class="error">' . $langs->trans("ErrorNoImagickReadimage") . '</font>';
         }
     }
 }
	/**
	 * Return amount of elements by month for several years
	 *
	 * @param int $endyear		End year
	 * @param int $startyear	Start year
	 * @param int $cachedelay accept for cache file (0=No read, no save of cache, -1=No read but save)
	 * @return array of values
	 */
	function getTransformRateByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0)
	{
		global $conf, $user, $langs;

		if ($startyear > $endyear) return - 1;

		$datay = array();

		// Search into cache
		if (! empty($cachedelay))
		{
			include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
			include_once DOL_DOCUMENT_ROOT . '/core/lib/json.lib.php';
		}

		$newpathofdestfile = $conf->user->dir_temp . '/' . get_class($this) . '_' . __FUNCTION__ . '_' . (empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix . '_') . $langs->defaultlang . '_user' . $user->id . '.cache';
		$newmask = '0644';

		$nowgmt = dol_now();

		$foundintocache = 0;
		if ($cachedelay > 0) {
			$filedate = dol_filemtime($newpathofdestfile);
			if ($filedate >= ($nowgmt - $cachedelay)) {
				$foundintocache = 1;

				$this->_lastfetchdate[get_class($this) . '_' . __FUNCTION__] = $filedate;
			} else {
				dol_syslog(get_class($this) . '::' . __FUNCTION__ . " cache file " . $newpathofdestfile . " is not found or older than now - cachedelay (" . $nowgmt . " - " . $cachedelay . ") so we can't use it.");
			}
		}

		// Load file into $data
		if ($foundintocache) // Cache file found and is not too old
		{
			dol_syslog(get_class($this) . '::' . __FUNCTION__ . " read data from cache file " . $newpathofdestfile . " " . $filedate . ".");
			$data = json_decode(file_get_contents($newpathofdestfile), true);
		} else {
			$year = $startyear;
			while ( $year <= $endyear ) {
				$datay[$year] = $this->getTransformRateByMonth($year);
				$year ++;
			}

			$data = array ();
			// $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
			for($i = 0; $i < 12; $i ++) {
				$data[$i][] = $datay[$endyear][$i][0]; // set label
				$year = $startyear;
				while ( $year <= $endyear ) {
					$data[$i][] = $datay[$year][$i][1]; // set yval for x=i
					$year ++;
				}
			}
		}

		// Save cache file
		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == - 1)) {
			dol_syslog(get_class($this) . '::' . __FUNCTION__ . " save cache file " . $newpathofdestfile . " onto disk.");
			if (! dol_is_dir($conf->user->dir_temp))
				dol_mkdir($conf->user->dir_temp);
			$fp = fopen($newpathofdestfile, 'w');
			fwrite($fp, json_encode($data));
			fclose($fp);
			if (! empty($conf->global->MAIN_UMASK))
				$newmask = $conf->global->MAIN_UMASK;
			@chmod($newpathofdestfile, octdec($newmask));

			$this->_lastfetchdate[get_class($this) . '_' . __FUNCTION__] = $nowgmt;
		}

		return $data;
	}
Exemplo n.º 5
0
}
// Construit liste des fichiers
clearstatcache();
$totalsize = 0;
$filearray = array();
$errorlevel = error_reporting();
error_reporting(0);
$handle = opendir($upload_dir);
error_reporting($errorlevel);
if (is_resource($handle)) {
    $i = 0;
    while (($file = readdir($handle)) !== false) {
        if (!is_dir($dir . $file) && substr($file, 0, 1) != '.' && substr($file, 0, 3) != 'CVS') {
            $filearray[$i]->name = $file;
            $filearray[$i]->size = dol_filesize($upload_dir . "/" . $file);
            $filearray[$i]->date = dol_filemtime($upload_dir . "/" . $file);
            $totalsize += $filearray[$i]->size;
            $i++;
        }
    }
    closedir($handle);
} else {
    //            print '<div class="error">'.$langs->trans("ErrorCanNotReadDir",$upload_dir).'</div>';
}
/*
print '<table class="border"width="100%">';
// Nbre fichiers
print '<tr><td>'.$langs->trans("NbOfAttachedFiles").'</td><td colspan="3">'.count($filearray).'</td></tr>';
//Total taille
print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td colspan="3">'.$totalsize.' '.$langs->trans("bytes").'</td></tr>';
print '</table>';
Exemplo n.º 6
0
            print '<td align="center">' . $langs->trans("ExpectedChecksum") . '</td>';
            print '<td align="center">' . $langs->trans("CurrentChecksum") . '</td>';
            print '<td align="right">' . $langs->trans("Size") . '</td>';
            print '<td align="right">' . $langs->trans("DateModification") . '</td>';
            print '</tr>' . "\n";
            $var = true;
            $tmpfilelist = dol_sort_array($file_list['updated'], 'filename');
            if (is_array($tmpfilelist) && count($tmpfilelist)) {
                foreach ($tmpfilelist as $file) {
                    $var = !$var;
                    print '<tr ' . $bc[$var] . '>';
                    print '<td>' . $file['filename'] . '</td>' . "\n";
                    print '<td align="center">' . $file['expectedmd5'] . '</td>' . "\n";
                    print '<td align="center">' . $file['md5'] . '</td>' . "\n";
                    print '<td align="right">' . dol_print_size(dol_filesize(DOL_DOCUMENT_ROOT . '/' . $file['filename'])) . '</td>' . "\n";
                    print '<td align="right">' . dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT . '/' . $file['filename']), 'dayhour') . '</td>' . "\n";
                    print "</tr>\n";
                }
            } else {
                print '<tr ' . $bc[false] . '><td colspan="5">' . $langs->trans("None") . '</td></tr>';
            }
            print '</table>';
        } else {
            print 'Error: Failed to found dolibarr_htdocs_dir into XML file ' . $xmlfile;
            $error++;
        }
    } else {
        print 'Error: Failed to parse XML for input file ' . $xmlfile;
        $error++;
    }
} else {
Exemplo n.º 7
0
 /**
  *		Export events from database into a cal file.
  *		@param		format			'vcal', 'ical/ics', 'rss'
  *		@param		type			'event' or 'journal'
  *		@param		cachedelay		Do not rebuild file if date older than cachedelay seconds
  *		@param		filename		Force filename
  *		@param		filters			Array of filters
  *		@return     int     		<0 if error, nb of events in new file if ok
  */
 function build_exportfile($format, $type, $cachedelay, $filename, $filters)
 {
     global $conf, $langs, $dolibarr_main_url_root, $mysoc;
     require_once DOL_DOCUMENT_ROOT . "/lib/xcal.lib.php";
     require_once DOL_DOCUMENT_ROOT . "/lib/date.lib.php";
     dol_syslog("ActionComm::build_exportfile Build export file format=" . $format . ", type=" . $type . ", cachedelay=" . $cachedelay . ", filename=" . $filename . ", filters size=" . sizeof($filters), LOG_DEBUG);
     // Check parameters
     if (empty($format)) {
         return -1;
     }
     // Clean parameters
     if (!$filename) {
         $extension = 'vcs';
         if ($format == 'ical') {
             $extension = 'ics';
         }
         $filename = $format . '.' . $extension;
     }
     // Create dir and define output file (definitive and temporary)
     $result = create_exdir($conf->agenda->dir_temp);
     $outputfile = $conf->agenda->dir_temp . '/' . $filename;
     $result = 0;
     $buildfile = true;
     $login = '';
     $logina = '';
     $logind = '';
     $logint = '';
     $now = dol_now();
     if ($cachedelay) {
         $nowgmt = dol_now();
         include_once DOL_DOCUMENT_ROOT . '/lib/files.lib.php';
         if (dol_filemtime($outputfile) > $nowgmt - $cachedelay) {
             dol_syslog("ActionComm::build_exportfile file " . $outputfile . " is not older than now - cachedelay (" . $nowgmt . " - " . $cachedelay . "). Build is canceled");
             $buildfile = false;
         }
     }
     if ($buildfile) {
         // Build event array
         $eventarray = array();
         $sql = "SELECT a.id,";
         $sql .= " a.datep,";
         // Start
         $sql .= " a.datep2,";
         // End
         $sql .= " a.durationp,";
         $sql .= " a.datec, a.tms as datem,";
         $sql .= " a.note, a.label, a.fk_action as type_id,";
         $sql .= " a.fk_soc,";
         $sql .= " a.fk_user_author, a.fk_user_mod,";
         $sql .= " a.fk_user_action, a.fk_user_done,";
         $sql .= " a.fk_contact, a.percent as percentage,";
         $sql .= " a.fk_element, a.elementtype,";
         $sql .= " a.priority, a.fulldayevent, a.location,";
         $sql .= " u.firstname, u.name,";
         $sql .= " s.nom as socname,";
         $sql .= " c.id as type_id, c.code as type_code, c.libelle";
         $sql .= " FROM (" . MAIN_DB_PREFIX . "c_actioncomm as c, " . MAIN_DB_PREFIX . "actioncomm as a)";
         $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "user as u on u.rowid = a.fk_user_author";
         $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s on s.rowid = a.fk_soc AND s.entity IN (0, " . $conf->entity . ")";
         $sql .= " WHERE a.fk_action=c.id";
         $sql .= " AND a.entity = " . $conf->entity;
         foreach ($filters as $key => $value) {
             if ($key == 'notolderthan') {
                 $sql .= " AND a.datep >= '" . $this->db->idate($now - $value * 24 * 60 * 60) . "'";
             }
             if ($key == 'year') {
                 $sql .= " AND a.datep BETWEEN '" . $this->db->idate(dol_get_first_day($value, 1)) . "' AND '" . $this->db->idate(dol_get_last_day($value, 12)) . "'";
             }
             if ($key == 'id') {
                 $sql .= " AND a.id=" . (is_numeric($value) ? $value : 0);
             }
             if ($key == 'idfrom') {
                 $sql .= " AND a.id >= " . (is_numeric($value) ? $value : 0);
             }
             if ($key == 'idto') {
                 $sql .= " AND a.id <= " . (is_numeric($value) ? $value : 0);
             }
             if ($key == 'login') {
                 $login = $value;
                 $userforfilter = new User($this->db);
                 $result = $userforfilter->fetch('', $value);
                 $sql .= " AND (";
                 $sql .= " a.fk_user_author = " . $userforfilter->id;
                 $sql .= " OR a.fk_user_action = " . $userforfilter->id;
                 $sql .= " OR a.fk_user_done = " . $userforfilter->id;
                 $sql .= ")";
             }
             if ($key == 'logina') {
                 $logina = $value;
                 $userforfilter = new User($this->db);
                 $result = $userforfilter->fetch('', $value);
                 $sql .= " AND a.fk_user_author = " . $userforfilter->id;
             }
             if ($key == 'logint') {
                 $logint = $value;
                 $userforfilter = new User($this->db);
                 $result = $userforfilter->fetch('', $value);
                 $sql .= " AND a.fk_user_action = " . $userforfilter->id;
             }
             if ($key == 'logind') {
                 $logind = $value;
                 $userforfilter = new User($this->db);
                 $result = $userforfilter->fetch('', $value);
                 $sql .= " AND a.fk_user_done = " . $userforfilter->id;
             }
         }
         $sql .= " AND a.datep IS NOT NULL";
         // To exclude corrupted events and avoid errors in lightning/sunbird import
         $sql .= " ORDER by datep";
         //print $sql;exit;
         dol_syslog("ActionComm::build_exportfile select events sql=" . $sql);
         $resql = $this->db->query($sql);
         if ($resql) {
             // Note: Output of sql request is encoded in $conf->file->character_set_client
             while ($obj = $this->db->fetch_object($resql)) {
                 $qualified = true;
                 // 'eid','startdate','duration','enddate','title','summary','category','email','url','desc','author'
                 $event = array();
                 $event['uid'] = 'dolibarragenda-' . $this->db->database_name . '-' . $obj->id . "@" . $_SERVER["SERVER_NAME"];
                 $event['type'] = $type;
                 //$datestart=$obj->datea?$obj->datea:$obj->datep;
                 //$dateend=$obj->datea2?$obj->datea2:$obj->datep2;
                 //$duration=$obj->durationa?$obj->durationa:$obj->durationp;
                 $datestart = $this->db->jdate($obj->datep);
                 //print $datestart.'x'; exit;
                 $dateend = $this->db->jdate($obj->datep2);
                 $duration = $obj->durationp;
                 $event['summary'] = $langs->convToOutputCharset($obj->label . ($obj->socname ? " (" . $obj->socname . ")" : ""));
                 $event['desc'] = $langs->convToOutputCharset($obj->note);
                 $event['startdate'] = $datestart;
                 $event['duration'] = $duration;
                 // Not required with type 'journal'
                 $event['enddate'] = $dateend;
                 // Not required with type 'journal'
                 $event['author'] = $obj->firstname . ($obj->name ? " " . $obj->name : "");
                 $event['priority'] = $obj->priority;
                 $event['fulldayevent'] = $obj->fulldayevent;
                 $event['location'] = $langs->convToOutputCharset($obj->location);
                 $event['transparency'] = 'TRANSPARENT';
                 // OPAQUE (busy) or TRANSPARENT (not busy)
                 $event['category'] = $langs->convToOutputCharset($obj->libelle);
                 // libelle type action
                 $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', $dolibarr_main_url_root);
                 $url = $urlwithouturlroot . DOL_URL_ROOT . '/comm/action/fiche.php?id=' . $obj->id;
                 $event['url'] = $url;
                 $event['created'] = $this->db->jdate($obj->datec);
                 $event['modified'] = $this->db->jdate($obj->datem);
                 if ($qualified && $datestart) {
                     $eventarray[$datestart] = $event;
                 }
             }
         } else {
             $this->error = $this->db->lasterror();
             dol_syslog("ActionComm::build_exportfile " . $this->db->lasterror(), LOG_ERR);
             return -1;
         }
         $langs->load("agenda");
         // Define title and desc
         $more = '';
         if ($login) {
             $more = $langs->transnoentities("User") . ' ' . $langs->convToOutputCharset($login);
         }
         if ($logina) {
             $more = $langs->transnoentities("ActionsAskedBy") . ' ' . $langs->convToOutputCharset($logina);
         }
         if ($logint) {
             $more = $langs->transnoentities("ActionsToDoBy") . ' ' . $langs->convToOutputCharset($logint);
         }
         if ($logind) {
             $more = $langs->transnoentities("ActionsDoneBy") . ' ' . $langs->convToOutputCharset($logind);
         }
         if ($more) {
             $title = $langs->convToOutputCharset('Dolibarr actions ' . $mysoc->name) . ' - ' . $more;
             $desc = $more;
             $desc .= $langs->convToOutputCharset(' (' . $mysoc->name . ' - built by Dolibarr)');
         } else {
             $title = $langs->convToOutputCharset('Dolibarr actions ' . $mysoc->name);
             $desc = $langs->transnoentities('ListOfActions');
             $desc .= $langs->convToOutputCharset(' (' . $mysoc->name . ' - built by Dolibarr)');
         }
         // Create temp file
         $outputfiletmp = tempnam($conf->agenda->dir_temp, 'tmp');
         // Temporary file (allow call of function by different threads
         @chmod($outputfiletmp, octdec($conf->global->MAIN_UMASK));
         // Write file
         if ($format == 'vcal') {
             $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
         }
         if ($format == 'ical') {
             $result = build_calfile($format, $title, $desc, $eventarray, $outputfiletmp);
         }
         if ($format == 'rss') {
             $result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp);
         }
         if ($result >= 0) {
             if (rename($outputfiletmp, $outputfile)) {
                 $result = 1;
             } else {
                 dol_syslog("ActionComm::build_exportfile failed to rename " . $outputfiletmp . " to " . $outputfile, LOG_ERR);
                 dol_delete_file($outputfiletmp, 0, 1);
                 $result = -1;
             }
         } else {
             dol_syslog("ActionComm::build_exportfile build_xxxfile function fails to for format=" . $format . " outputfiletmp=" . $outputfile, LOG_ERR);
             dol_delete_file($outputfiletmp, 0, 1);
             $langs->load("errors");
             $this->error = $langs->trans("ErrorFailToCreateFile", $outputfile);
         }
     }
     return $result;
 }
Exemplo n.º 8
0
/**
 *  Scan a directory and return a list of files/directories.
 *  Content for string is UTF8 and dir separator is "/".
 *  @param		$path        	Starting path from which to search
 *  @param		$types        	Can be "directories", "files", or "all"
 *  @param		$recursive		Determines whether subdirectories are searched
 *  @param		$filter        	Regex for include filter
 *  @param		$excludefilter  Array of Regex for exclude filter (example: array('\.meta$','^\.')
 *  @param		$sortcriteria	Sort criteria ("","name","date","size")
 *  @param		$sortorder		Sort order (SORT_ASC, SORT_DESC)
 *	@param		$mode			0=Return array minimum keys loaded (faster), 1=Force all keys like date and size to be loaded (slower), 2=Force load of date only, 3=Force load of size only
 *  @return		array			Array of array('name'=>'xxx','fullname'=>'/abc/xxx','date'=>'yyy','size'=>99,'type'=>'dir|file')
 */
function dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter="", $sortcriteria="name", $sortorder=SORT_ASC, $mode=0)
{
	dol_syslog("files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".$excludefilter);

	$loaddate=($mode==1||$mode==2)?true:false;
	$loadsize=($mode==1||$mode==3)?true:false;

	// Clean parameters
	$path=preg_replace('/([\\/]+)$/i','',$path);
	$newpath=dol_osencode($path);

	if (! is_dir($newpath)) return array();

	if ($dir = opendir($newpath))
	{
		$file_list = array();
		while (false !== ($file = readdir($dir)))
		{
			if (! utf8_check($file)) $file=utf8_encode($file);	// To be sure data is stored in utf8 in memory

			$qualified=1;

			// Define excludefilterarray
			$excludefilterarray=array('^\.');
			if (is_array($excludefilter))
			{
			     $excludefilterarray=array_merge($excludefilterarray,$excludefilter);
			}
			else if ($excludefilter) $excludefilterarray[]=$excludefilter;
            // Check if file is qualified
			foreach($excludefilterarray as $filt)
		    {
		         if (preg_match('/'.$filt.'/i',$file)) { $qualified=0; break; }
		    }

			if ($qualified)
			{
			    $isdir=is_dir(dol_osencode($path."/".$file));
			    // Check whether this is a file or directory and whether we're interested in that type
				if ($isdir && (($types=="directories") || ($types=="all") || $recursive))
				{
					// Add entry into file_list array
                    if (($types=="directories") || ($types=="all"))
                    {
    				    if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
    					if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);

    					if (! $filter || preg_match('/'.$filter.'/i',$path.'/'.$file))
    					{
    						$file_list[] = array(
    						"name" => $file,
    						"fullname" => $path.'/'.$file,
    						"date" => $filedate,
    						"size" => $filesize,
    						"type" => 'dir'
    						);
    					}
                    }

					// if we're in a directory and we want recursive behavior, call this function again
					if ($recursive)
					{
						$file_list = array_merge($file_list,dol_dir_list($path."/".$file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode));
					}
				}
				else if (! $isdir && (($types == "files") || ($types == "all")))
				{
				    // Add file into file_list array
					if ($loaddate || $sortcriteria == 'date') $filedate=dol_filemtime($path."/".$file);
					if ($loadsize || $sortcriteria == 'size') $filesize=dol_filesize($path."/".$file);

					if (! $filter || preg_match('/'.$filter.'/i',$path.'/'.$file))
					{
					    $file_list[] = array(
						"name" => $file,
						"fullname" => $path.'/'.$file,
						"date" => $filedate,
						"size" => $filesize,
						"type" => 'file'
						);
					}
				}
			}
		}
		closedir($dir);

		// Obtain a list of columns
		$myarray=array();
		foreach ($file_list as $key => $row)
		{
			$myarray[$key]  = $row[$sortcriteria];
		}
		// Sort the data
		if ($sortorder) array_multisort($myarray, $sortorder, $file_list);

		return $file_list;
	}
	else
	{
		return array();
	}
}
Exemplo n.º 9
0
/**
 * Test if Refresh needed
 *
 * @param string $directory Directory of cache
 * @param string $filename Name of filecache
 * @param int $cachetime Cachetime delay
 * @return boolean 0 no refresh 1 if refresh needed
 */
function dol_cache_refresh($directory, $filename, $cachetime)
{
    $now = dol_now();
    $cachefile = $directory . $filename;
    $refresh = !file_exists($cachefile) || $now - $cachetime > dol_filemtime($cachefile);
    return $refresh;
}
Exemplo n.º 10
0
    if (is_dir($dir . '/' . $year)) {
        $handle = opendir($dir . '/' . $year);
        if ($found) {
            print '<br>';
        }
        print '<br>';
        print '<table width="100%" class="noborder">';
        print '<tr class="liste_titre">';
        print '<td>' . $langs->trans("Reporting") . '</td>';
        print '<td align="right">' . $langs->trans("Size") . '</td>';
        print '<td align="right">' . $langs->trans("Date") . '</td>';
        print '</tr>';
        $var = true;
        if (is_resource($handle)) {
            while (($file = readdir($handle)) !== false) {
                if (preg_match('/^payment/i', $file)) {
                    $var = !$var;
                    $tfile = $dir . '/' . $year . '/' . $file;
                    $relativepath = $year . '/' . $file;
                    print "<tr " . $bc[$var] . ">" . '<td><a data-ajax="false" href="' . DOL_URL_ROOT . '/document.php?modulepart=facture_paiement&amp;file=' . urlencode($relativepath) . '">' . img_pdf() . ' ' . $file . '</a></td>';
                    print '<td align="right">' . dol_print_size(dol_filesize($tfile)) . '</td>';
                    print '<td align="right">' . dol_print_date(dol_filemtime($tfile), "dayhour") . '</td></tr>';
                }
            }
            closedir($handle);
        }
        print '</table>';
    }
}
llxFooter();
$db->close();
Exemplo n.º 11
0
/**
 *  Scan a directory and return a list of files/directories.
 *  Content for string is UTF8 and dir separator is "/".
 *
 *  @param	string		$path        	Starting path from which to search
 *  @param	string		$types        	Can be "directories", "files", or "all"
 *  @param	int			$recursive		Determines whether subdirectories are searched
 *  @param	string		$filter        	Regex filter to restrict list. This regex value must be escaped for '/', since this char is used for preg_match function
 *  @param	array		$excludefilter  Array of Regex for exclude filter (example: array('(\.meta|_preview\.png)$','^\.'))
 *  @param	string		$sortcriteria	Sort criteria ("","fullname","name","date","size")
 *  @param	string		$sortorder		Sort order (SORT_ASC, SORT_DESC)
 *	@param	int			$mode			0=Return array minimum keys loaded (faster), 1=Force all keys like date and size to be loaded (slower), 2=Force load of date only, 3=Force load of size only
 *  @param	int			$nohook			Disable all hooks
 *  @return	array						Array of array('name'=>'xxx','fullname'=>'/abc/xxx','date'=>'yyy','size'=>99,'type'=>'dir|file')
 */
function dol_dir_list($path, $types = "all", $recursive = 0, $filter = "", $excludefilter = "", $sortcriteria = "name", $sortorder = SORT_ASC, $mode = 0, $nohook = false)
{
    global $db, $hookmanager;
    global $object;
    dol_syslog("files.lib.php::dol_dir_list path=" . $path . " types=" . $types . " recursive=" . $recursive . " filter=" . $filter . " excludefilter=" . json_encode($excludefilter));
    //print 'xxx'."files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter);
    $loaddate = $mode == 1 || $mode == 2 ? true : false;
    $loadsize = $mode == 1 || $mode == 3 ? true : false;
    // Clean parameters
    $path = preg_replace('/([\\/]+)$/i', '', $path);
    $newpath = dol_osencode($path);
    if (!$nohook) {
        $hookmanager->initHooks(array('fileslib'));
        $parameters = array('path' => $newpath, 'types' => $types, 'recursive' => $recursive, 'filter' => $filter, 'excludefilter' => $excludefilter, 'sortcriteria' => $sortcriteria, 'sortorder' => $sortorder, 'loaddate' => $loaddate, 'loadsize' => $loadsize);
        $reshook = $hookmanager->executeHooks('getNodesList', $parameters, $object);
    }
    // $reshook may contain returns stacked by other modules
    // $reshook is always empty with an array for can not lose returns stacked with other modules
    // $hookmanager->resArray may contain array stacked by other modules
    if (!$nohook && !empty($hookmanager->resArray)) {
        return $hookmanager->resArray['nodes'];
    } else {
        if (!is_dir($newpath)) {
            return array();
        }
        if ($dir = opendir($newpath)) {
            $filedate = '';
            $filesize = '';
            $file_list = array();
            while (false !== ($file = readdir($dir))) {
                if (!utf8_check($file)) {
                    $file = utf8_encode($file);
                }
                // To be sure data is stored in utf8 in memory
                $qualified = 1;
                // Define excludefilterarray
                $excludefilterarray = array('^\\.');
                if (is_array($excludefilter)) {
                    $excludefilterarray = array_merge($excludefilterarray, $excludefilter);
                } else {
                    if ($excludefilter) {
                        $excludefilterarray[] = $excludefilter;
                    }
                }
                // Check if file is qualified
                foreach ($excludefilterarray as $filt) {
                    if (preg_match('/' . $filt . '/i', $file)) {
                        $qualified = 0;
                        break;
                    }
                }
                if ($qualified) {
                    $isdir = is_dir(dol_osencode($path . "/" . $file));
                    // Check whether this is a file or directory and whether we're interested in that type
                    if ($isdir && ($types == "directories" || $types == "all" || $recursive)) {
                        // Add entry into file_list array
                        if ($types == "directories" || $types == "all") {
                            if ($loaddate || $sortcriteria == 'date') {
                                $filedate = dol_filemtime($path . "/" . $file);
                            }
                            if ($loadsize || $sortcriteria == 'size') {
                                $filesize = dol_filesize($path . "/" . $file);
                            }
                            if (!$filter || preg_match('/' . $filter . '/i', $file)) {
                                preg_match('/([^\\/]+)\\/[^\\/]+$/', $path . '/' . $file, $reg);
                                $level1name = isset($reg[1]) ? $reg[1] : '';
                                $file_list[] = array("name" => $file, "path" => $path, "level1name" => $level1name, "fullname" => $path . '/' . $file, "date" => $filedate, "size" => $filesize, "type" => 'dir');
                            }
                        }
                        // if we're in a directory and we want recursive behavior, call this function again
                        if ($recursive) {
                            $file_list = array_merge($file_list, dol_dir_list($path . "/" . $file, $types, $recursive, $filter, $excludefilter, $sortcriteria, $sortorder, $mode));
                        }
                    } else {
                        if (!$isdir && ($types == "files" || $types == "all")) {
                            // Add file into file_list array
                            if ($loaddate || $sortcriteria == 'date') {
                                $filedate = dol_filemtime($path . "/" . $file);
                            }
                            if ($loadsize || $sortcriteria == 'size') {
                                $filesize = dol_filesize($path . "/" . $file);
                            }
                            if (!$filter || preg_match('/' . $filter . '/i', $file)) {
                                preg_match('/([^\\/]+)\\/[^\\/]+$/', $path . '/' . $file, $reg);
                                $level1name = isset($reg[1]) ? $reg[1] : '';
                                $file_list[] = array("name" => $file, "path" => $path, "level1name" => $level1name, "fullname" => $path . '/' . $file, "date" => $filedate, "size" => $filesize, "type" => 'file');
                            }
                        }
                    }
                }
            }
            closedir($dir);
            // Obtain a list of columns
            if (!empty($sortcriteria)) {
                $myarray = array();
                foreach ($file_list as $key => $row) {
                    $myarray[$key] = isset($row[$sortcriteria]) ? $row[$sortcriteria] : '';
                }
                // Sort the data
                if ($sortorder) {
                    array_multisort($myarray, $sortorder, $file_list);
                }
            }
            return $file_list;
        } else {
            return array();
        }
    }
}
Exemplo n.º 12
0
if ($_GET["action"] == 'edit')
{
	print '<textarea class="flat" name="description" cols="80">';
	print $ecmdir->description;
	print '</textarea>';
}
else print dol_nl2br($ecmdir->description);
print '</td></tr>';
print '<tr><td>'.$langs->trans("ECMCreationUser").'</td><td>';
$userecm=new User($db);
$userecm->fetch($ecmdir->fk_user_c);
print $userecm->getNomUrl(1);
print '</td></tr>';
*/
print '<tr><td>'.$langs->trans("ECMCreationDate").'</td><td>';
print dol_print_date(dol_filemtime($fullpath),'dayhour');
print '</td></tr>';
/*print '<tr><td>'.$langs->trans("ECMDirectoryForFiles").'</td><td>';
print '/ecm/'.$relativepath;
print '</td></tr>';
print '<tr><td>'.$langs->trans("ECMNbOfDocs").'</td><td>';
print sizeof($filearray);
print '</td></tr>';
print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td>';
print dol_print_size($totalsize);
print '</td></tr>';
*/
if ($_GET["action"] == 'edit')
{
	print '<tr><td colspan="2" align="center">';
	print '<input type="submit" class="button" name="submit" value="'.$langs->trans("Save").'">';
Exemplo n.º 13
0
 /**
  * Return count, and sum of products
  *
  * @param	int		$year			Year
  * @param	int		$cachedelay		Delay we accept for cache file (0=No read, no save of cache, -1=No read but save)
  * @return 	array					Array of values
  */
 function getAllByProductEntry($year, $cachedelay = 0)
 {
     global $conf, $user, $langs;
     $datay = array();
     // Search into cache
     if (!empty($cachedelay)) {
         include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
         include_once DOL_DOCUMENT_ROOT . '/core/lib/json.lib.php';
     }
     $newpathofdestfile = $conf->user->dir_temp . '/' . get_class($this) . '_' . __FUNCTION__ . '_' . (empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix . '_') . $langs->defaultlang . '_user' . $user->id . '.cache';
     $newmask = '0644';
     $nowgmt = dol_now();
     $foundintocache = 0;
     if ($cachedelay > 0) {
         $filedate = dol_filemtime($newpathofdestfile);
         if ($filedate >= $nowgmt - $cachedelay) {
             $foundintocache = 1;
             $this->_lastfetchdate[get_class($this) . '_' . __FUNCTION__] = $filedate;
         } else {
             dol_syslog(get_class($this) . '::' . __FUNCTION__ . " cache file " . $newpathofdestfile . " is not found or older than now - cachedelay (" . $nowgmt . " - " . $cachedelay . ") so we can't use it.");
         }
     }
     // Load file into $data
     if ($foundintocache) {
         dol_syslog(get_class($this) . '::' . __FUNCTION__ . " read data from cache file " . $newpathofdestfile . " " . $filedate . ".");
         $data = json_decode(file_get_contents($newpathofdestfile), true);
     } else {
         $data = $this->getAllByProduct($year);
         //					$data[$i][]=$datay[$year][$i][1];	// set yval for x=i
     }
     // Save cache file
     if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
         dol_syslog(get_class($this) . '::' . __FUNCTION__ . " save cache file " . $newpathofdestfile . " onto disk.");
         if (!dol_is_dir($conf->user->dir_temp)) {
             dol_mkdir($conf->user->dir_temp);
         }
         $fp = fopen($newpathofdestfile, 'w');
         if ($fp) {
             fwrite($fp, json_encode($data));
             fclose($fp);
             if (!empty($conf->global->MAIN_UMASK)) {
                 $newmask = $conf->global->MAIN_UMASK;
             }
             @chmod($newpathofdestfile, octdec($newmask));
         }
         $this->_lastfetchdate[get_class($this) . '_' . __FUNCTION__] = $nowgmt;
     }
     return $data;
 }
Exemplo n.º 14
0
 /**
  *      Return a string to show the box with list of available documents for object.
  *      This also set the property $this->numoffiles
  *
  *      @param      string				$modulepart         propal, facture, facture_fourn, ...
  *      @param      string				$filename           Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if $filedir is already complete)
  *      @param      string				$filedir            Directory to scan
  *      @param      string				$urlsource          Url of origin page (for return)
  *      @param      int					$genallowed         Generation is allowed (1/0 or array list of templates)
  *      @param      int					$delallowed         Remove is allowed (1/0)
  *      @param      string				$modelselected      Model to preselect by default
  *      @param      string				$allowgenifempty	Allow generation even if list of template ($genallowed) is empty (show however a warning)
  *      @param      string				$forcenomultilang	Do not show language option (even if MAIN_MULTILANGS defined)
  *      @param      int					$iconPDF            Show only PDF icon with link (1/0)
  * 		@param		int					$maxfilenamelength	Max length for filename shown
  * 		@param		string				$noform				Do not output html form tags
  * 		@param		string				$param				More param on http links
  * 		@param		string				$title				Title to show on top of form
  * 		@param		string				$buttonlabel		Label on submit button
  * 		@param		string				$codelang			Default language code to use on lang combo box if multilang is enabled
  * 		@param		HookManager			$hookmanager		Object hookmanager with instance of external modules hook classes
  * 		@return		string              					Output string with HTML array of documents (might be empty string)
  */
 function showdocuments($modulepart, $filename, $filedir, $urlsource, $genallowed, $delallowed = 0, $modelselected = '', $allowgenifempty = 1, $forcenomultilang = 0, $iconPDF = 0, $maxfilenamelength = 28, $noform = 0, $param = '', $title = '', $buttonlabel = '', $codelang = '', $hookmanager = false)
 {
     // filedir = conf->...dir_ouput."/".get_exdir(id)
     include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
     global $langs, $bc, $conf;
     $forname = 'builddoc';
     $out = '';
     $var = true;
     // Clean paramaters
     if ($iconPDF == 1) {
         $genallowed = '';
         $delallowed = 0;
         $modelselected = '';
         $forcenomultilang = 0;
     }
     //$filename = dol_sanitizeFileName($filename);    //Must be sanitized before calling show_documents
     $headershown = 0;
     $showempty = 0;
     $i = 0;
     $titletoshow = $langs->trans("Documents");
     if (!empty($title)) {
         $titletoshow = $title;
     }
     $out .= "\n" . '<!-- Start show_document -->' . "\n";
     //print 'filedir='.$filedir;
     // Affiche en-tete tableau
     if ($genallowed) {
         $modellist = array();
         if ($modulepart == 'company') {
             $showempty = 1;
             if (is_array($genallowed)) {
                 $modellist = $genallowed;
             } else {
                 include_once DOL_DOCUMENT_ROOT . '/core/modules/societe/modules_societe.class.php';
                 $modellist = ModeleThirdPartyDoc::liste_modeles($this->db);
             }
         } else {
             if ($modulepart == 'propal') {
                 if (is_array($genallowed)) {
                     $modellist = $genallowed;
                 } else {
                     include_once DOL_DOCUMENT_ROOT . '/core/modules/propale/modules_propale.php';
                     $modellist = ModelePDFPropales::liste_modeles($this->db);
                 }
             } else {
                 if ($modulepart == 'commande') {
                     if (is_array($genallowed)) {
                         $modellist = $genallowed;
                     } else {
                         include_once DOL_DOCUMENT_ROOT . '/core/modules/commande/modules_commande.php';
                         $modellist = ModelePDFCommandes::liste_modeles($this->db);
                     }
                 } elseif ($modulepart == 'expedition') {
                     if (is_array($genallowed)) {
                         $modellist = $genallowed;
                     } else {
                         include_once DOL_DOCUMENT_ROOT . '/core/modules/expedition/modules_expedition.php';
                         $modellist = ModelePDFExpedition::liste_modeles($this->db);
                     }
                 } elseif ($modulepart == 'livraison') {
                     if (is_array($genallowed)) {
                         $modellist = $genallowed;
                     } else {
                         include_once DOL_DOCUMENT_ROOT . '/core/modules/livraison/modules_livraison.php';
                         $modellist = ModelePDFDeliveryOrder::liste_modeles($this->db);
                     }
                 } else {
                     if ($modulepart == 'ficheinter') {
                         if (is_array($genallowed)) {
                             $modellist = $genallowed;
                         } else {
                             include_once DOL_DOCUMENT_ROOT . '/core/modules/fichinter/modules_fichinter.php';
                             $modellist = ModelePDFFicheinter::liste_modeles($this->db);
                         }
                     } elseif ($modulepart == 'facture') {
                         if (is_array($genallowed)) {
                             $modellist = $genallowed;
                         } else {
                             include_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
                             $modellist = ModelePDFFactures::liste_modeles($this->db);
                         }
                     } elseif ($modulepart == 'project') {
                         if (is_array($genallowed)) {
                             $modellist = $genallowed;
                         } else {
                             include_once DOL_DOCUMENT_ROOT . '/core/modules/project/modules_project.php';
                             $modellist = ModelePDFProjects::liste_modeles($this->db);
                         }
                     } elseif ($modulepart == 'export') {
                         if (is_array($genallowed)) {
                             $modellist = $genallowed;
                         } else {
                             include_once DOL_DOCUMENT_ROOT . '/core/modules/export/modules_export.php';
                             $modellist = ModeleExports::liste_modeles($this->db);
                         }
                     } else {
                         if ($modulepart == 'commande_fournisseur') {
                             if (is_array($genallowed)) {
                                 $modellist = $genallowed;
                             } else {
                                 include_once DOL_DOCUMENT_ROOT . '/core/modules/supplier_order/modules_commandefournisseur.php';
                                 $modellist = ModelePDFSuppliersOrders::liste_modeles($this->db);
                             }
                         } else {
                             if ($modulepart == 'facture_fournisseur') {
                                 if (is_array($genallowed)) {
                                     $modellist = $genallowed;
                                 } else {
                                     include_once DOL_DOCUMENT_ROOT . '/core/modules/supplier_invoice/modules_facturefournisseur.php';
                                     $modellist = ModelePDFSuppliersInvoices::liste_modeles($this->db);
                                 }
                             } else {
                                 if ($modulepart == 'remisecheque') {
                                     if (is_array($genallowed)) {
                                         $modellist = $genallowed;
                                     } else {
                                         include_once DOL_DOCUMENT_ROOT . '/core/modules/cheque/pdf/modules_chequereceipts.php';
                                         $modellist = ModeleChequeReceipts::liste_modeles($this->db);
                                     }
                                 } elseif ($modulepart == 'donation') {
                                     if (is_array($genallowed)) {
                                         $modellist = $genallowed;
                                     } else {
                                         include_once DOL_DOCUMENT_ROOT . '/core/modules/dons/modules_don.php';
                                         $modellist = ModeleDon::liste_modeles($this->db);
                                     }
                                 } else {
                                     if ($modulepart == 'unpaid') {
                                         $modellist = '';
                                     } else {
                                         // Generic feature, for external modules
                                         $file = dol_buildpath('/core/modules/' . $modulepart . '/modules_' . $modulepart . '.php', 0);
                                         if (file_exists($file)) {
                                             $res = (include_once $file);
                                         }
                                         $class = 'Modele' . ucfirst($modulepart);
                                         if (class_exists($class)) {
                                             $modellist = call_user_func($class . '::liste_modeles', $this->db);
                                         } else {
                                             dol_print_error($this->db, 'Bad value for modulepart');
                                             return -1;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $headershown = 1;
         $form = new Form($this->db);
         $buttonlabeltoshow = $buttonlabel;
         if (empty($buttonlabel)) {
             $buttonlabel = $langs->trans('Generate');
         }
         if (empty($noform)) {
             $out .= '<form action="' . $urlsource . (empty($conf->global->MAIN_JUMP_TAG) ? '' : '#builddoc') . '" name="' . $forname . '" id="' . $forname . '_form" method="post">';
         }
         $out .= '<input type="hidden" name="action" value="builddoc">';
         $out .= '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
         $out .= '<div class="titre">' . $titletoshow . '</div>';
         $out .= '<table class="liste formdoc" summary="listofdocumentstable" width="100%">';
         $out .= '<tr class="liste_titre">';
         // Model
         if (!empty($modellist)) {
             $out .= '<th align="center" class="formdoc liste_titre">';
             $out .= $langs->trans('Model') . ' ';
             if (is_array($modellist) && count($modellist) == 1) {
                 $arraykeys = array_keys($modellist);
                 $modelselected = $arraykeys[0];
             }
             $out .= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0);
             $out .= '</th>';
         } else {
             $out .= '<th align="left" class="formdoc liste_titre">';
             $out .= $langs->trans("Files");
             $out .= '</th>';
         }
         // Language code (if multilang)
         $out .= '<th align="center" class="formdoc liste_titre">';
         if (($allowgenifempty || is_array($modellist) && count($modellist) > 0) && $conf->global->MAIN_MULTILANGS && !$forcenomultilang) {
             include_once DOL_DOCUMENT_ROOT . '/core/class/html.formadmin.class.php';
             $formadmin = new FormAdmin($this->db);
             $defaultlang = $codelang ? $codelang : $langs->getDefaultLang();
             $out .= $formadmin->select_language($defaultlang);
         } else {
             $out .= '&nbsp;';
         }
         $out .= '</th>';
         // Button
         $out .= '<th align="center" colspan="' . ($delallowed ? '2' : '1') . '" class="formdocbutton liste_titre">';
         $out .= '<input class="button" id="' . $forname . '_generatebutton"';
         $out .= ' type="submit" value="' . $buttonlabel . '"';
         if (!$allowgenifempty && !is_array($modellist) && empty($modellist)) {
             $out .= ' disabled="disabled"';
         }
         $out .= '>';
         if ($allowgenifempty && !is_array($modellist) && empty($modellist) && $modulepart != 'unpaid') {
             $langs->load("errors");
             $out .= ' ' . img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
         }
         $out .= '</th>';
         $out .= '</tr>';
         // Execute hooks
         $parameters = array('socid' => isset($GLOBALS['socid']) ? $GLOBALS['socid'] : '', 'id' => isset($GLOBALS['id']) ? $GLOBALS['id'] : '', 'modulepart' => $modulepart);
         if (is_object($hookmanager)) {
             $out .= $hookmanager->executeHooks('formBuilddocOptions', $parameters, $GLOBALS['object']);
         }
     }
     // Get list of files
     if ($filedir) {
         $png = '';
         $filter = '';
         if ($iconPDF == 1) {
             $png = '\\.png$';
             $filter = $filename . '.pdf';
         }
         $file_list = dol_dir_list($filedir, 'files', 0, $filter, '\\.meta$' . ($png ? '|' . $png : ''), 'date', SORT_DESC);
         // Affiche en-tete tableau si non deja affiche
         if (!empty($file_list) && !$headershown && !$iconPDF) {
             $headershown = 1;
             $out .= '<div class="titre">' . $titletoshow . '</div>';
             $out .= '<table class="border" summary="listofdocumentstable" width="100%">';
         } else {
             if (empty($file_list) && !empty($iconPDF)) {
                 // For ajax treatment
                 $out .= '<div id="gen_pdf_' . $filename . '" class="linkobject hideobject">' . img_picto('', 'refresh') . '</div>' . "\n";
             }
         }
         // Loop on each file found
         foreach ($file_list as $file) {
             $var = !$var;
             // Define relative path for download link (depends on module)
             $relativepath = $file["name"];
             // Cas general
             if ($filename) {
                 $relativepath = $filename . "/" . $file["name"];
             }
             // Cas propal, facture...
             // Autre cas
             if ($modulepart == 'donation') {
                 $relativepath = get_exdir($filename, 2) . $file["name"];
             }
             if ($modulepart == 'export') {
                 $relativepath = $file["name"];
             }
             if (!$iconPDF) {
                 $out .= "<tr " . $bc[$var] . ">";
             }
             // Show file name with link to download
             if (!$iconPDF) {
                 $out .= '<td nowrap="nowrap">';
             }
             $out .= '<a href="' . DOL_URL_ROOT . '/document.php?modulepart=' . $modulepart . '&amp;file=' . urlencode($relativepath) . '"';
             $mime = dol_mimetype($relativepath, '', 0);
             if (preg_match('/text/', $mime)) {
                 $out .= ' target="_blank"';
             }
             $out .= '>';
             if (!$iconPDF) {
                 $out .= img_mime($file["name"], $langs->trans("File") . ': ' . $file["name"]) . ' ' . dol_trunc($file["name"], $maxfilenamelength);
             } else {
                 $out .= img_pdf($file["name"], 2);
             }
             $out .= '</a>' . "\n";
             if (!$iconPDF) {
                 $out .= '</td>';
                 // Show file size
                 $out .= '<td align="right" nowrap="nowrap">' . dol_print_size(dol_filesize($filedir . "/" . $file["name"])) . '</td>';
                 // Show file date
                 $out .= '<td align="right" nowrap="nowrap">' . dol_print_date(dol_filemtime($filedir . "/" . $file["name"]), 'dayhour') . '</td>';
             }
             if ($delallowed) {
                 $out .= '<td align="right">';
                 //$out.= '<a href="'.DOL_URL_ROOT.'/document.php?action=remove_file&amp;modulepart='.$modulepart.'&amp;file='.urlencode($relativepath);
                 $out .= '<a href="' . $urlsource . '&action=remove_file&modulepart=' . $modulepart . '&file=' . urlencode($relativepath);
                 $out .= $param ? '&' . $param : '';
                 $out .= '&urlsource=' . urlencode($urlsource);
                 $out .= '">' . img_delete() . '</a></td>';
             }
             if (!$iconPDF) {
                 $out .= '</tr>';
             }
             $this->numoffiles++;
         }
     }
     if ($headershown) {
         // Affiche pied du tableau
         $out .= "</table>\n";
         if ($genallowed) {
             if (empty($noform)) {
                 $out .= '</form>' . "\n";
             }
         }
     }
     $out .= '<!-- End show_document -->' . "\n";
     //return ($i?$i:$headershown);
     return $out;
 }