functions2.lib.php 94 KB

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