functions2.lib.php 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845
  1. <?php
  2. /* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2008-2012 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  5. * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
  6. * Copyright (C) 2015 Ferran Marcet <fmarcet@2byte.es>
  7. * Copyright (C) 2015-2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  8. * Copyright (C) 2017 Juanjo Menent <jmenent@2byte.es>
  9. *
  10. * This program is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  22. * or see https://www.gnu.org/
  23. */
  24. /**
  25. * \file htdocs/core/lib/functions2.lib.php
  26. * \brief A set of functions for Dolibarr
  27. * This file contains all rare functions.
  28. */
  29. // Enable this line to trace path when function is called.
  30. //print xdebug_print_function_stack('Functions2.lib was called');exit;
  31. /**
  32. * Same function than javascript unescape() function but in PHP.
  33. *
  34. * @param string $source String to decode
  35. * @return string Unescaped string
  36. */
  37. function jsUnEscape($source)
  38. {
  39. $decodedStr = "";
  40. $pos = 0;
  41. $len = strlen($source);
  42. while ($pos < $len) {
  43. $charAt = substr($source, $pos, 1);
  44. if ($charAt == '%') {
  45. $pos++;
  46. $charAt = substr($source, $pos, 1);
  47. if ($charAt == 'u') {
  48. // we got a unicode character
  49. $pos++;
  50. $unicodeHexVal = substr($source, $pos, 4);
  51. $unicode = hexdec($unicodeHexVal);
  52. $entity = "&#".$unicode.';';
  53. $decodedStr .= utf8_encode($entity);
  54. $pos += 4;
  55. } else {
  56. // we have an escaped ascii character
  57. $hexVal = substr($source, $pos, 2);
  58. $decodedStr .= chr(hexdec($hexVal));
  59. $pos += 2;
  60. }
  61. } else {
  62. $decodedStr .= $charAt;
  63. $pos++;
  64. }
  65. }
  66. return dol_html_entity_decode($decodedStr, ENT_COMPAT | ENT_HTML5);
  67. }
  68. /**
  69. * Return list of modules directories. We detect directories that contains a subdirectory /core/modules
  70. * We discard directory modules that contains 'disabled' into their name.
  71. *
  72. * @param string $subdir Sub directory (Example: '/mailings')
  73. * @return array Array of directories that can contains module descriptors
  74. */
  75. function dolGetModulesDirs($subdir = '')
  76. {
  77. global $conf;
  78. $modulesdir = array();
  79. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  80. // Default core/modules dir
  81. if ($type === 'main') {
  82. $modulesdir[$dirroot.'/core/modules'.$subdir.'/'] = $dirroot.'/core/modules'.$subdir.'/';
  83. }
  84. // Scan dir from external modules
  85. $handle = @opendir($dirroot);
  86. if (is_resource($handle)) {
  87. while (($file = readdir($handle)) !== false) {
  88. if (preg_match('/disabled/', $file)) {
  89. continue; // We discard module if it contains disabled into name.
  90. }
  91. if (is_dir($dirroot.'/'.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && $file != 'includes') {
  92. if (is_dir($dirroot.'/'.$file.'/core/modules'.$subdir.'/')) {
  93. $modulesdir[$dirroot.'/'.$file.'/core/modules'.$subdir.'/'] = $dirroot.'/'.$file.'/core/modules'.$subdir.'/';
  94. }
  95. }
  96. }
  97. closedir($handle);
  98. }
  99. }
  100. return $modulesdir;
  101. }
  102. /**
  103. * Try to guess default paper format according to language into $langs
  104. *
  105. * @param Translate $outputlangs Output lang to use to autodetect output format if setup not done
  106. * @return string Default paper format code
  107. */
  108. function dol_getDefaultFormat(Translate $outputlangs = null)
  109. {
  110. global $langs;
  111. $selected = 'EUA4';
  112. if (!$outputlangs) {
  113. $outputlangs = $langs;
  114. }
  115. if ($outputlangs->defaultlang == 'ca_CA') {
  116. $selected = 'CAP4'; // Canada
  117. }
  118. if ($outputlangs->defaultlang == 'en_US') {
  119. $selected = 'USLetter'; // US
  120. }
  121. return $selected;
  122. }
  123. /**
  124. * Output content of a file $filename in version of current language (otherwise may use an alternate language)
  125. *
  126. * @param Translate $langs Object language to use for output
  127. * @param string $filename Relative filename to output
  128. * @param int $searchalt 1=Search also in alternative languages
  129. * @return boolean true if OK, false if KO
  130. */
  131. function dol_print_file($langs, $filename, $searchalt = 0)
  132. {
  133. global $conf;
  134. // Test if file is in lang directory
  135. foreach ($langs->dir as $searchdir) {
  136. $formfile = ($searchdir."/langs/".$langs->defaultlang."/".$filename);
  137. dol_syslog('functions2::dol_print_file search file '.$formfile, LOG_DEBUG);
  138. if (is_readable($formfile)) {
  139. $content = file_get_contents($formfile);
  140. $isutf8 = utf8_check($content);
  141. if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') {
  142. print utf8_encode($content);
  143. } elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') {
  144. print utf8_decode($content);
  145. } else {
  146. print $content;
  147. }
  148. return true;
  149. } else {
  150. dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
  151. }
  152. if ($searchalt) {
  153. // Test si fichier dans repertoire de la langue alternative
  154. if ($langs->defaultlang != "en_US") {
  155. $formfilealt = $searchdir."/langs/en_US/".$filename;
  156. } else {
  157. $formfilealt = $searchdir."/langs/fr_FR/".$filename;
  158. }
  159. dol_syslog('functions2::dol_print_file search alt file '.$formfilealt, LOG_DEBUG);
  160. //print 'getcwd='.getcwd().' htmlfilealt='.$formfilealt.' X '.file_exists(getcwd().'/'.$formfilealt);
  161. if (is_readable($formfilealt)) {
  162. $content = file_get_contents($formfilealt);
  163. $isutf8 = utf8_check($content);
  164. if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') {
  165. print utf8_encode($content);
  166. } elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') {
  167. print utf8_decode($content);
  168. } else {
  169. print $content;
  170. }
  171. return true;
  172. } else {
  173. dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
  174. }
  175. }
  176. }
  177. return false;
  178. }
  179. /**
  180. * Show informations on an object
  181. * TODO Move this into html.formother
  182. *
  183. * @param object $object Objet to show
  184. * @param int $usetable Output into a table
  185. * @return void
  186. */
  187. function dol_print_object_info($object, $usetable = 0)
  188. {
  189. global $langs, $db;
  190. // Load translation files required by the page
  191. $langs->loadLangs(array('other', 'admin'));
  192. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  193. $deltadateforserver = getServerTimeZoneInt('now');
  194. $deltadateforclient = ((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
  195. //$deltadateforcompany=((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
  196. $deltadateforuser = round($deltadateforclient - $deltadateforserver);
  197. //print "x".$deltadateforserver." - ".$deltadateforclient." - ".$deltadateforuser;
  198. if ($usetable) {
  199. print '<table class="border tableforfield centpercent">';
  200. }
  201. // Import key
  202. if (!empty($object->import_key)) {
  203. if ($usetable) {
  204. print '<tr><td class="titlefield">';
  205. }
  206. print $langs->trans("ImportedWithSet");
  207. if ($usetable) {
  208. print '</td><td>';
  209. } else {
  210. print ': ';
  211. }
  212. print $object->import_key;
  213. if ($usetable) {
  214. print '</td></tr>';
  215. } else {
  216. print '<br>';
  217. }
  218. }
  219. // User creation (old method using already loaded object and not id is kept for backward compatibility)
  220. if (!empty($object->user_creation) || !empty($object->user_creation_id)) {
  221. if ($usetable) {
  222. print '<tr><td class="titlefield">';
  223. }
  224. print $langs->trans("CreatedBy");
  225. if ($usetable) {
  226. print '</td><td>';
  227. } else {
  228. print ': ';
  229. }
  230. if (is_object($object->user_creation)) {
  231. if ($object->user_creation->id) {
  232. print $object->user_creation->getNomUrl(-1, '', 0, 0, 0);
  233. } else {
  234. print $langs->trans("Unknown");
  235. }
  236. } else {
  237. $userstatic = new User($db);
  238. $userstatic->fetch($object->user_creation_id ? $object->user_creation_id : $object->user_creation);
  239. if ($userstatic->id) {
  240. print $userstatic->getNomUrl(-1, '', 0, 0, 0);
  241. } else {
  242. print $langs->trans("Unknown");
  243. }
  244. }
  245. if ($usetable) {
  246. print '</td></tr>';
  247. } else {
  248. print '<br>';
  249. }
  250. }
  251. // Date creation
  252. if (!empty($object->date_creation)) {
  253. if ($usetable) {
  254. print '<tr><td class="titlefield">';
  255. }
  256. print $langs->trans("DateCreation");
  257. if ($usetable) {
  258. print '</td><td>';
  259. } else {
  260. print ': ';
  261. }
  262. print dol_print_date($object->date_creation, 'dayhour', 'tzserver');
  263. if ($deltadateforuser) {
  264. print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_creation, "dayhour", "tzuserrel").' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
  265. }
  266. if ($usetable) {
  267. print '</td></tr>';
  268. } else {
  269. print '<br>';
  270. }
  271. }
  272. // User change (old method using already loaded object and not id is kept for backward compatibility)
  273. if (!empty($object->user_modification) || !empty($object->user_modification_id)) {
  274. if ($usetable) {
  275. print '<tr><td class="titlefield">';
  276. }
  277. print $langs->trans("ModifiedBy");
  278. if ($usetable) {
  279. print '</td><td>';
  280. } else {
  281. print ': ';
  282. }
  283. if (is_object($object->user_modification)) {
  284. if ($object->user_modification->id) {
  285. print $object->user_modification->getNomUrl(-1, '', 0, 0, 0);
  286. } else {
  287. print $langs->trans("Unknown");
  288. }
  289. } else {
  290. $userstatic = new User($db);
  291. $userstatic->fetch($object->user_modification_id ? $object->user_modification_id : $object->user_modification);
  292. if ($userstatic->id) {
  293. print $userstatic->getNomUrl(-1, '', 0, 0, 0);
  294. } else {
  295. print $langs->trans("Unknown");
  296. }
  297. }
  298. if ($usetable) {
  299. print '</td></tr>';
  300. } else {
  301. print '<br>';
  302. }
  303. }
  304. // Date change
  305. if (!empty($object->date_modification)) {
  306. if ($usetable) {
  307. print '<tr><td class="titlefield">';
  308. }
  309. print $langs->trans("DateLastModification");
  310. if ($usetable) {
  311. print '</td><td>';
  312. } else {
  313. print ': ';
  314. }
  315. print dol_print_date($object->date_modification, 'dayhour', 'tzserver');
  316. if ($deltadateforuser) {
  317. print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_modification, "dayhour", "tzuserrel").' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
  318. }
  319. if ($usetable) {
  320. print '</td></tr>';
  321. } else {
  322. print '<br>';
  323. }
  324. }
  325. // User validation (old method using already loaded object and not id is kept for backward compatibility)
  326. if (!empty($object->user_validation) || !empty($object->user_validation_id)) {
  327. if ($usetable) {
  328. print '<tr><td class="titlefield">';
  329. }
  330. print $langs->trans("ValidatedBy");
  331. if ($usetable) {
  332. print '</td><td>';
  333. } else {
  334. print ': ';
  335. }
  336. if (is_object($object->user_validation)) {
  337. if ($object->user_validation->id) {
  338. print $object->user_validation->getNomUrl(-1, '', 0, 0, 0);
  339. } else {
  340. print $langs->trans("Unknown");
  341. }
  342. } else {
  343. $userstatic = new User($db);
  344. $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation);
  345. if ($userstatic->id) {
  346. print $userstatic->getNomUrl(-1, '', 0, 0, 0);
  347. } else {
  348. print $langs->trans("Unknown");
  349. }
  350. }
  351. if ($usetable) {
  352. print '</td></tr>';
  353. } else {
  354. print '<br>';
  355. }
  356. }
  357. // Date validation
  358. if (!empty($object->date_validation)) {
  359. if ($usetable) {
  360. print '<tr><td class="titlefield">';
  361. }
  362. print $langs->trans("DateValidation");
  363. if ($usetable) {
  364. print '</td><td>';
  365. } else {
  366. print ': ';
  367. }
  368. print dol_print_date($object->date_validation, 'dayhour', 'tzserver');
  369. if ($deltadateforuser) {
  370. print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_validation, "dayhour", 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
  371. }
  372. if ($usetable) {
  373. print '</td></tr>';
  374. } else {
  375. print '<br>';
  376. }
  377. }
  378. // User approve (old method using already loaded object and not id is kept for backward compatibility)
  379. if (!empty($object->user_approve) || !empty($object->user_approve_id)) {
  380. if ($usetable) {
  381. print '<tr><td class="titlefield">';
  382. }
  383. print $langs->trans("ApprovedBy");
  384. if ($usetable) {
  385. print '</td><td>';
  386. } else {
  387. print ': ';
  388. }
  389. if (is_object($object->user_approve)) {
  390. if ($object->user_approve->id) {
  391. print $object->user_approve->getNomUrl(-1, '', 0, 0, 0);
  392. } else {
  393. print $langs->trans("Unknown");
  394. }
  395. } else {
  396. $userstatic = new User($db);
  397. $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve);
  398. if ($userstatic->id) {
  399. print $userstatic->getNomUrl(-1, '', 0, 0, 0);
  400. } else {
  401. print $langs->trans("Unknown");
  402. }
  403. }
  404. if ($usetable) {
  405. print '</td></tr>';
  406. } else {
  407. print '<br>';
  408. }
  409. }
  410. // Date approve
  411. if (!empty($object->date_approve)) {
  412. if ($usetable) {
  413. print '<tr><td class="titlefield">';
  414. }
  415. print $langs->trans("DateApprove");
  416. if ($usetable) {
  417. print '</td><td>';
  418. } else {
  419. print ': ';
  420. }
  421. print dol_print_date($object->date_approve, 'dayhour', 'tzserver');
  422. if ($deltadateforuser) {
  423. print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_approve, "dayhour", 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
  424. }
  425. if ($usetable) {
  426. print '</td></tr>';
  427. } else {
  428. print '<br>';
  429. }
  430. }
  431. // User approve
  432. if (!empty($object->user_approve_id2)) {
  433. if ($usetable) {
  434. print '<tr><td class="titlefield">';
  435. }
  436. print $langs->trans("ApprovedBy");
  437. if ($usetable) {
  438. print '</td><td>';
  439. } else {
  440. print ': ';
  441. }
  442. $userstatic = new User($db);
  443. $userstatic->fetch($object->user_approve_id2);
  444. if ($userstatic->id) {
  445. print $userstatic->getNomUrl(-1, '', 0, 0, 0);
  446. } else {
  447. print $langs->trans("Unknown");
  448. }
  449. if ($usetable) {
  450. print '</td></tr>';
  451. } else {
  452. print '<br>';
  453. }
  454. }
  455. // Date approve
  456. if (!empty($object->date_approve2)) {
  457. if ($usetable) {
  458. print '<tr><td class="titlefield">';
  459. }
  460. print $langs->trans("DateApprove2");
  461. if ($usetable) {
  462. print '</td><td>';
  463. } else {
  464. print ': ';
  465. }
  466. print dol_print_date($object->date_approve2, 'dayhour', 'tzserver');
  467. if ($deltadateforuser) {
  468. print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_approve2, "dayhour", 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
  469. }
  470. if ($usetable) {
  471. print '</td></tr>';
  472. } else {
  473. print '<br>';
  474. }
  475. }
  476. // User signature
  477. if (!empty($object->user_signature) || !empty($object->user_signature_id)) {
  478. if ($usetable) {
  479. print '<tr><td class="titlefield">';
  480. }
  481. print $langs->trans('SignedBy');
  482. if ($usetable) {
  483. print '</td><td>';
  484. } else {
  485. print ': ';
  486. }
  487. if (is_object($object->user_signature)) {
  488. if ($object->user_signature->id) {
  489. print $object->user_signature->getNomUrl(-1, '', 0, 0, 0);
  490. } else {
  491. print $langs->trans('Unknown');
  492. }
  493. } else {
  494. $userstatic = new User($db);
  495. $userstatic->fetch($object->user_signature_id ? $object->user_signature_id : $object->user_signature);
  496. if ($userstatic->id) {
  497. print $userstatic->getNomUrl(-1, '', 0, 0, 0);
  498. } else {
  499. print $langs->trans('Unknown');
  500. }
  501. }
  502. if ($usetable) {
  503. print '</td></tr>';
  504. } else {
  505. print '<br>';
  506. }
  507. }
  508. // Date signature
  509. if (!empty($object->date_signature)) {
  510. if ($usetable) {
  511. print '<tr><td class="titlefield">';
  512. }
  513. print $langs->trans('DateSigning');
  514. if ($usetable) {
  515. print '</td><td>';
  516. } else {
  517. print ': ';
  518. }
  519. print dol_print_date($object->date_signature, 'dayhour');
  520. if ($deltadateforuser) {
  521. print ' <span class="opacitymedium">'.$langs->trans('CurrentHour').'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_signature, 'dayhour', 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans('ClientHour').'</span>';
  522. }
  523. if ($usetable) {
  524. print '</td></tr>';
  525. } else {
  526. print '<br>';
  527. }
  528. }
  529. // User close
  530. if (!empty($object->user_cloture) || !empty($object->user_closing) || !empty($object->user_closing_id)) {
  531. if (isset($object->user_cloture) && !empty($object->user_cloture)) {
  532. $object->user_closing = $object->user_cloture;
  533. }
  534. if ($usetable) {
  535. print '<tr><td class="titlefield">';
  536. }
  537. print $langs->trans("ClosedBy");
  538. if ($usetable) {
  539. print '</td><td>';
  540. } else {
  541. print ': ';
  542. }
  543. if (is_object($object->user_closing)) {
  544. if ($object->user_closing->id) {
  545. print $object->user_closing->getNomUrl(-1, '', 0, 0, 0);
  546. } else {
  547. print $langs->trans("Unknown");
  548. }
  549. } else {
  550. $userstatic = new User($db);
  551. $userstatic->fetch($object->user_closing_id ? $object->user_closing_id : $object->user_closing);
  552. if ($userstatic->id) {
  553. print $userstatic->getNomUrl(-1, '', 0, 0, 0);
  554. } else {
  555. print $langs->trans("Unknown");
  556. }
  557. }
  558. if ($usetable) {
  559. print '</td></tr>';
  560. } else {
  561. print '<br>';
  562. }
  563. }
  564. // Date close
  565. if (!empty($object->date_cloture) || !empty($object->date_closing)) {
  566. if (isset($object->date_cloture) && !empty($object->date_cloture)) {
  567. $object->date_closing = $object->date_cloture;
  568. }
  569. if ($usetable) {
  570. print '<tr><td class="titlefield">';
  571. }
  572. print $langs->trans("DateClosing");
  573. if ($usetable) {
  574. print '</td><td>';
  575. } else {
  576. print ': ';
  577. }
  578. print dol_print_date($object->date_closing, 'dayhour', 'tzserver');
  579. if ($deltadateforuser) {
  580. print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_closing, "dayhour", 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
  581. }
  582. if ($usetable) {
  583. print '</td></tr>';
  584. } else {
  585. print '<br>';
  586. }
  587. }
  588. // User conciliate
  589. if (!empty($object->user_rappro) || !empty($object->user_rappro_id)) {
  590. if ($usetable) {
  591. print '<tr><td class="titlefield">';
  592. }
  593. print $langs->trans("ReconciledBy");
  594. if ($usetable) {
  595. print '</td><td>';
  596. } else {
  597. print ': ';
  598. }
  599. if (is_object($object->user_rappro)) {
  600. if ($object->user_rappro->id) {
  601. print $object->user_rappro->getNomUrl(-1, '', 0, 0, 0);
  602. } else {
  603. print $langs->trans("Unknown");
  604. }
  605. } else {
  606. $userstatic = new User($db);
  607. $userstatic->fetch($object->user_rappro_id ? $object->user_rappro_id : $object->user_rappro);
  608. if ($userstatic->id) {
  609. print $userstatic->getNomUrl(1, '', 0, 0, 0);
  610. } else {
  611. print $langs->trans("Unknown");
  612. }
  613. }
  614. if ($usetable) {
  615. print '</td></tr>';
  616. } else {
  617. print '<br>';
  618. }
  619. }
  620. // Date conciliate
  621. if (!empty($object->date_rappro)) {
  622. if ($usetable) {
  623. print '<tr><td class="titlefield">';
  624. }
  625. print $langs->trans("DateConciliating");
  626. if ($usetable) {
  627. print '</td><td>';
  628. } else {
  629. print ': ';
  630. }
  631. print dol_print_date($object->date_rappro, 'dayhour', 'tzserver');
  632. if ($deltadateforuser) {
  633. print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_rappro, "dayhour", 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
  634. }
  635. if ($usetable) {
  636. print '</td></tr>';
  637. } else {
  638. print '<br>';
  639. }
  640. }
  641. // Date send
  642. if (!empty($object->date_envoi)) {
  643. if ($usetable) {
  644. print '<tr><td class="titlefield">';
  645. }
  646. print $langs->trans("DateLastSend");
  647. if ($usetable) {
  648. print '</td><td>';
  649. } else {
  650. print ': ';
  651. }
  652. print dol_print_date($object->date_envoi, 'dayhour', 'tzserver');
  653. if ($deltadateforuser) {
  654. print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_envoi, "dayhour", 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
  655. }
  656. if ($usetable) {
  657. print '</td></tr>';
  658. } else {
  659. print '<br>';
  660. }
  661. }
  662. if ($usetable) {
  663. print '</table>';
  664. }
  665. }
  666. /**
  667. * Return an email formatted to include a tracking id
  668. * For example myemail@example.com becom myemail+trackingid@example.com
  669. *
  670. * @param string $email Email address (Ex: "toto@example.com", "John Do <johndo@example.com>")
  671. * @param string $trackingid Tracking id (Ex: thi123 for thirdparty with id 123)
  672. * @return string Return email tracker string
  673. */
  674. function dolAddEmailTrackId($email, $trackingid)
  675. {
  676. $tmp = explode('@', $email);
  677. return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1]) ? $tmp[1] : '');
  678. }
  679. /**
  680. * Return true if email has a domain name that can be resolved to MX type.
  681. *
  682. * @param string $mail Email address (Ex: "toto@example.com", "John Do <johndo@example.com>")
  683. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  684. */
  685. function isValidMailDomain($mail)
  686. {
  687. list($user, $domain) = explode("@", $mail, 2);
  688. return ($domain ? isValidMXRecord($domain) : 0);
  689. }
  690. /**
  691. * Url string validation
  692. * <http[s]> :// [user[:pass]@] hostname [port] [/path] [?getquery] [anchor]
  693. *
  694. * @param string $url Url
  695. * @param int $http 1: verify http is provided, 0: not verify http
  696. * @param int $pass 1: verify user and pass is provided, 0: not verify user and pass
  697. * @param int $port 1: verify port is provided, 0: not verify port
  698. * @param int $path 1: verify a path is provided "/" or "/..." or "/.../", 0: not verify path
  699. * @param int $query 1: verify query is provided, 0: not verify query
  700. * @param int $anchor 1: verify anchor is provided, 0: not verify anchor
  701. * @return int 1=Check is OK, 0=Check is KO
  702. */
  703. function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0, $anchor = 0)
  704. {
  705. $ValidUrl = 0;
  706. $urlregex = '';
  707. // SCHEME
  708. if ($http) {
  709. $urlregex .= "^(http:\/\/|https:\/\/)";
  710. }
  711. // USER AND PASS
  712. if ($pass) {
  713. $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)";
  714. }
  715. // HOSTNAME OR IP
  716. //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*"; // x allowed (ex. http://localhost, http://routerlogin)
  717. //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)+"; // x.x
  718. $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*"; // x ou x.xx (2 x ou plus)
  719. //use only one of the above
  720. // PORT
  721. if ($port) {
  722. $urlregex .= "(\:[0-9]{2,5})";
  723. }
  724. // PATH
  725. if ($path) {
  726. $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/";
  727. }
  728. // GET Query
  729. if ($query) {
  730. $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)";
  731. }
  732. // ANCHOR
  733. if ($anchor) {
  734. $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$";
  735. }
  736. // check
  737. if (preg_match('/'.$urlregex.'/i', $url)) {
  738. $ValidUrl = 1;
  739. }
  740. //print $urlregex.' - '.$url.' - '.$ValidUrl;
  741. return $ValidUrl;
  742. }
  743. /**
  744. * Check if VAT numero is valid (check done on syntax only, no database or remote access)
  745. *
  746. * @param Societe $company VAT number
  747. * @return int 1=Check is OK, 0=Check is KO
  748. */
  749. function isValidVATID($company)
  750. {
  751. if ($company->isInEEC()) { // Syntax check rules for EEC countries
  752. /* Disabled because some companies can have an address in Irland and a vat number in France.
  753. $vatprefix = $company->country_code;
  754. if ($vatprefix == 'GR') $vatprefix = '(EL|GR)';
  755. elseif ($vatprefix == 'MC') $vatprefix = 'FR'; // Monaco is using french VAT numbers
  756. else $vatprefix = preg_quote($vatprefix, '/');*/
  757. $vatprefix = '[a-zA-Z][a-zA-Z]';
  758. if (!preg_match('/^'.$vatprefix.'[a-zA-Z0-9\-\.]{5,14}$/i', str_replace(' ', '', $company->tva_intra))) {
  759. return 0;
  760. }
  761. }
  762. return 1;
  763. }
  764. /**
  765. * Clean an url string
  766. *
  767. * @param string $url Url
  768. * @param integer $http 1 = keep both http:// and https://, 0: remove http:// but not https://
  769. * @return string Cleaned url
  770. */
  771. function clean_url($url, $http = 1)
  772. {
  773. // Fixed by Matelli (see http://matelli.fr/showcases/patchs-dolibarr/fix-cleaning-url.html)
  774. // To include the minus sign in a char class, we must not escape it but put it at the end of the class
  775. // Also, there's no need of escape a dot sign in a class
  776. $regs = array();
  777. if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs)) {
  778. $proto = $regs[1];
  779. $domain = $regs[2];
  780. $port = isset($regs[3]) ? $regs[3] : '';
  781. //print $url." -> ".$proto." - ".$domain." - ".$port;
  782. //$url = dol_string_nospecial(trim($url));
  783. $url = trim($url);
  784. // Si http: defini on supprime le http (Si https on ne supprime pas)
  785. $newproto = $proto;
  786. if ($http == 0) {
  787. if (preg_match('/^http:[\\/]+/i', $url)) {
  788. $url = preg_replace('/^http:[\\/]+/i', '', $url);
  789. $newproto = '';
  790. }
  791. }
  792. // On passe le nom de domaine en minuscule
  793. $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain, '/').'/i', $newproto.strtolower($domain), $url);
  794. return $CleanUrl;
  795. } else {
  796. return $url;
  797. }
  798. }
  799. /**
  800. * Returns an email value with obfuscated parts.
  801. *
  802. * @param string $mail Email
  803. * @param string $replace Replacement character (defaul: *)
  804. * @param int $nbreplace Number of replacement character (default: 8)
  805. * @param int $nbdisplaymail Number of character unchanged (default: 4)
  806. * @param int $nbdisplaydomain Number of character unchanged of domain (default: 3)
  807. * @param bool $displaytld Display tld (default: true)
  808. * @return string Return email with hidden parts or '';
  809. */
  810. function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail = 4, $nbdisplaydomain = 3, $displaytld = true)
  811. {
  812. if (!isValidEmail($mail)) {
  813. return '';
  814. }
  815. $tab = explode('@', $mail);
  816. $tab2 = explode('.', $tab[1]);
  817. $string_replace = '';
  818. $mail_name = $tab[0];
  819. $mail_domaine = $tab2[0];
  820. $mail_tld = '';
  821. $nbofelem = count($tab2);
  822. for ($i = 1; $i < $nbofelem && $displaytld; $i++) {
  823. $mail_tld .= '.'.$tab2[$i];
  824. }
  825. for ($i = 0; $i < $nbreplace; $i++) {
  826. $string_replace .= $replace;
  827. }
  828. if (strlen($mail_name) > $nbdisplaymail) {
  829. $mail_name = substr($mail_name, 0, $nbdisplaymail);
  830. }
  831. if (strlen($mail_domaine) > $nbdisplaydomain) {
  832. $mail_domaine = substr($mail_domaine, strlen($mail_domaine) - $nbdisplaydomain);
  833. }
  834. return $mail_name.$string_replace.$mail_domaine.$mail_tld;
  835. }
  836. /**
  837. * Return lines of an html table from an array
  838. * Used by array2table function only
  839. *
  840. * @param array $data Array of data
  841. * @param string $troptions Options for tr
  842. * @param string $tdoptions Options for td
  843. * @return string
  844. */
  845. function array2tr($data, $troptions = '', $tdoptions = '')
  846. {
  847. $text = '<tr '.$troptions.'>';
  848. foreach ($data as $key => $item) {
  849. $text .= '<td '.$tdoptions.'>'.$item.'</td>';
  850. }
  851. $text .= '</tr>';
  852. return $text;
  853. }
  854. /**
  855. * Return an html table from an array
  856. *
  857. * @param array $data Array of data
  858. * @param int $tableMarkup Table markup
  859. * @param string $tableoptions Options for table
  860. * @param string $troptions Options for tr
  861. * @param string $tdoptions Options for td
  862. * @return string
  863. */
  864. function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = '', $tdoptions = '')
  865. {
  866. $text = '';
  867. if ($tableMarkup) {
  868. $text = '<table '.$tableoptions.'>';
  869. }
  870. foreach ($data as $key => $item) {
  871. if (is_array($item)) {
  872. $text .= array2tr($item, $troptions, $tdoptions);
  873. } else {
  874. $text .= '<tr '.$troptions.'>';
  875. $text .= '<td '.$tdoptions.'>'.$key.'</td>';
  876. $text .= '<td '.$tdoptions.'>'.$item.'</td>';
  877. $text .= '</tr>';
  878. }
  879. }
  880. if ($tableMarkup) {
  881. $text .= '</table>';
  882. }
  883. return $text;
  884. }
  885. /**
  886. * Return last or next value for a mask (according to area we should not reset)
  887. *
  888. * @param DoliDB $db Database handler
  889. * @param string $mask Mask to use
  890. * @param string $table Table containing field with counter
  891. * @param string $field Field containing already used values of counter
  892. * @param string $where To add a filter on selection (for exemple to filter on invoice types)
  893. * @param Societe $objsoc The company that own the object we need a counter for
  894. * @param string $date Date to use for the {y},{m},{d} tags.
  895. * @param string $mode 'next' for next value or 'last' for last value
  896. * @param bool $bentityon Activate the entity filter. Default is true (for modules not compatible with multicompany)
  897. * @param User $objuser Object user we need data from.
  898. * @param int $forceentity Entity id to force
  899. * @return string New value (numeric) or error message
  900. */
  901. function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $date = '', $mode = 'next', $bentityon = true, $objuser = null, $forceentity = null)
  902. {
  903. global $conf, $user;
  904. if (!is_object($objsoc)) {
  905. $valueforccc = $objsoc;
  906. } elseif ($table == "commande_fournisseur" || $table == "facture_fourn") {
  907. $valueforccc = dol_string_unaccent($objsoc->code_fournisseur);
  908. } else {
  909. $valueforccc = dol_string_unaccent($objsoc->code_client);
  910. }
  911. $sharetable = $table;
  912. if ($table == 'facture' || $table == 'invoice') {
  913. $sharetable = 'invoicenumber'; // for getEntity function
  914. }
  915. // Clean parameters
  916. if ($date == '') {
  917. $date = dol_now(); // We use local year and month of PHP server to search numbers
  918. }
  919. // but we should use local year and month of user
  920. // For debugging
  921. //dol_syslog("mask=".$mask, LOG_DEBUG);
  922. //include_once(DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php');
  923. //$mask='FA{yy}{mm}-{0000@99}';
  924. //$date=dol_mktime(12, 0, 0, 1, 1, 1900);
  925. //$date=dol_stringtotime('20130101');
  926. $hasglobalcounter = false;
  927. $reg = array();
  928. // Extract value for mask counter, mask raz and mask offset
  929. if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg)) {
  930. $masktri = $reg[1].(!empty($reg[2]) ? $reg[2] : '').(!empty($reg[3]) ? $reg[3] : '');
  931. $maskcounter = $reg[1];
  932. $hasglobalcounter = true;
  933. } else {
  934. // setting some defaults so the rest of the code won't fail if there is a third party counter
  935. $masktri = '00000';
  936. $maskcounter = '00000';
  937. }
  938. $maskraz = -1;
  939. $maskoffset = 0;
  940. $resetEveryMonth = false;
  941. if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) {
  942. return 'ErrorCounterMustHaveMoreThan3Digits';
  943. }
  944. // Extract value for third party mask counter
  945. $regClientRef = array();
  946. if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) {
  947. $maskrefclient = $regClientRef[1].$regClientRef[2];
  948. $maskrefclient_maskclientcode = $regClientRef[1];
  949. $maskrefclient_maskcounter = $regClientRef[2];
  950. $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
  951. $maskrefclient_clientcode = substr($valueforccc, 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code where n is length in mask
  952. $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
  953. $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
  954. if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) {
  955. return 'ErrorCounterMustHaveMoreThan3Digits';
  956. }
  957. } else {
  958. $maskrefclient = '';
  959. }
  960. // fail if there is neither a global nor a third party counter
  961. if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) {
  962. return 'ErrorBadMask';
  963. }
  964. // Extract value for third party type
  965. $regType = array();
  966. if (preg_match('/\{(t+)\}/i', $mask, $regType)) {
  967. $masktype = $regType[1];
  968. $masktype_value = substr(preg_replace('/^TE_/', '', $objsoc->typent_code), 0, dol_strlen($regType[1])); // get n first characters of thirdparty typent_code (where n is length in mask)
  969. $masktype_value = str_pad($masktype_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
  970. } else {
  971. $masktype = '';
  972. $masktype_value = '';
  973. }
  974. // Extract value for user
  975. $regType = array();
  976. if (preg_match('/\{(u+)\}/i', $mask, $regType)) {
  977. $lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  978. if (is_object($objuser)) {
  979. $lastname = $objuser->lastname;
  980. }
  981. $maskuser = $regType[1];
  982. $maskuser_value = substr($lastname, 0, dol_strlen($regType[1])); // get n first characters of user firstname (where n is length in mask)
  983. $maskuser_value = str_pad($maskuser_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
  984. } else {
  985. $maskuser = '';
  986. $maskuser_value = '';
  987. }
  988. // Personalized field {XXX-1} à {XXX-9}
  989. $maskperso = array();
  990. $maskpersonew = array();
  991. $tmpmask = $mask;
  992. $regKey = array();
  993. while (preg_match('/\{([A-Z]+)\-([1-9])\}/', $tmpmask, $regKey)) {
  994. $maskperso[$regKey[1]] = '{'.$regKey[1].'-'.$regKey[2].'}';
  995. $maskpersonew[$regKey[1]] = str_pad('', $regKey[2], '_', STR_PAD_RIGHT);
  996. $tmpmask = preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask);
  997. }
  998. if (strstr($mask, 'user_extra_')) {
  999. $start = "{user_extra_";
  1000. $end = "\}";
  1001. $extra = get_string_between($mask, "user_extra_", "}");
  1002. if (!empty($user->array_options['options_'.$extra])) {
  1003. $mask = preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
  1004. }
  1005. }
  1006. $maskwithonlyymcode = $mask;
  1007. $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $maskcounter, $maskwithonlyymcode);
  1008. $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
  1009. $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
  1010. $maskwithonlyymcode = preg_replace('/\{(t+)\}/i', $masktype_value, $maskwithonlyymcode);
  1011. $maskwithonlyymcode = preg_replace('/\{(u+)\}/i', $maskuser_value, $maskwithonlyymcode);
  1012. foreach ($maskperso as $key => $val) {
  1013. $maskwithonlyymcode = preg_replace('/'.preg_quote($val, '/').'/i', $maskpersonew[$key], $maskwithonlyymcode);
  1014. }
  1015. $maskwithnocode = $maskwithonlyymcode;
  1016. $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
  1017. $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
  1018. $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode);
  1019. $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
  1020. // Now maskwithnocode = 0000ddmmyyyyccc for example
  1021. // and maskcounter = 0000 for example
  1022. //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
  1023. //var_dump($reg);
  1024. // If an offset is asked
  1025. if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) {
  1026. $maskoffset = preg_replace('/^\+/', '', $reg[2]);
  1027. }
  1028. if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) {
  1029. $maskoffset = preg_replace('/^\+/', '', $reg[3]);
  1030. }
  1031. // Define $sqlwhere
  1032. $sqlwhere = '';
  1033. $yearoffset = 0; // Use year of current $date by default
  1034. $yearoffsettype = false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
  1035. // If a restore to zero after a month is asked we check if there is already a value for this year.
  1036. if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) {
  1037. $yearoffsettype = preg_replace('/^@/', '', $reg[2]);
  1038. }
  1039. if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) {
  1040. $yearoffsettype = preg_replace('/^@/', '', $reg[3]);
  1041. }
  1042. //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
  1043. if (is_numeric($yearoffsettype) && $yearoffsettype >= 1) {
  1044. $maskraz = $yearoffsettype; // For backward compatibility
  1045. } elseif ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1)) {
  1046. $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START;
  1047. }
  1048. //print "maskraz=".$maskraz; // -1=no reset
  1049. if ($maskraz > 0) { // A reset is required
  1050. if ($maskraz == 99) {
  1051. $maskraz = date('m', $date);
  1052. $resetEveryMonth = true;
  1053. }
  1054. if ($maskraz > 12) {
  1055. return 'ErrorBadMaskBadRazMonth';
  1056. }
  1057. // Define posy, posm and reg
  1058. if ($maskraz > 1) { // if reset is not first month, we need month and year into mask
  1059. if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) {
  1060. $posy = 2;
  1061. $posm = 3;
  1062. } elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
  1063. $posy = 3;
  1064. $posm = 2;
  1065. } else {
  1066. return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
  1067. }
  1068. if (dol_strlen($reg[$posy]) < 2) {
  1069. return 'ErrorCantUseRazWithYearOnOneDigit';
  1070. }
  1071. } else // if reset is for a specific month in year, we need year
  1072. {
  1073. if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
  1074. $posy = 3;
  1075. $posm = 2;
  1076. } elseif (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) {
  1077. $posy = 2;
  1078. $posm = 3;
  1079. } elseif (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
  1080. $posy = 2;
  1081. $posm = 0;
  1082. } else {
  1083. return 'ErrorCantUseRazIfNoYearInMask';
  1084. }
  1085. }
  1086. // Define length
  1087. $yearlen = $posy ?dol_strlen($reg[$posy]) : 0;
  1088. $monthlen = $posm ?dol_strlen($reg[$posm]) : 0;
  1089. // Define pos
  1090. $yearpos = (dol_strlen($reg[1]) + 1);
  1091. $monthpos = ($yearpos + $yearlen);
  1092. if ($posy == 3 && $posm == 2) { // if month is before year
  1093. $monthpos = (dol_strlen($reg[1]) + 1);
  1094. $yearpos = ($monthpos + $monthlen);
  1095. }
  1096. //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
  1097. // Define $yearcomp and $monthcomp (that will be use in the select where to search max number)
  1098. $monthcomp = $maskraz;
  1099. $yearcomp = 0;
  1100. if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') { // $yearoffsettype is - or +
  1101. $currentyear = date("Y", $date);
  1102. $fiscaldate = dol_mktime('0', '0', '0', $maskraz, '1', $currentyear);
  1103. $newyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear);
  1104. $nextnewyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear + 1);
  1105. //echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
  1106. // If after or equal of current fiscal date
  1107. if ($date >= $fiscaldate) {
  1108. // If before of next new year date
  1109. if ($date < $nextnewyeardate && $yearoffsettype == '+') {
  1110. $yearoffset = 1;
  1111. }
  1112. } elseif ($date >= $newyeardate && $yearoffsettype == '-') {
  1113. // If after or equal of current new year date
  1114. $yearoffset = -1;
  1115. }
  1116. } elseif (date("m", $date) < $maskraz && empty($resetEveryMonth)) {
  1117. // For backward compatibility
  1118. $yearoffset = -1;
  1119. } // If current month lower that month of return to zero, year is previous year
  1120. if ($yearlen == 4) {
  1121. $yearcomp = sprintf("%04d", date("Y", $date) + $yearoffset);
  1122. } elseif ($yearlen == 2) {
  1123. $yearcomp = sprintf("%02d", date("y", $date) + $yearoffset);
  1124. } elseif ($yearlen == 1) {
  1125. $yearcomp = substr(date('y', $date), 1, 1) + $yearoffset;
  1126. }
  1127. if ($monthcomp > 1 && empty($resetEveryMonth)) { // Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0)
  1128. if ($yearlen == 4) {
  1129. $yearcomp1 = sprintf("%04d", date("Y", $date) + $yearoffset + 1);
  1130. } elseif ($yearlen == 2) {
  1131. $yearcomp1 = sprintf("%02d", date("y", $date) + $yearoffset + 1);
  1132. }
  1133. $sqlwhere .= "(";
  1134. $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."'";
  1135. $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
  1136. $sqlwhere .= " OR";
  1137. $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp1)."'";
  1138. $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
  1139. $sqlwhere .= ')';
  1140. } elseif ($resetEveryMonth) {
  1141. $sqlwhere .= "(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."'";
  1142. $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
  1143. } else { // reset is done on january
  1144. $sqlwhere .= "(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."')";
  1145. }
  1146. }
  1147. //print "sqlwhere=".$sqlwhere." yearcomp=".$yearcomp."<br>\n"; // sqlwhere and yearcomp defined only if we ask a reset
  1148. //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
  1149. // Define $sqlstring
  1150. if (function_exists('mb_strrpos')) {
  1151. $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 0, 'UTF-8');
  1152. } else {
  1153. $posnumstart = strrpos($maskwithnocode, $maskcounter);
  1154. } // Pos of counter in final string (from 0 to ...)
  1155. if ($posnumstart < 0) {
  1156. return 'ErrorBadMaskFailedToLocatePosOfSequence';
  1157. }
  1158. $sqlstring = "SUBSTRING(".$field.", ".($posnumstart + 1).", ".dol_strlen($maskcounter).")";
  1159. // Define $maskLike
  1160. $maskLike = dol_string_nospecial($mask);
  1161. $maskLike = str_replace("%", "_", $maskLike);
  1162. // Replace protected special codes with matching number of _ as wild card caracter
  1163. $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
  1164. $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
  1165. $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
  1166. $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
  1167. $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
  1168. $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskLike);
  1169. if ($maskrefclient) {
  1170. $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
  1171. }
  1172. if ($masktype) {
  1173. $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
  1174. }
  1175. if ($maskuser) {
  1176. $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
  1177. }
  1178. foreach ($maskperso as $key => $val) {
  1179. $maskLike = str_replace(dol_string_nospecial($maskperso[$key]), $maskpersonew[$key], $maskLike);
  1180. }
  1181. // Get counter in database
  1182. $counter = 0;
  1183. $sql = "SELECT MAX(".$sqlstring.") as val";
  1184. $sql .= " FROM ".MAIN_DB_PREFIX.$table;
  1185. $sql .= " WHERE ".$field." LIKE '".$db->escape($maskLike)."'";
  1186. $sql .= " AND ".$field." NOT LIKE '(PROV%)'";
  1187. if ($bentityon) { // only if entity enable
  1188. $sql .= " AND entity IN (".getEntity($sharetable).")";
  1189. } elseif (!empty($forceentity)) {
  1190. $sql .= " AND entity IN (".$db->sanitize($forceentity).")";
  1191. }
  1192. if ($where) {
  1193. $sql .= $where;
  1194. }
  1195. if ($sqlwhere) {
  1196. $sql .= " AND ".$sqlwhere;
  1197. }
  1198. //print $sql.'<br>';
  1199. dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
  1200. $resql = $db->query($sql);
  1201. if ($resql) {
  1202. $obj = $db->fetch_object($resql);
  1203. $counter = $obj->val;
  1204. } else {
  1205. dol_print_error($db);
  1206. }
  1207. // Check if we must force counter to maskoffset
  1208. if (empty($counter)) {
  1209. $counter = $maskoffset;
  1210. } elseif (preg_match('/[^0-9]/i', $counter)) {
  1211. $counter = 0;
  1212. dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
  1213. } elseif ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) {
  1214. $counter = $maskoffset;
  1215. }
  1216. if ($mode == 'last') { // We found value for counter = last counter value. Now need to get corresponding ref of invoice.
  1217. $counterpadded = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
  1218. // Define $maskLike
  1219. $maskLike = dol_string_nospecial($mask);
  1220. $maskLike = str_replace("%", "_", $maskLike);
  1221. // Replace protected special codes with matching number of _ as wild card caracter
  1222. $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
  1223. $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
  1224. $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
  1225. $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
  1226. $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
  1227. $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), $counterpadded, $maskLike);
  1228. if ($maskrefclient) {
  1229. $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
  1230. }
  1231. if ($masktype) {
  1232. $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
  1233. }
  1234. if ($maskuser) {
  1235. $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
  1236. }
  1237. $ref = '';
  1238. $sql = "SELECT ".$field." as ref";
  1239. $sql .= " FROM ".MAIN_DB_PREFIX.$table;
  1240. $sql .= " WHERE ".$field." LIKE '".$db->escape($maskLike)."'";
  1241. $sql .= " AND ".$field." NOT LIKE '%PROV%'";
  1242. if ($bentityon) { // only if entity enable
  1243. $sql .= " AND entity IN (".getEntity($sharetable).")";
  1244. } elseif (!empty($forceentity)) {
  1245. $sql .= " AND entity IN (".$db->sanitize($forceentity).")";
  1246. }
  1247. if ($where) {
  1248. $sql .= $where;
  1249. }
  1250. if ($sqlwhere) {
  1251. $sql .= " AND ".$sqlwhere;
  1252. }
  1253. dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
  1254. $resql = $db->query($sql);
  1255. if ($resql) {
  1256. $obj = $db->fetch_object($resql);
  1257. if ($obj) {
  1258. $ref = $obj->ref;
  1259. }
  1260. } else {
  1261. dol_print_error($db);
  1262. }
  1263. $numFinal = $ref;
  1264. } elseif ($mode == 'next') {
  1265. $counter++;
  1266. $maskrefclient_counter = 0;
  1267. // If value for $counter has a length higher than $maskcounter chars
  1268. if ($counter >= pow(10, dol_strlen($maskcounter))) {
  1269. $counter = 'ErrorMaxNumberReachForThisMask';
  1270. }
  1271. if (!empty($maskrefclient_maskcounter)) {
  1272. //print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n<br>";
  1273. // Define $sqlstring
  1274. $maskrefclient_posnumstart = strpos($maskwithnocode, $maskrefclient_maskcounter, strpos($maskwithnocode, $maskrefclient)); // Pos of counter in final string (from 0 to ...)
  1275. if ($maskrefclient_posnumstart <= 0) {
  1276. return 'ErrorBadMask';
  1277. }
  1278. $maskrefclient_sqlstring = 'SUBSTRING('.$field.', '.($maskrefclient_posnumstart + 1).', '.dol_strlen($maskrefclient_maskcounter).')';
  1279. //print "x".$sqlstring;
  1280. // Define $maskrefclient_maskLike
  1281. $maskrefclient_maskLike = dol_string_nospecial($mask);
  1282. $maskrefclient_maskLike = str_replace("%", "_", $maskrefclient_maskLike);
  1283. // Replace protected special codes with matching number of _ as wild card caracter
  1284. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'), '____', $maskrefclient_maskLike);
  1285. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'), '__', $maskrefclient_maskLike);
  1286. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'), '_', $maskrefclient_maskLike);
  1287. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'), '__', $maskrefclient_maskLike);
  1288. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'), '__', $maskrefclient_maskLike);
  1289. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskrefclient_maskLike);
  1290. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), $maskrefclient_clientcode.str_pad("", dol_strlen($maskrefclient_maskcounter), "_"), $maskrefclient_maskLike);
  1291. // Get counter in database
  1292. $maskrefclient_sql = "SELECT MAX(".$maskrefclient_sqlstring.") as val";
  1293. $maskrefclient_sql .= " FROM ".MAIN_DB_PREFIX.$table;
  1294. //$sql.= " WHERE ".$field." not like '(%'";
  1295. $maskrefclient_sql .= " WHERE ".$field." LIKE '".$db->escape($maskrefclient_maskLike)."'";
  1296. if ($bentityon) { // only if entity enable
  1297. $maskrefclient_sql .= " AND entity IN (".getEntity($sharetable).")";
  1298. } elseif (!empty($forceentity)) {
  1299. $sql .= " AND entity IN (".$db->sanitize($forceentity).")";
  1300. }
  1301. if ($where) {
  1302. $maskrefclient_sql .= $where; //use the same optional where as general mask
  1303. }
  1304. if ($sqlwhere) {
  1305. $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask
  1306. }
  1307. $maskrefclient_sql .= " AND (SUBSTRING(".$field.", ".(strpos($maskwithnocode, $maskrefclient) + 1).", ".dol_strlen($maskrefclient_maskclientcode).") = '".$db->escape($maskrefclient_clientcode)."')";
  1308. dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
  1309. $maskrefclient_resql = $db->query($maskrefclient_sql);
  1310. if ($maskrefclient_resql) {
  1311. $maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
  1312. $maskrefclient_counter = $maskrefclient_obj->val;
  1313. } else {
  1314. dol_print_error($db);
  1315. }
  1316. if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) {
  1317. $maskrefclient_counter = $maskrefclient_maskoffset;
  1318. }
  1319. $maskrefclient_counter++;
  1320. }
  1321. // Build numFinal
  1322. $numFinal = $mask;
  1323. // We replace special codes except refclient
  1324. if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') { // yearoffsettype is - or +, so we don't want current year
  1325. $numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date) + $yearoffset, $numFinal);
  1326. $numFinal = preg_replace('/\{yy\}/i', date("y", $date) + $yearoffset, $numFinal);
  1327. $numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1) + $yearoffset, $numFinal);
  1328. } else // we want yyyy to be current year
  1329. {
  1330. $numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date), $numFinal);
  1331. $numFinal = preg_replace('/\{yy\}/i', date("y", $date), $numFinal);
  1332. $numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1), $numFinal);
  1333. }
  1334. $numFinal = preg_replace('/\{mm\}/i', date("m", $date), $numFinal);
  1335. $numFinal = preg_replace('/\{dd\}/i', date("d", $date), $numFinal);
  1336. // Now we replace the counter
  1337. $maskbefore = '{'.$masktri.'}';
  1338. $maskafter = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
  1339. //print 'x'.$numFinal.' - '.$maskbefore.' - '.$maskafter.'y';exit;
  1340. $numFinal = str_replace($maskbefore, $maskafter, $numFinal);
  1341. // Now we replace the refclient
  1342. if ($maskrefclient) {
  1343. //print "maskrefclient=".$maskrefclient." maskrefclient_counter=".$maskrefclient_counter." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskrefclient_clientcode=".$maskrefclient_clientcode." maskrefclient_maskcounter=".$maskrefclient_maskcounter."\n<br>";exit;
  1344. $maskrefclient_maskbefore = '{'.$maskrefclient.'}';
  1345. $maskrefclient_maskafter = $maskrefclient_clientcode;
  1346. if (dol_strlen($maskrefclient_maskcounter) > 0) {
  1347. $maskrefclient_maskafter .= str_pad($maskrefclient_counter, dol_strlen($maskrefclient_maskcounter), "0", STR_PAD_LEFT);
  1348. }
  1349. $numFinal = str_replace($maskrefclient_maskbefore, $maskrefclient_maskafter, $numFinal);
  1350. }
  1351. // Now we replace the type
  1352. if ($masktype) {
  1353. $masktype_maskbefore = '{'.$masktype.'}';
  1354. $masktype_maskafter = $masktype_value;
  1355. $numFinal = str_replace($masktype_maskbefore, $masktype_maskafter, $numFinal);
  1356. }
  1357. // Now we replace the user
  1358. if ($maskuser) {
  1359. $maskuser_maskbefore = '{'.$maskuser.'}';
  1360. $maskuser_maskafter = $maskuser_value;
  1361. $numFinal = str_replace($maskuser_maskbefore, $maskuser_maskafter, $numFinal);
  1362. }
  1363. }
  1364. dol_syslog("functions2::get_next_value return ".$numFinal, LOG_DEBUG);
  1365. return $numFinal;
  1366. }
  1367. /**
  1368. * Get string between
  1369. *
  1370. * @param string $string String to test
  1371. * @param int $start Value for start
  1372. * @param int $end Value for end
  1373. * @return string Return part of string
  1374. */
  1375. function get_string_between($string, $start, $end)
  1376. {
  1377. $string = " ".$string;
  1378. $ini = strpos($string, $start);
  1379. if ($ini == 0) {
  1380. return "";
  1381. }
  1382. $ini += strlen($start);
  1383. $len = strpos($string, $end, $ini) - $ini;
  1384. return substr($string, $ini, $len);
  1385. }
  1386. /**
  1387. * Check value
  1388. *
  1389. * @param string $mask Mask to use
  1390. * @param string $value Value
  1391. * @return int|string <0 or error string if KO, 0 if OK
  1392. */
  1393. function check_value($mask, $value)
  1394. {
  1395. $result = 0;
  1396. $hasglobalcounter = false;
  1397. // Extract value for mask counter, mask raz and mask offset
  1398. $reg = array();
  1399. if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $mask, $reg)) {
  1400. $masktri = $reg[1].(isset($reg[2]) ? $reg[2] : '').(isset($reg[3]) ? $reg[3] : '');
  1401. $maskcounter = $reg[1];
  1402. $hasglobalcounter = true;
  1403. } else {
  1404. // setting some defaults so the rest of the code won't fail if there is a third party counter
  1405. $masktri = '00000';
  1406. $maskcounter = '00000';
  1407. }
  1408. $maskraz = -1;
  1409. $maskoffset = 0;
  1410. if (dol_strlen($maskcounter) < 3) {
  1411. return 'ErrorCounterMustHaveMoreThan3Digits';
  1412. }
  1413. // Extract value for third party mask counter
  1414. $regClientRef = array();
  1415. if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) {
  1416. $maskrefclient = $regClientRef[1].$regClientRef[2];
  1417. $maskrefclient_maskclientcode = $regClientRef[1];
  1418. $maskrefclient_maskcounter = $regClientRef[2];
  1419. $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
  1420. $maskrefclient_clientcode = substr('', 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code to form maskrefclient_clientcode
  1421. $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
  1422. $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
  1423. if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) {
  1424. return 'ErrorCounterMustHaveMoreThan3Digits';
  1425. }
  1426. } else {
  1427. $maskrefclient = '';
  1428. }
  1429. // fail if there is neither a global nor a third party counter
  1430. if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) {
  1431. return 'ErrorBadMask';
  1432. }
  1433. $maskwithonlyymcode = $mask;
  1434. $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $maskcounter, $maskwithonlyymcode);
  1435. $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
  1436. $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
  1437. $maskwithnocode = $maskwithonlyymcode;
  1438. $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
  1439. $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
  1440. $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode);
  1441. $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
  1442. // Now maskwithnocode = 0000ddmmyyyyccc for example
  1443. // and maskcounter = 0000 for example
  1444. //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
  1445. // If an offset is asked
  1446. if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) {
  1447. $maskoffset = preg_replace('/^\+/', '', $reg[2]);
  1448. }
  1449. if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) {
  1450. $maskoffset = preg_replace('/^\+/', '', $reg[3]);
  1451. }
  1452. // Define $sqlwhere
  1453. // If a restore to zero after a month is asked we check if there is already a value for this year.
  1454. if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) {
  1455. $maskraz = preg_replace('/^@/', '', $reg[2]);
  1456. }
  1457. if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) {
  1458. $maskraz = preg_replace('/^@/', '', $reg[3]);
  1459. }
  1460. if ($maskraz >= 0) {
  1461. if ($maskraz == 99) {
  1462. $maskraz = date('m');
  1463. $resetEveryMonth = true;
  1464. }
  1465. if ($maskraz > 12) {
  1466. return 'ErrorBadMaskBadRazMonth';
  1467. }
  1468. // Define reg
  1469. if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) {
  1470. return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
  1471. }
  1472. if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
  1473. return 'ErrorCantUseRazIfNoYearInMask';
  1474. }
  1475. //print "x".$maskwithonlyymcode." ".$maskraz;
  1476. }
  1477. //print "masktri=".$masktri." maskcounter=".$maskcounter." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
  1478. if (function_exists('mb_strrpos')) {
  1479. $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 0, 'UTF-8');
  1480. } else {
  1481. $posnumstart = strrpos($maskwithnocode, $maskcounter);
  1482. } // Pos of counter in final string (from 0 to ...)
  1483. if ($posnumstart < 0) {
  1484. return 'ErrorBadMaskFailedToLocatePosOfSequence';
  1485. }
  1486. // Check we have a number in $value at position ($posnumstart+1).', '.dol_strlen($maskcounter)
  1487. // TODO
  1488. // Check length
  1489. $len = dol_strlen($maskwithnocode);
  1490. if (dol_strlen($value) != $len) {
  1491. $result = -1;
  1492. }
  1493. dol_syslog("functions2::check_value result=".$result, LOG_DEBUG);
  1494. return $result;
  1495. }
  1496. /**
  1497. * Convert a binary data to string that represent hexadecimal value
  1498. *
  1499. * @param string $bin Value to convert
  1500. * @param boolean $pad Add 0
  1501. * @param boolean $upper Convert to tupper
  1502. * @return string x
  1503. */
  1504. function binhex($bin, $pad = false, $upper = false)
  1505. {
  1506. $last = dol_strlen($bin) - 1;
  1507. for ($i = 0; $i <= $last; $i++) {
  1508. $x += $bin[$last - $i] * pow(2, $i);
  1509. }
  1510. $x = dechex($x);
  1511. if ($pad) {
  1512. while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) {
  1513. $x = "0$x";
  1514. }
  1515. }
  1516. if ($upper) {
  1517. $x = strtoupper($x);
  1518. }
  1519. return $x;
  1520. }
  1521. /**
  1522. * Convert an hexadecimal string into a binary string
  1523. *
  1524. * @param string $hexa Hexadecimal string to convert (example: 'FF')
  1525. * @return string bin
  1526. */
  1527. function hexbin($hexa)
  1528. {
  1529. $bin = '';
  1530. $strLength = dol_strlen($hexa);
  1531. for ($i = 0; $i < $strLength; $i++) {
  1532. $bin .= str_pad(decbin(hexdec($hexa[$i])), 4, '0', STR_PAD_LEFT);
  1533. }
  1534. return $bin;
  1535. }
  1536. /**
  1537. * Retourne le numero de la semaine par rapport a une date
  1538. *
  1539. * @param string $time Date au format 'timestamp'
  1540. * @return string Number of week
  1541. */
  1542. function numero_semaine($time)
  1543. {
  1544. $stime = strftime('%Y-%m-%d', $time);
  1545. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg)) {
  1546. // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS'
  1547. $annee = $reg[1];
  1548. $mois = $reg[2];
  1549. $jour = $reg[3];
  1550. }
  1551. /*
  1552. * Norme ISO-8601:
  1553. * - La semaine 1 de toute annee est celle qui contient le 4 janvier ou que la semaine 1 de toute annee est celle qui contient le 1er jeudi de janvier.
  1554. * - La majorite des annees ont 52 semaines mais les annees qui commence un jeudi et les annees bissextiles commencant un mercredi en possede 53.
  1555. * - Le 1er jour de la semaine est le Lundi
  1556. */
  1557. // Definition du Jeudi de la semaine
  1558. if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) { // Dimanche
  1559. $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60;
  1560. } elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) { // du Lundi au Mercredi
  1561. $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60;
  1562. } elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) { // du Vendredi au Samedi
  1563. $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60;
  1564. } else { // Jeudi
  1565. $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee);
  1566. }
  1567. // Definition du premier Jeudi de l'annee
  1568. if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 0) { // Dimanche
  1569. $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + 4 * 24 * 60 * 60;
  1570. } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) < 4) { // du Lundi au Mercredi
  1571. $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (4 - date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)))) * 24 * 60 * 60;
  1572. } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) > 4) { // du Vendredi au Samedi
  1573. $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (7 - (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) - 4)) * 24 * 60 * 60;
  1574. } else // Jeudi
  1575. {
  1576. $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine));
  1577. }
  1578. // Definition du numero de semaine: nb de jours entre "premier Jeudi de l'annee" et "Jeudi de la semaine";
  1579. $numeroSemaine = (
  1580. (
  1581. date("z", mktime(12, 0, 0, date("m", $jeudiSemaine), date("d", $jeudiSemaine), date("Y", $jeudiSemaine)))
  1582. -
  1583. date("z", mktime(12, 0, 0, date("m", $premierJeudiAnnee), date("d", $premierJeudiAnnee), date("Y", $premierJeudiAnnee)))
  1584. ) / 7
  1585. ) + 1;
  1586. // Cas particulier de la semaine 53
  1587. if ($numeroSemaine == 53) {
  1588. // Les annees qui commence un Jeudi et les annees bissextiles commencant un Mercredi en possede 53
  1589. if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 4 || (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 3 && date("z", mktime(12, 0, 0, 12, 31, date("Y", $jeudiSemaine))) == 365)) {
  1590. $numeroSemaine = 53;
  1591. } else {
  1592. $numeroSemaine = 1;
  1593. }
  1594. }
  1595. //echo $jour."-".$mois."-".$annee." (".date("d-m-Y",$premierJeudiAnnee)." - ".date("d-m-Y",$jeudiSemaine).") -> ".$numeroSemaine."<BR>";
  1596. return sprintf("%02d", $numeroSemaine);
  1597. }
  1598. /**
  1599. * Convertit une masse d'une unite vers une autre unite
  1600. *
  1601. * @param float $weight Masse a convertir
  1602. * @param int $from_unit Unite originale en puissance de 10
  1603. * @param int $to_unit Nouvelle unite en puissance de 10
  1604. * @return float Masse convertie
  1605. */
  1606. function weight_convert($weight, &$from_unit, $to_unit)
  1607. {
  1608. /* Pour convertire 320 gr en Kg appeler
  1609. * $f = -3
  1610. * weigh_convert(320, $f, 0) retournera 0.32
  1611. *
  1612. */
  1613. $weight = is_numeric($weight) ? $weight : 0;
  1614. while ($from_unit <> $to_unit) {
  1615. if ($from_unit > $to_unit) {
  1616. $weight = $weight * 10;
  1617. $from_unit = $from_unit - 1;
  1618. $weight = weight_convert($weight, $from_unit, $to_unit);
  1619. }
  1620. if ($from_unit < $to_unit) {
  1621. $weight = $weight / 10;
  1622. $from_unit = $from_unit + 1;
  1623. $weight = weight_convert($weight, $from_unit, $to_unit);
  1624. }
  1625. }
  1626. return $weight;
  1627. }
  1628. /**
  1629. * Save personnal parameter
  1630. *
  1631. * @param DoliDB $db Handler database
  1632. * @param Conf $conf Object conf
  1633. * @param User $user Object user
  1634. * @param array $tab Array (key=>value) with all parameters to save
  1635. * @return int <0 if KO, >0 if OK
  1636. *
  1637. * @see dolibarr_get_const(), dolibarr_set_const(), dolibarr_del_const()
  1638. */
  1639. function dol_set_user_param($db, $conf, &$user, $tab)
  1640. {
  1641. // Verification parametres
  1642. if (count($tab) < 1) {
  1643. return -1;
  1644. }
  1645. $db->begin();
  1646. // We remove old parameters for all keys in $tab
  1647. $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param";
  1648. $sql .= " WHERE fk_user = ".((int) $user->id);
  1649. $sql .= " AND entity = ".((int) $conf->entity);
  1650. $sql .= " AND param in (";
  1651. $i = 0;
  1652. foreach ($tab as $key => $value) {
  1653. if ($i > 0) {
  1654. $sql .= ',';
  1655. }
  1656. $sql .= "'".$db->escape($key)."'";
  1657. $i++;
  1658. }
  1659. $sql .= ")";
  1660. dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
  1661. $resql = $db->query($sql);
  1662. if (!$resql) {
  1663. dol_print_error($db);
  1664. $db->rollback();
  1665. return -1;
  1666. }
  1667. foreach ($tab as $key => $value) {
  1668. // Set new parameters
  1669. if ($value) {
  1670. $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,entity,param,value)";
  1671. $sql .= " VALUES (".((int) $user->id).",".((int) $conf->entity).",";
  1672. $sql .= " '".$db->escape($key)."','".$db->escape($value)."')";
  1673. dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
  1674. $result = $db->query($sql);
  1675. if (!$result) {
  1676. dol_print_error($db);
  1677. $db->rollback();
  1678. return -1;
  1679. }
  1680. $user->conf->$key = $value;
  1681. //print "key=".$key." user->conf->key=".$user->conf->$key;
  1682. } else {
  1683. unset($user->conf->$key);
  1684. }
  1685. }
  1686. $db->commit();
  1687. return 1;
  1688. }
  1689. /**
  1690. * Returns formated reduction
  1691. *
  1692. * @param int $reduction Reduction percentage
  1693. * @param Translate $langs Output language
  1694. * @return string Formated reduction
  1695. */
  1696. function dol_print_reduction($reduction, $langs)
  1697. {
  1698. $string = '';
  1699. if ($reduction == 100) {
  1700. $string = $langs->transnoentities("Offered");
  1701. } else {
  1702. $string = vatrate($reduction, true);
  1703. }
  1704. return $string;
  1705. }
  1706. /**
  1707. * Return OS version.
  1708. * Note that PHP_OS returns only OS (not version) and OS PHP was built on, not necessarly OS PHP runs on.
  1709. *
  1710. * @param string $option Option string
  1711. * @return string OS version
  1712. */
  1713. function version_os($option = '')
  1714. {
  1715. if ($option == 'smr') {
  1716. $osversion = php_uname('s').' '.php_uname('m').' '.php_uname('r');
  1717. } else {
  1718. $osversion = php_uname();
  1719. }
  1720. return $osversion;
  1721. }
  1722. /**
  1723. * Return PHP version
  1724. *
  1725. * @return string PHP version
  1726. * @see versionphparray(), versioncompare()
  1727. */
  1728. function version_php()
  1729. {
  1730. return phpversion();
  1731. }
  1732. /**
  1733. * Return Dolibarr version
  1734. *
  1735. * @return string Dolibarr version
  1736. * @see versiondolibarrarray(), versioncompare()
  1737. */
  1738. function version_dolibarr()
  1739. {
  1740. return DOL_VERSION;
  1741. }
  1742. /**
  1743. * Return web server version
  1744. *
  1745. * @return string Web server version
  1746. */
  1747. function version_webserver()
  1748. {
  1749. return $_SERVER["SERVER_SOFTWARE"];
  1750. }
  1751. /**
  1752. * Return list of activated modules usable for document generation
  1753. *
  1754. * @param DoliDB $db Database handler
  1755. * @param string $type Type of models (company, invoice, ...)
  1756. * @param int $maxfilenamelength Max length of value to show
  1757. * @return array|int 0 if no module is activated, or array(key=>label). For modules that need directory scan, key is completed with ":filename".
  1758. */
  1759. function getListOfModels($db, $type, $maxfilenamelength = 0)
  1760. {
  1761. global $conf, $langs;
  1762. $liste = array();
  1763. $found = 0;
  1764. $dirtoscan = '';
  1765. $sql = "SELECT nom as id, nom as doc_template_name, libelle as label, description as description";
  1766. $sql .= " FROM ".MAIN_DB_PREFIX."document_model";
  1767. $sql .= " WHERE type = '".$db->escape($type)."'";
  1768. $sql .= " AND entity IN (0,".$conf->entity.")";
  1769. $sql .= " ORDER BY description DESC";
  1770. dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG);
  1771. $resql = $db->query($sql);
  1772. if ($resql) {
  1773. $num = $db->num_rows($resql);
  1774. $i = 0;
  1775. while ($i < $num) {
  1776. $found = 1;
  1777. $obj = $db->fetch_object($resql);
  1778. // If this generation module needs to scan a directory, then description field is filled
  1779. // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...).
  1780. if (!empty($obj->description)) { // A list of directories to scan is defined
  1781. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1782. $const = $obj->description;
  1783. //irtoscan.=($dirtoscan?',':'').preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
  1784. $dirtoscan = preg_replace('/[\r\n]+/', ',', trim($conf->global->$const));
  1785. $listoffiles = array();
  1786. // Now we add models found in directories scanned
  1787. $listofdir = explode(',', $dirtoscan);
  1788. foreach ($listofdir as $key => $tmpdir) {
  1789. $tmpdir = trim($tmpdir);
  1790. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  1791. if (!$tmpdir) {
  1792. unset($listofdir[$key]);
  1793. continue;
  1794. }
  1795. if (is_dir($tmpdir)) {
  1796. // all type of template is allowed
  1797. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
  1798. if (count($tmpfiles)) {
  1799. $listoffiles = array_merge($listoffiles, $tmpfiles);
  1800. }
  1801. }
  1802. }
  1803. if (count($listoffiles)) {
  1804. foreach ($listoffiles as $record) {
  1805. $max = ($maxfilenamelength ? $maxfilenamelength : 28);
  1806. $liste[$obj->id.':'.$record['fullname']] = dol_trunc($record['name'], $max, 'middle');
  1807. }
  1808. } else {
  1809. $liste[0] = $obj->label.': '.$langs->trans("None");
  1810. }
  1811. } else {
  1812. if ($type == 'member' && $obj->doc_template_name == 'standard') { // Special case, if member template, we add variant per format
  1813. global $_Avery_Labels;
  1814. include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
  1815. foreach ($_Avery_Labels as $key => $val) {
  1816. $liste[$obj->id.':'.$key] = ($obj->label ? $obj->label : $obj->doc_template_name).' '.$val['name'];
  1817. }
  1818. } else {
  1819. // Common usage
  1820. $liste[$obj->id] = $obj->label ? $obj->label : $obj->doc_template_name;
  1821. }
  1822. }
  1823. $i++;
  1824. }
  1825. } else {
  1826. dol_print_error($db);
  1827. return -1;
  1828. }
  1829. if ($found) {
  1830. return $liste;
  1831. } else {
  1832. return 0;
  1833. }
  1834. }
  1835. /**
  1836. * This function evaluates a string that should be a valid IPv4
  1837. * Note: For ip 169.254.0.0, it returns 0 with some PHP (5.6.24) and 2 with some minor patchs of PHP (5.6.25). See https://github.com/php/php-src/pull/1954.
  1838. *
  1839. * @param string $ip IP Address
  1840. * @return int 0 if not valid or reserved range, 1 if valid and public IP, 2 if valid and private range IP
  1841. */
  1842. function is_ip($ip)
  1843. {
  1844. // First we test if it is a valid IPv4
  1845. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  1846. // Then we test if it is a private range
  1847. if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
  1848. return 2;
  1849. }
  1850. // Then we test if it is a reserved range
  1851. if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) {
  1852. return 0;
  1853. }
  1854. return 1;
  1855. }
  1856. return 0;
  1857. }
  1858. /**
  1859. * Build a login from lastname, firstname
  1860. *
  1861. * @param string $lastname Lastname
  1862. * @param string $firstname Firstname
  1863. * @return string Login
  1864. */
  1865. function dol_buildlogin($lastname, $firstname)
  1866. {
  1867. global $conf;
  1868. //$conf->global->MAIN_BUILD_LOGIN_RULE = 'f.lastname';
  1869. if (!empty($conf->global->MAIN_BUILD_LOGIN_RULE) && $conf->global->MAIN_BUILD_LOGIN_RULE == 'f.lastname') { // f.lastname
  1870. $login = strtolower(dol_string_unaccent(dol_trunc($firstname, 1, 'right', 'UTF-8', 1)));
  1871. $login .= ($login ? '.' : '');
  1872. $login .= strtolower(dol_string_unaccent($lastname));
  1873. $login = dol_string_nospecial($login, ''); // For special names
  1874. } else { // firstname.lastname
  1875. $login = strtolower(dol_string_unaccent($firstname));
  1876. $login .= ($login ? '.' : '');
  1877. $login .= strtolower(dol_string_unaccent($lastname));
  1878. $login = dol_string_nospecial($login, ''); // For special names
  1879. }
  1880. // TODO Add a hook to allow external modules to suggest new rules
  1881. return $login;
  1882. }
  1883. /**
  1884. * Return array to use for SoapClient constructor
  1885. *
  1886. * @return array
  1887. */
  1888. function getSoapParams()
  1889. {
  1890. global $conf;
  1891. $params = array();
  1892. $proxyuse = (empty($conf->global->MAIN_PROXY_USE) ?false:true);
  1893. $proxyhost = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_HOST);
  1894. $proxyport = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_PORT);
  1895. $proxyuser = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_USER);
  1896. $proxypass = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_PASS);
  1897. $timeout = (empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 10 : $conf->global->MAIN_USE_CONNECT_TIMEOUT); // Connection timeout
  1898. $response_timeout = (empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT); // Response timeout
  1899. //print extension_loaded('soap');
  1900. if ($proxyuse) {
  1901. $params = array('connection_timeout'=>$timeout,
  1902. 'response_timeout'=>$response_timeout,
  1903. 'proxy_use' => 1,
  1904. 'proxy_host' => $proxyhost,
  1905. 'proxy_port' => $proxyport,
  1906. 'proxy_login' => $proxyuser,
  1907. 'proxy_password' => $proxypass,
  1908. 'trace' => 1
  1909. );
  1910. } else {
  1911. $params = array('connection_timeout'=>$timeout,
  1912. 'response_timeout'=>$response_timeout,
  1913. 'proxy_use' => 0,
  1914. 'proxy_host' => false,
  1915. 'proxy_port' => false,
  1916. 'proxy_login' => false,
  1917. 'proxy_password' => false,
  1918. 'trace' => 1
  1919. );
  1920. }
  1921. return $params;
  1922. }
  1923. /**
  1924. * Return link url to an object
  1925. *
  1926. * @param int $objectid Id of record
  1927. * @param string $objecttype Type of object ('invoice', 'order', 'expedition_bon', 'myobject@mymodule', ...)
  1928. * @param int $withpicto Picto to show
  1929. * @param string $option More options
  1930. * @return string URL of link to object id/type
  1931. */
  1932. function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '')
  1933. {
  1934. global $db, $conf, $langs;
  1935. $ret = '';
  1936. $regs = array();
  1937. // If we ask a resource form external module (instead of default path)
  1938. if (preg_match('/^([^@]+)@([^@]+)$/i', $objecttype, $regs)) {
  1939. $myobject = $regs[1];
  1940. $module = $regs[2];
  1941. } else {
  1942. // Parse $objecttype (ex: project_task)
  1943. $module = $myobject = $objecttype;
  1944. if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  1945. $module = $regs[1];
  1946. $myobject = $regs[2];
  1947. }
  1948. }
  1949. // Generic case for $classpath
  1950. $classpath = $module.'/class';
  1951. // Special cases, to work with non standard path
  1952. if ($objecttype == 'facture' || $objecttype == 'invoice') {
  1953. $langs->load('bills');
  1954. $classpath = 'compta/facture/class';
  1955. $module = 'facture';
  1956. $myobject = 'facture';
  1957. } elseif ($objecttype == 'commande' || $objecttype == 'order') {
  1958. $langs->load('orders');
  1959. $classpath = 'commande/class';
  1960. $module = 'commande';
  1961. $myobject = 'commande';
  1962. } elseif ($objecttype == 'propal') {
  1963. $langs->load('propal');
  1964. $classpath = 'comm/propal/class';
  1965. } elseif ($objecttype == 'supplier_proposal') {
  1966. $langs->load('supplier_proposal');
  1967. $classpath = 'supplier_proposal/class';
  1968. } elseif ($objecttype == 'shipping') {
  1969. $langs->load('sendings');
  1970. $classpath = 'expedition/class';
  1971. $myobject = 'expedition';
  1972. $module = 'expedition_bon';
  1973. } elseif ($objecttype == 'delivery') {
  1974. $langs->load('deliveries');
  1975. $classpath = 'delivery/class';
  1976. $myobject = 'delivery';
  1977. $module = 'delivery_note';
  1978. } elseif ($objecttype == 'contract') {
  1979. $langs->load('contracts');
  1980. $classpath = 'contrat/class';
  1981. $module = 'contrat';
  1982. $myobject = 'contrat';
  1983. } elseif ($objecttype == 'member') {
  1984. $langs->load('members');
  1985. $classpath = 'adherents/class';
  1986. $module = 'adherent';
  1987. $myobject = 'adherent';
  1988. } elseif ($objecttype == 'cabinetmed_cons') {
  1989. $classpath = 'cabinetmed/class';
  1990. $module = 'cabinetmed';
  1991. $myobject = 'cabinetmedcons';
  1992. } elseif ($objecttype == 'fichinter') {
  1993. $langs->load('interventions');
  1994. $classpath = 'fichinter/class';
  1995. $module = 'ficheinter';
  1996. $myobject = 'fichinter';
  1997. } elseif ($objecttype == 'project') {
  1998. $langs->load('projects');
  1999. $classpath = 'projet/class';
  2000. $module = 'projet';
  2001. } elseif ($objecttype == 'task') {
  2002. $langs->load('projects');
  2003. $classpath = 'projet/class';
  2004. $module = 'projet';
  2005. $myobject = 'task';
  2006. } elseif ($objecttype == 'stock') {
  2007. $classpath = 'product/stock/class';
  2008. $module = 'stock';
  2009. $myobject = 'stock';
  2010. } elseif ($objecttype == 'inventory') {
  2011. $classpath = 'product/inventory/class';
  2012. $module = 'stock';
  2013. $myobject = 'inventory';
  2014. } elseif ($objecttype == 'mo') {
  2015. $classpath = 'mrp/class';
  2016. $module = 'mrp';
  2017. $myobject = 'mo';
  2018. } elseif ($objecttype == 'productlot') {
  2019. $classpath = 'product/stock/class';
  2020. $module = 'stock';
  2021. $myobject = 'productlot';
  2022. }
  2023. // Generic case for $classfile and $classname
  2024. $classfile = strtolower($myobject);
  2025. $classname = ucfirst($myobject);
  2026. //print "objecttype=".$objecttype." module=".$module." subelement=".$subelement." classfile=".$classfile." classname=".$classname." classpath=".$classpath;
  2027. if ($objecttype == 'invoice_supplier') {
  2028. $classfile = 'fournisseur.facture';
  2029. $classname = 'FactureFournisseur';
  2030. $classpath = 'fourn/class';
  2031. $module = 'fournisseur';
  2032. } elseif ($objecttype == 'order_supplier') {
  2033. $classfile = 'fournisseur.commande';
  2034. $classname = 'CommandeFournisseur';
  2035. $classpath = 'fourn/class';
  2036. $module = 'fournisseur';
  2037. } elseif ($objecttype == 'supplier_proposal') {
  2038. $classfile = 'supplier_proposal';
  2039. $classname = 'SupplierProposal';
  2040. $classpath = 'supplier_proposal/class';
  2041. $module = 'supplier_proposal';
  2042. } elseif ($objecttype == 'stock') {
  2043. $classpath = 'product/stock/class';
  2044. $classfile = 'entrepot';
  2045. $classname = 'Entrepot';
  2046. } elseif ($objecttype == 'facturerec') {
  2047. $classpath = 'compta/facture/class';
  2048. $classfile = 'facture-rec';
  2049. $classname = 'FactureRec';
  2050. $module='facture';
  2051. }
  2052. if (!empty($conf->$module->enabled)) {
  2053. $res = dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  2054. if ($res) {
  2055. if (class_exists($classname)) {
  2056. $object = new $classname($db);
  2057. $res = $object->fetch($objectid);
  2058. if ($res > 0) {
  2059. $ret = $object->getNomUrl($withpicto, $option);
  2060. } elseif ($res == 0) {
  2061. $ret = $langs->trans('Deleted');
  2062. }
  2063. unset($object);
  2064. } else {
  2065. dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
  2066. }
  2067. }
  2068. }
  2069. return $ret;
  2070. }
  2071. /**
  2072. * Clean corrupted tree (orphelins linked to a not existing parent), record linked to themself and child-parent loop
  2073. *
  2074. * @param DoliDB $db Database handler
  2075. * @param string $tabletocleantree Table to clean
  2076. * @param string $fieldfkparent Field name that contains id of parent
  2077. * @return int Nb of records fixed/deleted
  2078. */
  2079. function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
  2080. {
  2081. $totalnb = 0;
  2082. $listofid = array();
  2083. $listofparentid = array();
  2084. // Get list of all id in array listofid and all parents in array listofparentid
  2085. $sql = "SELECT rowid, ".$fieldfkparent." as parent_id FROM ".MAIN_DB_PREFIX.$tabletocleantree;
  2086. $resql = $db->query($sql);
  2087. if ($resql) {
  2088. $num = $db->num_rows($resql);
  2089. $i = 0;
  2090. while ($i < $num) {
  2091. $obj = $db->fetch_object($resql);
  2092. $listofid[] = $obj->rowid;
  2093. if ($obj->parent_id > 0) {
  2094. $listofparentid[$obj->rowid] = $obj->parent_id;
  2095. }
  2096. $i++;
  2097. }
  2098. } else {
  2099. dol_print_error($db);
  2100. }
  2101. if (count($listofid)) {
  2102. print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
  2103. // Check loops on each other
  2104. $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid"; // So we update only records linked to themself
  2105. $resql = $db->query($sql);
  2106. if ($resql) {
  2107. $nb = $db->affected_rows($sql);
  2108. if ($nb > 0) {
  2109. print '<br>Some record that were parent of themself were cleaned.';
  2110. }
  2111. $totalnb += $nb;
  2112. }
  2113. //else dol_print_error($db);
  2114. // Check other loops
  2115. $listofidtoclean = array();
  2116. foreach ($listofparentid as $id => $pid) {
  2117. // Check depth
  2118. //print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
  2119. $cursor = $id;
  2120. $arrayidparsed = array(); // We start from child $id
  2121. while ($cursor > 0) {
  2122. $arrayidparsed[$cursor] = 1;
  2123. if ($arrayidparsed[$listofparentid[$cursor]]) { // We detect a loop. A record with a parent that was already into child
  2124. print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
  2125. unset($arrayidparsed);
  2126. $listofidtoclean[$cursor] = $id;
  2127. break;
  2128. }
  2129. $cursor = $listofparentid[$cursor];
  2130. }
  2131. if (count($listofidtoclean)) {
  2132. break;
  2133. }
  2134. }
  2135. $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
  2136. $sql .= " SET ".$fieldfkparent." = 0";
  2137. $sql .= " WHERE rowid IN (".$db->sanitize(join(',', $listofidtoclean)).")"; // So we update only records detected wrong
  2138. $resql = $db->query($sql);
  2139. if ($resql) {
  2140. $nb = $db->affected_rows($sql);
  2141. if ($nb > 0) {
  2142. // Removed orphelins records
  2143. print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
  2144. print join(',', $listofidtoclean);
  2145. }
  2146. $totalnb += $nb;
  2147. }
  2148. //else dol_print_error($db);
  2149. // Check and clean orphelins
  2150. $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
  2151. $sql .= " SET ".$fieldfkparent." = 0";
  2152. $sql .= " WHERE ".$fieldfkparent." NOT IN (".$db->sanitize(join(',', $listofid), 1).")"; // So we update only records linked to a non existing parent
  2153. $resql = $db->query($sql);
  2154. if ($resql) {
  2155. $nb = $db->affected_rows($sql);
  2156. if ($nb > 0) {
  2157. // Removed orphelins records
  2158. print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
  2159. print join(',', $listofid);
  2160. }
  2161. $totalnb += $nb;
  2162. }
  2163. //else dol_print_error($db);
  2164. print '<br>We fixed '.$totalnb.' record(s). Some records may still be corrupted. New check may be required.';
  2165. return $totalnb;
  2166. }
  2167. }
  2168. /**
  2169. * Convert an array with RGB value into hex RGB value.
  2170. * This is the opposite function of colorStringToArray
  2171. *
  2172. * @param array $arraycolor Array
  2173. * @param string $colorifnotfound Color code to return if entry not defined or not a RGB format
  2174. * @return string RGB hex value (without # before). For example: 'FF00FF', '01FF02'
  2175. * @see colorStringToArray(), colorHexToRgb()
  2176. */
  2177. function colorArrayToHex($arraycolor, $colorifnotfound = '888888')
  2178. {
  2179. if (!is_array($arraycolor)) {
  2180. return $colorifnotfound;
  2181. }
  2182. if (empty($arraycolor)) {
  2183. return $colorifnotfound;
  2184. }
  2185. return sprintf("%02s", dechex($arraycolor[0])).sprintf("%02s", dechex($arraycolor[1])).sprintf("%02s", dechex($arraycolor[2]));
  2186. }
  2187. /**
  2188. * Convert a string RGB value ('FFFFFF', '255,255,255') into an array RGB array(255,255,255).
  2189. * This is the opposite function of colorArrayToHex.
  2190. * If entry is already an array, return it.
  2191. *
  2192. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  2193. * @param array $colorifnotfound Color code array to return if entry not defined
  2194. * @return array RGB hex value (without # before). For example: FF00FF
  2195. * @see colorArrayToHex(), colorHexToRgb()
  2196. */
  2197. function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88))
  2198. {
  2199. if (is_array($stringcolor)) {
  2200. return $stringcolor; // If already into correct output format, we return as is
  2201. }
  2202. $reg = array();
  2203. $tmp = preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/', $stringcolor, $reg);
  2204. if (!$tmp) {
  2205. $tmp = explode(',', $stringcolor);
  2206. if (count($tmp) < 3) {
  2207. return $colorifnotfound;
  2208. }
  2209. return $tmp;
  2210. }
  2211. return array(hexdec($reg[1]), hexdec($reg[2]), hexdec($reg[3]));
  2212. }
  2213. /**
  2214. * @param string $color the color you need to valid
  2215. * @param boolean $allow_white in case of white isn't valid
  2216. * @return boolean
  2217. */
  2218. function colorValidateHex($color, $allow_white = true)
  2219. {
  2220. if (!$allow_white && ($color === '#fff' || $color === '#ffffff')) {
  2221. return false;
  2222. }
  2223. if (preg_match('/^#[a-f0-9]{6}$/i', $color)) { //hex color is valid
  2224. return true;
  2225. }
  2226. return false;
  2227. }
  2228. /**
  2229. * Change color to make it less aggressive (ratio is negative) or more aggressive (ratio is positive)
  2230. *
  2231. * @param string $hex Color in hex ('#AA1122' or 'AA1122' or '#a12' or 'a12')
  2232. * @param integer $ratio Default=-50. Note: 0=Component color is unchanged, -100=Component color become 88, +100=Component color become 00 or FF
  2233. * @param integer $brightness Default=0. Adjust brightness. -100=Decrease brightness by 100%, +100=Increase of 100%.
  2234. * @return string New string of color
  2235. * @see colorAdjustBrightness()
  2236. */
  2237. function colorAgressiveness($hex, $ratio = -50, $brightness = 0)
  2238. {
  2239. if (empty($ratio)) {
  2240. $ratio = 0; // To avoid null
  2241. }
  2242. // Steps should be between -255 and 255. Negative = darker, positive = lighter
  2243. $ratio = max(-100, min(100, $ratio));
  2244. // Normalize into a six character long hex string
  2245. $hex = str_replace('#', '', $hex);
  2246. if (strlen($hex) == 3) {
  2247. $hex = str_repeat(substr($hex, 0, 1), 2).str_repeat(substr($hex, 1, 1), 2).str_repeat(substr($hex, 2, 1), 2);
  2248. }
  2249. // Split into three parts: R, G and B
  2250. $color_parts = str_split($hex, 2);
  2251. $return = '#';
  2252. foreach ($color_parts as $color) {
  2253. $color = hexdec($color); // Convert to decimal
  2254. if ($ratio > 0) { // We increase aggressivity
  2255. if ($color > 127) {
  2256. $color += ((255 - $color) * ($ratio / 100));
  2257. }
  2258. if ($color < 128) {
  2259. $color -= ($color * ($ratio / 100));
  2260. }
  2261. } else // We decrease agressiveness
  2262. {
  2263. if ($color > 128) {
  2264. $color -= (($color - 128) * (abs($ratio) / 100));
  2265. }
  2266. if ($color < 127) {
  2267. $color += ((128 - $color) * (abs($ratio) / 100));
  2268. }
  2269. }
  2270. if ($brightness > 0) {
  2271. $color = ($color * (100 + abs($brightness)) / 100);
  2272. } else {
  2273. $color = ($color * (100 - abs($brightness)) / 100);
  2274. }
  2275. $color = max(0, min(255, $color)); // Adjust color to stay into valid range
  2276. $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
  2277. }
  2278. //var_dump($hex.' '.$ratio.' -> '.$return);
  2279. return $return;
  2280. }
  2281. /**
  2282. * @param string $hex Color in hex ('#AA1122' or 'AA1122' or '#a12' or 'a12')
  2283. * @param integer $steps Step/offset added to each color component. It should be between -255 and 255. Negative = darker, positive = lighter
  2284. * @return string New color with format '#AA1122'
  2285. * @see colorAgressiveness()
  2286. */
  2287. function colorAdjustBrightness($hex, $steps)
  2288. {
  2289. // Steps should be between -255 and 255. Negative = darker, positive = lighter
  2290. $steps = max(-255, min(255, $steps));
  2291. // Normalize into a six character long hex string
  2292. $hex = str_replace('#', '', $hex);
  2293. if (strlen($hex) == 3) {
  2294. $hex = str_repeat(substr($hex, 0, 1), 2).str_repeat(substr($hex, 1, 1), 2).str_repeat(substr($hex, 2, 1), 2);
  2295. }
  2296. // Split into three parts: R, G and B
  2297. $color_parts = str_split($hex, 2);
  2298. $return = '#';
  2299. foreach ($color_parts as $color) {
  2300. $color = hexdec($color); // Convert to decimal
  2301. $color = max(0, min(255, $color + $steps)); // Adjust color
  2302. $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
  2303. }
  2304. return $return;
  2305. }
  2306. /**
  2307. * @param string $hex color in hex
  2308. * @param integer $percent 0 to 100
  2309. * @return string
  2310. */
  2311. function colorDarker($hex, $percent)
  2312. {
  2313. $steps = intval(255 * $percent / 100) * -1;
  2314. return colorAdjustBrightness($hex, $steps);
  2315. }
  2316. /**
  2317. * @param string $hex color in hex
  2318. * @param integer $percent 0 to 100
  2319. * @return string
  2320. */
  2321. function colorLighten($hex, $percent)
  2322. {
  2323. $steps = intval(255 * $percent / 100);
  2324. return colorAdjustBrightness($hex, $steps);
  2325. }
  2326. /**
  2327. * @param string $hex color in hex
  2328. * @param float $alpha 0 to 1 to add alpha channel
  2329. * @param bool $returnArray true=return an array instead, false=return string
  2330. * @return string|array String or array
  2331. */
  2332. function colorHexToRgb($hex, $alpha = false, $returnArray = false)
  2333. {
  2334. $string = '';
  2335. $hex = str_replace('#', '', $hex);
  2336. $length = strlen($hex);
  2337. $rgb = array();
  2338. $rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
  2339. $rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
  2340. $rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
  2341. if ($alpha !== false) {
  2342. $rgb['a'] = floatval($alpha);
  2343. $string = 'rgba('.implode(',', $rgb).')';
  2344. } else {
  2345. $string = 'rgb('.implode(',', $rgb).')';
  2346. }
  2347. if ($returnArray) {
  2348. return $rgb;
  2349. } else {
  2350. return $string;
  2351. }
  2352. }
  2353. /**
  2354. * Applies the Cartesian product algorithm to an array
  2355. * Source: http://stackoverflow.com/a/15973172
  2356. *
  2357. * @param array $input Array of products
  2358. * @return array Array of combinations
  2359. */
  2360. function cartesianArray(array $input)
  2361. {
  2362. // filter out empty values
  2363. $input = array_filter($input);
  2364. $result = array(array());
  2365. foreach ($input as $key => $values) {
  2366. $append = array();
  2367. foreach ($result as $product) {
  2368. foreach ($values as $item) {
  2369. $product[$key] = $item;
  2370. $append[] = $product;
  2371. }
  2372. }
  2373. $result = $append;
  2374. }
  2375. return $result;
  2376. }
  2377. /**
  2378. * Get name of directory where the api_...class.php file is stored
  2379. *
  2380. * @param string $moduleobject Module object name
  2381. * @return string Directory name
  2382. */
  2383. function getModuleDirForApiClass($moduleobject)
  2384. {
  2385. $moduledirforclass = $moduleobject;
  2386. if ($moduledirforclass != 'api') {
  2387. $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass);
  2388. }
  2389. if ($moduleobject == 'contracts') {
  2390. $moduledirforclass = 'contrat';
  2391. } elseif (in_array($moduleobject, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents'))) {
  2392. $moduledirforclass = 'api';
  2393. } elseif ($moduleobject == 'contact' || $moduleobject == 'contacts' || $moduleobject == 'customer' || $moduleobject == 'thirdparty' || $moduleobject == 'thirdparties') {
  2394. $moduledirforclass = 'societe';
  2395. } elseif ($moduleobject == 'propale' || $moduleobject == 'proposals') {
  2396. $moduledirforclass = 'comm/propal';
  2397. } elseif ($moduleobject == 'agenda' || $moduleobject == 'agendaevents') {
  2398. $moduledirforclass = 'comm/action';
  2399. } elseif ($moduleobject == 'adherent' || $moduleobject == 'members' || $moduleobject == 'memberstypes' || $moduleobject == 'subscriptions') {
  2400. $moduledirforclass = 'adherents';
  2401. } elseif ($moduleobject == 'don' || $moduleobject == 'donations') {
  2402. $moduledirforclass = 'don';
  2403. } elseif ($moduleobject == 'banque' || $moduleobject == 'bankaccounts') {
  2404. $moduledirforclass = 'compta/bank';
  2405. } elseif ($moduleobject == 'category' || $moduleobject == 'categorie') {
  2406. $moduledirforclass = 'categories';
  2407. } elseif ($moduleobject == 'order' || $moduleobject == 'orders') {
  2408. $moduledirforclass = 'commande';
  2409. } elseif ($moduleobject == 'shipments') {
  2410. $moduledirforclass = 'expedition';
  2411. } elseif ($moduleobject == 'facture' || $moduleobject == 'invoice' || $moduleobject == 'invoices') {
  2412. $moduledirforclass = 'compta/facture';
  2413. } elseif ($moduleobject == 'project' || $moduleobject == 'projects' || $moduleobject == 'task' || $moduleobject == 'tasks') {
  2414. $moduledirforclass = 'projet';
  2415. } elseif ($moduleobject == 'stock' || $moduleobject == 'stockmovements' || $moduleobject == 'warehouses') {
  2416. $moduledirforclass = 'product/stock';
  2417. } elseif ($moduleobject == 'supplierproposals' || $moduleobject == 'supplierproposal' || $moduleobject == 'supplier_proposal') {
  2418. $moduledirforclass = 'supplier_proposal';
  2419. } elseif ($moduleobject == 'fournisseur' || $moduleobject == 'supplierinvoices' || $moduleobject == 'supplierorders') {
  2420. $moduledirforclass = 'fourn';
  2421. } elseif ($moduleobject == 'ficheinter' || $moduleobject == 'interventions') {
  2422. $moduledirforclass = 'fichinter';
  2423. } elseif ($moduleobject == 'mos') {
  2424. $moduledirforclass = 'mrp';
  2425. } elseif (in_array($moduleobject, array('products', 'expensereports', 'users', 'tickets', 'boms', 'receptions'))) {
  2426. $moduledirforclass = preg_replace('/s$/', '', $moduleobject);
  2427. }
  2428. return $moduledirforclass;
  2429. }
  2430. /**
  2431. * Return 2 hexa code randomly
  2432. *
  2433. * @param int $min Between 0 and 255
  2434. * @param int $max Between 0 and 255
  2435. * @return string A color string '12'
  2436. */
  2437. function randomColorPart($min = 0, $max = 255)
  2438. {
  2439. return str_pad(dechex(mt_rand($min, $max)), 2, '0', STR_PAD_LEFT);
  2440. }
  2441. /**
  2442. * Return hexadecimal color randomly
  2443. *
  2444. * @param int $min Between 0 and 255
  2445. * @param int $max Between 0 and 255
  2446. * @return string A color string '123456'
  2447. */
  2448. function randomColor($min = 0, $max = 255)
  2449. {
  2450. return randomColorPart($min, $max).randomColorPart($min, $max).randomColorPart($min, $max);
  2451. }
  2452. if (!function_exists('dolEscapeXML')) {
  2453. /**
  2454. * Encode string for xml usage
  2455. *
  2456. * @param string $string String to encode
  2457. * @return string String encoded
  2458. */
  2459. function dolEscapeXML($string)
  2460. {
  2461. return strtr($string, array('\''=>'&apos;', '"'=>'&quot;', '&'=>'&amp;', '<'=>'&lt;', '>'=>'&gt;'));
  2462. }
  2463. }
  2464. /**
  2465. * Convert links to local wrapper to medias files into a string into a public external URL readable on internet
  2466. *
  2467. * @param string $notetoshow Text to convert
  2468. * @return string String
  2469. */
  2470. function convertBackOfficeMediasLinksToPublicLinks($notetoshow)
  2471. {
  2472. global $dolibarr_main_url_root;
  2473. // Define $urlwithroot
  2474. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  2475. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  2476. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  2477. $notetoshow = preg_replace('/src="[a-zA-Z0-9_\/\-\.]*(viewimage\.php\?modulepart=medias[^"]*)"/', 'src="'.$urlwithroot.'/\1"', $notetoshow);
  2478. return $notetoshow;
  2479. }
  2480. /**
  2481. * Function to format a value into a defined format for French administration (no thousand separator & decimal separator force to ',' with two decimals)
  2482. * Function used into accountancy FEC export
  2483. *
  2484. * @param float $amount Amount to format
  2485. * @return string Chain with formatted upright
  2486. * @see price2num() Format a numeric into a price for FEC files
  2487. */
  2488. function price2fec($amount)
  2489. {
  2490. global $conf;
  2491. // Clean parameters
  2492. if (empty($amount)) {
  2493. $amount = 0; // To have a numeric value if amount not defined or = ''
  2494. }
  2495. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  2496. // Output decimal number by default
  2497. $nbdecimal = (empty($conf->global->ACCOUNTING_FEC_DECIMAL_LENGTH) ? 2 : $conf->global->ACCOUNTING_FEC_DECIMAL_LENGTH);
  2498. // Output separators by default
  2499. $dec = (empty($conf->global->ACCOUNTING_FEC_DECIMAL_SEPARATOR) ? ',' : $conf->global->ACCOUNTING_FEC_DECIMAL_SEPARATOR);
  2500. $thousand = (empty($conf->global->ACCOUNTING_FEC_THOUSAND_SEPARATOR) ? '' : $conf->global->ACCOUNTING_FEC_THOUSAND_SEPARATOR);
  2501. // Format number
  2502. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  2503. return $output;
  2504. }
  2505. /**
  2506. * Check the syntax of some PHP code.
  2507. *
  2508. * @param string $code PHP code to check.
  2509. * @return boolean|array If false, then check was successful, otherwise an array(message,line) of errors is returned.
  2510. */
  2511. function phpSyntaxError($code)
  2512. {
  2513. if (!defined("CR")) {
  2514. define("CR", "\r");
  2515. }
  2516. if (!defined("LF")) {
  2517. define("LF", "\n");
  2518. }
  2519. if (!defined("CRLF")) {
  2520. define("CRLF", "\r\n");
  2521. }
  2522. $braces = 0;
  2523. $inString = 0;
  2524. foreach (token_get_all('<?php '.$code) as $token) {
  2525. if (is_array($token)) {
  2526. switch ($token[0]) {
  2527. case T_CURLY_OPEN:
  2528. case T_DOLLAR_OPEN_CURLY_BRACES:
  2529. case T_START_HEREDOC:
  2530. ++$inString;
  2531. break;
  2532. case T_END_HEREDOC:
  2533. --$inString;
  2534. break;
  2535. }
  2536. } elseif ($inString & 1) {
  2537. switch ($token) {
  2538. case '`':
  2539. case '\'':
  2540. case '"':
  2541. --$inString;
  2542. break;
  2543. }
  2544. } else {
  2545. switch ($token) {
  2546. case '`':
  2547. case '\'':
  2548. case '"':
  2549. ++$inString;
  2550. break;
  2551. case '{':
  2552. ++$braces;
  2553. break;
  2554. case '}':
  2555. if ($inString) {
  2556. --$inString;
  2557. } else {
  2558. --$braces;
  2559. if ($braces < 0) {
  2560. break 2;
  2561. }
  2562. }
  2563. break;
  2564. }
  2565. }
  2566. }
  2567. $inString = @ini_set('log_errors', false);
  2568. $token = @ini_set('display_errors', true);
  2569. ob_start();
  2570. $code = substr($code, strlen('<?php '));
  2571. $braces || $code = "if(0){{$code}\n}";
  2572. if (eval($code) === false) {
  2573. if ($braces) {
  2574. $braces = PHP_INT_MAX;
  2575. } else {
  2576. false !== strpos($code, CR) && $code = strtr(str_replace(CRLF, LF, $code), CR, LF);
  2577. $braces = substr_count($code, LF);
  2578. }
  2579. $code = ob_get_clean();
  2580. $code = strip_tags($code);
  2581. if (preg_match("'syntax error, (.+) in .+ on line (\d+)$'s", $code, $code)) {
  2582. $code[2] = (int) $code[2];
  2583. $code = $code[2] <= $braces
  2584. ? array($code[1], $code[2])
  2585. : array('unexpected $end'.substr($code[1], 14), $braces);
  2586. } else {
  2587. $code = array('syntax error', 0);
  2588. }
  2589. } else {
  2590. ob_end_clean();
  2591. $code = false;
  2592. }
  2593. @ini_set('display_errors', $token);
  2594. @ini_set('log_errors', $inString);
  2595. return $code;
  2596. }