functions2.lib.php 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131
  1. <?php
  2. /* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2008-2012 Regis Houssin <regis.houssin@capnetworks.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 <http://www.gnu.org/licenses/>.
  22. * or see http://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. }
  56. else {
  57. // we have an escaped ascii character
  58. $hexVal = substr($source, $pos, 2);
  59. $decodedStr .= chr(hexdec($hexVal));
  60. $pos += 2;
  61. }
  62. } else {
  63. $decodedStr .= $charAt;
  64. $pos++;
  65. }
  66. }
  67. return dol_html_entity_decode($decodedStr, ENT_COMPAT);
  68. }
  69. /**
  70. * Return list of modules directories. We detect directories that contains a subdirectory /core/modules
  71. * We discard directory modules that contains 'disabled' into their name.
  72. *
  73. * @param string $subdir Sub directory (Example: '/mailings')
  74. * @return array Array of directories that can contains module descriptors
  75. */
  76. function dolGetModulesDirs($subdir='')
  77. {
  78. global $conf;
  79. $modulesdir=array();
  80. foreach ($conf->file->dol_document_root as $type => $dirroot)
  81. {
  82. // Default core/modules dir
  83. if ($type === 'main') {
  84. $modulesdir[$dirroot . '/core/modules' . $subdir . '/'] = $dirroot . '/core/modules' . $subdir . '/';
  85. }
  86. // Scan dir from external modules
  87. $handle=@opendir($dirroot);
  88. if (is_resource($handle))
  89. {
  90. while (($file = readdir($handle))!==false)
  91. {
  92. if (preg_match('/disabled/',$file)) continue; // We discard module if it contains disabled into name.
  93. if (is_dir($dirroot.'/'.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && $file != 'includes')
  94. {
  95. if (is_dir($dirroot . '/' . $file . '/core/modules'.$subdir.'/'))
  96. {
  97. $modulesdir[$dirroot . '/' . $file . '/core/modules'.$subdir.'/'] = $dirroot . '/' . $file . '/core/modules'.$subdir.'/';
  98. }
  99. }
  100. }
  101. closedir($handle);
  102. }
  103. }
  104. return $modulesdir;
  105. }
  106. /**
  107. * Try to guess default paper format according to language into $langs
  108. *
  109. * @param Translate $outputlangs Output lang to use to autodetect output format if setup not done
  110. * @return string Default paper format code
  111. */
  112. function dol_getDefaultFormat(Translate $outputlangs = null)
  113. {
  114. global $langs;
  115. $selected='EUA4';
  116. if (!$outputlangs) {
  117. $outputlangs=$langs;
  118. }
  119. if ($outputlangs->defaultlang == 'ca_CA') $selected='CAP4'; // Canada
  120. if ($outputlangs->defaultlang == 'en_US') $selected='USLetter'; // US
  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. {
  137. $formfile=($searchdir."/langs/".$langs->defaultlang."/".$filename);
  138. dol_syslog('functions2::dol_print_file search file '.$formfile, LOG_DEBUG);
  139. if (is_readable($formfile))
  140. {
  141. $content=file_get_contents($formfile);
  142. $isutf8=utf8_check($content);
  143. if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
  144. elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
  145. else print $content;
  146. return true;
  147. }
  148. else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
  149. if ($searchalt) {
  150. // Test si fichier dans repertoire de la langue alternative
  151. if ($langs->defaultlang != "en_US") $formfilealt = $searchdir."/langs/en_US/".$filename;
  152. else $formfilealt = $searchdir."/langs/fr_FR/".$filename;
  153. dol_syslog('functions2::dol_print_file search alt file '.$formfilealt, LOG_DEBUG);
  154. //print 'getcwd='.getcwd().' htmlfilealt='.$formfilealt.' X '.file_exists(getcwd().'/'.$formfilealt);
  155. if (is_readable($formfilealt))
  156. {
  157. $content=file_get_contents($formfilealt);
  158. $isutf8=utf8_check($content);
  159. if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
  160. elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
  161. else print $content;
  162. return true;
  163. }
  164. else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
  165. }
  166. }
  167. return false;
  168. }
  169. /**
  170. * Show informations on an object
  171. * TODO Move this into html.formother
  172. *
  173. * @param object $object Objet to show
  174. * @param int $usetable Output into a table
  175. * @return void
  176. */
  177. function dol_print_object_info($object, $usetable=0)
  178. {
  179. global $langs,$db;
  180. $langs->load("other");
  181. $langs->load("admin");
  182. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  183. $deltadateforserver=getServerTimeZoneInt('now');
  184. $deltadateforclient=((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
  185. //$deltadateforcompany=((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
  186. $deltadateforuser=round($deltadateforclient-$deltadateforserver);
  187. //print "x".$deltadateforserver." - ".$deltadateforclient." - ".$deltadateforuser;
  188. if ($usetable) print '<table class="border centpercent">';
  189. // Import key
  190. if (! empty($object->import_key))
  191. {
  192. if ($usetable) print '<tr><td class="titlefield">';
  193. print $langs->trans("ImportedWithSet");
  194. if ($usetable) print '</td><td>';
  195. else print ': ';
  196. print $object->import_key;
  197. if ($usetable) print '</td></tr>';
  198. else print '<br>';
  199. }
  200. // User creation (old method using already loaded object and not id is kept for backward compatibility)
  201. if (! empty($object->user_creation) || ! empty($object->user_creation_id))
  202. {
  203. if ($usetable) print '<tr><td class="titlefield">';
  204. print $langs->trans("CreatedBy");
  205. if ($usetable) print '</td><td>';
  206. else print ': ';
  207. if (is_object($object->user_creation))
  208. {
  209. if ($object->user_creation->id) print $object->user_creation->getNomUrl(1, '', 0, 0, 0);
  210. else print $langs->trans("Unknown");
  211. }
  212. else
  213. {
  214. $userstatic=new User($db);
  215. $userstatic->fetch($object->user_creation_id ? $object->user_creation_id : $object->user_creation);
  216. if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
  217. else print $langs->trans("Unknown");
  218. }
  219. if ($usetable) print '</td></tr>';
  220. else print '<br>';
  221. }
  222. // Date creation
  223. if (! empty($object->date_creation))
  224. {
  225. if ($usetable) print '<tr><td class="titlefield">';
  226. print $langs->trans("DateCreation");
  227. if ($usetable) print '</td><td>';
  228. else print ': ';
  229. print dol_print_date($object->date_creation, 'dayhour');
  230. if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_creation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
  231. if ($usetable) print '</td></tr>';
  232. else print '<br>';
  233. }
  234. // User change (old method using already loaded object and not id is kept for backward compatibility)
  235. if (! empty($object->user_modification) || ! empty($object->user_modification_id))
  236. {
  237. if ($usetable) print '<tr><td class="titlefield">';
  238. print $langs->trans("ModifiedBy");
  239. if ($usetable) print '</td><td>';
  240. else print ': ';
  241. if (is_object($object->user_modification))
  242. {
  243. if ($object->user_modification->id) print $object->user_modification->getNomUrl(1, '', 0, 0, 0);
  244. else print $langs->trans("Unknown");
  245. }
  246. else
  247. {
  248. $userstatic=new User($db);
  249. $userstatic->fetch($object->user_modification_id ? $object->user_modification_id : $object->user_modification);
  250. if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
  251. else print $langs->trans("Unknown");
  252. }
  253. if ($usetable) print '</td></tr>';
  254. else print '<br>';
  255. }
  256. // Date change
  257. if (! empty($object->date_modification))
  258. {
  259. if ($usetable) print '<tr><td class="titlefield">';
  260. print $langs->trans("DateLastModification");
  261. if ($usetable) print '</td><td>';
  262. else print ': ';
  263. print dol_print_date($object->date_modification, 'dayhour');
  264. if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_modification+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
  265. if ($usetable) print '</td></tr>';
  266. else print '<br>';
  267. }
  268. // User validation (old method using already loaded object and not id is kept for backward compatibility)
  269. if (! empty($object->user_validation) || ! empty($object->user_validation_id))
  270. {
  271. if ($usetable) print '<tr><td class="titlefield">';
  272. print $langs->trans("ValidatedBy");
  273. if ($usetable) print '</td><td>';
  274. else print ': ';
  275. if (is_object($object->user_validation))
  276. {
  277. if ($object->user_validation->id) print $object->user_validation->getNomUrl(1, '', 0, 0, 0);
  278. else print $langs->trans("Unknown");
  279. }
  280. else
  281. {
  282. $userstatic=new User($db);
  283. $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation);
  284. if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
  285. else print $langs->trans("Unknown");
  286. }
  287. if ($usetable) print '</td></tr>';
  288. else print '<br>';
  289. }
  290. // Date validation
  291. if (! empty($object->date_validation))
  292. {
  293. if ($usetable) print '<tr><td class="titlefield">';
  294. print $langs->trans("DateValidation");
  295. if ($usetable) print '</td><td>';
  296. else print ': ';
  297. print dol_print_date($object->date_validation, 'dayhour');
  298. if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_validation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
  299. if ($usetable) print '</td></tr>';
  300. else print '<br>';
  301. }
  302. // User approve (old method using already loaded object and not id is kept for backward compatibility)
  303. if (! empty($object->user_approve) || ! empty($object->user_approve_id))
  304. {
  305. if ($usetable) print '<tr><td class="titlefield">';
  306. print $langs->trans("ApprovedBy");
  307. if ($usetable) print '</td><td>';
  308. else print ': ';
  309. if (is_object($object->user_approve))
  310. {
  311. if ($object->user_approve->id) print $object->user_approve->getNomUrl(1, '', 0, 0, 0);
  312. else print $langs->trans("Unknown");
  313. }
  314. else
  315. {
  316. $userstatic=new User($db);
  317. $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve);
  318. if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
  319. else print $langs->trans("Unknown");
  320. }
  321. if ($usetable) print '</td></tr>';
  322. else print '<br>';
  323. }
  324. // Date approve
  325. if (! empty($object->date_approve))
  326. {
  327. if ($usetable) print '<tr><td class="titlefield">';
  328. print $langs->trans("DateApprove");
  329. if ($usetable) print '</td><td>';
  330. else print ': ';
  331. print dol_print_date($object->date_approve, 'dayhour');
  332. if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
  333. if ($usetable) print '</td></tr>';
  334. else print '<br>';
  335. }
  336. // User approve
  337. if (! empty($object->user_approve_id2))
  338. {
  339. if ($usetable) print '<tr><td class="titlefield">';
  340. print $langs->trans("ApprovedBy");
  341. if ($usetable) print '</td><td>';
  342. else print ': ';
  343. $userstatic=new User($db);
  344. $userstatic->fetch($object->user_approve_id2);
  345. if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
  346. else print $langs->trans("Unknown");
  347. if ($usetable) print '</td></tr>';
  348. else print '<br>';
  349. }
  350. // Date approve
  351. if (! empty($object->date_approve2))
  352. {
  353. if ($usetable) print '<tr><td class="titlefield">';
  354. print $langs->trans("DateApprove2");
  355. if ($usetable) print '</td><td>';
  356. else print ': ';
  357. print dol_print_date($object->date_approve2, 'dayhour');
  358. if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve2+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
  359. if ($usetable) print '</td></tr>';
  360. else print '<br>';
  361. }
  362. // User close
  363. if (! empty($object->user_cloture))
  364. {
  365. if ($usetable) print '<tr><td class="titlefield">';
  366. print $langs->trans("ClosedBy");
  367. if ($usetable) print '</td><td>';
  368. else print ': ';
  369. if (is_object($object->user_cloture))
  370. {
  371. if ($object->user_cloture->id) print $object->user_cloture->getNomUrl(1, '', 0, 0, 0);
  372. else print $langs->trans("Unknown");
  373. }
  374. else
  375. {
  376. $userstatic=new User($db);
  377. $userstatic->fetch($object->user_cloture);
  378. if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
  379. else print $langs->trans("Unknown");
  380. }
  381. if ($usetable) print '</td></tr>';
  382. else print '<br>';
  383. }
  384. // Date close
  385. if (! empty($object->date_cloture))
  386. {
  387. if ($usetable) print '<tr><td class="titlefield">';
  388. print $langs->trans("DateClosing");
  389. if ($usetable) print '</td><td>';
  390. else print ': ';
  391. print dol_print_date($object->date_cloture, 'dayhour');
  392. if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_cloture+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
  393. if ($usetable) print '</td></tr>';
  394. else print '<br>';
  395. }
  396. // User conciliate
  397. if (! empty($object->user_rappro))
  398. {
  399. if ($usetable) print '<tr><td class="titlefield">';
  400. print $langs->trans("ConciliatedBy");
  401. if ($usetable) print '</td><td>';
  402. else print ': ';
  403. if (is_object($object->user_rappro))
  404. {
  405. if ($object->user_rappro->id) print $object->user_rappro->getNomUrl(1, '', 0, 0, 0);
  406. else print $langs->trans("Unknown");
  407. }
  408. else
  409. {
  410. $userstatic=new User($db);
  411. $userstatic->fetch($object->user_rappro);
  412. if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
  413. else print $langs->trans("Unknown");
  414. }
  415. if ($usetable) print '</td></tr>';
  416. else print '<br>';
  417. }
  418. // Date conciliate
  419. if (! empty($object->date_rappro))
  420. {
  421. if ($usetable) print '<tr><td class="titlefield">';
  422. print $langs->trans("DateConciliating");
  423. if ($usetable) print '</td><td>';
  424. else print ': ';
  425. print dol_print_date($object->date_rappro, 'dayhour');
  426. if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_rappro+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
  427. if ($usetable) print '</td></tr>';
  428. else print '<br>';
  429. }
  430. // Date send
  431. if (! empty($object->date_envoi))
  432. {
  433. if ($usetable) print '<tr><td class="titlefield">';
  434. print $langs->trans("DateLastSend");
  435. if ($usetable) print '</td><td>';
  436. else print ': ';
  437. print dol_print_date($object->date_envoi, 'dayhour');
  438. if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_envoi+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
  439. if ($usetable) print '</td></tr>';
  440. else print '<br>';
  441. }
  442. if ($usetable) print '</table>';
  443. }
  444. /**
  445. * Return an email formatted to include a tracking id
  446. * For example myemail@example.com becom myemail+trackingid@example.com
  447. *
  448. * @param string $email Email address (Ex: "toto@example.com", "John Do <johndo@example.com>")
  449. * @param string $trackingid Tracking id (Ex: thi123 for thirdparty with id 123)
  450. * @return string Return email tracker string
  451. */
  452. function dolAddEmailTrackId($email, $trackingid)
  453. {
  454. $tmp=explode('@',$email);
  455. return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1])?$tmp[1]:'');
  456. }
  457. /**
  458. * Return true if email has a domain name that can't be resolved
  459. *
  460. * @param string $mail Email address (Ex: "toto@example.com", "John Do <johndo@example.com>")
  461. * @return boolean True if domain email is OK, False if KO
  462. */
  463. function isValidMailDomain($mail)
  464. {
  465. list($user, $domain) = explode("@", $mail, 2);
  466. if (checkdnsrr($domain, "MX"))
  467. {
  468. return true;
  469. }
  470. else
  471. {
  472. return false;
  473. }
  474. }
  475. /**
  476. * Url string validation
  477. * <http[s]> :// [user[:pass]@] hostname [port] [/path] [?getquery] [anchor]
  478. *
  479. * @param string $url Url
  480. * @param int $http 1: verify http is provided, 0: not verify http
  481. * @param int $pass 1: verify user and pass is provided, 0: not verify user and pass
  482. * @param int $port 1: verify port is provided, 0: not verify port
  483. * @param int $path 1: verify a path is provided "/" or "/..." or "/.../", 0: not verify path
  484. * @param int $query 1: verify query is provided, 0: not verify query
  485. * @param int $anchor 1: verify anchor is provided, 0: not verify anchor
  486. * @return int 1=Check is OK, 0=Check is KO
  487. */
  488. function isValidUrl($url,$http=0,$pass=0,$port=0,$path=0,$query=0,$anchor=0)
  489. {
  490. $ValidUrl = 0;
  491. $urlregex = '';
  492. // SCHEME
  493. if ($http) $urlregex .= "^(http:\/\/|https:\/\/)";
  494. // USER AND PASS
  495. if ($pass) $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)";
  496. // HOSTNAME OR IP
  497. //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*"; // x allowed (ex. http://localhost, http://routerlogin)
  498. //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)+"; // x.x
  499. $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*"; // x ou x.xx (2 x ou plus)
  500. //use only one of the above
  501. // PORT
  502. if ($port) $urlregex .= "(\:[0-9]{2,5})";
  503. // PATH
  504. if ($path) $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/";
  505. // GET Query
  506. if ($query) $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)";
  507. // ANCHOR
  508. if ($anchor) $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$";
  509. // check
  510. if (preg_match('/'.$urlregex.'/i', $url))
  511. {
  512. $ValidUrl = 1;
  513. }
  514. //print $urlregex.' - '.$url.' - '.$ValidUrl;
  515. return $ValidUrl;
  516. }
  517. /**
  518. * Clean an url string
  519. *
  520. * @param string $url Url
  521. * @param integer $http 1 = keep both http:// and https://, 0: remove http:// but not https://
  522. * @return string Cleaned url
  523. */
  524. function clean_url($url,$http=1)
  525. {
  526. // Fixed by Matelli (see http://matelli.fr/showcases/patchs-dolibarr/fix-cleaning-url.html)
  527. // To include the minus sign in a char class, we must not escape it but put it at the end of the class
  528. // Also, there's no need of escape a dot sign in a class
  529. if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i',$url,$regs))
  530. {
  531. $proto=$regs[1];
  532. $domain=$regs[2];
  533. $port=isset($regs[3])?$regs[3]:'';
  534. //print $url." -> ".$proto." - ".$domain." - ".$port;
  535. //$url = dol_string_nospecial(trim($url));
  536. $url = trim($url);
  537. // Si http: defini on supprime le http (Si https on ne supprime pas)
  538. $newproto=$proto;
  539. if ($http==0)
  540. {
  541. if (preg_match('/^http:[\\/]+/i',$url))
  542. {
  543. $url = preg_replace('/^http:[\\/]+/i','',$url);
  544. $newproto = '';
  545. }
  546. }
  547. // On passe le nom de domaine en minuscule
  548. $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain,'/').'/i', $newproto.strtolower($domain), $url);
  549. return $CleanUrl;
  550. }
  551. else return $url;
  552. }
  553. /**
  554. * Returns an email value with obfuscated parts.
  555. *
  556. * @param string $mail Email
  557. * @param string $replace Replacement character (defaul: *)
  558. * @param int $nbreplace Number of replacement character (default: 8)
  559. * @param int $nbdisplaymail Number of character unchanged (default: 4)
  560. * @param int $nbdisplaydomain Number of character unchanged of domain (default: 3)
  561. * @param bool $displaytld Display tld (default: true)
  562. * @return string Return email with hidden parts or '';
  563. */
  564. function dolObfuscateEmail($mail, $replace="*", $nbreplace=8, $nbdisplaymail=4, $nbdisplaydomain=3, $displaytld=true)
  565. {
  566. if(!isValidEmail($mail))return '';
  567. $tab = explode('@', $mail);
  568. $tab2 = explode('.',$tab[1]);
  569. $string_replace = '';
  570. $mail_name = $tab[0];
  571. $mail_domaine = $tab2[0];
  572. $mail_tld = '';
  573. $nbofelem = count($tab2);
  574. for($i=1; $i < $nbofelem && $displaytld; $i++)
  575. {
  576. $mail_tld .= '.'.$tab2[$i];
  577. }
  578. for($i=0; $i < $nbreplace; $i++){
  579. $string_replace .= $replace;
  580. }
  581. if(strlen($mail_name) > $nbdisplaymail){
  582. $mail_name = substr($mail_name, 0, $nbdisplaymail);
  583. }
  584. if(strlen($mail_domaine) > $nbdisplaydomain){
  585. $mail_domaine = substr($mail_domaine, strlen($mail_domaine)-$nbdisplaydomain);
  586. }
  587. return $mail_name . $string_replace . $mail_domaine . $mail_tld;
  588. }
  589. /**
  590. * Return lines of an html table from an array
  591. * Used by array2table function only
  592. *
  593. * @param array $data Array of data
  594. * @param string $troptions Options for tr
  595. * @param string $tdoptions Options for td
  596. * @return string
  597. */
  598. function array2tr($data,$troptions='',$tdoptions='')
  599. {
  600. $text = '<tr '.$troptions.'>' ;
  601. foreach($data as $key => $item){
  602. $text.= '<td '.$tdoptions.'>'.$item.'</td>' ;
  603. }
  604. $text.= '</tr>' ;
  605. return $text ;
  606. }
  607. /**
  608. * Return an html table from an array
  609. *
  610. * @param array $data Array of data
  611. * @param int $tableMarkup Table markup
  612. * @param string $tableoptions Options for table
  613. * @param string $troptions Options for tr
  614. * @param string $tdoptions Options for td
  615. * @return string
  616. */
  617. function array2table($data,$tableMarkup=1,$tableoptions='',$troptions='',$tdoptions='')
  618. {
  619. $text='' ;
  620. if($tableMarkup) $text = '<table '.$tableoptions.'>' ;
  621. foreach($data as $key => $item){
  622. if(is_array($item)){
  623. $text.=array2tr($item,$troptions,$tdoptions);
  624. } else {
  625. $text.= '<tr '.$troptions.'>' ;
  626. $text.= '<td '.$tdoptions.'>'.$key.'</td>' ;
  627. $text.= '<td '.$tdoptions.'>'.$item.'</td>' ;
  628. $text.= '</tr>' ;
  629. }
  630. }
  631. if($tableMarkup) $text.= '</table>' ;
  632. return $text ;
  633. }
  634. /**
  635. * Return last or next value for a mask (according to area we should not reset)
  636. *
  637. * @param DoliDB $db Database handler
  638. * @param string $mask Mask to use
  639. * @param string $table Table containing field with counter
  640. * @param string $field Field containing already used values of counter
  641. * @param string $where To add a filter on selection (for exemple to filter on invoice types)
  642. * @param Societe $objsoc The company that own the object we need a counter for
  643. * @param string $date Date to use for the {y},{m},{d} tags.
  644. * @param string $mode 'next' for next value or 'last' for last value
  645. * @param bool $bentityon Activate the entity filter. Default is true (for modules not compatible with multicompany)
  646. * @return string New value (numeric) or error message
  647. */
  648. function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$mode='next', $bentityon=true)
  649. {
  650. global $conf;
  651. if (! is_object($objsoc)) $valueforccc=$objsoc;
  652. else if($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=$objsoc->code_fournisseur;
  653. else $valueforccc=$objsoc->code_client;
  654. // Clean parameters
  655. if ($date == '') $date=dol_now(); // We use local year and month of PHP server to search numbers
  656. // but we should use local year and month of user
  657. // For debugging
  658. //include_once(DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php');
  659. //$mask='FA{yy}{mm}-{0000@99}';
  660. //$date=dol_mktime(12, 0, 0, 1, 1, 1900);
  661. //$date=dol_stringtotime('20130101');
  662. $hasglobalcounter=false;
  663. // Extract value for mask counter, mask raz and mask offset
  664. if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$mask,$reg))
  665. {
  666. $masktri=$reg[1].(! empty($reg[2])?$reg[2]:'').(! empty($reg[3])?$reg[3]:'');
  667. $maskcounter=$reg[1];
  668. $hasglobalcounter=true;
  669. }
  670. else
  671. {
  672. // setting some defaults so the rest of the code won't fail if there is a third party counter
  673. $masktri='00000';
  674. $maskcounter='00000';
  675. }
  676. $maskraz=-1;
  677. $maskoffset=0;
  678. $resetEveryMonth=false;
  679. if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits';
  680. // Extract value for third party mask counter
  681. if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
  682. {
  683. $maskrefclient=$regClientRef[1].$regClientRef[2];
  684. $maskrefclient_maskclientcode=$regClientRef[1];
  685. $maskrefclient_maskcounter=$regClientRef[2];
  686. $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset
  687. $maskrefclient_clientcode=substr($valueforccc,0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code where n is length in mask
  688. $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
  689. $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
  690. if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
  691. }
  692. else $maskrefclient='';
  693. // fail if there is neither a global nor a third party counter
  694. if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
  695. {
  696. return 'ErrorBadMask';
  697. }
  698. // Extract value for third party type
  699. if (preg_match('/\{(t+)\}/i',$mask,$regType))
  700. {
  701. $masktype=$regType[1];
  702. $masktype_value=substr(preg_replace('/^TE_/','',$objsoc->typent_code),0,dol_strlen($regType[1]));// get n first characters of thirdpaty typent_code (where n is length in mask)
  703. $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
  704. }
  705. else
  706. {
  707. $masktype='';
  708. $masktype_value='';
  709. }
  710. // Personalized field {XXX-1} à {XXX-9}
  711. /*$maskperso=array();
  712. $maskpersonew=array();
  713. $tmpmask=$mask;
  714. while (preg_match('/\{([A-Z]+)\-([1-9])\}/i',$tmpmask,$regKey))
  715. {
  716. $maskperso[$regKey[1]]='\{'.$regKey[1]+'\-'.$regKey[2].'\}';
  717. $maskpersonew[$regKey[1]]=str_pad('', '_', $regKey[2], STR_PAD_RIGHT);
  718. $tmpmask=preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew, $tmpmask);
  719. }*/
  720. $maskwithonlyymcode=$mask;
  721. $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$maskcounter,$maskwithonlyymcode);
  722. $maskwithonlyymcode=preg_replace('/\{dd\}/i','dd',$maskwithonlyymcode);
  723. $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i',$maskrefclient,$maskwithonlyymcode);
  724. $maskwithonlyymcode=preg_replace('/\{(t+)\}/i',$masktype_value,$maskwithonlyymcode);
  725. /*foreach($maskperso as $key => $val)
  726. {
  727. $maskwithonlyymcode=preg_replace('/'.$val.'/i', $maskpersonew[$key], $maskwithonlyymcode);
  728. }*/
  729. $maskwithnocode=$maskwithonlyymcode;
  730. $maskwithnocode=preg_replace('/\{yyyy\}/i','yyyy',$maskwithnocode);
  731. $maskwithnocode=preg_replace('/\{yy\}/i','yy',$maskwithnocode);
  732. $maskwithnocode=preg_replace('/\{y\}/i','y',$maskwithnocode);
  733. $maskwithnocode=preg_replace('/\{mm\}/i','mm',$maskwithnocode);
  734. // Now maskwithnocode = 0000ddmmyyyyccc for example
  735. // and maskcounter = 0000 for example
  736. //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
  737. //var_dump($reg);
  738. // If an offset is asked
  739. if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
  740. if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
  741. // Define $sqlwhere
  742. $sqlwhere='';
  743. $yearoffset=0; // Use year of current $date by default
  744. $yearoffsettype=false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
  745. // If a restore to zero after a month is asked we check if there is already a value for this year.
  746. if (! empty($reg[2]) && preg_match('/^@/',$reg[2])) $yearoffsettype = preg_replace('/^@/','',$reg[2]);
  747. if (! empty($reg[3]) && preg_match('/^@/',$reg[3])) $yearoffsettype = preg_replace('/^@/','',$reg[3]);
  748. //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
  749. if (is_numeric($yearoffsettype) && $yearoffsettype >= 1)
  750. $maskraz=$yearoffsettype; // For backward compatibility
  751. else if ($yearoffsettype === '0' || (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1))
  752. $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START;
  753. //print "maskraz=".$maskraz; // -1=no reset
  754. if ($maskraz > 0) { // A reset is required
  755. if ($maskraz == 99) {
  756. $maskraz = date('m', $date);
  757. $resetEveryMonth = true;
  758. }
  759. if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
  760. // Define posy, posm and reg
  761. if ($maskraz > 1) // if reset is not first month, we need month and year into mask
  762. {
  763. if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
  764. elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
  765. else return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
  766. if (dol_strlen($reg[$posy]) < 2) return 'ErrorCantUseRazWithYearOnOneDigit';
  767. }
  768. else // if reset is for a specific month in year, we need year
  769. {
  770. if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
  771. else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
  772. else if (preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=0; }
  773. else return 'ErrorCantUseRazIfNoYearInMask';
  774. }
  775. // Define length
  776. $yearlen = $posy?dol_strlen($reg[$posy]):0;
  777. $monthlen = $posm?dol_strlen($reg[$posm]):0;
  778. // Define pos
  779. $yearpos = (dol_strlen($reg[1])+1);
  780. $monthpos = ($yearpos+$yearlen);
  781. if ($posy == 3 && $posm == 2) { // if month is before year
  782. $monthpos = (dol_strlen($reg[1])+1);
  783. $yearpos = ($monthpos+$monthlen);
  784. }
  785. //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
  786. // Define $yearcomp and $monthcomp (that will be use in the select where to search max number)
  787. $monthcomp=$maskraz;
  788. $yearcomp=0;
  789. if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=') // $yearoffsettype is - or +
  790. {
  791. $currentyear=date("Y", $date);
  792. $fiscaldate=dol_mktime('0','0','0',$maskraz,'1',$currentyear);
  793. $newyeardate=dol_mktime('0','0','0','1','1',$currentyear);
  794. $nextnewyeardate=dol_mktime('0','0','0','1','1',$currentyear+1);
  795. //echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
  796. // If after or equal of current fiscal date
  797. if ($date >= $fiscaldate)
  798. {
  799. // If before of next new year date
  800. if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset=1;
  801. }
  802. // If after or equal of current new year date
  803. else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset=-1;
  804. }
  805. // For backward compatibility
  806. else if (date("m",$date) < $maskraz && empty($resetEveryMonth)) { $yearoffset=-1; } // If current month lower that month of return to zero, year is previous year
  807. if ($yearlen == 4) $yearcomp=sprintf("%04d",date("Y",$date)+$yearoffset);
  808. elseif ($yearlen == 2) $yearcomp=sprintf("%02d",date("y",$date)+$yearoffset);
  809. elseif ($yearlen == 1) $yearcomp=substr(date("y",$date),2,1)+$yearoffset;
  810. 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)
  811. {
  812. if ($yearlen == 4) $yearcomp1=sprintf("%04d",date("Y",$date)+$yearoffset+1);
  813. elseif ($yearlen == 2) $yearcomp1=sprintf("%02d",date("y",$date)+$yearoffset+1);
  814. $sqlwhere.="(";
  815. $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
  816. $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
  817. $sqlwhere.=" OR";
  818. $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'";
  819. $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
  820. $sqlwhere.=')';
  821. }
  822. else if ($resetEveryMonth)
  823. {
  824. $sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
  825. $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
  826. }
  827. else // reset is done on january
  828. {
  829. $sqlwhere.='(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
  830. }
  831. }
  832. //print "sqlwhere=".$sqlwhere." yearcomp=".$yearcomp."<br>\n"; // sqlwhere and yearcomp defined only if we ask a reset
  833. //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
  834. // Define $sqlstring
  835. if (function_exists('mb_strrpos'))
  836. {
  837. $posnumstart=mb_strrpos($maskwithnocode,$maskcounter, 'UTF-8');
  838. }
  839. else
  840. {
  841. $posnumstart=strrpos($maskwithnocode,$maskcounter);
  842. } // Pos of counter in final string (from 0 to ...)
  843. if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
  844. $sqlstring='SUBSTRING('.$field.', '.($posnumstart+1).', '.dol_strlen($maskcounter).')';
  845. // Define $maskLike
  846. $maskLike = dol_string_nospecial($mask);
  847. $maskLike = str_replace("%","_",$maskLike);
  848. // Replace protected special codes with matching number of _ as wild card caracter
  849. $maskLike = preg_replace('/\{yyyy\}/i','____',$maskLike);
  850. $maskLike = preg_replace('/\{yy\}/i','__',$maskLike);
  851. $maskLike = preg_replace('/\{y\}/i','_',$maskLike);
  852. $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
  853. $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
  854. $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskLike);
  855. if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
  856. if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
  857. // Get counter in database
  858. $counter=0;
  859. $sql = "SELECT MAX(".$sqlstring.") as val";
  860. $sql.= " FROM ".MAIN_DB_PREFIX.$table;
  861. $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
  862. $sql.= " AND ".$field." NOT LIKE '(PROV%)'";
  863. if ($bentityon) // only if entity enable
  864. $sql.= " AND entity IN (".getEntity($table, 1).")";
  865. if ($where) $sql.=$where;
  866. if ($sqlwhere) $sql.=' AND '.$sqlwhere;
  867. //print $sql.'<br>';
  868. dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
  869. $resql=$db->query($sql);
  870. if ($resql)
  871. {
  872. $obj = $db->fetch_object($resql);
  873. $counter = $obj->val;
  874. }
  875. else dol_print_error($db);
  876. // Check if we must force counter to maskoffset
  877. if (empty($counter) || preg_match('/[^0-9]/i',$counter)) $counter=$maskoffset;
  878. else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter=$maskoffset;
  879. if ($mode == 'last') // We found value for counter = last counter value. Now need to get corresponding ref of invoice.
  880. {
  881. $counterpadded=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
  882. // Define $maskLike
  883. $maskLike = dol_string_nospecial($mask);
  884. $maskLike = str_replace("%","_",$maskLike);
  885. // Replace protected special codes with matching number of _ as wild card caracter
  886. $maskLike = preg_replace('/\{yyyy\}/i','____',$maskLike);
  887. $maskLike = preg_replace('/\{yy\}/i','__',$maskLike);
  888. $maskLike = preg_replace('/\{y\}/i','_',$maskLike);
  889. $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
  890. $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
  891. $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),$counterpadded,$maskLike);
  892. if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
  893. if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
  894. $ref='';
  895. $sql = "SELECT ".$field." as ref";
  896. $sql.= " FROM ".MAIN_DB_PREFIX.$table;
  897. $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
  898. $sql.= " AND ".$field." NOT LIKE '%PROV%'";
  899. if ($bentityon) // only if entity enable
  900. $sql.= " AND entity IN (".getEntity($table, 1).")";
  901. if ($where) $sql.=$where;
  902. if ($sqlwhere) $sql.=' AND '.$sqlwhere;
  903. dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
  904. $resql=$db->query($sql);
  905. if ($resql)
  906. {
  907. $obj = $db->fetch_object($resql);
  908. if ($obj) $ref = $obj->ref;
  909. }
  910. else dol_print_error($db);
  911. $numFinal=$ref;
  912. }
  913. else if ($mode == 'next')
  914. {
  915. $counter++;
  916. // If value for $counter has a length higher than $maskcounter chars
  917. if ($counter >= pow(10, dol_strlen($maskcounter)))
  918. {
  919. $counter='ErrorMaxNumberReachForThisMask';
  920. }
  921. if (! empty($maskrefclient_maskcounter))
  922. {
  923. //print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n<br>";
  924. // Define $sqlstring
  925. $maskrefclient_posnumstart=strpos($maskwithnocode,$maskrefclient_maskcounter,strpos($maskwithnocode,$maskrefclient)); // Pos of counter in final string (from 0 to ...)
  926. if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask';
  927. $maskrefclient_sqlstring='SUBSTRING('.$field.', '.($maskrefclient_posnumstart+1).', '.dol_strlen($maskrefclient_maskcounter).')';
  928. //print "x".$sqlstring;
  929. // Define $maskrefclient_maskLike
  930. $maskrefclient_maskLike = dol_string_nospecial($mask);
  931. $maskrefclient_maskLike = str_replace("%","_",$maskrefclient_maskLike);
  932. // Replace protected special codes with matching number of _ as wild card caracter
  933. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'),'____',$maskrefclient_maskLike);
  934. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'),'__',$maskrefclient_maskLike);
  935. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'),'_',$maskrefclient_maskLike);
  936. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'),'__',$maskrefclient_maskLike);
  937. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'),'__',$maskrefclient_maskLike);
  938. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskrefclient_maskLike);
  939. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),$maskrefclient_clientcode.str_pad("",dol_strlen($maskrefclient_maskcounter),"_"),$maskrefclient_maskLike);
  940. // Get counter in database
  941. $maskrefclient_counter=0;
  942. $maskrefclient_sql = "SELECT MAX(".$maskrefclient_sqlstring.") as val";
  943. $maskrefclient_sql.= " FROM ".MAIN_DB_PREFIX.$table;
  944. //$sql.= " WHERE ".$field." not like '(%'";
  945. $maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
  946. if ($bentityon) // only if entity enable
  947. $maskrefclient_sql.= " AND entity IN (".getEntity($table, 1).")";
  948. if ($where) $maskrefclient_sql.=$where; //use the same optional where as general mask
  949. if ($sqlwhere) $maskrefclient_sql.=' AND '.$sqlwhere; //use the same sqlwhere as general mask
  950. $maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode,$maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
  951. dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
  952. $maskrefclient_resql=$db->query($maskrefclient_sql);
  953. if ($maskrefclient_resql)
  954. {
  955. $maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
  956. $maskrefclient_counter = $maskrefclient_obj->val;
  957. }
  958. else dol_print_error($db);
  959. if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i',$maskrefclient_counter)) $maskrefclient_counter=$maskrefclient_maskoffset;
  960. $maskrefclient_counter++;
  961. }
  962. // Build numFinal
  963. $numFinal = $mask;
  964. // We replace special codes except refclient
  965. if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=') // yearoffsettype is - or +, so we don't want current year
  966. {
  967. $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
  968. $numFinal = preg_replace('/\{yy\}/i', date("y",$date)+$yearoffset, $numFinal);
  969. $numFinal = preg_replace('/\{y\}/i', substr(date("y",$date),1,1)+$yearoffset, $numFinal);
  970. }
  971. else // we want yyyy to be current year
  972. {
  973. $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date), $numFinal);
  974. $numFinal = preg_replace('/\{yy\}/i', date("y",$date), $numFinal);
  975. $numFinal = preg_replace('/\{y\}/i', substr(date("y",$date),1,1), $numFinal);
  976. }
  977. $numFinal = preg_replace('/\{mm\}/i', date("m",$date), $numFinal);
  978. $numFinal = preg_replace('/\{dd\}/i', date("d",$date), $numFinal);
  979. // Now we replace the counter
  980. $maskbefore='{'.$masktri.'}';
  981. $maskafter=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
  982. //print 'x'.$maskbefore.'-'.$maskafter.'y';
  983. $numFinal = str_replace($maskbefore,$maskafter,$numFinal);
  984. // Now we replace the refclient
  985. if ($maskrefclient)
  986. {
  987. //print "maskrefclient=".$maskrefclient." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
  988. $maskrefclient_maskbefore='{'.$maskrefclient.'}';
  989. $maskrefclient_maskafter=$maskrefclient_clientcode.str_pad($maskrefclient_counter,dol_strlen($maskrefclient_maskcounter),"0",STR_PAD_LEFT);
  990. $numFinal = str_replace($maskrefclient_maskbefore,$maskrefclient_maskafter,$numFinal);
  991. }
  992. // Now we replace the type
  993. if ($masktype)
  994. {
  995. $masktype_maskbefore='{'.$masktype.'}';
  996. $masktype_maskafter=$masktype_value;
  997. $numFinal = str_replace($masktype_maskbefore,$masktype_maskafter,$numFinal);
  998. }
  999. }
  1000. dol_syslog("functions2::get_next_value return ".$numFinal,LOG_DEBUG);
  1001. return $numFinal;
  1002. }
  1003. /**
  1004. * Check value
  1005. *
  1006. * @param string $mask Mask to use
  1007. * @param string $value Value
  1008. * @return int <0 if KO, 0 if OK
  1009. */
  1010. function check_value($mask,$value)
  1011. {
  1012. $result=0;
  1013. $hasglobalcounter=false;
  1014. // Extract value for mask counter, mask raz and mask offset
  1015. if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i',$mask,$reg))
  1016. {
  1017. $masktri=$reg[1].(isset($reg[2])?$reg[2]:'').(isset($reg[3])?$reg[3]:'');
  1018. $maskcounter=$reg[1];
  1019. $hasglobalcounter=true;
  1020. }
  1021. else
  1022. {
  1023. // setting some defaults so the rest of the code won't fail if there is a third party counter
  1024. $masktri='00000';
  1025. $maskcounter='00000';
  1026. }
  1027. $maskraz=-1;
  1028. $maskoffset=0;
  1029. if (dol_strlen($maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
  1030. // Extract value for third party mask counter
  1031. if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
  1032. {
  1033. $maskrefclient=$regClientRef[1].$regClientRef[2];
  1034. $maskrefclient_maskclientcode=$regClientRef[1];
  1035. $maskrefclient_maskcounter=$regClientRef[2];
  1036. $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset
  1037. $maskrefclient_clientcode=substr('',0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code to form maskrefclient_clientcode
  1038. $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
  1039. $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
  1040. if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
  1041. }
  1042. else $maskrefclient='';
  1043. // fail if there is neither a global nor a third party counter
  1044. if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
  1045. {
  1046. return 'ErrorBadMask';
  1047. }
  1048. $maskwithonlyymcode=$mask;
  1049. $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i',$maskcounter,$maskwithonlyymcode);
  1050. $maskwithonlyymcode=preg_replace('/\{dd\}/i','dd',$maskwithonlyymcode);
  1051. $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i',$maskrefclient,$maskwithonlyymcode);
  1052. $maskwithnocode=$maskwithonlyymcode;
  1053. $maskwithnocode=preg_replace('/\{yyyy\}/i','yyyy',$maskwithnocode);
  1054. $maskwithnocode=preg_replace('/\{yy\}/i','yy',$maskwithnocode);
  1055. $maskwithnocode=preg_replace('/\{y\}/i','y',$maskwithnocode);
  1056. $maskwithnocode=preg_replace('/\{mm\}/i','mm',$maskwithnocode);
  1057. // Now maskwithnocode = 0000ddmmyyyyccc for example
  1058. // and maskcounter = 0000 for example
  1059. //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
  1060. // If an offset is asked
  1061. if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
  1062. if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
  1063. // Define $sqlwhere
  1064. // If a restore to zero after a month is asked we check if there is already a value for this year.
  1065. if (! empty($reg[2]) && preg_match('/^@/',$reg[2])) $maskraz=preg_replace('/^@/','',$reg[2]);
  1066. if (! empty($reg[3]) && preg_match('/^@/',$reg[3])) $maskraz=preg_replace('/^@/','',$reg[3]);
  1067. if ($maskraz >= 0)
  1068. {
  1069. if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
  1070. // Define reg
  1071. if ($maskraz > 1 && ! preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
  1072. if ($maskraz <= 1 && ! preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazIfNoYearInMask';
  1073. //print "x".$maskwithonlyymcode." ".$maskraz;
  1074. }
  1075. //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
  1076. // Check we have a number in ($posnumstart+1).', '.dol_strlen($maskcounter)
  1077. //
  1078. // Check length
  1079. $len=dol_strlen($maskwithnocode);
  1080. if (dol_strlen($value) != $len) $result=-1;
  1081. // Define $maskLike
  1082. $maskLike = dol_string_nospecial($mask);
  1083. $maskLike = str_replace("%","_",$maskLike);
  1084. // Replace protected special codes with matching number of _ as wild card caracter
  1085. $maskLike = str_replace(dol_string_nospecial('{yyyy}'),'____',$maskLike);
  1086. $maskLike = str_replace(dol_string_nospecial('{yy}'),'__',$maskLike);
  1087. $maskLike = str_replace(dol_string_nospecial('{y}'),'_',$maskLike);
  1088. $maskLike = str_replace(dol_string_nospecial('{mm}'),'__',$maskLike);
  1089. $maskLike = str_replace(dol_string_nospecial('{dd}'),'__',$maskLike);
  1090. $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskLike);
  1091. if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",strlen($maskrefclient),"_"),$maskLike);
  1092. dol_syslog("functions2::check_value result=".$result,LOG_DEBUG);
  1093. return $result;
  1094. }
  1095. /**
  1096. * Convert a binary data to string that represent hexadecimal value
  1097. *
  1098. * @param string $bin Value to convert
  1099. * @param boolean $pad Add 0
  1100. * @param boolean $upper Convert to tupper
  1101. * @return string x
  1102. */
  1103. function binhex($bin, $pad=false, $upper=false)
  1104. {
  1105. $last = dol_strlen($bin)-1;
  1106. for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
  1107. $x = dechex($x);
  1108. if($pad){ while(dol_strlen($x) < intval(dol_strlen($bin))/4){ $x = "0$x"; } }
  1109. if($upper){ $x = strtoupper($x); }
  1110. return $x;
  1111. }
  1112. /**
  1113. * Convert an hexadecimal string into a binary string
  1114. *
  1115. * @param string $hexa Hexadecimal string to convert (example: 'FF')
  1116. * @return string bin
  1117. */
  1118. function hexbin($hexa)
  1119. {
  1120. $bin='';
  1121. $strLength = dol_strlen($hexa);
  1122. for($i=0;$i<$strLength;$i++)
  1123. {
  1124. $bin.=str_pad(decbin(hexdec($hexa{$i})),4,'0',STR_PAD_LEFT);
  1125. }
  1126. return $bin;
  1127. }
  1128. /**
  1129. * Retourne le numero de la semaine par rapport a une date
  1130. *
  1131. * @param string $time Date au format 'timestamp'
  1132. * @return string Number of week
  1133. */
  1134. function numero_semaine($time)
  1135. {
  1136. $stime = strftime('%Y-%m-%d',$time);
  1137. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i',$stime,$reg))
  1138. {
  1139. // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS'
  1140. $annee = $reg[1];
  1141. $mois = $reg[2];
  1142. $jour = $reg[3];
  1143. }
  1144. /*
  1145. * Norme ISO-8601:
  1146. * - 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.
  1147. * - La majorite des annees ont 52 semaines mais les annees qui commence un jeudi et les annees bissextiles commencant un mercredi en possede 53.
  1148. * - Le 1er jour de la semaine est le Lundi
  1149. */
  1150. // Definition du Jeudi de la semaine
  1151. if (date("w",mktime(12,0,0,$mois,$jour,$annee))==0) // Dimanche
  1152. $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-3*24*60*60;
  1153. else if (date("w",mktime(12,0,0,$mois,$jour,$annee))<4) // du Lundi au Mercredi
  1154. $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)+(4-date("w",mktime(12,0,0,$mois,$jour,$annee)))*24*60*60;
  1155. else if (date("w",mktime(12,0,0,$mois,$jour,$annee))>4) // du Vendredi au Samedi
  1156. $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-(date("w",mktime(12,0,0,$mois,$jour,$annee))-4)*24*60*60;
  1157. else // Jeudi
  1158. $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee);
  1159. // Definition du premier Jeudi de l'annee
  1160. if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==0) // Dimanche
  1161. {
  1162. $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+4*24*60*60;
  1163. }
  1164. else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))<4) // du Lundi au Mercredi
  1165. {
  1166. $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;
  1167. }
  1168. else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))>4) // du Vendredi au Samedi
  1169. {
  1170. $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;
  1171. }
  1172. else // Jeudi
  1173. {
  1174. $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine));
  1175. }
  1176. // Definition du numero de semaine: nb de jours entre "premier Jeudi de l'annee" et "Jeudi de la semaine";
  1177. $numeroSemaine = (
  1178. (
  1179. date("z",mktime(12,0,0,date("m",$jeudiSemaine),date("d",$jeudiSemaine),date("Y",$jeudiSemaine)))
  1180. -
  1181. date("z",mktime(12,0,0,date("m",$premierJeudiAnnee),date("d",$premierJeudiAnnee),date("Y",$premierJeudiAnnee)))
  1182. ) / 7
  1183. ) + 1;
  1184. // Cas particulier de la semaine 53
  1185. if ($numeroSemaine==53)
  1186. {
  1187. // Les annees qui commence un Jeudi et les annees bissextiles commencant un Mercredi en possede 53
  1188. 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))
  1189. {
  1190. $numeroSemaine = 53;
  1191. }
  1192. else
  1193. {
  1194. $numeroSemaine = 1;
  1195. }
  1196. }
  1197. //echo $jour."-".$mois."-".$annee." (".date("d-m-Y",$premierJeudiAnnee)." - ".date("d-m-Y",$jeudiSemaine).") -> ".$numeroSemaine."<BR>";
  1198. return sprintf("%02d",$numeroSemaine);
  1199. }
  1200. /**
  1201. * Convertit une masse d'une unite vers une autre unite
  1202. *
  1203. * @param float $weight Masse a convertir
  1204. * @param int $from_unit Unite originale en puissance de 10
  1205. * @param int $to_unit Nouvelle unite en puissance de 10
  1206. * @return float Masse convertie
  1207. */
  1208. function weight_convert($weight,&$from_unit,$to_unit)
  1209. {
  1210. /* Pour convertire 320 gr en Kg appeler
  1211. * $f = -3
  1212. * weigh_convert(320, $f, 0) retournera 0.32
  1213. *
  1214. */
  1215. while ($from_unit <> $to_unit)
  1216. {
  1217. if ($from_unit > $to_unit)
  1218. {
  1219. $weight = $weight * 10;
  1220. $from_unit = $from_unit - 1;
  1221. $weight = weight_convert($weight,$from_unit, $to_unit);
  1222. }
  1223. if ($from_unit < $to_unit)
  1224. {
  1225. $weight = $weight / 10;
  1226. $from_unit = $from_unit + 1;
  1227. $weight = weight_convert($weight,$from_unit, $to_unit);
  1228. }
  1229. }
  1230. return $weight;
  1231. }
  1232. /**
  1233. * Save personnal parameter
  1234. *
  1235. * @param DoliDB $db Handler database
  1236. * @param Conf $conf Object conf
  1237. * @param User $user Object user
  1238. * @param array $tab Array (key=>value) with all parameters to save
  1239. * @return int <0 if KO, >0 if OK
  1240. *
  1241. * @see dolibarr_get_const, dolibarr_set_const, dolibarr_del_const
  1242. */
  1243. function dol_set_user_param($db, $conf, &$user, $tab)
  1244. {
  1245. // Verification parametres
  1246. if (count($tab) < 1) return -1;
  1247. $db->begin();
  1248. // We remove old parameters for all keys in $tab
  1249. $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param";
  1250. $sql.= " WHERE fk_user = ".$user->id;
  1251. $sql.= " AND entity = ".$conf->entity;
  1252. $sql.= " AND param in (";
  1253. $i=0;
  1254. foreach ($tab as $key => $value)
  1255. {
  1256. if ($i > 0) $sql.=',';
  1257. $sql.="'".$key."'";
  1258. $i++;
  1259. }
  1260. $sql.= ")";
  1261. dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
  1262. $resql=$db->query($sql);
  1263. if (! $resql)
  1264. {
  1265. dol_print_error($db);
  1266. $db->rollback();
  1267. return -1;
  1268. }
  1269. foreach ($tab as $key => $value)
  1270. {
  1271. // Set new parameters
  1272. if ($value)
  1273. {
  1274. $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,entity,param,value)";
  1275. $sql.= " VALUES (".$user->id.",".$conf->entity.",";
  1276. $sql.= " '".$key."','".$db->escape($value)."')";
  1277. dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
  1278. $result=$db->query($sql);
  1279. if (! $result)
  1280. {
  1281. dol_print_error($db);
  1282. $db->rollback();
  1283. return -1;
  1284. }
  1285. $user->conf->$key = $value;
  1286. //print "key=".$key." user->conf->key=".$user->conf->$key;
  1287. }
  1288. else
  1289. {
  1290. unset($user->conf->$key);
  1291. }
  1292. }
  1293. $db->commit();
  1294. return 1;
  1295. }
  1296. /**
  1297. * Returns formated reduction
  1298. *
  1299. * @param int $reduction Reduction percentage
  1300. * @param Translate $langs Output language
  1301. * @return string Formated reduction
  1302. */
  1303. function dol_print_reduction($reduction,$langs)
  1304. {
  1305. $string = '';
  1306. if ($reduction == 100)
  1307. {
  1308. $string = $langs->transnoentities("Offered");
  1309. }
  1310. else
  1311. {
  1312. $string = price($reduction).'%';
  1313. }
  1314. return $string;
  1315. }
  1316. /**
  1317. * Return OS version.
  1318. * Note that PHP_OS returns only OS (not version) and OS PHP was built on, not necessarly OS PHP runs on.
  1319. *
  1320. * @return string OS version
  1321. */
  1322. function version_os()
  1323. {
  1324. $osversion=php_uname();
  1325. return $osversion;
  1326. }
  1327. /**
  1328. * Return PHP version
  1329. *
  1330. * @return string PHP version
  1331. * @see versionphparray
  1332. */
  1333. function version_php()
  1334. {
  1335. return phpversion();
  1336. }
  1337. /**
  1338. * Return Dolibarr version
  1339. *
  1340. * @return string Dolibarr version
  1341. * @see versiondolibarrarray
  1342. */
  1343. function version_dolibarr()
  1344. {
  1345. return DOL_VERSION;
  1346. }
  1347. /**
  1348. * Return web server version
  1349. *
  1350. * @return string Web server version
  1351. */
  1352. function version_webserver()
  1353. {
  1354. return $_SERVER["SERVER_SOFTWARE"];
  1355. }
  1356. /**
  1357. * Return list of activated modules usable for document generation
  1358. *
  1359. * @param DoliDB $db Database handler
  1360. * @param string $type Type of models (company, invoice, ...)
  1361. * @param int $maxfilenamelength Max length of value to show
  1362. * @return mixed 0 if no module is activated, or array(key=>label). For modules that need directory scan, key is completed with ":filename".
  1363. */
  1364. function getListOfModels($db,$type,$maxfilenamelength=0)
  1365. {
  1366. global $conf,$langs;
  1367. $liste=array();
  1368. $found=0;
  1369. $dirtoscan='';
  1370. $sql = "SELECT nom as id, nom as lib, libelle as label, description as description";
  1371. $sql.= " FROM ".MAIN_DB_PREFIX."document_model";
  1372. $sql.= " WHERE type = '".$type."'";
  1373. $sql.= " AND entity IN (0,".(! empty($conf->multicompany->enabled) && ! empty($conf->multicompany->transverse_mode)?"1,":"").$conf->entity.")";
  1374. $sql.= " ORDER BY description DESC";
  1375. dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG);
  1376. $resql = $db->query($sql);
  1377. if ($resql)
  1378. {
  1379. $num = $db->num_rows($resql);
  1380. $i = 0;
  1381. while ($i < $num)
  1382. {
  1383. $found=1;
  1384. $obj = $db->fetch_object($resql);
  1385. // If this generation module needs to scan a directory, then description field is filled
  1386. // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...).
  1387. if (! empty($obj->description)) // A list of directories to scan is defined
  1388. {
  1389. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1390. $const=$obj->description;
  1391. //irtoscan.=($dirtoscan?',':'').preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
  1392. $dirtoscan= preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
  1393. $listoffiles=array();
  1394. // Now we add models found in directories scanned
  1395. $listofdir=explode(',',$dirtoscan);
  1396. foreach($listofdir as $key=>$tmpdir)
  1397. {
  1398. $tmpdir=trim($tmpdir);
  1399. $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
  1400. if (! $tmpdir) { unset($listofdir[$key]); continue; }
  1401. if (is_dir($tmpdir))
  1402. {
  1403. $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0);
  1404. if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
  1405. }
  1406. }
  1407. if (count($listoffiles))
  1408. {
  1409. foreach($listoffiles as $record)
  1410. {
  1411. $max=($maxfilenamelength?$maxfilenamelength:28);
  1412. $liste[$obj->id.':'.$record['fullname']]=dol_trunc($record['name'],$max,'middle');
  1413. }
  1414. }
  1415. else
  1416. {
  1417. $liste[0]=$obj->label.': '.$langs->trans("None");
  1418. }
  1419. }
  1420. else
  1421. {
  1422. if ($type == 'member' && $obj->lib == 'standard') // Special case, if member template, we add variant per format
  1423. {
  1424. global $_Avery_Labels;
  1425. include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
  1426. foreach($_Avery_Labels as $key => $val)
  1427. {
  1428. $liste[$obj->id.':'.$key]=($obj->label?$obj->label:$obj->lib).' '.$val['name'];
  1429. }
  1430. }
  1431. else // Common usage
  1432. {
  1433. $liste[$obj->id]=$obj->label?$obj->label:$obj->lib;
  1434. }
  1435. }
  1436. $i++;
  1437. }
  1438. }
  1439. else
  1440. {
  1441. dol_print_error($db);
  1442. return -1;
  1443. }
  1444. if ($found) return $liste;
  1445. else return 0;
  1446. }
  1447. /**
  1448. * This function evaluates a string that should be a valid IPv4
  1449. * 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.
  1450. *
  1451. * @param string $ip IP Address
  1452. * @return int 0 if not valid or reserved range, 1 if valid and public IP, 2 if valid and private range IP
  1453. */
  1454. function is_ip($ip)
  1455. {
  1456. // First we test if it is a valid IPv4
  1457. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  1458. // Then we test if it is a private range
  1459. if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
  1460. // Then we test if it is a reserved range
  1461. if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
  1462. return 1;
  1463. }
  1464. return 0;
  1465. }
  1466. /**
  1467. * Build a login from lastname, firstname
  1468. *
  1469. * @param string $lastname Lastname
  1470. * @param string $firstname Firstname
  1471. * @return string Login
  1472. */
  1473. function dol_buildlogin($lastname,$firstname)
  1474. {
  1475. $login=strtolower(dol_string_unaccent($firstname));
  1476. $login.=($login?'.':'');
  1477. $login.=strtolower(dol_string_unaccent($lastname));
  1478. $login=dol_string_nospecial($login,''); // For special names
  1479. return $login;
  1480. }
  1481. /**
  1482. * Return array to use for SoapClient constructor
  1483. *
  1484. * @return array
  1485. */
  1486. function getSoapParams()
  1487. {
  1488. global $conf;
  1489. $params=array();
  1490. $proxyuse =(empty($conf->global->MAIN_PROXY_USE)?false:true);
  1491. $proxyhost=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_HOST);
  1492. $proxyport=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_PORT);
  1493. $proxyuser=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_USER);
  1494. $proxypass=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_PASS);
  1495. $timeout =(empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)?10:$conf->global->MAIN_USE_CONNECT_TIMEOUT); // Connection timeout
  1496. $response_timeout=(empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT)?30:$conf->global->MAIN_USE_RESPONSE_TIMEOUT); // Response timeout
  1497. //print extension_loaded('soap');
  1498. if ($proxyuse)
  1499. {
  1500. $params=array('connection_timeout'=>$timeout,
  1501. 'response_timeout'=>$response_timeout,
  1502. 'proxy_use' => 1,
  1503. 'proxy_host' => $proxyhost,
  1504. 'proxy_port' => $proxyport,
  1505. 'proxy_login' => $proxyuser,
  1506. 'proxy_password' => $proxypass,
  1507. 'trace' => 1
  1508. );
  1509. }
  1510. else
  1511. {
  1512. $params=array('connection_timeout'=>$timeout,
  1513. 'response_timeout'=>$response_timeout,
  1514. 'proxy_use' => 0,
  1515. 'proxy_host' => false,
  1516. 'proxy_port' => false,
  1517. 'proxy_login' => false,
  1518. 'proxy_password' => false,
  1519. 'trace' => 1
  1520. );
  1521. }
  1522. return $params;
  1523. }
  1524. /**
  1525. * List urls of element
  1526. *
  1527. * @param int $objectid Id of record
  1528. * @param string $objecttype Type of object ('invoice', 'order', 'expedition_bon', ...)
  1529. * @param int $withpicto Picto to show
  1530. * @param string $option More options
  1531. * @return string URL of link to object id/type
  1532. */
  1533. function dolGetElementUrl($objectid,$objecttype,$withpicto=0,$option='')
  1534. {
  1535. global $db,$conf;
  1536. $ret='';
  1537. // Parse element/subelement (ex: project_task)
  1538. $module = $element = $subelement = $objecttype;
  1539. if (preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
  1540. {
  1541. $module = $element = $regs[1];
  1542. $subelement = $regs[2];
  1543. }
  1544. $classpath = $element.'/class';
  1545. // To work with non standard path
  1546. if ($objecttype == 'facture' || $objecttype == 'invoice') {
  1547. $classpath = 'compta/facture/class';
  1548. $module='facture';
  1549. $subelement='facture';
  1550. }
  1551. if ($objecttype == 'commande' || $objecttype == 'order') {
  1552. $classpath = 'commande/class';
  1553. $module='commande';
  1554. $subelement='commande';
  1555. }
  1556. if ($objecttype == 'propal') {
  1557. $classpath = 'comm/propal/class';
  1558. }
  1559. if ($objecttype == 'supplier_proposal') {
  1560. $classpath = 'supplier_proposal/class';
  1561. }
  1562. if ($objecttype == 'shipping') {
  1563. $classpath = 'expedition/class';
  1564. $subelement = 'expedition';
  1565. $module = 'expedition_bon';
  1566. }
  1567. if ($objecttype == 'delivery') {
  1568. $classpath = 'livraison/class';
  1569. $subelement = 'livraison';
  1570. $module = 'livraison_bon';
  1571. }
  1572. if ($objecttype == 'contract') {
  1573. $classpath = 'contrat/class';
  1574. $module='contrat';
  1575. $subelement='contrat';
  1576. }
  1577. if ($objecttype == 'member') {
  1578. $classpath = 'adherents/class';
  1579. $module='adherent';
  1580. $subelement='adherent';
  1581. }
  1582. if ($objecttype == 'cabinetmed_cons') {
  1583. $classpath = 'cabinetmed/class';
  1584. $module='cabinetmed';
  1585. $subelement='cabinetmedcons';
  1586. }
  1587. if ($objecttype == 'fichinter') {
  1588. $classpath = 'fichinter/class';
  1589. $module='ficheinter';
  1590. $subelement='fichinter';
  1591. }
  1592. //print "objecttype=".$objecttype." module=".$module." subelement=".$subelement;
  1593. $classfile = strtolower($subelement); $classname = ucfirst($subelement);
  1594. if ($objecttype == 'invoice_supplier') {
  1595. $classfile = 'fournisseur.facture';
  1596. $classname='FactureFournisseur';
  1597. $classpath = 'fourn/class';
  1598. $module='fournisseur';
  1599. }
  1600. if ($objecttype == 'order_supplier') {
  1601. $classfile = 'fournisseur.commande';
  1602. $classname='CommandeFournisseur';
  1603. $classpath = 'fourn/class';
  1604. $module='fournisseur';
  1605. }
  1606. if (! empty($conf->$module->enabled))
  1607. {
  1608. $res=dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  1609. if ($res)
  1610. {
  1611. $object = new $classname($db);
  1612. $res=$object->fetch($objectid);
  1613. if ($res > 0) $ret=$object->getNomUrl($withpicto,$option);
  1614. unset($object);
  1615. }
  1616. }
  1617. return $ret;
  1618. }
  1619. /**
  1620. * Clean corrupted tree (orphelins linked to a not existing parent), record linked to themself and child-parent loop
  1621. *
  1622. * @param DoliDB $db Database handler
  1623. * @param string $tabletocleantree Table to clean
  1624. * @param string $fieldfkparent Field name that contains id of parent
  1625. * @return int Nb of records fixed/deleted
  1626. */
  1627. function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
  1628. {
  1629. $totalnb=0;
  1630. $listofid=array();
  1631. $listofparentid=array();
  1632. // Get list of all id in array listofid and all parents in array listofparentid
  1633. $sql='SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
  1634. $resql = $db->query($sql);
  1635. if ($resql)
  1636. {
  1637. $num = $db->num_rows($resql);
  1638. $i = 0;
  1639. while ($i < $num)
  1640. {
  1641. $obj = $db->fetch_object($resql);
  1642. $listofid[]=$obj->rowid;
  1643. if ($obj->parent_id > 0) $listofparentid[$obj->rowid]=$obj->parent_id;
  1644. $i++;
  1645. }
  1646. }
  1647. else
  1648. {
  1649. dol_print_error($db);
  1650. }
  1651. if (count($listofid))
  1652. {
  1653. print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
  1654. // Check loops on each other
  1655. $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid"; // So we update only records linked to themself
  1656. $resql = $db->query($sql);
  1657. if ($resql)
  1658. {
  1659. $nb=$db->affected_rows($sql);
  1660. if ($nb > 0)
  1661. {
  1662. print '<br>Some record that were parent of themself were cleaned.';
  1663. }
  1664. $totalnb+=$nb;
  1665. }
  1666. //else dol_print_error($db);
  1667. // Check other loops
  1668. $listofidtoclean=array();
  1669. foreach($listofparentid as $id => $pid)
  1670. {
  1671. // Check depth
  1672. //print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
  1673. $cursor=$id; $arrayidparsed=array(); // We start from child $id
  1674. while ($cursor > 0)
  1675. {
  1676. $arrayidparsed[$cursor]=1;
  1677. if ($arrayidparsed[$listofparentid[$cursor]]) // We detect a loop. A record with a parent that was already into child
  1678. {
  1679. print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
  1680. unset($arrayidparsed);
  1681. $listofidtoclean[$cursor]=$id;
  1682. break;
  1683. }
  1684. $cursor=$listofparentid[$cursor];
  1685. }
  1686. if (count($listofidtoclean)) break;
  1687. }
  1688. $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
  1689. $sql.= " SET ".$fieldfkparent." = 0";
  1690. $sql.= " WHERE rowid IN (".join(',',$listofidtoclean).")"; // So we update only records detected wrong
  1691. $resql = $db->query($sql);
  1692. if ($resql)
  1693. {
  1694. $nb=$db->affected_rows($sql);
  1695. if ($nb > 0)
  1696. {
  1697. // Removed orphelins records
  1698. print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
  1699. print join(',',$listofidtoclean);
  1700. }
  1701. $totalnb+=$nb;
  1702. }
  1703. //else dol_print_error($db);
  1704. // Check and clean orphelins
  1705. $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
  1706. $sql.= " SET ".$fieldfkparent." = 0";
  1707. $sql.= " WHERE ".$fieldfkparent." NOT IN (".join(',',$listofid).")"; // So we update only records linked to a non existing parent
  1708. $resql = $db->query($sql);
  1709. if ($resql)
  1710. {
  1711. $nb=$db->affected_rows($sql);
  1712. if ($nb > 0)
  1713. {
  1714. // Removed orphelins records
  1715. print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
  1716. print join(',',$listofid);
  1717. }
  1718. $totalnb+=$nb;
  1719. }
  1720. //else dol_print_error($db);
  1721. print '<br>We fixed '.$totalnb.' record(s). Some records may still be corrupted. New check may be required.';
  1722. return $totalnb;
  1723. }
  1724. }
  1725. /**
  1726. * Get an array with properties of an element
  1727. *
  1728. * @param string $element_type Element type: 'action', 'facture', 'project_task' or 'object@modulext'...
  1729. * @return array (module, classpath, element, subelement, classfile, classname)
  1730. */
  1731. function getElementProperties($element_type)
  1732. {
  1733. // Parse element/subelement (ex: project_task)
  1734. $module = $element = $subelement = $element_type;
  1735. // If we ask an resource form external module (instead of default path)
  1736. if (preg_match('/^([^@]+)@([^@]+)$/i',$element_type,$regs))
  1737. {
  1738. $element = $subelement = $regs[1];
  1739. $module = $regs[2];
  1740. }
  1741. //print '<br />1. element : '.$element.' - module : '.$module .'<br />';
  1742. if ( preg_match('/^([^_]+)_([^_]+)/i',$element,$regs))
  1743. {
  1744. $module = $element = $regs[1];
  1745. $subelement = $regs[2];
  1746. }
  1747. // For compat
  1748. if($element_type == "action") {
  1749. $classpath = 'comm/action/class';
  1750. $subelement = 'Actioncomm';
  1751. $module = 'agenda';
  1752. }
  1753. // To work with non standard path
  1754. if ($element_type == 'facture' || $element_type == 'invoice') {
  1755. $classpath = 'compta/facture/class';
  1756. $module='facture';
  1757. $subelement='facture';
  1758. }
  1759. if ($element_type == 'commande' || $element_type == 'order') {
  1760. $classpath = 'commande/class';
  1761. $module='commande';
  1762. $subelement='commande';
  1763. }
  1764. if ($element_type == 'propal') {
  1765. $classpath = 'comm/propal/class';
  1766. }
  1767. if ($element_type == 'supplier_proposal') {
  1768. $classpath = 'supplier_proposal/class';
  1769. }
  1770. if ($element_type == 'shipping') {
  1771. $classpath = 'expedition/class';
  1772. $subelement = 'expedition';
  1773. $module = 'expedition_bon';
  1774. }
  1775. if ($element_type == 'delivery') {
  1776. $classpath = 'livraison/class';
  1777. $subelement = 'livraison';
  1778. $module = 'livraison_bon';
  1779. }
  1780. if ($element_type == 'contract') {
  1781. $classpath = 'contrat/class';
  1782. $module='contrat';
  1783. $subelement='contrat';
  1784. }
  1785. if ($element_type == 'member') {
  1786. $classpath = 'adherents/class';
  1787. $module='adherent';
  1788. $subelement='adherent';
  1789. }
  1790. if ($element_type == 'cabinetmed_cons') {
  1791. $classpath = 'cabinetmed/class';
  1792. $module='cabinetmed';
  1793. $subelement='cabinetmedcons';
  1794. }
  1795. if ($element_type == 'fichinter') {
  1796. $classpath = 'fichinter/class';
  1797. $module='ficheinter';
  1798. $subelement='fichinter';
  1799. }
  1800. if ($element_type == 'dolresource' || $element_type == 'resource') {
  1801. $classpath = 'resource/class';
  1802. $module='resource';
  1803. $subelement='dolresource';
  1804. }
  1805. if ($element_type == 'propaldet') {
  1806. $classpath = 'comm/propal/class';
  1807. $module='propal';
  1808. $subelement='propaleligne';
  1809. }
  1810. if ($element_type == 'order_supplier') {
  1811. $classpath = 'fourn/class';
  1812. $module='fournisseur';
  1813. $subelement='commandefournisseur';
  1814. $classfile='fournisseur.commande';
  1815. }
  1816. if ($element_type == 'invoice_supplier') {
  1817. $classpath = 'fourn/class';
  1818. $module='fournisseur';
  1819. $subelement='facturefournisseur';
  1820. $classfile='fournisseur.facture';
  1821. }
  1822. if (!isset($classfile)) $classfile = strtolower($subelement);
  1823. if (!isset($classname)) $classname = ucfirst($subelement);
  1824. if (!isset($classpath)) $classpath = $module.'/class';
  1825. $element_properties = array(
  1826. 'module' => $module,
  1827. 'classpath' => $classpath,
  1828. 'element' => $element,
  1829. 'subelement' => $subelement,
  1830. 'classfile' => $classfile,
  1831. 'classname' => $classname
  1832. );
  1833. return $element_properties;
  1834. }
  1835. /**
  1836. * Fetch an object from its id and element_type
  1837. * Inclusion of classes is automatic
  1838. *
  1839. * @param int $element_id Element id
  1840. * @param string $element_type Element type
  1841. * @param ref $element_ref Element ref (Use this if element_id but not both)
  1842. * @return int|object object || 0 || -1 if error
  1843. */
  1844. function fetchObjectByElement($element_id, $element_type, $element_ref='')
  1845. {
  1846. global $conf;
  1847. global $db,$conf;
  1848. $element_prop = getElementProperties($element_type);
  1849. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled)
  1850. {
  1851. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  1852. $objecttmp = new $element_prop['classname']($db);
  1853. $ret = $objecttmp->fetch($element_id, $element_ref);
  1854. if ($ret >= 0)
  1855. {
  1856. return $objecttmp;
  1857. }
  1858. }
  1859. return 0;
  1860. }
  1861. /**
  1862. * Convert an array with RGB value into hex RGB value.
  1863. * This is the opposite function of colorStringToArray
  1864. *
  1865. * @param array $arraycolor Array
  1866. * @param string $colorifnotfound Color code to return if entry not defined or not a RGB format
  1867. * @return string RGB hex value (without # before). For example: 'FF00FF', '01FF02'
  1868. * @see colorStringToArray
  1869. */
  1870. function colorArrayToHex($arraycolor,$colorifnotfound='888888')
  1871. {
  1872. if (! is_array($arraycolor)) return $colorifnotfound;
  1873. if (empty($arraycolor)) return $colorifnotfound;
  1874. return sprintf("%02s",dechex($arraycolor[0])).sprintf("%02s",dechex($arraycolor[1])).sprintf("%02s",dechex($arraycolor[2]));
  1875. }
  1876. /**
  1877. * Convert a string RGB value ('FFFFFF', '255,255,255') into an array RGB array(255,255,255).
  1878. * This is the opposite function of colorArrayToHex.
  1879. * If entry is already an array, return it.
  1880. *
  1881. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  1882. * @param array $colorifnotfound Color code array to return if entry not defined
  1883. * @return string RGB hex value (without # before). For example: FF00FF
  1884. * @see colorArrayToHex
  1885. */
  1886. function colorStringToArray($stringcolor,$colorifnotfound=array(88,88,88))
  1887. {
  1888. if (is_array($stringcolor)) return $stringcolor; // If already into correct output format, we return as is
  1889. $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);
  1890. if (! $tmp)
  1891. {
  1892. $tmp=explode(',',$stringcolor);
  1893. if (count($tmp) < 3) return $colorifnotfound;
  1894. return $tmp;
  1895. }
  1896. return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3]));
  1897. }
  1898. /**
  1899. * Applies the Cartesian product algorithm to an array
  1900. * Source: http://stackoverflow.com/a/15973172
  1901. *
  1902. * @param array $input Array of products
  1903. * @return array Array of combinations
  1904. */
  1905. function cartesianArray(array $input) {
  1906. // filter out empty values
  1907. $input = array_filter($input);
  1908. $result = array(array());
  1909. foreach ($input as $key => $values) {
  1910. $append = array();
  1911. foreach($result as $product) {
  1912. foreach($values as $item) {
  1913. $product[$key] = $item;
  1914. $append[] = $product;
  1915. }
  1916. }
  1917. $result = $append;
  1918. }
  1919. return $result;
  1920. }