functions2.lib.php 95 KB

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