functions2.lib.php 78 KB

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