functions2.lib.php 91 KB

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