functions2.lib.php 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600
  1. <?php
  2. /* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2008-2012 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  5. * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
  6. * Copyright (C) 2015 Ferran Marcet <fmarcet@2byte.es>
  7. * Copyright (C) 2015-2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  8. * Copyright (C) 2017 Juanjo Menent <jmenent@2byte.es>
  9. *
  10. * This program is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  22. * or see https://www.gnu.org/
  23. */
  24. /**
  25. * \file htdocs/core/lib/functions2.lib.php
  26. * \brief A set of functions for Dolibarr
  27. * This file contains all rare functions.
  28. */
  29. // Enable this line to trace path when function is called.
  30. //print xdebug_print_function_stack('Functions2.lib was called');exit;
  31. /**
  32. * Same function than javascript unescape() function but in PHP.
  33. *
  34. * @param string $source String to decode
  35. * @return string Unescaped string
  36. */
  37. function jsUnEscape($source)
  38. {
  39. $decodedStr = "";
  40. $pos = 0;
  41. $len = strlen($source);
  42. while ($pos < $len) {
  43. $charAt = substr($source, $pos, 1);
  44. if ($charAt == '%') {
  45. $pos++;
  46. $charAt = substr($source, $pos, 1);
  47. if ($charAt == 'u') {
  48. // we got a unicode character
  49. $pos++;
  50. $unicodeHexVal = substr($source, $pos, 4);
  51. $unicode = hexdec($unicodeHexVal);
  52. $entity = "&#".$unicode.';';
  53. $decodedStr .= utf8_encode($entity);
  54. $pos += 4;
  55. }
  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 tableforfield 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. return checkdnsrr($domain, "MX");
  467. }
  468. /**
  469. * Url string validation
  470. * <http[s]> :// [user[:pass]@] hostname [port] [/path] [?getquery] [anchor]
  471. *
  472. * @param string $url Url
  473. * @param int $http 1: verify http is provided, 0: not verify http
  474. * @param int $pass 1: verify user and pass is provided, 0: not verify user and pass
  475. * @param int $port 1: verify port is provided, 0: not verify port
  476. * @param int $path 1: verify a path is provided "/" or "/..." or "/.../", 0: not verify path
  477. * @param int $query 1: verify query is provided, 0: not verify query
  478. * @param int $anchor 1: verify anchor is provided, 0: not verify anchor
  479. * @return int 1=Check is OK, 0=Check is KO
  480. */
  481. function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0, $anchor = 0)
  482. {
  483. $ValidUrl = 0;
  484. $urlregex = '';
  485. // SCHEME
  486. if ($http) $urlregex .= "^(http:\/\/|https:\/\/)";
  487. // USER AND PASS
  488. if ($pass) $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)";
  489. // HOSTNAME OR IP
  490. //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*"; // x allowed (ex. http://localhost, http://routerlogin)
  491. //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)+"; // x.x
  492. $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*"; // x ou x.xx (2 x ou plus)
  493. //use only one of the above
  494. // PORT
  495. if ($port) $urlregex .= "(\:[0-9]{2,5})";
  496. // PATH
  497. if ($path) $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/";
  498. // GET Query
  499. if ($query) $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)";
  500. // ANCHOR
  501. if ($anchor) $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$";
  502. // check
  503. if (preg_match('/'.$urlregex.'/i', $url))
  504. {
  505. $ValidUrl = 1;
  506. }
  507. //print $urlregex.' - '.$url.' - '.$ValidUrl;
  508. return $ValidUrl;
  509. }
  510. /**
  511. * Check if VAT numero is valid (check done on syntax only, no database or remote access)
  512. *
  513. * @param Societe $company VAT number
  514. * @return int 1=Check is OK, 0=Check is KO
  515. */
  516. function isValidVATID($company)
  517. {
  518. if ($company->isInEEC()) // Syntax check rules for EEC countries
  519. {
  520. /* Disabled because some companies can have an address in Irland and a vat number in France.
  521. $vatprefix = $company->country_code;
  522. if ($vatprefix == 'GR') $vatprefix = '(EL|GR)';
  523. elseif ($vatprefix == 'MC') $vatprefix = 'FR'; // Monaco is using french VAT numbers
  524. else $vatprefix = preg_quote($vatprefix, '/');*/
  525. $vatprefix = '[a-zA-Z][a-zA-Z]';
  526. if (! preg_match('/^'.$vatprefix.'[a-zA-Z0-9\-\.]{5,14}$/i', str_replace(' ', '', $company->tva_intra)))
  527. {
  528. return 0;
  529. }
  530. }
  531. return 1;
  532. }
  533. /**
  534. * Clean an url string
  535. *
  536. * @param string $url Url
  537. * @param integer $http 1 = keep both http:// and https://, 0: remove http:// but not https://
  538. * @return string Cleaned url
  539. */
  540. function clean_url($url, $http = 1)
  541. {
  542. // Fixed by Matelli (see http://matelli.fr/showcases/patchs-dolibarr/fix-cleaning-url.html)
  543. // To include the minus sign in a char class, we must not escape it but put it at the end of the class
  544. // Also, there's no need of escape a dot sign in a class
  545. if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs))
  546. {
  547. $proto = $regs[1];
  548. $domain = $regs[2];
  549. $port = isset($regs[3]) ? $regs[3] : '';
  550. //print $url." -> ".$proto." - ".$domain." - ".$port;
  551. //$url = dol_string_nospecial(trim($url));
  552. $url = trim($url);
  553. // Si http: defini on supprime le http (Si https on ne supprime pas)
  554. $newproto = $proto;
  555. if ($http == 0)
  556. {
  557. if (preg_match('/^http:[\\/]+/i', $url))
  558. {
  559. $url = preg_replace('/^http:[\\/]+/i', '', $url);
  560. $newproto = '';
  561. }
  562. }
  563. // On passe le nom de domaine en minuscule
  564. $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain, '/').'/i', $newproto.strtolower($domain), $url);
  565. return $CleanUrl;
  566. }
  567. else return $url;
  568. }
  569. /**
  570. * Returns an email value with obfuscated parts.
  571. *
  572. * @param string $mail Email
  573. * @param string $replace Replacement character (defaul: *)
  574. * @param int $nbreplace Number of replacement character (default: 8)
  575. * @param int $nbdisplaymail Number of character unchanged (default: 4)
  576. * @param int $nbdisplaydomain Number of character unchanged of domain (default: 3)
  577. * @param bool $displaytld Display tld (default: true)
  578. * @return string Return email with hidden parts or '';
  579. */
  580. function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail = 4, $nbdisplaydomain = 3, $displaytld = true)
  581. {
  582. if (!isValidEmail($mail))return '';
  583. $tab = explode('@', $mail);
  584. $tab2 = explode('.', $tab[1]);
  585. $string_replace = '';
  586. $mail_name = $tab[0];
  587. $mail_domaine = $tab2[0];
  588. $mail_tld = '';
  589. $nbofelem = count($tab2);
  590. for ($i = 1; $i < $nbofelem && $displaytld; $i++)
  591. {
  592. $mail_tld .= '.'.$tab2[$i];
  593. }
  594. for ($i = 0; $i < $nbreplace; $i++) {
  595. $string_replace .= $replace;
  596. }
  597. if (strlen($mail_name) > $nbdisplaymail) {
  598. $mail_name = substr($mail_name, 0, $nbdisplaymail);
  599. }
  600. if (strlen($mail_domaine) > $nbdisplaydomain) {
  601. $mail_domaine = substr($mail_domaine, strlen($mail_domaine) - $nbdisplaydomain);
  602. }
  603. return $mail_name.$string_replace.$mail_domaine.$mail_tld;
  604. }
  605. /**
  606. * Return lines of an html table from an array
  607. * Used by array2table function only
  608. *
  609. * @param array $data Array of data
  610. * @param string $troptions Options for tr
  611. * @param string $tdoptions Options for td
  612. * @return string
  613. */
  614. function array2tr($data, $troptions = '', $tdoptions = '')
  615. {
  616. $text = '<tr '.$troptions.'>';
  617. foreach ($data as $key => $item) {
  618. $text .= '<td '.$tdoptions.'>'.$item.'</td>';
  619. }
  620. $text .= '</tr>';
  621. return $text;
  622. }
  623. /**
  624. * Return an html table from an array
  625. *
  626. * @param array $data Array of data
  627. * @param int $tableMarkup Table markup
  628. * @param string $tableoptions Options for table
  629. * @param string $troptions Options for tr
  630. * @param string $tdoptions Options for td
  631. * @return string
  632. */
  633. function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = '', $tdoptions = '')
  634. {
  635. $text = '';
  636. if ($tableMarkup) $text = '<table '.$tableoptions.'>';
  637. foreach ($data as $key => $item) {
  638. if (is_array($item)) {
  639. $text .= array2tr($item, $troptions, $tdoptions);
  640. } else {
  641. $text .= '<tr '.$troptions.'>';
  642. $text .= '<td '.$tdoptions.'>'.$key.'</td>';
  643. $text .= '<td '.$tdoptions.'>'.$item.'</td>';
  644. $text .= '</tr>';
  645. }
  646. }
  647. if ($tableMarkup) $text .= '</table>';
  648. return $text;
  649. }
  650. /**
  651. * Return last or next value for a mask (according to area we should not reset)
  652. *
  653. * @param DoliDB $db Database handler
  654. * @param string $mask Mask to use
  655. * @param string $table Table containing field with counter
  656. * @param string $field Field containing already used values of counter
  657. * @param string $where To add a filter on selection (for exemple to filter on invoice types)
  658. * @param Societe $objsoc The company that own the object we need a counter for
  659. * @param string $date Date to use for the {y},{m},{d} tags.
  660. * @param string $mode 'next' for next value or 'last' for last value
  661. * @param bool $bentityon Activate the entity filter. Default is true (for modules not compatible with multicompany)
  662. * @param User $objuser Object user we need data from.
  663. * @param int $forceentity Entity id to force
  664. * @return string New value (numeric) or error message
  665. */
  666. function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $date = '', $mode = 'next', $bentityon = true, $objuser = null, $forceentity = null)
  667. {
  668. global $conf,$user;
  669. if (! is_object($objsoc)) $valueforccc=$objsoc;
  670. elseif ($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=dol_string_unaccent($objsoc->code_fournisseur);
  671. else $valueforccc=dol_string_unaccent($objsoc->code_client);
  672. $sharetable = $table;
  673. if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function
  674. // Clean parameters
  675. if ($date == '') $date=dol_now(); // We use local year and month of PHP server to search numbers
  676. // but we should use local year and month of user
  677. // For debugging
  678. //dol_syslog("mask=".$mask, LOG_DEBUG);
  679. //include_once(DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php');
  680. //$mask='FA{yy}{mm}-{0000@99}';
  681. //$date=dol_mktime(12, 0, 0, 1, 1, 1900);
  682. //$date=dol_stringtotime('20130101');
  683. $hasglobalcounter = false;
  684. // Extract value for mask counter, mask raz and mask offset
  685. if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg))
  686. {
  687. $masktri = $reg[1].(!empty($reg[2]) ? $reg[2] : '').(!empty($reg[3]) ? $reg[3] : '');
  688. $maskcounter = $reg[1];
  689. $hasglobalcounter = true;
  690. }
  691. else
  692. {
  693. // setting some defaults so the rest of the code won't fail if there is a third party counter
  694. $masktri = '00000';
  695. $maskcounter = '00000';
  696. }
  697. $maskraz = -1;
  698. $maskoffset = 0;
  699. $resetEveryMonth = false;
  700. if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits';
  701. // Extract value for third party mask counter
  702. if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef))
  703. {
  704. $maskrefclient = $regClientRef[1].$regClientRef[2];
  705. $maskrefclient_maskclientcode = $regClientRef[1];
  706. $maskrefclient_maskcounter = $regClientRef[2];
  707. $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
  708. $maskrefclient_clientcode = substr($valueforccc, 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code where n is length in mask
  709. $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
  710. $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
  711. if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
  712. }
  713. else $maskrefclient = '';
  714. // fail if there is neither a global nor a third party counter
  715. if (!$hasglobalcounter && ($maskrefclient_maskcounter == ''))
  716. {
  717. return 'ErrorBadMask';
  718. }
  719. // Extract value for third party type
  720. if (preg_match('/\{(t+)\}/i', $mask, $regType))
  721. {
  722. $masktype = $regType[1];
  723. $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)
  724. $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
  725. }
  726. else
  727. {
  728. $masktype = '';
  729. $masktype_value = '';
  730. }
  731. // Extract value for user
  732. if (preg_match('/\{(u+)\}/i', $mask, $regType))
  733. {
  734. $lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  735. if (is_object($objuser)) $lastname = $objuser->lastname;
  736. $maskuser=$regType[1];
  737. $maskuser_value=substr($lastname, 0, dol_strlen($regType[1]));// get n first characters of user firstname (where n is length in mask)
  738. $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
  739. }
  740. else
  741. {
  742. $maskuser='';
  743. $maskuser_value='';
  744. }
  745. // Personalized field {XXX-1} à {XXX-9}
  746. $maskperso=array();
  747. $maskpersonew=array();
  748. $tmpmask=$mask;
  749. while (preg_match('/\{([A-Z]+)\-([1-9])\}/', $tmpmask, $regKey))
  750. {
  751. $maskperso[$regKey[1]]='{'.$regKey[1].'-'.$regKey[2].'}';
  752. $maskpersonew[$regKey[1]]=str_pad('', $regKey[2], '_', STR_PAD_RIGHT);
  753. $tmpmask=preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask);
  754. }
  755. if (strstr($mask, 'user_extra_'))
  756. {
  757. $start = "{user_extra_";
  758. $end = "\}";
  759. $extra= get_string_between($mask, "user_extra_", "}");
  760. if (!empty($user->array_options['options_'.$extra])) {
  761. $mask = preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
  762. }
  763. }
  764. $maskwithonlyymcode=$mask;
  765. $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $maskcounter, $maskwithonlyymcode);
  766. $maskwithonlyymcode=preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
  767. $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
  768. $maskwithonlyymcode=preg_replace('/\{(t+)\}/i', $masktype_value, $maskwithonlyymcode);
  769. $maskwithonlyymcode=preg_replace('/\{(u+)\}/i', $maskuser_value, $maskwithonlyymcode);
  770. foreach($maskperso as $key => $val)
  771. {
  772. $maskwithonlyymcode=preg_replace('/'.preg_quote($val, '/').'/i', $maskpersonew[$key], $maskwithonlyymcode);
  773. }
  774. $maskwithnocode=$maskwithonlyymcode;
  775. $maskwithnocode=preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
  776. $maskwithnocode=preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
  777. $maskwithnocode=preg_replace('/\{y\}/i', 'y', $maskwithnocode);
  778. $maskwithnocode=preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
  779. // Now maskwithnocode = 0000ddmmyyyyccc for example
  780. // and maskcounter = 0000 for example
  781. //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
  782. //var_dump($reg);
  783. // If an offset is asked
  784. if (! empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset=preg_replace('/^\+/', '', $reg[2]);
  785. if (! empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset=preg_replace('/^\+/', '', $reg[3]);
  786. // Define $sqlwhere
  787. $sqlwhere='';
  788. $yearoffset=0; // Use year of current $date by default
  789. $yearoffsettype=false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
  790. // If a restore to zero after a month is asked we check if there is already a value for this year.
  791. if (! empty($reg[2]) && preg_match('/^@/', $reg[2])) $yearoffsettype = preg_replace('/^@/', '', $reg[2]);
  792. if (! empty($reg[3]) && preg_match('/^@/', $reg[3])) $yearoffsettype = preg_replace('/^@/', '', $reg[3]);
  793. //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
  794. if (is_numeric($yearoffsettype) && $yearoffsettype >= 1)
  795. $maskraz=$yearoffsettype; // For backward compatibility
  796. elseif ($yearoffsettype === '0' || (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1))
  797. $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START;
  798. //print "maskraz=".$maskraz; // -1=no reset
  799. if ($maskraz > 0) { // A reset is required
  800. if ($maskraz == 99) {
  801. $maskraz = date('m', $date);
  802. $resetEveryMonth = true;
  803. }
  804. if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
  805. // Define posy, posm and reg
  806. if ($maskraz > 1) // if reset is not first month, we need month and year into mask
  807. {
  808. if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; }
  809. elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; }
  810. else return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
  811. if (dol_strlen($reg[$posy]) < 2) return 'ErrorCantUseRazWithYearOnOneDigit';
  812. }
  813. else // if reset is for a specific month in year, we need year
  814. {
  815. if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; }
  816. elseif (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; }
  817. elseif (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 0; }
  818. else return 'ErrorCantUseRazIfNoYearInMask';
  819. }
  820. // Define length
  821. $yearlen = $posy ?dol_strlen($reg[$posy]) : 0;
  822. $monthlen = $posm ?dol_strlen($reg[$posm]) : 0;
  823. // Define pos
  824. $yearpos = (dol_strlen($reg[1]) + 1);
  825. $monthpos = ($yearpos + $yearlen);
  826. if ($posy == 3 && $posm == 2) { // if month is before year
  827. $monthpos = (dol_strlen($reg[1]) + 1);
  828. $yearpos = ($monthpos + $monthlen);
  829. }
  830. //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
  831. // Define $yearcomp and $monthcomp (that will be use in the select where to search max number)
  832. $monthcomp = $maskraz;
  833. $yearcomp = 0;
  834. if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') // $yearoffsettype is - or +
  835. {
  836. $currentyear = date("Y", $date);
  837. $fiscaldate = dol_mktime('0', '0', '0', $maskraz, '1', $currentyear);
  838. $newyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear);
  839. $nextnewyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear + 1);
  840. //echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
  841. // If after or equal of current fiscal date
  842. if ($date >= $fiscaldate)
  843. {
  844. // If before of next new year date
  845. if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset = 1;
  846. }
  847. // If after or equal of current new year date
  848. elseif ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset = -1;
  849. }
  850. // For backward compatibility
  851. elseif (date("m", $date) < $maskraz && empty($resetEveryMonth)) { $yearoffset = -1; } // If current month lower that month of return to zero, year is previous year
  852. if ($yearlen == 4) $yearcomp = sprintf("%04d", date("Y", $date) + $yearoffset);
  853. elseif ($yearlen == 2) $yearcomp = sprintf("%02d", date("y", $date) + $yearoffset);
  854. elseif ($yearlen == 1) $yearcomp = substr(date("y", $date), 2, 1) + $yearoffset;
  855. 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)
  856. {
  857. if ($yearlen == 4) $yearcomp1 = sprintf("%04d", date("Y", $date) + $yearoffset + 1);
  858. elseif ($yearlen == 2) $yearcomp1 = sprintf("%02d", date("y", $date) + $yearoffset + 1);
  859. $sqlwhere .= "(";
  860. $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
  861. $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
  862. $sqlwhere .= " OR";
  863. $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'";
  864. $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
  865. $sqlwhere .= ')';
  866. }
  867. elseif ($resetEveryMonth)
  868. {
  869. $sqlwhere .= "(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
  870. $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
  871. }
  872. else // reset is done on january
  873. {
  874. $sqlwhere .= '(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
  875. }
  876. }
  877. //print "sqlwhere=".$sqlwhere." yearcomp=".$yearcomp."<br>\n"; // sqlwhere and yearcomp defined only if we ask a reset
  878. //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
  879. // Define $sqlstring
  880. if (function_exists('mb_strrpos'))
  881. {
  882. $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 'UTF-8');
  883. }
  884. else
  885. {
  886. $posnumstart = strrpos($maskwithnocode, $maskcounter);
  887. } // Pos of counter in final string (from 0 to ...)
  888. if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
  889. $sqlstring = 'SUBSTRING('.$field.', '.($posnumstart + 1).', '.dol_strlen($maskcounter).')';
  890. // Define $maskLike
  891. $maskLike = dol_string_nospecial($mask);
  892. $maskLike = str_replace("%", "_", $maskLike);
  893. // Replace protected special codes with matching number of _ as wild card caracter
  894. $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
  895. $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
  896. $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
  897. $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
  898. $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
  899. $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskLike);
  900. if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
  901. if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
  902. if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
  903. foreach ($maskperso as $key => $val)
  904. {
  905. $maskLike = str_replace(dol_string_nospecial($maskperso[$key]), $maskpersonew[$key], $maskLike);
  906. }
  907. // Get counter in database
  908. $counter = 0;
  909. $sql = "SELECT MAX(".$sqlstring.") as val";
  910. $sql .= " FROM ".MAIN_DB_PREFIX.$table;
  911. $sql .= " WHERE ".$field." LIKE '".$maskLike."'";
  912. $sql .= " AND ".$field." NOT LIKE '(PROV%)'";
  913. if ($bentityon) // only if entity enable
  914. $sql .= " AND entity IN (".getEntity($sharetable).")";
  915. elseif (!empty($forceentity))
  916. $sql .= " AND entity IN (".$forceentity.")";
  917. if ($where) $sql .= $where;
  918. if ($sqlwhere) $sql .= ' AND '.$sqlwhere;
  919. //print $sql.'<br>';
  920. dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
  921. $resql = $db->query($sql);
  922. if ($resql)
  923. {
  924. $obj = $db->fetch_object($resql);
  925. $counter = $obj->val;
  926. }
  927. else dol_print_error($db);
  928. // Check if we must force counter to maskoffset
  929. if (empty($counter)) $counter = $maskoffset;
  930. elseif (preg_match('/[^0-9]/i', $counter))
  931. {
  932. $counter = 0;
  933. dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
  934. }
  935. elseif ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter = $maskoffset;
  936. if ($mode == 'last') // We found value for counter = last counter value. Now need to get corresponding ref of invoice.
  937. {
  938. $counterpadded = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
  939. // Define $maskLike
  940. $maskLike = dol_string_nospecial($mask);
  941. $maskLike = str_replace("%", "_", $maskLike);
  942. // Replace protected special codes with matching number of _ as wild card caracter
  943. $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
  944. $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
  945. $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
  946. $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
  947. $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
  948. $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), $counterpadded, $maskLike);
  949. if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
  950. if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
  951. if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
  952. $ref = '';
  953. $sql = "SELECT ".$field." as ref";
  954. $sql .= " FROM ".MAIN_DB_PREFIX.$table;
  955. $sql .= " WHERE ".$field." LIKE '".$maskLike."'";
  956. $sql .= " AND ".$field." NOT LIKE '%PROV%'";
  957. if ($bentityon) // only if entity enable
  958. $sql .= " AND entity IN (".getEntity($sharetable).")";
  959. elseif (!empty($forceentity))
  960. $sql .= " AND entity IN (".$forceentity.")";
  961. if ($where) $sql .= $where;
  962. if ($sqlwhere) $sql .= ' AND '.$sqlwhere;
  963. dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
  964. $resql = $db->query($sql);
  965. if ($resql)
  966. {
  967. $obj = $db->fetch_object($resql);
  968. if ($obj) $ref = $obj->ref;
  969. }
  970. else dol_print_error($db);
  971. $numFinal = $ref;
  972. }
  973. elseif ($mode == 'next')
  974. {
  975. $counter++;
  976. // If value for $counter has a length higher than $maskcounter chars
  977. if ($counter >= pow(10, dol_strlen($maskcounter)))
  978. {
  979. $counter = 'ErrorMaxNumberReachForThisMask';
  980. }
  981. if (!empty($maskrefclient_maskcounter))
  982. {
  983. //print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n<br>";
  984. // Define $sqlstring
  985. $maskrefclient_posnumstart = strpos($maskwithnocode, $maskrefclient_maskcounter, strpos($maskwithnocode, $maskrefclient)); // Pos of counter in final string (from 0 to ...)
  986. if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask';
  987. $maskrefclient_sqlstring = 'SUBSTRING('.$field.', '.($maskrefclient_posnumstart + 1).', '.dol_strlen($maskrefclient_maskcounter).')';
  988. //print "x".$sqlstring;
  989. // Define $maskrefclient_maskLike
  990. $maskrefclient_maskLike = dol_string_nospecial($mask);
  991. $maskrefclient_maskLike = str_replace("%", "_", $maskrefclient_maskLike);
  992. // Replace protected special codes with matching number of _ as wild card caracter
  993. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'), '____', $maskrefclient_maskLike);
  994. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'), '__', $maskrefclient_maskLike);
  995. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'), '_', $maskrefclient_maskLike);
  996. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'), '__', $maskrefclient_maskLike);
  997. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'), '__', $maskrefclient_maskLike);
  998. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskrefclient_maskLike);
  999. $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), $maskrefclient_clientcode.str_pad("", dol_strlen($maskrefclient_maskcounter), "_"), $maskrefclient_maskLike);
  1000. // Get counter in database
  1001. $maskrefclient_counter = 0;
  1002. $maskrefclient_sql = "SELECT MAX(".$maskrefclient_sqlstring.") as val";
  1003. $maskrefclient_sql .= " FROM ".MAIN_DB_PREFIX.$table;
  1004. //$sql.= " WHERE ".$field." not like '(%'";
  1005. $maskrefclient_sql .= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
  1006. if ($bentityon) // only if entity enable
  1007. $maskrefclient_sql .= " AND entity IN (".getEntity($sharetable).")";
  1008. elseif (!empty($forceentity))
  1009. $sql .= " AND entity IN (".$forceentity.")";
  1010. if ($where) $maskrefclient_sql .= $where; //use the same optional where as general mask
  1011. if ($sqlwhere) $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask
  1012. $maskrefclient_sql .= ' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode, $maskrefclient) + 1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
  1013. dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
  1014. $maskrefclient_resql = $db->query($maskrefclient_sql);
  1015. if ($maskrefclient_resql)
  1016. {
  1017. $maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
  1018. $maskrefclient_counter = $maskrefclient_obj->val;
  1019. }
  1020. else dol_print_error($db);
  1021. if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) $maskrefclient_counter = $maskrefclient_maskoffset;
  1022. $maskrefclient_counter++;
  1023. }
  1024. // Build numFinal
  1025. $numFinal = $mask;
  1026. // We replace special codes except refclient
  1027. if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') // yearoffsettype is - or +, so we don't want current year
  1028. {
  1029. $numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date) + $yearoffset, $numFinal);
  1030. $numFinal = preg_replace('/\{yy\}/i', date("y", $date) + $yearoffset, $numFinal);
  1031. $numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1) + $yearoffset, $numFinal);
  1032. }
  1033. else // we want yyyy to be current year
  1034. {
  1035. $numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date), $numFinal);
  1036. $numFinal = preg_replace('/\{yy\}/i', date("y", $date), $numFinal);
  1037. $numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1), $numFinal);
  1038. }
  1039. $numFinal = preg_replace('/\{mm\}/i', date("m", $date), $numFinal);
  1040. $numFinal = preg_replace('/\{dd\}/i', date("d", $date), $numFinal);
  1041. // Now we replace the counter
  1042. $maskbefore = '{'.$masktri.'}';
  1043. $maskafter = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
  1044. //print 'x'.$maskbefore.'-'.$maskafter.'y';
  1045. $numFinal = str_replace($maskbefore, $maskafter, $numFinal);
  1046. // Now we replace the refclient
  1047. if ($maskrefclient)
  1048. {
  1049. //print "maskrefclient=".$maskrefclient." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskrefclient_clientcode=".$maskrefclient_clientcode."\n<br>";exit;
  1050. $maskrefclient_maskbefore='{'.$maskrefclient.'}';
  1051. $maskrefclient_maskafter=$maskrefclient_clientcode.str_pad($maskrefclient_counter, dol_strlen($maskrefclient_maskcounter), "0", STR_PAD_LEFT);
  1052. $numFinal = str_replace($maskrefclient_maskbefore, $maskrefclient_maskafter, $numFinal);
  1053. }
  1054. // Now we replace the type
  1055. if ($masktype)
  1056. {
  1057. $masktype_maskbefore='{'.$masktype.'}';
  1058. $masktype_maskafter=$masktype_value;
  1059. $numFinal = str_replace($masktype_maskbefore, $masktype_maskafter, $numFinal);
  1060. }
  1061. // Now we replace the user
  1062. if ($maskuser)
  1063. {
  1064. $maskuser_maskbefore='{'.$maskuser.'}';
  1065. $maskuser_maskafter=$maskuser_value;
  1066. $numFinal = str_replace($maskuser_maskbefore, $maskuser_maskafter, $numFinal);
  1067. }
  1068. }
  1069. dol_syslog("functions2::get_next_value return ".$numFinal, LOG_DEBUG);
  1070. return $numFinal;
  1071. }
  1072. /**
  1073. * Get string between
  1074. *
  1075. * @param string $string String to test
  1076. * @param int $start Value for start
  1077. * @param int $end Value for end
  1078. * @return string Return part of string
  1079. */
  1080. function get_string_between($string, $start, $end)
  1081. {
  1082. $string = " ".$string;
  1083. $ini = strpos($string, $start);
  1084. if ($ini == 0) return "";
  1085. $ini += strlen($start);
  1086. $len = strpos($string, $end, $ini) - $ini;
  1087. return substr($string, $ini, $len);
  1088. }
  1089. /**
  1090. * Check value
  1091. *
  1092. * @param string $mask Mask to use
  1093. * @param string $value Value
  1094. * @return int|string <0 or error string if KO, 0 if OK
  1095. */
  1096. function check_value($mask, $value)
  1097. {
  1098. $result=0;
  1099. $hasglobalcounter=false;
  1100. // Extract value for mask counter, mask raz and mask offset
  1101. if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $mask, $reg))
  1102. {
  1103. $masktri=$reg[1].(isset($reg[2])?$reg[2]:'').(isset($reg[3])?$reg[3]:'');
  1104. $maskcounter=$reg[1];
  1105. $hasglobalcounter=true;
  1106. }
  1107. else
  1108. {
  1109. // setting some defaults so the rest of the code won't fail if there is a third party counter
  1110. $masktri='00000';
  1111. $maskcounter='00000';
  1112. }
  1113. $maskraz=-1;
  1114. $maskoffset=0;
  1115. if (dol_strlen($maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
  1116. // Extract value for third party mask counter
  1117. if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef))
  1118. {
  1119. $maskrefclient=$regClientRef[1].$regClientRef[2];
  1120. $maskrefclient_maskclientcode=$regClientRef[1];
  1121. $maskrefclient_maskcounter=$regClientRef[2];
  1122. $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset
  1123. $maskrefclient_clientcode=substr('', 0, dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code to form maskrefclient_clientcode
  1124. $maskrefclient_clientcode=str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
  1125. $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
  1126. if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
  1127. }
  1128. else $maskrefclient='';
  1129. // fail if there is neither a global nor a third party counter
  1130. if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
  1131. {
  1132. return 'ErrorBadMask';
  1133. }
  1134. $maskwithonlyymcode=$mask;
  1135. $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $maskcounter, $maskwithonlyymcode);
  1136. $maskwithonlyymcode=preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
  1137. $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
  1138. $maskwithnocode=$maskwithonlyymcode;
  1139. $maskwithnocode=preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
  1140. $maskwithnocode=preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
  1141. $maskwithnocode=preg_replace('/\{y\}/i', 'y', $maskwithnocode);
  1142. $maskwithnocode=preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
  1143. // Now maskwithnocode = 0000ddmmyyyyccc for example
  1144. // and maskcounter = 0000 for example
  1145. //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
  1146. // If an offset is asked
  1147. if (! empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset=preg_replace('/^\+/', '', $reg[2]);
  1148. if (! empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset=preg_replace('/^\+/', '', $reg[3]);
  1149. // Define $sqlwhere
  1150. // If a restore to zero after a month is asked we check if there is already a value for this year.
  1151. if (! empty($reg[2]) && preg_match('/^@/', $reg[2])) $maskraz=preg_replace('/^@/', '', $reg[2]);
  1152. if (! empty($reg[3]) && preg_match('/^@/', $reg[3])) $maskraz=preg_replace('/^@/', '', $reg[3]);
  1153. if ($maskraz >= 0)
  1154. {
  1155. if ($maskraz == 99) {
  1156. $maskraz = date('m');
  1157. $resetEveryMonth = true;
  1158. }
  1159. if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
  1160. // Define reg
  1161. if ($maskraz > 1 && ! preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
  1162. if ($maskraz <= 1 && ! preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazIfNoYearInMask';
  1163. //print "x".$maskwithonlyymcode." ".$maskraz;
  1164. }
  1165. //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
  1166. // Check we have a number in ($posnumstart+1).', '.dol_strlen($maskcounter)
  1167. //
  1168. // Check length
  1169. $len = dol_strlen($maskwithnocode);
  1170. if (dol_strlen($value) != $len) $result = -1;
  1171. // Define $maskLike
  1172. /* seems not used
  1173. $maskLike = dol_string_nospecial($mask);
  1174. $maskLike = str_replace("%","_",$maskLike);
  1175. // Replace protected special codes with matching number of _ as wild card caracter
  1176. $maskLike = str_replace(dol_string_nospecial('{yyyy}'),'____',$maskLike);
  1177. $maskLike = str_replace(dol_string_nospecial('{yy}'),'__',$maskLike);
  1178. $maskLike = str_replace(dol_string_nospecial('{y}'),'_',$maskLike);
  1179. $maskLike = str_replace(dol_string_nospecial('{mm}'),'__',$maskLike);
  1180. $maskLike = str_replace(dol_string_nospecial('{dd}'),'__',$maskLike);
  1181. $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskLike);
  1182. if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",strlen($maskrefclient),"_"),$maskLike);
  1183. */
  1184. dol_syslog("functions2::check_value result=".$result, LOG_DEBUG);
  1185. return $result;
  1186. }
  1187. /**
  1188. * Convert a binary data to string that represent hexadecimal value
  1189. *
  1190. * @param string $bin Value to convert
  1191. * @param boolean $pad Add 0
  1192. * @param boolean $upper Convert to tupper
  1193. * @return string x
  1194. */
  1195. function binhex($bin, $pad = false, $upper = false)
  1196. {
  1197. $last = dol_strlen($bin) - 1;
  1198. for ($i = 0; $i <= $last; $i++) { $x += $bin[$last - $i] * pow(2, $i); }
  1199. $x = dechex($x);
  1200. if ($pad) { while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) { $x = "0$x"; } }
  1201. if ($upper) { $x = strtoupper($x); }
  1202. return $x;
  1203. }
  1204. /**
  1205. * Convert an hexadecimal string into a binary string
  1206. *
  1207. * @param string $hexa Hexadecimal string to convert (example: 'FF')
  1208. * @return string bin
  1209. */
  1210. function hexbin($hexa)
  1211. {
  1212. $bin = '';
  1213. $strLength = dol_strlen($hexa);
  1214. for ($i = 0; $i < $strLength; $i++)
  1215. {
  1216. $bin .= str_pad(decbin(hexdec($hexa[$i])), 4, '0', STR_PAD_LEFT);
  1217. }
  1218. return $bin;
  1219. }
  1220. /**
  1221. * Retourne le numero de la semaine par rapport a une date
  1222. *
  1223. * @param string $time Date au format 'timestamp'
  1224. * @return string Number of week
  1225. */
  1226. function numero_semaine($time)
  1227. {
  1228. $stime = strftime('%Y-%m-%d', $time);
  1229. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg))
  1230. {
  1231. // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS'
  1232. $annee = $reg[1];
  1233. $mois = $reg[2];
  1234. $jour = $reg[3];
  1235. }
  1236. /*
  1237. * Norme ISO-8601:
  1238. * - 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.
  1239. * - La majorite des annees ont 52 semaines mais les annees qui commence un jeudi et les annees bissextiles commencant un mercredi en possede 53.
  1240. * - Le 1er jour de la semaine est le Lundi
  1241. */
  1242. // Definition du Jeudi de la semaine
  1243. if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) // Dimanche
  1244. $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60;
  1245. elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) // du Lundi au Mercredi
  1246. $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60;
  1247. elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) // du Vendredi au Samedi
  1248. $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60;
  1249. else // Jeudi
  1250. $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee);
  1251. // Definition du premier Jeudi de l'annee
  1252. if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 0) // Dimanche
  1253. {
  1254. $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + 4 * 24 * 60 * 60;
  1255. }
  1256. elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) < 4) // du Lundi au Mercredi
  1257. {
  1258. $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;
  1259. }
  1260. elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) > 4) // du Vendredi au Samedi
  1261. {
  1262. $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;
  1263. }
  1264. else // Jeudi
  1265. {
  1266. $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine));
  1267. }
  1268. // Definition du numero de semaine: nb de jours entre "premier Jeudi de l'annee" et "Jeudi de la semaine";
  1269. $numeroSemaine = (
  1270. (
  1271. date("z", mktime(12, 0, 0, date("m", $jeudiSemaine), date("d", $jeudiSemaine), date("Y", $jeudiSemaine)))
  1272. -
  1273. date("z", mktime(12, 0, 0, date("m", $premierJeudiAnnee), date("d", $premierJeudiAnnee), date("Y", $premierJeudiAnnee)))
  1274. ) / 7
  1275. ) + 1;
  1276. // Cas particulier de la semaine 53
  1277. if ($numeroSemaine == 53)
  1278. {
  1279. // Les annees qui commence un Jeudi et les annees bissextiles commencant un Mercredi en possede 53
  1280. 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))
  1281. {
  1282. $numeroSemaine = 53;
  1283. }
  1284. else
  1285. {
  1286. $numeroSemaine = 1;
  1287. }
  1288. }
  1289. //echo $jour."-".$mois."-".$annee." (".date("d-m-Y",$premierJeudiAnnee)." - ".date("d-m-Y",$jeudiSemaine).") -> ".$numeroSemaine."<BR>";
  1290. return sprintf("%02d", $numeroSemaine);
  1291. }
  1292. /**
  1293. * Convertit une masse d'une unite vers une autre unite
  1294. *
  1295. * @param float $weight Masse a convertir
  1296. * @param int $from_unit Unite originale en puissance de 10
  1297. * @param int $to_unit Nouvelle unite en puissance de 10
  1298. * @return float Masse convertie
  1299. */
  1300. function weight_convert($weight, &$from_unit, $to_unit)
  1301. {
  1302. /* Pour convertire 320 gr en Kg appeler
  1303. * $f = -3
  1304. * weigh_convert(320, $f, 0) retournera 0.32
  1305. *
  1306. */
  1307. while ($from_unit <> $to_unit)
  1308. {
  1309. if ($from_unit > $to_unit)
  1310. {
  1311. $weight = $weight * 10;
  1312. $from_unit = $from_unit - 1;
  1313. $weight = weight_convert($weight, $from_unit, $to_unit);
  1314. }
  1315. if ($from_unit < $to_unit)
  1316. {
  1317. $weight = $weight / 10;
  1318. $from_unit = $from_unit + 1;
  1319. $weight = weight_convert($weight, $from_unit, $to_unit);
  1320. }
  1321. }
  1322. return $weight;
  1323. }
  1324. /**
  1325. * Save personnal parameter
  1326. *
  1327. * @param DoliDB $db Handler database
  1328. * @param Conf $conf Object conf
  1329. * @param User $user Object user
  1330. * @param array $tab Array (key=>value) with all parameters to save
  1331. * @return int <0 if KO, >0 if OK
  1332. *
  1333. * @see dolibarr_get_const(), dolibarr_set_const(), dolibarr_del_const()
  1334. */
  1335. function dol_set_user_param($db, $conf, &$user, $tab)
  1336. {
  1337. // Verification parametres
  1338. if (count($tab) < 1) return -1;
  1339. $db->begin();
  1340. // We remove old parameters for all keys in $tab
  1341. $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param";
  1342. $sql .= " WHERE fk_user = ".$user->id;
  1343. $sql .= " AND entity = ".$conf->entity;
  1344. $sql .= " AND param in (";
  1345. $i = 0;
  1346. foreach ($tab as $key => $value)
  1347. {
  1348. if ($i > 0) $sql .= ',';
  1349. $sql .= "'".$db->escape($key)."'";
  1350. $i++;
  1351. }
  1352. $sql .= ")";
  1353. dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
  1354. $resql = $db->query($sql);
  1355. if (!$resql)
  1356. {
  1357. dol_print_error($db);
  1358. $db->rollback();
  1359. return -1;
  1360. }
  1361. foreach ($tab as $key => $value)
  1362. {
  1363. // Set new parameters
  1364. if ($value)
  1365. {
  1366. $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,entity,param,value)";
  1367. $sql .= " VALUES (".$user->id.",".$conf->entity.",";
  1368. $sql .= " '".$db->escape($key)."','".$db->escape($value)."')";
  1369. dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
  1370. $result = $db->query($sql);
  1371. if (!$result)
  1372. {
  1373. dol_print_error($db);
  1374. $db->rollback();
  1375. return -1;
  1376. }
  1377. $user->conf->$key = $value;
  1378. //print "key=".$key." user->conf->key=".$user->conf->$key;
  1379. }
  1380. else
  1381. {
  1382. unset($user->conf->$key);
  1383. }
  1384. }
  1385. $db->commit();
  1386. return 1;
  1387. }
  1388. /**
  1389. * Returns formated reduction
  1390. *
  1391. * @param int $reduction Reduction percentage
  1392. * @param Translate $langs Output language
  1393. * @return string Formated reduction
  1394. */
  1395. function dol_print_reduction($reduction, $langs)
  1396. {
  1397. $string = '';
  1398. if ($reduction == 100)
  1399. {
  1400. $string = $langs->transnoentities("Offered");
  1401. }
  1402. else
  1403. {
  1404. $string = vatrate($reduction, true);
  1405. }
  1406. return $string;
  1407. }
  1408. /**
  1409. * Return OS version.
  1410. * Note that PHP_OS returns only OS (not version) and OS PHP was built on, not necessarly OS PHP runs on.
  1411. *
  1412. * @param string $option Option string
  1413. * @return string OS version
  1414. */
  1415. function version_os($option = '')
  1416. {
  1417. if ($option == 'smr') $osversion = php_uname('s').' '.php_uname('m').' '.php_uname('r');
  1418. else $osversion = php_uname();
  1419. return $osversion;
  1420. }
  1421. /**
  1422. * Return PHP version
  1423. *
  1424. * @return string PHP version
  1425. * @see versionphparray()
  1426. */
  1427. function version_php()
  1428. {
  1429. return phpversion();
  1430. }
  1431. /**
  1432. * Return Dolibarr version
  1433. *
  1434. * @return string Dolibarr version
  1435. * @see versiondolibarrarray()
  1436. */
  1437. function version_dolibarr()
  1438. {
  1439. return DOL_VERSION;
  1440. }
  1441. /**
  1442. * Return web server version
  1443. *
  1444. * @return string Web server version
  1445. */
  1446. function version_webserver()
  1447. {
  1448. return $_SERVER["SERVER_SOFTWARE"];
  1449. }
  1450. /**
  1451. * Return list of activated modules usable for document generation
  1452. *
  1453. * @param DoliDB $db Database handler
  1454. * @param string $type Type of models (company, invoice, ...)
  1455. * @param int $maxfilenamelength Max length of value to show
  1456. * @return mixed 0 if no module is activated, or array(key=>label). For modules that need directory scan, key is completed with ":filename".
  1457. */
  1458. function getListOfModels($db, $type, $maxfilenamelength = 0)
  1459. {
  1460. global $conf,$langs;
  1461. $liste=array();
  1462. $found=0;
  1463. $dirtoscan='';
  1464. $sql = "SELECT nom as id, nom as doc_template_name, libelle as label, description as description";
  1465. $sql.= " FROM ".MAIN_DB_PREFIX."document_model";
  1466. $sql.= " WHERE type = '".$type."'";
  1467. $sql.= " AND entity IN (0,".$conf->entity.")";
  1468. $sql.= " ORDER BY description DESC";
  1469. dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG);
  1470. $resql = $db->query($sql);
  1471. if ($resql)
  1472. {
  1473. $num = $db->num_rows($resql);
  1474. $i = 0;
  1475. while ($i < $num)
  1476. {
  1477. $found=1;
  1478. $obj = $db->fetch_object($resql);
  1479. // If this generation module needs to scan a directory, then description field is filled
  1480. // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...).
  1481. if (! empty($obj->description)) // A list of directories to scan is defined
  1482. {
  1483. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1484. $const=$obj->description;
  1485. //irtoscan.=($dirtoscan?',':'').preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
  1486. $dirtoscan= preg_replace('/[\r\n]+/', ',', trim($conf->global->$const));
  1487. $listoffiles=array();
  1488. // Now we add models found in directories scanned
  1489. $listofdir=explode(',', $dirtoscan);
  1490. foreach($listofdir as $key=>$tmpdir)
  1491. {
  1492. $tmpdir=trim($tmpdir);
  1493. $tmpdir=preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  1494. if (! $tmpdir) { unset($listofdir[$key]); continue; }
  1495. if (is_dir($tmpdir))
  1496. {
  1497. // all type of template is allowed
  1498. $tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
  1499. if (count($tmpfiles)) $listoffiles=array_merge($listoffiles, $tmpfiles);
  1500. }
  1501. }
  1502. if (count($listoffiles))
  1503. {
  1504. foreach($listoffiles as $record)
  1505. {
  1506. $max=($maxfilenamelength?$maxfilenamelength:28);
  1507. $liste[$obj->id.':'.$record['fullname']]=dol_trunc($record['name'], $max, 'middle');
  1508. }
  1509. }
  1510. else
  1511. {
  1512. $liste[0]=$obj->label.': '.$langs->trans("None");
  1513. }
  1514. }
  1515. else
  1516. {
  1517. if ($type == 'member' && $obj->doc_template_name == 'standard') // Special case, if member template, we add variant per format
  1518. {
  1519. global $_Avery_Labels;
  1520. include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
  1521. foreach($_Avery_Labels as $key => $val)
  1522. {
  1523. $liste[$obj->id.':'.$key]=($obj->label?$obj->label:$obj->doc_template_name).' '.$val['name'];
  1524. }
  1525. }
  1526. else // Common usage
  1527. {
  1528. $liste[$obj->id]=$obj->label?$obj->label:$obj->doc_template_name;
  1529. }
  1530. }
  1531. $i++;
  1532. }
  1533. }
  1534. else
  1535. {
  1536. dol_print_error($db);
  1537. return -1;
  1538. }
  1539. if ($found) return $liste;
  1540. else return 0;
  1541. }
  1542. /**
  1543. * This function evaluates a string that should be a valid IPv4
  1544. * 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.
  1545. *
  1546. * @param string $ip IP Address
  1547. * @return int 0 if not valid or reserved range, 1 if valid and public IP, 2 if valid and private range IP
  1548. */
  1549. function is_ip($ip)
  1550. {
  1551. // First we test if it is a valid IPv4
  1552. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  1553. // Then we test if it is a private range
  1554. if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
  1555. // Then we test if it is a reserved range
  1556. if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
  1557. return 1;
  1558. }
  1559. return 0;
  1560. }
  1561. /**
  1562. * Build a login from lastname, firstname
  1563. *
  1564. * @param string $lastname Lastname
  1565. * @param string $firstname Firstname
  1566. * @return string Login
  1567. */
  1568. function dol_buildlogin($lastname, $firstname)
  1569. {
  1570. $login = strtolower(dol_string_unaccent($firstname));
  1571. $login .= ($login ? '.' : '');
  1572. $login .= strtolower(dol_string_unaccent($lastname));
  1573. $login = dol_string_nospecial($login, ''); // For special names
  1574. return $login;
  1575. }
  1576. /**
  1577. * Return array to use for SoapClient constructor
  1578. *
  1579. * @return array
  1580. */
  1581. function getSoapParams()
  1582. {
  1583. global $conf;
  1584. $params = array();
  1585. $proxyuse = (empty($conf->global->MAIN_PROXY_USE) ?false:true);
  1586. $proxyhost = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_HOST);
  1587. $proxyport = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_PORT);
  1588. $proxyuser = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_USER);
  1589. $proxypass = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_PASS);
  1590. $timeout = (empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 10 : $conf->global->MAIN_USE_CONNECT_TIMEOUT); // Connection timeout
  1591. $response_timeout = (empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT); // Response timeout
  1592. //print extension_loaded('soap');
  1593. if ($proxyuse)
  1594. {
  1595. $params = array('connection_timeout'=>$timeout,
  1596. 'response_timeout'=>$response_timeout,
  1597. 'proxy_use' => 1,
  1598. 'proxy_host' => $proxyhost,
  1599. 'proxy_port' => $proxyport,
  1600. 'proxy_login' => $proxyuser,
  1601. 'proxy_password' => $proxypass,
  1602. 'trace' => 1
  1603. );
  1604. }
  1605. else
  1606. {
  1607. $params = array('connection_timeout'=>$timeout,
  1608. 'response_timeout'=>$response_timeout,
  1609. 'proxy_use' => 0,
  1610. 'proxy_host' => false,
  1611. 'proxy_port' => false,
  1612. 'proxy_login' => false,
  1613. 'proxy_password' => false,
  1614. 'trace' => 1
  1615. );
  1616. }
  1617. return $params;
  1618. }
  1619. /**
  1620. * Return link url to an object
  1621. *
  1622. * @param int $objectid Id of record
  1623. * @param string $objecttype Type of object ('invoice', 'order', 'expedition_bon', ...)
  1624. * @param int $withpicto Picto to show
  1625. * @param string $option More options
  1626. * @return string URL of link to object id/type
  1627. */
  1628. function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '')
  1629. {
  1630. global $db, $conf, $langs;
  1631. $ret = '';
  1632. // Parse element/subelement (ex: project_task)
  1633. $module = $element = $subelement = $objecttype;
  1634. if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
  1635. {
  1636. $module = $element = $regs[1];
  1637. $subelement = $regs[2];
  1638. }
  1639. // Generic case for $classpath
  1640. $classpath = $element.'/class';
  1641. // Special cases, to work with non standard path
  1642. if ($objecttype == 'facture' || $objecttype == 'invoice') {
  1643. $classpath = 'compta/facture/class';
  1644. $module='facture';
  1645. $subelement='facture';
  1646. }
  1647. elseif ($objecttype == 'commande' || $objecttype == 'order') {
  1648. $classpath = 'commande/class';
  1649. $module='commande';
  1650. $subelement='commande';
  1651. }
  1652. elseif ($objecttype == 'propal') {
  1653. $classpath = 'comm/propal/class';
  1654. }
  1655. elseif ($objecttype == 'supplier_proposal') {
  1656. $classpath = 'supplier_proposal/class';
  1657. }
  1658. elseif ($objecttype == 'shipping') {
  1659. $classpath = 'expedition/class';
  1660. $subelement = 'expedition';
  1661. $module = 'expedition_bon';
  1662. }
  1663. elseif ($objecttype == 'delivery') {
  1664. $classpath = 'livraison/class';
  1665. $subelement = 'livraison';
  1666. $module = 'livraison_bon';
  1667. }
  1668. elseif ($objecttype == 'contract') {
  1669. $classpath = 'contrat/class';
  1670. $module='contrat';
  1671. $subelement='contrat';
  1672. }
  1673. elseif ($objecttype == 'member') {
  1674. $classpath = 'adherents/class';
  1675. $module='adherent';
  1676. $subelement='adherent';
  1677. }
  1678. elseif ($objecttype == 'cabinetmed_cons') {
  1679. $classpath = 'cabinetmed/class';
  1680. $module='cabinetmed';
  1681. $subelement='cabinetmedcons';
  1682. }
  1683. elseif ($objecttype == 'fichinter') {
  1684. $classpath = 'fichinter/class';
  1685. $module='ficheinter';
  1686. $subelement='fichinter';
  1687. }
  1688. elseif ($objecttype == 'task') {
  1689. $classpath = 'projet/class';
  1690. $module='projet';
  1691. $subelement='task';
  1692. }
  1693. elseif ($objecttype == 'stock') {
  1694. $classpath = 'product/stock/class';
  1695. $module='stock';
  1696. $subelement='stock';
  1697. }
  1698. elseif ($objecttype == 'inventory') {
  1699. $classpath = 'product/inventory/class';
  1700. $module='stock';
  1701. $subelement='inventory';
  1702. }
  1703. // Generic case for $classfile and $classname
  1704. $classfile = strtolower($subelement); $classname = ucfirst($subelement);
  1705. //print "objecttype=".$objecttype." module=".$module." subelement=".$subelement." classfile=".$classfile." classname=".$classname;
  1706. if ($objecttype == 'invoice_supplier') {
  1707. $classfile = 'fournisseur.facture';
  1708. $classname = 'FactureFournisseur';
  1709. $classpath = 'fourn/class';
  1710. $module = 'fournisseur';
  1711. }
  1712. elseif ($objecttype == 'order_supplier') {
  1713. $classfile = 'fournisseur.commande';
  1714. $classname = 'CommandeFournisseur';
  1715. $classpath = 'fourn/class';
  1716. $module = 'fournisseur';
  1717. }
  1718. elseif ($objecttype == 'stock') {
  1719. $classpath = 'product/stock/class';
  1720. $classfile = 'entrepot';
  1721. $classname = 'Entrepot';
  1722. }
  1723. if (!empty($conf->$module->enabled))
  1724. {
  1725. $res = dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  1726. if ($res)
  1727. {
  1728. if (class_exists($classname))
  1729. {
  1730. $object = new $classname($db);
  1731. $res = $object->fetch($objectid);
  1732. if ($res > 0) {
  1733. $ret = $object->getNomUrl($withpicto, $option);
  1734. } elseif ($res == 0) {
  1735. $ret = $langs->trans('Deleted');
  1736. }
  1737. unset($object);
  1738. }
  1739. else dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
  1740. }
  1741. }
  1742. return $ret;
  1743. }
  1744. /**
  1745. * Clean corrupted tree (orphelins linked to a not existing parent), record linked to themself and child-parent loop
  1746. *
  1747. * @param DoliDB $db Database handler
  1748. * @param string $tabletocleantree Table to clean
  1749. * @param string $fieldfkparent Field name that contains id of parent
  1750. * @return int Nb of records fixed/deleted
  1751. */
  1752. function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
  1753. {
  1754. $totalnb = 0;
  1755. $listofid = array();
  1756. $listofparentid = array();
  1757. // Get list of all id in array listofid and all parents in array listofparentid
  1758. $sql = 'SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
  1759. $resql = $db->query($sql);
  1760. if ($resql)
  1761. {
  1762. $num = $db->num_rows($resql);
  1763. $i = 0;
  1764. while ($i < $num)
  1765. {
  1766. $obj = $db->fetch_object($resql);
  1767. $listofid[] = $obj->rowid;
  1768. if ($obj->parent_id > 0) $listofparentid[$obj->rowid] = $obj->parent_id;
  1769. $i++;
  1770. }
  1771. }
  1772. else
  1773. {
  1774. dol_print_error($db);
  1775. }
  1776. if (count($listofid))
  1777. {
  1778. print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
  1779. // Check loops on each other
  1780. $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid"; // So we update only records linked to themself
  1781. $resql = $db->query($sql);
  1782. if ($resql)
  1783. {
  1784. $nb = $db->affected_rows($sql);
  1785. if ($nb > 0)
  1786. {
  1787. print '<br>Some record that were parent of themself were cleaned.';
  1788. }
  1789. $totalnb += $nb;
  1790. }
  1791. //else dol_print_error($db);
  1792. // Check other loops
  1793. $listofidtoclean = array();
  1794. foreach ($listofparentid as $id => $pid)
  1795. {
  1796. // Check depth
  1797. //print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
  1798. $cursor = $id; $arrayidparsed = array(); // We start from child $id
  1799. while ($cursor > 0)
  1800. {
  1801. $arrayidparsed[$cursor] = 1;
  1802. if ($arrayidparsed[$listofparentid[$cursor]]) // We detect a loop. A record with a parent that was already into child
  1803. {
  1804. print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
  1805. unset($arrayidparsed);
  1806. $listofidtoclean[$cursor] = $id;
  1807. break;
  1808. }
  1809. $cursor = $listofparentid[$cursor];
  1810. }
  1811. if (count($listofidtoclean)) break;
  1812. }
  1813. $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
  1814. $sql .= " SET ".$fieldfkparent." = 0";
  1815. $sql .= " WHERE rowid IN (".join(',', $listofidtoclean).")"; // So we update only records detected wrong
  1816. $resql = $db->query($sql);
  1817. if ($resql)
  1818. {
  1819. $nb = $db->affected_rows($sql);
  1820. if ($nb > 0)
  1821. {
  1822. // Removed orphelins records
  1823. print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
  1824. print join(',', $listofidtoclean);
  1825. }
  1826. $totalnb += $nb;
  1827. }
  1828. //else dol_print_error($db);
  1829. // Check and clean orphelins
  1830. $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
  1831. $sql .= " SET ".$fieldfkparent." = 0";
  1832. $sql .= " WHERE ".$fieldfkparent." NOT IN (".join(',', $listofid).")"; // So we update only records linked to a non existing parent
  1833. $resql = $db->query($sql);
  1834. if ($resql)
  1835. {
  1836. $nb = $db->affected_rows($sql);
  1837. if ($nb > 0)
  1838. {
  1839. // Removed orphelins records
  1840. print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
  1841. print join(',', $listofid);
  1842. }
  1843. $totalnb += $nb;
  1844. }
  1845. //else dol_print_error($db);
  1846. print '<br>We fixed '.$totalnb.' record(s). Some records may still be corrupted. New check may be required.';
  1847. return $totalnb;
  1848. }
  1849. }
  1850. /**
  1851. * Get an array with properties of an element
  1852. *
  1853. * @param string $element_type Element type: 'action', 'facture', 'project_task' or 'object@modulext'...
  1854. * @return array (module, classpath, element, subelement, classfile, classname)
  1855. */
  1856. function getElementProperties($element_type)
  1857. {
  1858. // Parse element/subelement (ex: project_task)
  1859. $module = $element_type;
  1860. $element = $element_type;
  1861. $subelement = $element_type;
  1862. // If we ask an resource form external module (instead of default path)
  1863. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  1864. $element = $subelement = $regs[1];
  1865. $module = $regs[2];
  1866. }
  1867. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  1868. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  1869. $module = $element = $regs[1];
  1870. $subelement = $regs[2];
  1871. }
  1872. // For compat
  1873. if ($element_type == "action") {
  1874. $classpath = 'comm/action/class';
  1875. $subelement = 'Actioncomm';
  1876. $module = 'agenda';
  1877. }
  1878. // To work with non standard path
  1879. if ($element_type == 'facture' || $element_type == 'invoice') {
  1880. $classpath = 'compta/facture/class';
  1881. $module = 'facture';
  1882. $subelement = 'facture';
  1883. }
  1884. if ($element_type == 'commande' || $element_type == 'order') {
  1885. $classpath = 'commande/class';
  1886. $module = 'commande';
  1887. $subelement = 'commande';
  1888. }
  1889. if ($element_type == 'propal') {
  1890. $classpath = 'comm/propal/class';
  1891. }
  1892. if ($element_type == 'supplier_proposal') {
  1893. $classpath = 'supplier_proposal/class';
  1894. }
  1895. if ($element_type == 'shipping') {
  1896. $classpath = 'expedition/class';
  1897. $subelement = 'expedition';
  1898. $module = 'expedition_bon';
  1899. }
  1900. if ($element_type == 'delivery') {
  1901. $classpath = 'livraison/class';
  1902. $subelement = 'livraison';
  1903. $module = 'livraison_bon';
  1904. }
  1905. if ($element_type == 'contract') {
  1906. $classpath = 'contrat/class';
  1907. $module = 'contrat';
  1908. $subelement = 'contrat';
  1909. }
  1910. if ($element_type == 'member') {
  1911. $classpath = 'adherents/class';
  1912. $module = 'adherent';
  1913. $subelement = 'adherent';
  1914. }
  1915. if ($element_type == 'cabinetmed_cons') {
  1916. $classpath = 'cabinetmed/class';
  1917. $module = 'cabinetmed';
  1918. $subelement = 'cabinetmedcons';
  1919. }
  1920. if ($element_type == 'fichinter') {
  1921. $classpath = 'fichinter/class';
  1922. $module = 'ficheinter';
  1923. $subelement = 'fichinter';
  1924. }
  1925. if ($element_type == 'dolresource' || $element_type == 'resource') {
  1926. $classpath = 'resource/class';
  1927. $module = 'resource';
  1928. $subelement = 'dolresource';
  1929. }
  1930. if ($element_type == 'propaldet') {
  1931. $classpath = 'comm/propal/class';
  1932. $module = 'propal';
  1933. $subelement = 'propaleligne';
  1934. }
  1935. if ($element_type == 'order_supplier') {
  1936. $classpath = 'fourn/class';
  1937. $module = 'fournisseur';
  1938. $subelement = 'commandefournisseur';
  1939. $classfile = 'fournisseur.commande';
  1940. }
  1941. if ($element_type == 'invoice_supplier') {
  1942. $classpath = 'fourn/class';
  1943. $module = 'fournisseur';
  1944. $subelement = 'facturefournisseur';
  1945. $classfile = 'fournisseur.facture';
  1946. }
  1947. if ($element_type == "service") {
  1948. $classpath = 'product/class';
  1949. $subelement = 'product';
  1950. }
  1951. if (!isset($classfile)) $classfile = strtolower($subelement);
  1952. if (!isset($classname)) $classname = ucfirst($subelement);
  1953. if (!isset($classpath)) $classpath = $module.'/class';
  1954. $element_properties = array(
  1955. 'module' => $module,
  1956. 'classpath' => $classpath,
  1957. 'element' => $element,
  1958. 'subelement' => $subelement,
  1959. 'classfile' => $classfile,
  1960. 'classname' => $classname
  1961. );
  1962. return $element_properties;
  1963. }
  1964. /**
  1965. * Fetch an object from its id and element_type
  1966. * Inclusion of classes is automatic
  1967. *
  1968. * @param int $element_id Element id
  1969. * @param string $element_type Element type
  1970. * @param string $element_ref Element ref (Use this or element_id but not both)
  1971. * @return int|object object || 0 || -1 if error
  1972. */
  1973. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  1974. {
  1975. global $conf, $db;
  1976. $element_prop = getElementProperties($element_type);
  1977. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled)
  1978. {
  1979. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  1980. $objecttmp = new $element_prop['classname']($db);
  1981. $ret = $objecttmp->fetch($element_id, $element_ref);
  1982. if ($ret >= 0)
  1983. {
  1984. return $objecttmp;
  1985. }
  1986. }
  1987. return 0;
  1988. }
  1989. /**
  1990. * Convert an array with RGB value into hex RGB value.
  1991. * This is the opposite function of colorStringToArray
  1992. *
  1993. * @param array $arraycolor Array
  1994. * @param string $colorifnotfound Color code to return if entry not defined or not a RGB format
  1995. * @return string RGB hex value (without # before). For example: 'FF00FF', '01FF02'
  1996. * @see colorStringToArray(), colorHexToRgb()
  1997. */
  1998. function colorArrayToHex($arraycolor, $colorifnotfound = '888888')
  1999. {
  2000. if (!is_array($arraycolor)) return $colorifnotfound;
  2001. if (empty($arraycolor)) return $colorifnotfound;
  2002. return sprintf("%02s", dechex($arraycolor[0])).sprintf("%02s", dechex($arraycolor[1])).sprintf("%02s", dechex($arraycolor[2]));
  2003. }
  2004. /**
  2005. * Convert a string RGB value ('FFFFFF', '255,255,255') into an array RGB array(255,255,255).
  2006. * This is the opposite function of colorArrayToHex.
  2007. * If entry is already an array, return it.
  2008. *
  2009. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  2010. * @param array $colorifnotfound Color code array to return if entry not defined
  2011. * @return array RGB hex value (without # before). For example: FF00FF
  2012. * @see colorArrayToHex(), colorHexToRgb()
  2013. */
  2014. function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88))
  2015. {
  2016. if (is_array($stringcolor)) return $stringcolor; // If already into correct output format, we return as is
  2017. $reg = array();
  2018. $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);
  2019. if (!$tmp)
  2020. {
  2021. $tmp = explode(',', $stringcolor);
  2022. if (count($tmp) < 3) return $colorifnotfound;
  2023. return $tmp;
  2024. }
  2025. return array(hexdec($reg[1]), hexdec($reg[2]), hexdec($reg[3]));
  2026. }
  2027. /**
  2028. * @param string $color the color you need to valid
  2029. * @param boolean $allow_white in case of white isn't valid
  2030. * @return boolean
  2031. */
  2032. function colorValidateHex($color, $allow_white = true)
  2033. {
  2034. if(!$allow_white && ($color === '#fff' || $color === '#ffffff') ) return false;
  2035. if(preg_match('/^#[a-f0-9]{6}$/i', $color)) //hex color is valid
  2036. {
  2037. return true;
  2038. }
  2039. return false;
  2040. }
  2041. /**
  2042. * Change color to make it less aggressive (ratio is negative) or more aggressive (ratio is positive)
  2043. *
  2044. * @param string $hex Color in hex ('#AA1122' or 'AA1122' or '#a12' or 'a12')
  2045. * @param integer $ratio Default=-50. Note: 0=Component color is unchanged, -100=Component color become 88, +100=Component color become 00 or FF
  2046. * @param integer $brightness Default=0. Adjust brightness. -100=Decrease brightness by 100%, +100=Increase of 100%.
  2047. * @return string New string of color
  2048. * @see colorAdjustBrightness()
  2049. */
  2050. function colorAgressiveness($hex, $ratio = -50, $brightness = 0)
  2051. {
  2052. if (empty($ratio)) $ratio = 0; // To avoid null
  2053. // Steps should be between -255 and 255. Negative = darker, positive = lighter
  2054. $ratio = max(-100, min(100, $ratio));
  2055. // Normalize into a six character long hex string
  2056. $hex = str_replace('#', '', $hex);
  2057. if (strlen($hex) == 3) {
  2058. $hex = str_repeat(substr($hex, 0, 1), 2).str_repeat(substr($hex, 1, 1), 2).str_repeat(substr($hex, 2, 1), 2);
  2059. }
  2060. // Split into three parts: R, G and B
  2061. $color_parts = str_split($hex, 2);
  2062. $return = '#';
  2063. foreach ($color_parts as $color) {
  2064. $color = hexdec($color); // Convert to decimal
  2065. if ($ratio > 0) // We increase aggressivity
  2066. {
  2067. if ($color > 127) $color += ((255 - $color) * ($ratio / 100));
  2068. if ($color < 128) $color -= ($color * ($ratio / 100));
  2069. }
  2070. else // We decrease agressiveness
  2071. {
  2072. if ($color > 128) $color -= (($color - 128) * (abs($ratio) / 100));
  2073. if ($color < 127) $color += ((128 - $color) * (abs($ratio) / 100));
  2074. }
  2075. if ($brightness > 0)
  2076. {
  2077. $color = ($color * (100 + abs($brightness)) / 100);
  2078. }
  2079. else
  2080. {
  2081. $color = ($color * (100 - abs($brightness)) / 100);
  2082. }
  2083. $color = max(0, min(255, $color)); // Adjust color to stay into valid range
  2084. $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
  2085. }
  2086. //var_dump($hex.' '.$ratio.' -> '.$return);
  2087. return $return;
  2088. }
  2089. /**
  2090. * @param string $hex Color in hex ('#AA1122' or 'AA1122' or '#a12' or 'a12')
  2091. * @param integer $steps Step/offset added to each color component. It should be between -255 and 255. Negative = darker, positive = lighter
  2092. * @return string New color with format '#AA1122'
  2093. * @see colorAgressiveness()
  2094. */
  2095. function colorAdjustBrightness($hex, $steps)
  2096. {
  2097. // Steps should be between -255 and 255. Negative = darker, positive = lighter
  2098. $steps = max(-255, min(255, $steps));
  2099. // Normalize into a six character long hex string
  2100. $hex = str_replace('#', '', $hex);
  2101. if (strlen($hex) == 3) {
  2102. $hex = str_repeat(substr($hex, 0, 1), 2).str_repeat(substr($hex, 1, 1), 2).str_repeat(substr($hex, 2, 1), 2);
  2103. }
  2104. // Split into three parts: R, G and B
  2105. $color_parts = str_split($hex, 2);
  2106. $return = '#';
  2107. foreach ($color_parts as $color) {
  2108. $color = hexdec($color); // Convert to decimal
  2109. $color = max(0, min(255, $color + $steps)); // Adjust color
  2110. $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
  2111. }
  2112. return $return;
  2113. }
  2114. /**
  2115. * @param string $hex color in hex
  2116. * @param integer $percent 0 to 100
  2117. * @return string
  2118. */
  2119. function colorDarker($hex, $percent)
  2120. {
  2121. $steps = intval(255 * $percent / 100) * -1;
  2122. return colorAdjustBrightness($hex, $steps);
  2123. }
  2124. /**
  2125. * @param string $hex color in hex
  2126. * @param integer $percent 0 to 100
  2127. * @return string
  2128. */
  2129. function colorLighten($hex, $percent)
  2130. {
  2131. $steps = intval(255 * $percent / 100);
  2132. return colorAdjustBrightness($hex, $steps);
  2133. }
  2134. /**
  2135. * @param string $hex color in hex
  2136. * @param float $alpha 0 to 1 to add alpha channel
  2137. * @param bool $returnArray Array set to 1 to return an array instead of string
  2138. * @return string|array String or array
  2139. */
  2140. function colorHexToRgb($hex, $alpha = false, $returnArray = false)
  2141. {
  2142. $string = '';
  2143. $hex = str_replace('#', '', $hex);
  2144. $length = strlen($hex);
  2145. $rgb = array();
  2146. $rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
  2147. $rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
  2148. $rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
  2149. if ($alpha !== false) {
  2150. $rgb['a'] = floatval($alpha);
  2151. $string = 'rgba('.implode(',', $rgb).')';
  2152. }
  2153. else {
  2154. $string = 'rgb('.implode(',', $rgb).')';
  2155. }
  2156. if ($returnArray) {
  2157. return $rgb;
  2158. }
  2159. else {
  2160. return $string;
  2161. }
  2162. }
  2163. /**
  2164. * Applies the Cartesian product algorithm to an array
  2165. * Source: http://stackoverflow.com/a/15973172
  2166. *
  2167. * @param array $input Array of products
  2168. * @return array Array of combinations
  2169. */
  2170. function cartesianArray(array $input)
  2171. {
  2172. // filter out empty values
  2173. $input = array_filter($input);
  2174. $result = array(array());
  2175. foreach ($input as $key => $values) {
  2176. $append = array();
  2177. foreach ($result as $product) {
  2178. foreach ($values as $item) {
  2179. $product[$key] = $item;
  2180. $append[] = $product;
  2181. }
  2182. }
  2183. $result = $append;
  2184. }
  2185. return $result;
  2186. }
  2187. /**
  2188. * Get name of directory where the api_...class.php file is stored
  2189. *
  2190. * @param string $module Module name
  2191. * @return string Directory name
  2192. */
  2193. function getModuleDirForApiClass($module)
  2194. {
  2195. $moduledirforclass = $module;
  2196. if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass);
  2197. if ($module == 'contracts') {
  2198. $moduledirforclass = 'contrat';
  2199. }
  2200. elseif (in_array($module, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents'))) {
  2201. $moduledirforclass = 'api';
  2202. }
  2203. elseif ($module == 'contact' || $module == 'contacts' || $module == 'customer' || $module == 'thirdparty' || $module == 'thirdparties') {
  2204. $moduledirforclass = 'societe';
  2205. }
  2206. elseif ($module == 'propale' || $module == 'proposals') {
  2207. $moduledirforclass = 'comm/propal';
  2208. }
  2209. elseif ($module == 'agenda' || $module == 'agendaevents') {
  2210. $moduledirforclass = 'comm/action';
  2211. }
  2212. elseif ($module == 'adherent' || $module == 'members' || $module == 'memberstypes' || $module == 'subscriptions') {
  2213. $moduledirforclass = 'adherents';
  2214. }
  2215. elseif ($module == 'don' || $module == 'donations') {
  2216. $moduledirforclass = 'don';
  2217. }
  2218. elseif ($module == 'banque' || $module == 'bankaccounts') {
  2219. $moduledirforclass = 'compta/bank';
  2220. }
  2221. elseif ($module == 'category' || $module == 'categorie') {
  2222. $moduledirforclass = 'categories';
  2223. }
  2224. elseif ($module == 'order' || $module == 'orders') {
  2225. $moduledirforclass = 'commande';
  2226. }
  2227. elseif ($module == 'shipments') {
  2228. $moduledirforclass = 'expedition';
  2229. }
  2230. elseif ($module == 'facture' || $module == 'invoice' || $module == 'invoices') {
  2231. $moduledirforclass = 'compta/facture';
  2232. }
  2233. elseif ($module == 'products') {
  2234. $moduledirforclass = 'product';
  2235. }
  2236. elseif ($module == 'project' || $module == 'projects' || $module == 'tasks') {
  2237. $moduledirforclass = 'projet';
  2238. }
  2239. elseif ($module == 'task') {
  2240. $moduledirforclass = 'projet';
  2241. }
  2242. elseif ($module == 'stock' || $module == 'stockmovements' || $module == 'warehouses') {
  2243. $moduledirforclass = 'product/stock';
  2244. }
  2245. elseif ($module == 'supplierproposals' || $module == 'supplierproposal' || $module == 'supplier_proposal') {
  2246. $moduledirforclass = 'supplier_proposal';
  2247. }
  2248. elseif ($module == 'fournisseur' || $module == 'supplierinvoices' || $module == 'supplierorders') {
  2249. $moduledirforclass = 'fourn';
  2250. }
  2251. elseif ($module == 'expensereports') {
  2252. $moduledirforclass = 'expensereport';
  2253. }
  2254. elseif ($module == 'users') {
  2255. $moduledirforclass = 'user';
  2256. }
  2257. elseif ($module == 'ficheinter' || $module == 'interventions') {
  2258. $moduledirforclass = 'fichinter';
  2259. }
  2260. elseif ($module == 'tickets') {
  2261. $moduledirforclass = 'ticket';
  2262. }
  2263. elseif ($module == 'boms') {
  2264. $moduledirforclass = 'bom';
  2265. }
  2266. return $moduledirforclass;
  2267. }
  2268. /**
  2269. * Return 2 hexa code randomly
  2270. *
  2271. * @param int $min Between 0 and 255
  2272. * @param int $max Between 0 and 255
  2273. * @return string A color string '12'
  2274. */
  2275. function randomColorPart($min = 0, $max = 255)
  2276. {
  2277. return str_pad(dechex(mt_rand($min, $max)), 2, '0', STR_PAD_LEFT);
  2278. }
  2279. /**
  2280. * Return hexadecimal color randomly
  2281. *
  2282. * @param int $min Between 0 and 255
  2283. * @param int $max Between 0 and 255
  2284. * @return string A color string '123456'
  2285. */
  2286. function randomColor($min = 0, $max = 255)
  2287. {
  2288. return randomColorPart($min, $max).randomColorPart($min, $max).randomColorPart($min, $max);
  2289. }
  2290. if (!function_exists('dolEscapeXML'))
  2291. {
  2292. /**
  2293. * Encode string for xml usage
  2294. *
  2295. * @param string $string String to encode
  2296. * @return string String encoded
  2297. */
  2298. function dolEscapeXML($string)
  2299. {
  2300. return strtr($string, array('\''=>'&apos;', '"'=>'&quot;', '&'=>'&amp;', '<'=>'&lt;', '>'=>'&gt;'));
  2301. }
  2302. }
  2303. /**
  2304. * Return automatic or manual in current language
  2305. *
  2306. * @param string $automaticmanual Value to test (1, 'automatic', 'true' or 0, 'manual', 'false')
  2307. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Automatic/Manual
  2308. * @param int $color 0=texte only, 1=Text is formated with a color font style ('ok' or 'error'), 2=Text is formated with 'ok' color.
  2309. * @return string HTML string
  2310. */
  2311. function autoOrManual($automaticmanual, $case = 1, $color = 0)
  2312. {
  2313. global $langs;
  2314. $result = 'unknown'; $classname = '';
  2315. if ($automaticmanual == 1 || strtolower($automaticmanual) == 'automatic' || strtolower($automaticmanual) == 'true') // A mettre avant test sur no a cause du == 0
  2316. {
  2317. $result = $langs->trans('automatic');
  2318. if ($case == 1 || $case == 3) $result = $langs->trans("Automatic");
  2319. if ($case == 2) $result = '<input type="checkbox" value="1" checked disabled>';
  2320. if ($case == 3) $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  2321. $classname = 'ok';
  2322. }
  2323. elseif ($automaticmanual == 0 || strtolower($automaticmanual) == 'manual' || strtolower($automaticmanual) == 'false')
  2324. {
  2325. $result = $langs->trans("manual");
  2326. if ($case == 1 || $case == 3) $result = $langs->trans("Manual");
  2327. if ($case == 2) $result = '<input type="checkbox" value="0" disabled>';
  2328. if ($case == 3) $result = '<input type="checkbox" value="0" disabled> '.$result;
  2329. if ($color == 2) $classname = 'ok';
  2330. else $classname = 'error';
  2331. }
  2332. if ($color) return '<font class="'.$classname.'">'.$result.'</font>';
  2333. return $result;
  2334. }
  2335. /**
  2336. * Convert links to local wrapper to medias files into a string into a public external URL readable on internet
  2337. *
  2338. * @param string $notetoshow Text to convert
  2339. * @return string String
  2340. */
  2341. function convertBackOfficeMediasLinksToPublicLinks($notetoshow)
  2342. {
  2343. global $dolibarr_main_url_root;
  2344. // Define $urlwithroot
  2345. $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  2346. $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  2347. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  2348. $notetoshow=preg_replace('/src="[a-zA-Z0-9_\/\-\.]*(viewimage\.php\?modulepart=medias[^"]*)"/', 'src="'.$urlwithroot.'/\1"', $notetoshow);
  2349. return $notetoshow;
  2350. }