functions2.lib.php 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371
  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 <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. // Load translation files required by the page
  181. $langs->loadLangs(array('other', '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. * @param User $objuser Object user we need data from.
  647. * @param int $forceentity Entity id to force
  648. * @return string New value (numeric) or error message
  649. */
  650. function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$mode='next', $bentityon=true, $objuser=null, $forceentity=null)
  651. {
  652. global $conf,$user;
  653. if (! is_object($objsoc)) $valueforccc=$objsoc;
  654. else if ($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=dol_string_unaccent($objsoc->code_fournisseur);
  655. else $valueforccc=dol_string_unaccent($objsoc->code_client);
  656. $sharetable = $table;
  657. if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function
  658. // Clean parameters
  659. if ($date == '') $date=dol_now(); // We use local year and month of PHP server to search numbers
  660. // but we should use local year and month of user
  661. // For debugging
  662. //dol_syslog("mask=".$mask, LOG_DEBUG);
  663. //include_once(DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php');
  664. //$mask='FA{yy}{mm}-{0000@99}';
  665. //$date=dol_mktime(12, 0, 0, 1, 1, 1900);
  666. //$date=dol_stringtotime('20130101');
  667. $hasglobalcounter=false;
  668. // Extract value for mask counter, mask raz and mask offset
  669. if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$mask,$reg))
  670. {
  671. $masktri=$reg[1].(! empty($reg[2])?$reg[2]:'').(! empty($reg[3])?$reg[3]:'');
  672. $maskcounter=$reg[1];
  673. $hasglobalcounter=true;
  674. }
  675. else
  676. {
  677. // setting some defaults so the rest of the code won't fail if there is a third party counter
  678. $masktri='00000';
  679. $maskcounter='00000';
  680. }
  681. $maskraz=-1;
  682. $maskoffset=0;
  683. $resetEveryMonth=false;
  684. if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits';
  685. // Extract value for third party mask counter
  686. if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
  687. {
  688. $maskrefclient=$regClientRef[1].$regClientRef[2];
  689. $maskrefclient_maskclientcode=$regClientRef[1];
  690. $maskrefclient_maskcounter=$regClientRef[2];
  691. $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset
  692. $maskrefclient_clientcode=substr($valueforccc,0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code where n is length in mask
  693. $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
  694. $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
  695. if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
  696. }
  697. else $maskrefclient='';
  698. // fail if there is neither a global nor a third party counter
  699. if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
  700. {
  701. return 'ErrorBadMask';
  702. }
  703. // Extract value for third party type
  704. if (preg_match('/\{(t+)\}/i',$mask,$regType))
  705. {
  706. $masktype=$regType[1];
  707. $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)
  708. $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
  709. }
  710. else
  711. {
  712. $masktype='';
  713. $masktype_value='';
  714. }
  715. // Extract value for user
  716. if (preg_match('/\{(u+)\}/i',$mask,$regType))
  717. {
  718. $lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  719. if (is_object($objuser)) $lastname = $objuser->lastname;
  720. $maskuser=$regType[1];
  721. $maskuser_value=substr($lastname,0,dol_strlen($regType[1]));// get n first characters of user firstname (where n is length in mask)
  722. $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
  723. }
  724. else
  725. {
  726. $maskuser='';
  727. $maskuser_value='';
  728. }
  729. // Personalized field {XXX-1} à {XXX-9}
  730. $maskperso=array();
  731. $maskpersonew=array();
  732. $tmpmask=$mask;
  733. while (preg_match('/\{([A-Z]+)\-([1-9])\}/',$tmpmask,$regKey))
  734. {
  735. $maskperso[$regKey[1]]='{'.$regKey[1].'-'.$regKey[2].'}';
  736. $maskpersonew[$regKey[1]]=str_pad('', $regKey[2], '_', STR_PAD_RIGHT);
  737. $tmpmask=preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask);
  738. }
  739. if (strstr($mask,'user_extra_'))
  740. {
  741. $start = "{user_extra_";
  742. $end = "\}";
  743. $extra= get_string_between($mask, "user_extra_", "}");
  744. if(!empty($user->array_options['options_'.$extra])){
  745. $mask = preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
  746. }
  747. }
  748. $maskwithonlyymcode=$mask;
  749. $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$maskcounter,$maskwithonlyymcode);
  750. $maskwithonlyymcode=preg_replace('/\{dd\}/i','dd',$maskwithonlyymcode);
  751. $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i',$maskrefclient,$maskwithonlyymcode);
  752. $maskwithonlyymcode=preg_replace('/\{(t+)\}/i',$masktype_value,$maskwithonlyymcode);
  753. $maskwithonlyymcode=preg_replace('/\{(u+)\}/i',$maskuser_value,$maskwithonlyymcode);
  754. foreach($maskperso as $key => $val)
  755. {
  756. $maskwithonlyymcode=preg_replace('/'.preg_quote($val,'/').'/i', $maskpersonew[$key], $maskwithonlyymcode);
  757. }
  758. $maskwithnocode=$maskwithonlyymcode;
  759. $maskwithnocode=preg_replace('/\{yyyy\}/i','yyyy',$maskwithnocode);
  760. $maskwithnocode=preg_replace('/\{yy\}/i','yy',$maskwithnocode);
  761. $maskwithnocode=preg_replace('/\{y\}/i','y',$maskwithnocode);
  762. $maskwithnocode=preg_replace('/\{mm\}/i','mm',$maskwithnocode);
  763. // Now maskwithnocode = 0000ddmmyyyyccc for example
  764. // and maskcounter = 0000 for example
  765. //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
  766. //var_dump($reg);
  767. // If an offset is asked
  768. if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
  769. if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
  770. // Define $sqlwhere
  771. $sqlwhere='';
  772. $yearoffset=0; // Use year of current $date by default
  773. $yearoffsettype=false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
  774. // If a restore to zero after a month is asked we check if there is already a value for this year.
  775. if (! empty($reg[2]) && preg_match('/^@/',$reg[2])) $yearoffsettype = preg_replace('/^@/','',$reg[2]);
  776. if (! empty($reg[3]) && preg_match('/^@/',$reg[3])) $yearoffsettype = preg_replace('/^@/','',$reg[3]);
  777. //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
  778. if (is_numeric($yearoffsettype) && $yearoffsettype >= 1)
  779. $maskraz=$yearoffsettype; // For backward compatibility
  780. else if ($yearoffsettype === '0' || (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1))
  781. $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START;
  782. //print "maskraz=".$maskraz; // -1=no reset
  783. if ($maskraz > 0) { // A reset is required
  784. if ($maskraz == 99) {
  785. $maskraz = date('m', $date);
  786. $resetEveryMonth = true;
  787. }
  788. if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
  789. // Define posy, posm and reg
  790. if ($maskraz > 1) // if reset is not first month, we need month and year into mask
  791. {
  792. if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
  793. elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
  794. else return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
  795. if (dol_strlen($reg[$posy]) < 2) return 'ErrorCantUseRazWithYearOnOneDigit';
  796. }
  797. else // if reset is for a specific month in year, we need year
  798. {
  799. if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
  800. else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
  801. else if (preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=0; }
  802. else return 'ErrorCantUseRazIfNoYearInMask';
  803. }
  804. // Define length
  805. $yearlen = $posy?dol_strlen($reg[$posy]):0;
  806. $monthlen = $posm?dol_strlen($reg[$posm]):0;
  807. // Define pos
  808. $yearpos = (dol_strlen($reg[1])+1);
  809. $monthpos = ($yearpos+$yearlen);
  810. if ($posy == 3 && $posm == 2) { // if month is before year
  811. $monthpos = (dol_strlen($reg[1])+1);
  812. $yearpos = ($monthpos+$monthlen);
  813. }
  814. //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
  815. // Define $yearcomp and $monthcomp (that will be use in the select where to search max number)
  816. $monthcomp=$maskraz;
  817. $yearcomp=0;
  818. if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=') // $yearoffsettype is - or +
  819. {
  820. $currentyear=date("Y", $date);
  821. $fiscaldate=dol_mktime('0','0','0',$maskraz,'1',$currentyear);
  822. $newyeardate=dol_mktime('0','0','0','1','1',$currentyear);
  823. $nextnewyeardate=dol_mktime('0','0','0','1','1',$currentyear+1);
  824. //echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
  825. // If after or equal of current fiscal date
  826. if ($date >= $fiscaldate)
  827. {
  828. // If before of next new year date
  829. if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset=1;
  830. }
  831. // If after or equal of current new year date
  832. else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset=-1;
  833. }
  834. // For backward compatibility
  835. else if (date("m",$date) < $maskraz && empty($resetEveryMonth)) { $yearoffset=-1; } // If current month lower that month of return to zero, year is previous year
  836. if ($yearlen == 4) $yearcomp=sprintf("%04d",date("Y",$date)+$yearoffset);
  837. elseif ($yearlen == 2) $yearcomp=sprintf("%02d",date("y",$date)+$yearoffset);
  838. elseif ($yearlen == 1) $yearcomp=substr(date("y",$date),2,1)+$yearoffset;
  839. 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)
  840. {
  841. if ($yearlen == 4) $yearcomp1=sprintf("%04d",date("Y",$date)+$yearoffset+1);
  842. elseif ($yearlen == 2) $yearcomp1=sprintf("%02d",date("y",$date)+$yearoffset+1);
  843. $sqlwhere.="(";
  844. $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
  845. $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
  846. $sqlwhere.=" OR";
  847. $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'";
  848. $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
  849. $sqlwhere.=')';
  850. }
  851. else if ($resetEveryMonth)
  852. {
  853. $sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
  854. $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
  855. }
  856. else // reset is done on january
  857. {
  858. $sqlwhere.='(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
  859. }
  860. }
  861. //print "sqlwhere=".$sqlwhere." yearcomp=".$yearcomp."<br>\n"; // sqlwhere and yearcomp defined only if we ask a reset
  862. //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
  863. // Define $sqlstring
  864. if (function_exists('mb_strrpos'))
  865. {
  866. $posnumstart=mb_strrpos($maskwithnocode,$maskcounter, 'UTF-8');
  867. }
  868. else
  869. {
  870. $posnumstart=strrpos($maskwithnocode,$maskcounter);
  871. } // Pos of counter in final string (from 0 to ...)
  872. if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
  873. $sqlstring='SUBSTRING('.$field.', '.($posnumstart+1).', '.dol_strlen($maskcounter).')';
  874. // Define $maskLike
  875. $maskLike = dol_string_nospecial($mask);
  876. $maskLike = str_replace("%","_",$maskLike);
  877. // Replace protected special codes with matching number of _ as wild card caracter
  878. $maskLike = preg_replace('/\{yyyy\}/i','____',$maskLike);
  879. $maskLike = preg_replace('/\{yy\}/i','__',$maskLike);
  880. $maskLike = preg_replace('/\{y\}/i','_',$maskLike);
  881. $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
  882. $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
  883. $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskLike);
  884. if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
  885. if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
  886. if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
  887. foreach($maskperso as $key => $val)
  888. {
  889. $maskLike = str_replace(dol_string_nospecial($maskperso[$key]),$maskpersonew[$key],$maskLike);
  890. }
  891. // Get counter in database
  892. $counter=0;
  893. $sql = "SELECT MAX(".$sqlstring.") as val";
  894. $sql.= " FROM ".MAIN_DB_PREFIX.$table;
  895. $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
  896. $sql.= " AND ".$field." NOT LIKE '(PROV%)'";
  897. if ($bentityon) // only if entity enable
  898. $sql.= " AND entity IN (".getEntity($sharetable).")";
  899. else if (! empty($forceentity))
  900. $sql.= " AND entity IN (".$forceentity.")";
  901. if ($where) $sql.=$where;
  902. if ($sqlwhere) $sql.=' AND '.$sqlwhere;
  903. //print $sql.'<br>';
  904. dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
  905. $resql=$db->query($sql);
  906. if ($resql)
  907. {
  908. $obj = $db->fetch_object($resql);
  909. $counter = $obj->val;
  910. }
  911. else dol_print_error($db);
  912. // Check if we must force counter to maskoffset
  913. if (empty($counter)) $counter=$maskoffset;
  914. else if (preg_match('/[^0-9]/i',$counter))
  915. {
  916. $counter=0;
  917. dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
  918. }
  919. else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter=$maskoffset;
  920. if ($mode == 'last') // We found value for counter = last counter value. Now need to get corresponding ref of invoice.
  921. {
  922. $counterpadded=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
  923. // Define $maskLike
  924. $maskLike = dol_string_nospecial($mask);
  925. $maskLike = str_replace("%","_",$maskLike);
  926. // Replace protected special codes with matching number of _ as wild card caracter
  927. $maskLike = preg_replace('/\{yyyy\}/i','____',$maskLike);
  928. $maskLike = preg_replace('/\{yy\}/i','__',$maskLike);
  929. $maskLike = preg_replace('/\{y\}/i','_',$maskLike);
  930. $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
  931. $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
  932. $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),$counterpadded,$maskLike);
  933. if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
  934. if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
  935. if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
  936. $ref='';
  937. $sql = "SELECT ".$field." as ref";
  938. $sql.= " FROM ".MAIN_DB_PREFIX.$table;
  939. $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
  940. $sql.= " AND ".$field." NOT LIKE '%PROV%'";
  941. if ($bentityon) // only if entity enable
  942. $sql.= " AND entity IN (".getEntity($sharetable).")";
  943. else if (! empty($forceentity))
  944. $sql.= " AND entity IN (".$forceentity.")";
  945. if ($where) $sql.=$where;
  946. if ($sqlwhere) $sql.=' AND '.$sqlwhere;
  947. dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
  948. $resql=$db->query($sql);
  949. if ($resql)
  950. {
  951. $obj = $db->fetch_object($resql);
  952. if ($obj) $ref = $obj->ref;
  953. }
  954. else dol_print_error($db);
  955. $numFinal=$ref;
  956. }
  957. else if ($mode == 'next')
  958. {
  959. $counter++;
  960. // If value for $counter has a length higher than $maskcounter chars
  961. if ($counter >= pow(10, dol_strlen($maskcounter)))
  962. {
  963. $counter='ErrorMaxNumberReachForThisMask';
  964. }
  965. if (! empty($maskrefclient_maskcounter))
  966. {
  967. //print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n<br>";
  968. // Define $sqlstring
  969. $maskrefclient_posnumstart=strpos($maskwithnocode,$maskrefclient_maskcounter,strpos($maskwithnocode,$maskrefclient)); // Pos of counter in final string (from 0 to ...)
  970. if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask';
  971. $maskrefclient_sqlstring='SUBSTRING('.$field.', '.($maskrefclient_posnumstart+1).', '.dol_strlen($maskrefclient_maskcounter).')';
  972. //print "x".$sqlstring;
  973. // Define $maskrefclient_maskLike
  974. $maskrefclient_maskLike = dol_string_nospecial($mask);
  975. $maskrefclient_maskLike = str_replace("%","_",$maskrefclient_maskLike);
  976. // Replace protected special codes with matching number of _ as wild card caracter
  977. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'),'____',$maskrefclient_maskLike);
  978. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'),'__',$maskrefclient_maskLike);
  979. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'),'_',$maskrefclient_maskLike);
  980. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'),'__',$maskrefclient_maskLike);
  981. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'),'__',$maskrefclient_maskLike);
  982. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskrefclient_maskLike);
  983. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),$maskrefclient_clientcode.str_pad("",dol_strlen($maskrefclient_maskcounter),"_"),$maskrefclient_maskLike);
  984. // Get counter in database
  985. $maskrefclient_counter=0;
  986. $maskrefclient_sql = "SELECT MAX(".$maskrefclient_sqlstring.") as val";
  987. $maskrefclient_sql.= " FROM ".MAIN_DB_PREFIX.$table;
  988. //$sql.= " WHERE ".$field." not like '(%'";
  989. $maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
  990. if ($bentityon) // only if entity enable
  991. $maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")";
  992. else if (! empty($forceentity))
  993. $sql.= " AND entity IN (".$forceentity.")";
  994. if ($where) $maskrefclient_sql.=$where; //use the same optional where as general mask
  995. if ($sqlwhere) $maskrefclient_sql.=' AND '.$sqlwhere; //use the same sqlwhere as general mask
  996. $maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode,$maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
  997. dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
  998. $maskrefclient_resql=$db->query($maskrefclient_sql);
  999. if ($maskrefclient_resql)
  1000. {
  1001. $maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
  1002. $maskrefclient_counter = $maskrefclient_obj->val;
  1003. }
  1004. else dol_print_error($db);
  1005. if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i',$maskrefclient_counter)) $maskrefclient_counter=$maskrefclient_maskoffset;
  1006. $maskrefclient_counter++;
  1007. }
  1008. // Build numFinal
  1009. $numFinal = $mask;
  1010. // We replace special codes except refclient
  1011. if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=') // yearoffsettype is - or +, so we don't want current year
  1012. {
  1013. $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
  1014. $numFinal = preg_replace('/\{yy\}/i', date("y",$date)+$yearoffset, $numFinal);
  1015. $numFinal = preg_replace('/\{y\}/i', substr(date("y",$date),1,1)+$yearoffset, $numFinal);
  1016. }
  1017. else // we want yyyy to be current year
  1018. {
  1019. $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date), $numFinal);
  1020. $numFinal = preg_replace('/\{yy\}/i', date("y",$date), $numFinal);
  1021. $numFinal = preg_replace('/\{y\}/i', substr(date("y",$date),1,1), $numFinal);
  1022. }
  1023. $numFinal = preg_replace('/\{mm\}/i', date("m",$date), $numFinal);
  1024. $numFinal = preg_replace('/\{dd\}/i', date("d",$date), $numFinal);
  1025. // Now we replace the counter
  1026. $maskbefore='{'.$masktri.'}';
  1027. $maskafter=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
  1028. //print 'x'.$maskbefore.'-'.$maskafter.'y';
  1029. $numFinal = str_replace($maskbefore,$maskafter,$numFinal);
  1030. // Now we replace the refclient
  1031. if ($maskrefclient)
  1032. {
  1033. //print "maskrefclient=".$maskrefclient." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskrefclient_clientcode=".$maskrefclient_clientcode."\n<br>";exit;
  1034. $maskrefclient_maskbefore='{'.$maskrefclient.'}';
  1035. $maskrefclient_maskafter=$maskrefclient_clientcode.str_pad($maskrefclient_counter,dol_strlen($maskrefclient_maskcounter),"0",STR_PAD_LEFT);
  1036. $numFinal = str_replace($maskrefclient_maskbefore,$maskrefclient_maskafter,$numFinal);
  1037. }
  1038. // Now we replace the type
  1039. if ($masktype)
  1040. {
  1041. $masktype_maskbefore='{'.$masktype.'}';
  1042. $masktype_maskafter=$masktype_value;
  1043. $numFinal = str_replace($masktype_maskbefore,$masktype_maskafter,$numFinal);
  1044. }
  1045. // Now we replace the user
  1046. if ($maskuser)
  1047. {
  1048. $maskuser_maskbefore='{'.$maskuser.'}';
  1049. $maskuser_maskafter=$maskuser_value;
  1050. $numFinal = str_replace($maskuser_maskbefore,$maskuser_maskafter,$numFinal);
  1051. }
  1052. }
  1053. dol_syslog("functions2::get_next_value return ".$numFinal,LOG_DEBUG);
  1054. return $numFinal;
  1055. }
  1056. /**
  1057. * Get string between
  1058. *
  1059. * @param string $string String to test
  1060. * @param int $start Value for start
  1061. * @param int $end Value for end
  1062. * @return string Return part of string
  1063. */
  1064. function get_string_between($string, $start, $end)
  1065. {
  1066. $string = " ".$string;
  1067. $ini = strpos($string,$start);
  1068. if ($ini == 0) return "";
  1069. $ini += strlen($start);
  1070. $len = strpos($string,$end,$ini) - $ini;
  1071. return substr($string,$ini,$len);
  1072. }
  1073. /**
  1074. * Check value
  1075. *
  1076. * @param string $mask Mask to use
  1077. * @param string $value Value
  1078. * @return int|string <0 or error string if KO, 0 if OK
  1079. */
  1080. function check_value($mask,$value)
  1081. {
  1082. $result=0;
  1083. $hasglobalcounter=false;
  1084. // Extract value for mask counter, mask raz and mask offset
  1085. if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i',$mask,$reg))
  1086. {
  1087. $masktri=$reg[1].(isset($reg[2])?$reg[2]:'').(isset($reg[3])?$reg[3]:'');
  1088. $maskcounter=$reg[1];
  1089. $hasglobalcounter=true;
  1090. }
  1091. else
  1092. {
  1093. // setting some defaults so the rest of the code won't fail if there is a third party counter
  1094. $masktri='00000';
  1095. $maskcounter='00000';
  1096. }
  1097. $maskraz=-1;
  1098. $maskoffset=0;
  1099. if (dol_strlen($maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
  1100. // Extract value for third party mask counter
  1101. if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
  1102. {
  1103. $maskrefclient=$regClientRef[1].$regClientRef[2];
  1104. $maskrefclient_maskclientcode=$regClientRef[1];
  1105. $maskrefclient_maskcounter=$regClientRef[2];
  1106. $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset
  1107. $maskrefclient_clientcode=substr('',0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code to form maskrefclient_clientcode
  1108. $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
  1109. $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
  1110. if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
  1111. }
  1112. else $maskrefclient='';
  1113. // fail if there is neither a global nor a third party counter
  1114. if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
  1115. {
  1116. return 'ErrorBadMask';
  1117. }
  1118. $maskwithonlyymcode=$mask;
  1119. $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i',$maskcounter,$maskwithonlyymcode);
  1120. $maskwithonlyymcode=preg_replace('/\{dd\}/i','dd',$maskwithonlyymcode);
  1121. $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i',$maskrefclient,$maskwithonlyymcode);
  1122. $maskwithnocode=$maskwithonlyymcode;
  1123. $maskwithnocode=preg_replace('/\{yyyy\}/i','yyyy',$maskwithnocode);
  1124. $maskwithnocode=preg_replace('/\{yy\}/i','yy',$maskwithnocode);
  1125. $maskwithnocode=preg_replace('/\{y\}/i','y',$maskwithnocode);
  1126. $maskwithnocode=preg_replace('/\{mm\}/i','mm',$maskwithnocode);
  1127. // Now maskwithnocode = 0000ddmmyyyyccc for example
  1128. // and maskcounter = 0000 for example
  1129. //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
  1130. // If an offset is asked
  1131. if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
  1132. if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
  1133. // Define $sqlwhere
  1134. // If a restore to zero after a month is asked we check if there is already a value for this year.
  1135. if (! empty($reg[2]) && preg_match('/^@/',$reg[2])) $maskraz=preg_replace('/^@/','',$reg[2]);
  1136. if (! empty($reg[3]) && preg_match('/^@/',$reg[3])) $maskraz=preg_replace('/^@/','',$reg[3]);
  1137. if ($maskraz >= 0)
  1138. {
  1139. if ($maskraz == 99) {
  1140. $maskraz = date('m');
  1141. $resetEveryMonth = true;
  1142. }
  1143. if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
  1144. // Define reg
  1145. if ($maskraz > 1 && ! preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
  1146. if ($maskraz <= 1 && ! preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazIfNoYearInMask';
  1147. //print "x".$maskwithonlyymcode." ".$maskraz;
  1148. }
  1149. //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
  1150. // Check we have a number in ($posnumstart+1).', '.dol_strlen($maskcounter)
  1151. //
  1152. // Check length
  1153. $len=dol_strlen($maskwithnocode);
  1154. if (dol_strlen($value) != $len) $result=-1;
  1155. // Define $maskLike
  1156. /* seems not used
  1157. $maskLike = dol_string_nospecial($mask);
  1158. $maskLike = str_replace("%","_",$maskLike);
  1159. // Replace protected special codes with matching number of _ as wild card caracter
  1160. $maskLike = str_replace(dol_string_nospecial('{yyyy}'),'____',$maskLike);
  1161. $maskLike = str_replace(dol_string_nospecial('{yy}'),'__',$maskLike);
  1162. $maskLike = str_replace(dol_string_nospecial('{y}'),'_',$maskLike);
  1163. $maskLike = str_replace(dol_string_nospecial('{mm}'),'__',$maskLike);
  1164. $maskLike = str_replace(dol_string_nospecial('{dd}'),'__',$maskLike);
  1165. $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskLike);
  1166. if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",strlen($maskrefclient),"_"),$maskLike);
  1167. */
  1168. dol_syslog("functions2::check_value result=".$result,LOG_DEBUG);
  1169. return $result;
  1170. }
  1171. /**
  1172. * Convert a binary data to string that represent hexadecimal value
  1173. *
  1174. * @param string $bin Value to convert
  1175. * @param boolean $pad Add 0
  1176. * @param boolean $upper Convert to tupper
  1177. * @return string x
  1178. */
  1179. function binhex($bin, $pad=false, $upper=false)
  1180. {
  1181. $last = dol_strlen($bin)-1;
  1182. for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
  1183. $x = dechex($x);
  1184. if($pad){ while(dol_strlen($x) < intval(dol_strlen($bin))/4){ $x = "0$x"; } }
  1185. if($upper){ $x = strtoupper($x); }
  1186. return $x;
  1187. }
  1188. /**
  1189. * Convert an hexadecimal string into a binary string
  1190. *
  1191. * @param string $hexa Hexadecimal string to convert (example: 'FF')
  1192. * @return string bin
  1193. */
  1194. function hexbin($hexa)
  1195. {
  1196. $bin='';
  1197. $strLength = dol_strlen($hexa);
  1198. for($i=0;$i<$strLength;$i++)
  1199. {
  1200. $bin.=str_pad(decbin(hexdec($hexa{$i})),4,'0',STR_PAD_LEFT);
  1201. }
  1202. return $bin;
  1203. }
  1204. /**
  1205. * Retourne le numero de la semaine par rapport a une date
  1206. *
  1207. * @param string $time Date au format 'timestamp'
  1208. * @return string Number of week
  1209. */
  1210. function numero_semaine($time)
  1211. {
  1212. $stime = strftime('%Y-%m-%d',$time);
  1213. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i',$stime,$reg))
  1214. {
  1215. // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS'
  1216. $annee = $reg[1];
  1217. $mois = $reg[2];
  1218. $jour = $reg[3];
  1219. }
  1220. /*
  1221. * Norme ISO-8601:
  1222. * - 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.
  1223. * - La majorite des annees ont 52 semaines mais les annees qui commence un jeudi et les annees bissextiles commencant un mercredi en possede 53.
  1224. * - Le 1er jour de la semaine est le Lundi
  1225. */
  1226. // Definition du Jeudi de la semaine
  1227. if (date("w",mktime(12,0,0,$mois,$jour,$annee))==0) // Dimanche
  1228. $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-3*24*60*60;
  1229. else if (date("w",mktime(12,0,0,$mois,$jour,$annee))<4) // du Lundi au Mercredi
  1230. $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)+(4-date("w",mktime(12,0,0,$mois,$jour,$annee)))*24*60*60;
  1231. else if (date("w",mktime(12,0,0,$mois,$jour,$annee))>4) // du Vendredi au Samedi
  1232. $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-(date("w",mktime(12,0,0,$mois,$jour,$annee))-4)*24*60*60;
  1233. else // Jeudi
  1234. $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee);
  1235. // Definition du premier Jeudi de l'annee
  1236. if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==0) // Dimanche
  1237. {
  1238. $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+4*24*60*60;
  1239. }
  1240. else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))<4) // du Lundi au Mercredi
  1241. {
  1242. $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;
  1243. }
  1244. else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))>4) // du Vendredi au Samedi
  1245. {
  1246. $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;
  1247. }
  1248. else // Jeudi
  1249. {
  1250. $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine));
  1251. }
  1252. // Definition du numero de semaine: nb de jours entre "premier Jeudi de l'annee" et "Jeudi de la semaine";
  1253. $numeroSemaine = (
  1254. (
  1255. date("z",mktime(12,0,0,date("m",$jeudiSemaine),date("d",$jeudiSemaine),date("Y",$jeudiSemaine)))
  1256. -
  1257. date("z",mktime(12,0,0,date("m",$premierJeudiAnnee),date("d",$premierJeudiAnnee),date("Y",$premierJeudiAnnee)))
  1258. ) / 7
  1259. ) + 1;
  1260. // Cas particulier de la semaine 53
  1261. if ($numeroSemaine==53)
  1262. {
  1263. // Les annees qui commence un Jeudi et les annees bissextiles commencant un Mercredi en possede 53
  1264. 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))
  1265. {
  1266. $numeroSemaine = 53;
  1267. }
  1268. else
  1269. {
  1270. $numeroSemaine = 1;
  1271. }
  1272. }
  1273. //echo $jour."-".$mois."-".$annee." (".date("d-m-Y",$premierJeudiAnnee)." - ".date("d-m-Y",$jeudiSemaine).") -> ".$numeroSemaine."<BR>";
  1274. return sprintf("%02d",$numeroSemaine);
  1275. }
  1276. /**
  1277. * Convertit une masse d'une unite vers une autre unite
  1278. *
  1279. * @param float $weight Masse a convertir
  1280. * @param int $from_unit Unite originale en puissance de 10
  1281. * @param int $to_unit Nouvelle unite en puissance de 10
  1282. * @return float Masse convertie
  1283. */
  1284. function weight_convert($weight,&$from_unit,$to_unit)
  1285. {
  1286. /* Pour convertire 320 gr en Kg appeler
  1287. * $f = -3
  1288. * weigh_convert(320, $f, 0) retournera 0.32
  1289. *
  1290. */
  1291. while ($from_unit <> $to_unit)
  1292. {
  1293. if ($from_unit > $to_unit)
  1294. {
  1295. $weight = $weight * 10;
  1296. $from_unit = $from_unit - 1;
  1297. $weight = weight_convert($weight,$from_unit, $to_unit);
  1298. }
  1299. if ($from_unit < $to_unit)
  1300. {
  1301. $weight = $weight / 10;
  1302. $from_unit = $from_unit + 1;
  1303. $weight = weight_convert($weight,$from_unit, $to_unit);
  1304. }
  1305. }
  1306. return $weight;
  1307. }
  1308. /**
  1309. * Save personnal parameter
  1310. *
  1311. * @param DoliDB $db Handler database
  1312. * @param Conf $conf Object conf
  1313. * @param User $user Object user
  1314. * @param array $tab Array (key=>value) with all parameters to save
  1315. * @return int <0 if KO, >0 if OK
  1316. *
  1317. * @see dolibarr_get_const, dolibarr_set_const, dolibarr_del_const
  1318. */
  1319. function dol_set_user_param($db, $conf, &$user, $tab)
  1320. {
  1321. // Verification parametres
  1322. if (count($tab) < 1) return -1;
  1323. $db->begin();
  1324. // We remove old parameters for all keys in $tab
  1325. $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param";
  1326. $sql.= " WHERE fk_user = ".$user->id;
  1327. $sql.= " AND entity = ".$conf->entity;
  1328. $sql.= " AND param in (";
  1329. $i=0;
  1330. foreach ($tab as $key => $value)
  1331. {
  1332. if ($i > 0) $sql.=',';
  1333. $sql.="'".$db->escape($key)."'";
  1334. $i++;
  1335. }
  1336. $sql.= ")";
  1337. dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
  1338. $resql=$db->query($sql);
  1339. if (! $resql)
  1340. {
  1341. dol_print_error($db);
  1342. $db->rollback();
  1343. return -1;
  1344. }
  1345. foreach ($tab as $key => $value)
  1346. {
  1347. // Set new parameters
  1348. if ($value)
  1349. {
  1350. $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,entity,param,value)";
  1351. $sql.= " VALUES (".$user->id.",".$conf->entity.",";
  1352. $sql.= " '".$db->escape($key)."','".$db->escape($value)."')";
  1353. dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
  1354. $result=$db->query($sql);
  1355. if (! $result)
  1356. {
  1357. dol_print_error($db);
  1358. $db->rollback();
  1359. return -1;
  1360. }
  1361. $user->conf->$key = $value;
  1362. //print "key=".$key." user->conf->key=".$user->conf->$key;
  1363. }
  1364. else
  1365. {
  1366. unset($user->conf->$key);
  1367. }
  1368. }
  1369. $db->commit();
  1370. return 1;
  1371. }
  1372. /**
  1373. * Returns formated reduction
  1374. *
  1375. * @param int $reduction Reduction percentage
  1376. * @param Translate $langs Output language
  1377. * @return string Formated reduction
  1378. */
  1379. function dol_print_reduction($reduction,$langs)
  1380. {
  1381. $string = '';
  1382. if ($reduction == 100)
  1383. {
  1384. $string = $langs->transnoentities("Offered");
  1385. }
  1386. else
  1387. {
  1388. $string = vatrate($reduction,true);
  1389. }
  1390. return $string;
  1391. }
  1392. /**
  1393. * Return OS version.
  1394. * Note that PHP_OS returns only OS (not version) and OS PHP was built on, not necessarly OS PHP runs on.
  1395. *
  1396. * @return string OS version
  1397. */
  1398. function version_os()
  1399. {
  1400. $osversion=php_uname();
  1401. return $osversion;
  1402. }
  1403. /**
  1404. * Return PHP version
  1405. *
  1406. * @return string PHP version
  1407. * @see versionphparray
  1408. */
  1409. function version_php()
  1410. {
  1411. return phpversion();
  1412. }
  1413. /**
  1414. * Return Dolibarr version
  1415. *
  1416. * @return string Dolibarr version
  1417. * @see versiondolibarrarray
  1418. */
  1419. function version_dolibarr()
  1420. {
  1421. return DOL_VERSION;
  1422. }
  1423. /**
  1424. * Return web server version
  1425. *
  1426. * @return string Web server version
  1427. */
  1428. function version_webserver()
  1429. {
  1430. return $_SERVER["SERVER_SOFTWARE"];
  1431. }
  1432. /**
  1433. * Return list of activated modules usable for document generation
  1434. *
  1435. * @param DoliDB $db Database handler
  1436. * @param string $type Type of models (company, invoice, ...)
  1437. * @param int $maxfilenamelength Max length of value to show
  1438. * @return mixed 0 if no module is activated, or array(key=>label). For modules that need directory scan, key is completed with ":filename".
  1439. */
  1440. function getListOfModels($db,$type,$maxfilenamelength=0)
  1441. {
  1442. global $conf,$langs;
  1443. $liste=array();
  1444. $found=0;
  1445. $dirtoscan='';
  1446. $sql = "SELECT nom as id, nom as lib, libelle as label, description as description";
  1447. $sql.= " FROM ".MAIN_DB_PREFIX."document_model";
  1448. $sql.= " WHERE type = '".$type."'";
  1449. $sql.= " AND entity IN (0,".$conf->entity.")";
  1450. $sql.= " ORDER BY description DESC";
  1451. dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG);
  1452. $resql = $db->query($sql);
  1453. if ($resql)
  1454. {
  1455. $num = $db->num_rows($resql);
  1456. $i = 0;
  1457. while ($i < $num)
  1458. {
  1459. $found=1;
  1460. $obj = $db->fetch_object($resql);
  1461. // If this generation module needs to scan a directory, then description field is filled
  1462. // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...).
  1463. if (! empty($obj->description)) // A list of directories to scan is defined
  1464. {
  1465. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1466. $const=$obj->description;
  1467. //irtoscan.=($dirtoscan?',':'').preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
  1468. $dirtoscan= preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
  1469. $listoffiles=array();
  1470. // Now we add models found in directories scanned
  1471. $listofdir=explode(',',$dirtoscan);
  1472. foreach($listofdir as $key=>$tmpdir)
  1473. {
  1474. $tmpdir=trim($tmpdir);
  1475. $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
  1476. if (! $tmpdir) { unset($listofdir[$key]); continue; }
  1477. if (is_dir($tmpdir))
  1478. {
  1479. // all type of template is allowed
  1480. $tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
  1481. if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
  1482. }
  1483. }
  1484. if (count($listoffiles))
  1485. {
  1486. foreach($listoffiles as $record)
  1487. {
  1488. $max=($maxfilenamelength?$maxfilenamelength:28);
  1489. $liste[$obj->id.':'.$record['fullname']]=dol_trunc($record['name'],$max,'middle');
  1490. }
  1491. }
  1492. else
  1493. {
  1494. $liste[0]=$obj->label.': '.$langs->trans("None");
  1495. }
  1496. }
  1497. else
  1498. {
  1499. if ($type == 'member' && $obj->lib == 'standard') // Special case, if member template, we add variant per format
  1500. {
  1501. global $_Avery_Labels;
  1502. include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
  1503. foreach($_Avery_Labels as $key => $val)
  1504. {
  1505. $liste[$obj->id.':'.$key]=($obj->label?$obj->label:$obj->lib).' '.$val['name'];
  1506. }
  1507. }
  1508. else // Common usage
  1509. {
  1510. $liste[$obj->id]=$obj->label?$obj->label:$obj->lib;
  1511. }
  1512. }
  1513. $i++;
  1514. }
  1515. }
  1516. else
  1517. {
  1518. dol_print_error($db);
  1519. return -1;
  1520. }
  1521. if ($found) return $liste;
  1522. else return 0;
  1523. }
  1524. /**
  1525. * This function evaluates a string that should be a valid IPv4
  1526. * 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.
  1527. *
  1528. * @param string $ip IP Address
  1529. * @return int 0 if not valid or reserved range, 1 if valid and public IP, 2 if valid and private range IP
  1530. */
  1531. function is_ip($ip)
  1532. {
  1533. // First we test if it is a valid IPv4
  1534. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  1535. // Then we test if it is a private range
  1536. if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
  1537. // Then we test if it is a reserved range
  1538. if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
  1539. return 1;
  1540. }
  1541. return 0;
  1542. }
  1543. /**
  1544. * Build a login from lastname, firstname
  1545. *
  1546. * @param string $lastname Lastname
  1547. * @param string $firstname Firstname
  1548. * @return string Login
  1549. */
  1550. function dol_buildlogin($lastname,$firstname)
  1551. {
  1552. $login=strtolower(dol_string_unaccent($firstname));
  1553. $login.=($login?'.':'');
  1554. $login.=strtolower(dol_string_unaccent($lastname));
  1555. $login=dol_string_nospecial($login,''); // For special names
  1556. return $login;
  1557. }
  1558. /**
  1559. * Return array to use for SoapClient constructor
  1560. *
  1561. * @return array
  1562. */
  1563. function getSoapParams()
  1564. {
  1565. global $conf;
  1566. $params=array();
  1567. $proxyuse =(empty($conf->global->MAIN_PROXY_USE)?false:true);
  1568. $proxyhost=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_HOST);
  1569. $proxyport=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_PORT);
  1570. $proxyuser=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_USER);
  1571. $proxypass=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_PASS);
  1572. $timeout =(empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)?10:$conf->global->MAIN_USE_CONNECT_TIMEOUT); // Connection timeout
  1573. $response_timeout=(empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT)?30:$conf->global->MAIN_USE_RESPONSE_TIMEOUT); // Response timeout
  1574. //print extension_loaded('soap');
  1575. if ($proxyuse)
  1576. {
  1577. $params=array('connection_timeout'=>$timeout,
  1578. 'response_timeout'=>$response_timeout,
  1579. 'proxy_use' => 1,
  1580. 'proxy_host' => $proxyhost,
  1581. 'proxy_port' => $proxyport,
  1582. 'proxy_login' => $proxyuser,
  1583. 'proxy_password' => $proxypass,
  1584. 'trace' => 1
  1585. );
  1586. }
  1587. else
  1588. {
  1589. $params=array('connection_timeout'=>$timeout,
  1590. 'response_timeout'=>$response_timeout,
  1591. 'proxy_use' => 0,
  1592. 'proxy_host' => false,
  1593. 'proxy_port' => false,
  1594. 'proxy_login' => false,
  1595. 'proxy_password' => false,
  1596. 'trace' => 1
  1597. );
  1598. }
  1599. return $params;
  1600. }
  1601. /**
  1602. * Return link url to an object
  1603. *
  1604. * @param int $objectid Id of record
  1605. * @param string $objecttype Type of object ('invoice', 'order', 'expedition_bon', ...)
  1606. * @param int $withpicto Picto to show
  1607. * @param string $option More options
  1608. * @return string URL of link to object id/type
  1609. */
  1610. function dolGetElementUrl($objectid,$objecttype,$withpicto=0,$option='')
  1611. {
  1612. global $db, $conf, $langs;
  1613. $ret='';
  1614. // Parse element/subelement (ex: project_task)
  1615. $module = $element = $subelement = $objecttype;
  1616. if (preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
  1617. {
  1618. $module = $element = $regs[1];
  1619. $subelement = $regs[2];
  1620. }
  1621. $classpath = $element.'/class';
  1622. // To work with non standard path
  1623. if ($objecttype == 'facture' || $objecttype == 'invoice') {
  1624. $classpath = 'compta/facture/class';
  1625. $module='facture';
  1626. $subelement='facture';
  1627. }
  1628. if ($objecttype == 'commande' || $objecttype == 'order') {
  1629. $classpath = 'commande/class';
  1630. $module='commande';
  1631. $subelement='commande';
  1632. }
  1633. if ($objecttype == 'propal') {
  1634. $classpath = 'comm/propal/class';
  1635. }
  1636. if ($objecttype == 'supplier_proposal') {
  1637. $classpath = 'supplier_proposal/class';
  1638. }
  1639. if ($objecttype == 'shipping') {
  1640. $classpath = 'expedition/class';
  1641. $subelement = 'expedition';
  1642. $module = 'expedition_bon';
  1643. }
  1644. if ($objecttype == 'delivery') {
  1645. $classpath = 'livraison/class';
  1646. $subelement = 'livraison';
  1647. $module = 'livraison_bon';
  1648. }
  1649. if ($objecttype == 'contract') {
  1650. $classpath = 'contrat/class';
  1651. $module='contrat';
  1652. $subelement='contrat';
  1653. }
  1654. if ($objecttype == 'member') {
  1655. $classpath = 'adherents/class';
  1656. $module='adherent';
  1657. $subelement='adherent';
  1658. }
  1659. if ($objecttype == 'cabinetmed_cons') {
  1660. $classpath = 'cabinetmed/class';
  1661. $module='cabinetmed';
  1662. $subelement='cabinetmedcons';
  1663. }
  1664. if ($objecttype == 'fichinter') {
  1665. $classpath = 'fichinter/class';
  1666. $module='ficheinter';
  1667. $subelement='fichinter';
  1668. }
  1669. if ($objecttype == 'task') {
  1670. $classpath = 'projet/class';
  1671. $module='projet';
  1672. $subelement='task';
  1673. }
  1674. if ($objecttype == 'stock') {
  1675. $classpath = 'product/stock/class';
  1676. $module='stock';
  1677. $subelement='stock';
  1678. }
  1679. //print "objecttype=".$objecttype." module=".$module." subelement=".$subelement;
  1680. $classfile = strtolower($subelement); $classname = ucfirst($subelement);
  1681. if ($objecttype == 'invoice_supplier') {
  1682. $classfile = 'fournisseur.facture';
  1683. $classname='FactureFournisseur';
  1684. $classpath = 'fourn/class';
  1685. $module='fournisseur';
  1686. }
  1687. elseif ($objecttype == 'order_supplier') {
  1688. $classfile = 'fournisseur.commande';
  1689. $classname='CommandeFournisseur';
  1690. $classpath = 'fourn/class';
  1691. $module='fournisseur';
  1692. }
  1693. elseif ($objecttype == 'stock') {
  1694. $classpath = 'product/stock/class';
  1695. $classfile='entrepot';
  1696. $classname='Entrepot';
  1697. }
  1698. if (! empty($conf->$module->enabled))
  1699. {
  1700. $res=dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  1701. if ($res)
  1702. {
  1703. if (class_exists($classname))
  1704. {
  1705. $object = new $classname($db);
  1706. $res=$object->fetch($objectid);
  1707. if ($res > 0) {
  1708. $ret=$object->getNomUrl($withpicto,$option);
  1709. } elseif($res==0) {
  1710. $ret=$langs->trans('Deleted');
  1711. }
  1712. unset($object);
  1713. }
  1714. else dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
  1715. }
  1716. }
  1717. return $ret;
  1718. }
  1719. /**
  1720. * Clean corrupted tree (orphelins linked to a not existing parent), record linked to themself and child-parent loop
  1721. *
  1722. * @param DoliDB $db Database handler
  1723. * @param string $tabletocleantree Table to clean
  1724. * @param string $fieldfkparent Field name that contains id of parent
  1725. * @return int Nb of records fixed/deleted
  1726. */
  1727. function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
  1728. {
  1729. $totalnb=0;
  1730. $listofid=array();
  1731. $listofparentid=array();
  1732. // Get list of all id in array listofid and all parents in array listofparentid
  1733. $sql='SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
  1734. $resql = $db->query($sql);
  1735. if ($resql)
  1736. {
  1737. $num = $db->num_rows($resql);
  1738. $i = 0;
  1739. while ($i < $num)
  1740. {
  1741. $obj = $db->fetch_object($resql);
  1742. $listofid[]=$obj->rowid;
  1743. if ($obj->parent_id > 0) $listofparentid[$obj->rowid]=$obj->parent_id;
  1744. $i++;
  1745. }
  1746. }
  1747. else
  1748. {
  1749. dol_print_error($db);
  1750. }
  1751. if (count($listofid))
  1752. {
  1753. print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
  1754. // Check loops on each other
  1755. $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid"; // So we update only records linked to themself
  1756. $resql = $db->query($sql);
  1757. if ($resql)
  1758. {
  1759. $nb=$db->affected_rows($sql);
  1760. if ($nb > 0)
  1761. {
  1762. print '<br>Some record that were parent of themself were cleaned.';
  1763. }
  1764. $totalnb+=$nb;
  1765. }
  1766. //else dol_print_error($db);
  1767. // Check other loops
  1768. $listofidtoclean=array();
  1769. foreach($listofparentid as $id => $pid)
  1770. {
  1771. // Check depth
  1772. //print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
  1773. $cursor=$id; $arrayidparsed=array(); // We start from child $id
  1774. while ($cursor > 0)
  1775. {
  1776. $arrayidparsed[$cursor]=1;
  1777. if ($arrayidparsed[$listofparentid[$cursor]]) // We detect a loop. A record with a parent that was already into child
  1778. {
  1779. print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
  1780. unset($arrayidparsed);
  1781. $listofidtoclean[$cursor]=$id;
  1782. break;
  1783. }
  1784. $cursor=$listofparentid[$cursor];
  1785. }
  1786. if (count($listofidtoclean)) break;
  1787. }
  1788. $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
  1789. $sql.= " SET ".$fieldfkparent." = 0";
  1790. $sql.= " WHERE rowid IN (".join(',',$listofidtoclean).")"; // So we update only records detected wrong
  1791. $resql = $db->query($sql);
  1792. if ($resql)
  1793. {
  1794. $nb=$db->affected_rows($sql);
  1795. if ($nb > 0)
  1796. {
  1797. // Removed orphelins records
  1798. print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
  1799. print join(',',$listofidtoclean);
  1800. }
  1801. $totalnb+=$nb;
  1802. }
  1803. //else dol_print_error($db);
  1804. // Check and clean orphelins
  1805. $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
  1806. $sql.= " SET ".$fieldfkparent." = 0";
  1807. $sql.= " WHERE ".$fieldfkparent." NOT IN (".join(',',$listofid).")"; // So we update only records linked to a non existing parent
  1808. $resql = $db->query($sql);
  1809. if ($resql)
  1810. {
  1811. $nb=$db->affected_rows($sql);
  1812. if ($nb > 0)
  1813. {
  1814. // Removed orphelins records
  1815. print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
  1816. print join(',',$listofid);
  1817. }
  1818. $totalnb+=$nb;
  1819. }
  1820. //else dol_print_error($db);
  1821. print '<br>We fixed '.$totalnb.' record(s). Some records may still be corrupted. New check may be required.';
  1822. return $totalnb;
  1823. }
  1824. }
  1825. /**
  1826. * Get an array with properties of an element
  1827. *
  1828. * @param string $element_type Element type: 'action', 'facture', 'project_task' or 'object@modulext'...
  1829. * @return array (module, classpath, element, subelement, classfile, classname)
  1830. */
  1831. function getElementProperties($element_type)
  1832. {
  1833. // Parse element/subelement (ex: project_task)
  1834. $module = $element = $subelement = $element_type;
  1835. // If we ask an resource form external module (instead of default path)
  1836. if (preg_match('/^([^@]+)@([^@]+)$/i',$element_type,$regs))
  1837. {
  1838. $element = $subelement = $regs[1];
  1839. $module = $regs[2];
  1840. }
  1841. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  1842. if ( preg_match('/^([^_]+)_([^_]+)/i',$element,$regs))
  1843. {
  1844. $module = $element = $regs[1];
  1845. $subelement = $regs[2];
  1846. }
  1847. // For compat
  1848. if($element_type == "action") {
  1849. $classpath = 'comm/action/class';
  1850. $subelement = 'Actioncomm';
  1851. $module = 'agenda';
  1852. }
  1853. // To work with non standard path
  1854. if ($element_type == 'facture' || $element_type == 'invoice') {
  1855. $classpath = 'compta/facture/class';
  1856. $module='facture';
  1857. $subelement='facture';
  1858. }
  1859. if ($element_type == 'commande' || $element_type == 'order') {
  1860. $classpath = 'commande/class';
  1861. $module='commande';
  1862. $subelement='commande';
  1863. }
  1864. if ($element_type == 'propal') {
  1865. $classpath = 'comm/propal/class';
  1866. }
  1867. if ($element_type == 'supplier_proposal') {
  1868. $classpath = 'supplier_proposal/class';
  1869. }
  1870. if ($element_type == 'shipping') {
  1871. $classpath = 'expedition/class';
  1872. $subelement = 'expedition';
  1873. $module = 'expedition_bon';
  1874. }
  1875. if ($element_type == 'delivery') {
  1876. $classpath = 'livraison/class';
  1877. $subelement = 'livraison';
  1878. $module = 'livraison_bon';
  1879. }
  1880. if ($element_type == 'contract') {
  1881. $classpath = 'contrat/class';
  1882. $module='contrat';
  1883. $subelement='contrat';
  1884. }
  1885. if ($element_type == 'member') {
  1886. $classpath = 'adherents/class';
  1887. $module='adherent';
  1888. $subelement='adherent';
  1889. }
  1890. if ($element_type == 'cabinetmed_cons') {
  1891. $classpath = 'cabinetmed/class';
  1892. $module='cabinetmed';
  1893. $subelement='cabinetmedcons';
  1894. }
  1895. if ($element_type == 'fichinter') {
  1896. $classpath = 'fichinter/class';
  1897. $module='ficheinter';
  1898. $subelement='fichinter';
  1899. }
  1900. if ($element_type == 'dolresource' || $element_type == 'resource') {
  1901. $classpath = 'resource/class';
  1902. $module='resource';
  1903. $subelement='dolresource';
  1904. }
  1905. if ($element_type == 'propaldet') {
  1906. $classpath = 'comm/propal/class';
  1907. $module='propal';
  1908. $subelement='propaleligne';
  1909. }
  1910. if ($element_type == 'order_supplier') {
  1911. $classpath = 'fourn/class';
  1912. $module='fournisseur';
  1913. $subelement='commandefournisseur';
  1914. $classfile='fournisseur.commande';
  1915. }
  1916. if ($element_type == 'invoice_supplier') {
  1917. $classpath = 'fourn/class';
  1918. $module='fournisseur';
  1919. $subelement='facturefournisseur';
  1920. $classfile='fournisseur.facture';
  1921. }
  1922. if (!isset($classfile)) $classfile = strtolower($subelement);
  1923. if (!isset($classname)) $classname = ucfirst($subelement);
  1924. if (!isset($classpath)) $classpath = $module.'/class';
  1925. $element_properties = array(
  1926. 'module' => $module,
  1927. 'classpath' => $classpath,
  1928. 'element' => $element,
  1929. 'subelement' => $subelement,
  1930. 'classfile' => $classfile,
  1931. 'classname' => $classname
  1932. );
  1933. return $element_properties;
  1934. }
  1935. /**
  1936. * Fetch an object from its id and element_type
  1937. * Inclusion of classes is automatic
  1938. *
  1939. * @param int $element_id Element id
  1940. * @param string $element_type Element type
  1941. * @param ref $element_ref Element ref (Use this if element_id but not both)
  1942. * @return int|object object || 0 || -1 if error
  1943. */
  1944. function fetchObjectByElement($element_id, $element_type, $element_ref='')
  1945. {
  1946. global $conf;
  1947. global $db,$conf;
  1948. $element_prop = getElementProperties($element_type);
  1949. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled)
  1950. {
  1951. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  1952. $objecttmp = new $element_prop['classname']($db);
  1953. $ret = $objecttmp->fetch($element_id, $element_ref);
  1954. if ($ret >= 0)
  1955. {
  1956. return $objecttmp;
  1957. }
  1958. }
  1959. return 0;
  1960. }
  1961. /**
  1962. * Convert an array with RGB value into hex RGB value.
  1963. * This is the opposite function of colorStringToArray
  1964. *
  1965. * @param array $arraycolor Array
  1966. * @param string $colorifnotfound Color code to return if entry not defined or not a RGB format
  1967. * @return string RGB hex value (without # before). For example: 'FF00FF', '01FF02'
  1968. * @see colorStringToArray
  1969. */
  1970. function colorArrayToHex($arraycolor,$colorifnotfound='888888')
  1971. {
  1972. if (! is_array($arraycolor)) return $colorifnotfound;
  1973. if (empty($arraycolor)) return $colorifnotfound;
  1974. return sprintf("%02s",dechex($arraycolor[0])).sprintf("%02s",dechex($arraycolor[1])).sprintf("%02s",dechex($arraycolor[2]));
  1975. }
  1976. /**
  1977. * Convert a string RGB value ('FFFFFF', '255,255,255') into an array RGB array(255,255,255).
  1978. * This is the opposite function of colorArrayToHex.
  1979. * If entry is already an array, return it.
  1980. *
  1981. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  1982. * @param array $colorifnotfound Color code array to return if entry not defined
  1983. * @return string RGB hex value (without # before). For example: FF00FF
  1984. * @see colorArrayToHex
  1985. */
  1986. function colorStringToArray($stringcolor,$colorifnotfound=array(88,88,88))
  1987. {
  1988. if (is_array($stringcolor)) return $stringcolor; // If already into correct output format, we return as is
  1989. $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);
  1990. if (! $tmp)
  1991. {
  1992. $tmp=explode(',',$stringcolor);
  1993. if (count($tmp) < 3) return $colorifnotfound;
  1994. return $tmp;
  1995. }
  1996. return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3]));
  1997. }
  1998. /**
  1999. * Applies the Cartesian product algorithm to an array
  2000. * Source: http://stackoverflow.com/a/15973172
  2001. *
  2002. * @param array $input Array of products
  2003. * @return array Array of combinations
  2004. */
  2005. function cartesianArray(array $input)
  2006. {
  2007. // filter out empty values
  2008. $input = array_filter($input);
  2009. $result = array(array());
  2010. foreach ($input as $key => $values) {
  2011. $append = array();
  2012. foreach($result as $product) {
  2013. foreach($values as $item) {
  2014. $product[$key] = $item;
  2015. $append[] = $product;
  2016. }
  2017. }
  2018. $result = $append;
  2019. }
  2020. return $result;
  2021. }
  2022. /**
  2023. * Get name of directory where the api_...class.php file is stored
  2024. *
  2025. * @param string $module Module name
  2026. * @return string Directory name
  2027. */
  2028. function getModuleDirForApiClass($module)
  2029. {
  2030. $moduledirforclass=$module;
  2031. if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i','',$moduledirforclass);
  2032. if ($module == 'contracts') {
  2033. $moduledirforclass = 'contrat';
  2034. }
  2035. elseif (in_array($module, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents'))) {
  2036. $moduledirforclass = 'api';
  2037. }
  2038. elseif ($module == 'contact' || $module == 'contacts' || $module == 'customer' || $module == 'thirdparty' || $module == 'thirdparties') {
  2039. $moduledirforclass = 'societe';
  2040. }
  2041. elseif ($module == 'propale' || $module == 'proposals') {
  2042. $moduledirforclass = 'comm/propal';
  2043. }
  2044. elseif ($module == 'agenda' || $module == 'agendaevents') {
  2045. $moduledirforclass = 'comm/action';
  2046. }
  2047. elseif ($module == 'adherent' || $module == 'members' || $module == 'memberstypes' || $module == 'subscriptions') {
  2048. $moduledirforclass = 'adherents';
  2049. }
  2050. elseif ($module == 'don' || $module == 'donations') {
  2051. $moduledirforclass = 'don';
  2052. }
  2053. elseif ($module == 'banque' || $module == 'bankaccounts') {
  2054. $moduledirforclass = 'compta/bank';
  2055. }
  2056. elseif ($module == 'category' || $module == 'categorie') {
  2057. $moduledirforclass = 'categories';
  2058. }
  2059. elseif ($module == 'order' || $module == 'orders') {
  2060. $moduledirforclass = 'commande';
  2061. }
  2062. elseif ($module == 'shipments') {
  2063. $moduledirforclass = 'expedition';
  2064. }
  2065. elseif ($module == 'facture' || $module == 'invoice' || $module == 'invoices') {
  2066. $moduledirforclass = 'compta/facture';
  2067. }
  2068. elseif ($module == 'products') {
  2069. $moduledirforclass = 'product';
  2070. }
  2071. elseif ($module == 'project' || $module == 'projects' || $module == 'tasks') {
  2072. $moduledirforclass = 'projet';
  2073. }
  2074. elseif ($module == 'task') {
  2075. $moduledirforclass = 'projet';
  2076. }
  2077. elseif ($module == 'stock' || $module == 'stockmovements' || $module == 'warehouses') {
  2078. $moduledirforclass = 'product/stock';
  2079. }
  2080. elseif ($module == 'supplierproposals' || $module == 'supplierproposal' || $module == 'supplier_proposal') {
  2081. $moduledirforclass = 'supplier_proposal';
  2082. }
  2083. elseif ($module == 'fournisseur' || $module == 'supplierinvoices' || $module == 'supplierorders') {
  2084. $moduledirforclass = 'fourn';
  2085. }
  2086. elseif ($module == 'expensereports') {
  2087. $moduledirforclass = 'expensereport';
  2088. }
  2089. elseif ($module == 'users') {
  2090. $moduledirforclass = 'user';
  2091. }
  2092. elseif ($module == 'ficheinter' || $module == 'interventions') {
  2093. $moduledirforclass = 'fichinter';
  2094. }
  2095. elseif ($module == 'tickets') {
  2096. $moduledirforclass = 'ticket';
  2097. }
  2098. return $moduledirforclass;
  2099. }
  2100. /*
  2101. * Return 2 hexa code randomly
  2102. *
  2103. * @param int $min Between 0 and 255
  2104. * @param int $max Between 0 and 255
  2105. * @return String Color string
  2106. */
  2107. function random_color_part($min=0,$max=255)
  2108. {
  2109. return str_pad( dechex( mt_rand( $min, $max) ), 2, '0', STR_PAD_LEFT);
  2110. }
  2111. /*
  2112. * Return hexadecimal color randomly
  2113. *
  2114. * @param int $min Between 0 and 255
  2115. * @param int $max Between 0 and 255
  2116. * @return String Color string
  2117. */
  2118. function random_color($min=0, $max=255)
  2119. {
  2120. return random_color_part($min, $max) . random_color_part($min, $max) . random_color_part($min, $max);
  2121. }
  2122. /**
  2123. * Function to format a value into a defined format for French administration (no thousand separator & decimal separator force to ',' with two decimals)
  2124. * Function used into accountancy FEC export
  2125. *
  2126. * @param float $amount Amount to format
  2127. * @return string Chain with formatted upright
  2128. * @see price2num() Format a numeric into a price for FEC files
  2129. */
  2130. function price2fec($amount)
  2131. {
  2132. global $conf;
  2133. // Clean parameters
  2134. if (empty($amount)) $amount=0; // To have a numeric value if amount not defined or = ''
  2135. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  2136. // Output decimal number by default
  2137. $nbdecimal = (empty($conf->global->ACCOUNTING_FEC_DECIMAL_LENGTH) ? 2 : $conf->global->ACCOUNTING_FEC_DECIMAL_LENGTH);
  2138. // Output separators by default
  2139. $dec = (empty($conf->global->ACCOUNTING_FEC_DECIMAL_SEPARATOR) ? ',' : $conf->global->ACCOUNTING_FEC_DECIMAL_SEPARATOR);
  2140. $thousand = (empty($conf->global->ACCOUNTING_FEC_THOUSAND_SEPARATOR) ? '' : $conf->global->ACCOUNTING_FEC_THOUSAND_SEPARATOR);
  2141. // Format number
  2142. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  2143. return $output;
  2144. }