dolibarr 23.0.3
geoipmaxmind.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2009-2019 Laurent Destailleur <eldy@users.sourceforge.org>
3 * Copyright (C) 2011-2013 Juanjo Menent <jmenent@2byte.es>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
27// Load Dolibarr environment
28require '../main.inc.php';
36require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
37require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
38require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
39require_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
40require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
41
42// Security check
43if (!$user->admin) {
45}
46
47// Load translation files required by the page
48$langs->loadLangs(array("admin", "errors"));
49
50$action = GETPOST('action', 'aZ09');
51
52if (!isset($conf->global->GEOIP_VERSION)) {
53 $conf->global->GEOIP_VERSION = '2';
54}
55
56
57/*
58 * Actions
59 */
60
61if ($action == 'set') {
62 $error = 0;
63
64 $res1 = dolibarr_set_const($db, "GEOIP_VERSION", GETPOST('geoipversion', 'aZ09'), 'chaine', 0, '', $conf->entity);
65 if (!($res1 > 0)) {
66 $error++;
67 }
68
69 if (getDolGlobalString('GEOIP_VERSION') == 'php') {
70 $gimcdf = GETPOST("GEOIPMAXMIND_COUNTRY_DATAFILE");
71 if ($gimcdf) {
72 if (!preg_match('/\.(dat|mmdb)$/', $gimcdf)) {
73 setEventMessages($langs->trans("ErrorFileMustHaveFormat", '.dat|.mmdb'), null, 'errors');
74 $error++;
75 }
76
77 if (!$error) {
78 $res2 = dolibarr_set_const($db, "GEOIPMAXMIND_COUNTRY_DATAFILE", $gimcdf, 'chaine', 0, '', $conf->entity);
79 if (!($res2 > 0)) {
80 $error++;
81 }
82 }
83 }
84 } else {
85 $gimcdf = GETPOST("GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED");
86 if ($gimcdf && !preg_match('/\.(dat|mmdb)$/', $gimcdf)) {
87 setEventMessages($langs->trans("ErrorFileMustHaveFormat", '.dat|.mmdb'), null, 'errors');
88 $error++;
89 }
90
91 if (!$error) {
92 $varname = 'GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED';
93 if (isset($_FILES[$varname]) && $_FILES[$varname]["name"]) {
94 $diroffile = getMultidirOutput(null, 'geoipmaxmind');
95 if ($diroffile) {
96 $dirforterms = $diroffile.'/';
97 $original_file = $_FILES[$varname]["name"];
98 // @phan-suppress-next-line PhanTypeInvalidDimOffset
99 $result = dol_move_uploaded_file($_FILES[$varname]["tmp_name"], $dirforterms.$original_file, 1, 0, $_FILES[$varname]['error']);
100 if ((int) $result > 0) {
101 dolibarr_set_const($db, $varname, $original_file, 'chaine', 0, '', $conf->entity);
102 } else {
103 $error++;
104 setEventMessages($langs->trans("Error").' '.$langs->transnoentitiesnoconv((string) $result), null, 'errors');
105 }
106 }
107 }
108 }
109 }
110
111 if (!$error) {
112 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
113 } else {
114 //setEventMessages($langs->trans("Error"), null, 'errors');
115 }
116}
117
118$documenturl = getDolGlobalString('DOL_URL_ROOT_DOCUMENT_PHP', DOL_URL_ROOT.'/document.php');
119
120
121/*
122 * View
123 */
124
125$form = new Form($db);
126$formfile = new FormFile($db);
127
128llxHeader('', '', '', '', 0, 0, '', '', '', 'mod-admin page-geoipmaxmind');
129
130$linkback = '<a href="'.dolBuildUrl(DOL_URL_ROOT.'/admin/modules.php', ['restore_lastsearch_values' => 1]).'">'.img_picto($langs->trans("BackToModuleList"), 'back', 'class="pictofixedwidth"').'<span class="hideonsmartphone">'.$langs->trans("BackToModuleList").'</span></a>';
131
132print load_fiche_titre($langs->trans("GeoIPMaxmindSetup"), $linkback, 'title_setup');
133print '<br>';
134
135$version = '';
136$geoip = '';
137if (getDolGlobalString('GEOIP_VERSION') == 'php') {
138 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
139} else {
140 $diroffile = getMultidirOutput(null, 'geoipmaxmind');
141 $datafile = $diroffile . '/' . getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED');
142}
143if ($datafile) {
144 $geoip = new DolGeoIP('country', $datafile);
145}
146
147// Mode
148print '<form action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data" method="post">';
149print '<input type="hidden" name="token" value="'.newToken().'">';
150print '<input type="hidden" name="action" value="set">';
151
152print '<div class="div-table-responsive-no-min">';
153print '<table class="noborder centpercent">';
154print '<tr class="liste_titre">';
155print '<td>'.$langs->trans("Parameter").'</td><td></td>';
156print '<td class="right"></td>';
157print "</tr>\n";
158
159// Lib version
160print '<tr class="oddeven"><td>'.$langs->trans("GeoIPLibVersion").'</td>';
161print '<td>';
162$arrayofvalues = array('php' => 'Native PHP functions', '1' => 'Embedded GeoIP v1', '2' => 'Embedded GeoIP v2');
163print $form->selectarray('geoipversion', $arrayofvalues, getDolGlobalString('GEOIP_VERSION', '2'));
164if (getDolGlobalString('GEOIP_VERSION') == 'php') {
165 if ($geoip) {
166 $version = $geoip->getVersion();
167 }
168 if ($version) {
169 print '<br>'.$langs->trans("Version").': '.$version;
170 }
171}
172print '</td>';
173print '<td>';
174print '</td></tr>';
175
176// Path to database file
177print '<tr class="oddeven"><td>'.$langs->trans("PathToGeoIPMaxmindCountryDataFile").'</td>';
178print '<td>';
179if (getDolGlobalString('GEOIP_VERSION') == 'php') {
180 $gimcdf = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
181
182 if (function_exists('geoip_db_filename')) {
183 print 'Using geoip PHP internal functions. Value must be '.geoip_db_filename(GEOIP_COUNTRY_EDITION).' or '.geoip_db_filename(GEOIP_CITY_EDITION_REV1).' or /pathtodatafile/GeoLite2-Country.mmdb<br>';
184 }
185 print '<input type="text" class="minwidth200" name="GEOIPMAXMIND_COUNTRY_DATAFILE" value="'.dol_escape_htmltag(getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE')).'">';
186 if (!file_exists(str_replace('DOL_DATA_ROOT', DOL_DATA_ROOT, $gimcdf))) {
187 print '<div class="error">'.$langs->trans("ErrorFileNotFound", $gimcdf).'</div>';
188 }
189} else {
190 $modulepart = 'geoipmaxmind';
191 print '<div class="inline-block nobordernopadding valignmiddle "><div class="inline-block marginrightonly">';
192 $maxfilesizearray = getMaxFileSizeArray();
193 $maxmin = $maxfilesizearray['maxmin'];
194 if ($maxmin > 0) {
195 print '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
196 }
197 print '<input type="file" class="flat minwidth100 maxwidthinputfileonsmartphone" name="GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED" id="GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED">';
198
199 // TODO Move this into a function $out = getHelpOnUploadMax();
200 $out = '';
201 if (getDolGlobalString('MAIN_UPLOAD_DOC')) {
202 $max = getDolGlobalString('MAIN_UPLOAD_DOC'); // In Kb
203 $maxphp = @ini_get('upload_max_filesize'); // In unknown
204 if (preg_match('/k$/i', $maxphp)) {
205 $maxphp = preg_replace('/k$/i', '', $maxphp);
206 $maxphp = (int) $maxphp * 1;
207 }
208 if (preg_match('/m$/i', $maxphp)) {
209 $maxphp = preg_replace('/m$/i', '', $maxphp);
210 $maxphp = (int) $maxphp * 1024;
211 }
212 if (preg_match('/g$/i', $maxphp)) {
213 $maxphp = preg_replace('/g$/i', '', $maxphp);
214 $maxphp = (int) $maxphp * 1024 * 1024;
215 }
216 if (preg_match('/t$/i', $maxphp)) {
217 $maxphp = preg_replace('/t$/i', '', $maxphp);
218 $maxphp = (int) $maxphp * 1024 * 1024 * 1024;
219 }
220 $maxphp2 = @ini_get('post_max_size'); // In unknown
221 if (preg_match('/k$/i', $maxphp2)) {
222 $maxphp2 = preg_replace('/k$/i', '', $maxphp2);
223 $maxphp2 = (int) $maxphp2 * 1;
224 }
225 if (preg_match('/m$/i', $maxphp2)) {
226 $maxphp2 = preg_replace('/m$/i', '', $maxphp2);
227 $maxphp2 = (int) $maxphp2 * 1024;
228 }
229 if (preg_match('/g$/i', $maxphp2)) {
230 $maxphp2 = preg_replace('/g$/i', '', $maxphp2);
231 $maxphp2 = (int) $maxphp2 * 1024 * 1024;
232 }
233 if (preg_match('/t$/i', $maxphp2)) {
234 $maxphp2 = preg_replace('/t$/i', '', $maxphp2);
235 $maxphp2 = (int) $maxphp2 * 1024 * 1024 * 1024;
236 }
237 // Now $max and $maxphp and $maxphp2 are in Kb
238 $maxmin = $max;
239 $maxphptoshow = $maxphptoshowparam = '';
240 if ($maxphp > 0) {
241 $maxmin = min($max, $maxphp);
242 $maxphptoshow = $maxphp;
243 $maxphptoshowparam = 'upload_max_filesize';
244 }
245 if ($maxphp2 > 0) {
246 $maxmin = min($max, $maxphp2);
247 if ($maxphp2 < $maxphp) {
248 $maxphptoshow = $maxphp2;
249 $maxphptoshowparam = 'post_max_size';
250 }
251 }
252
253 $langs->load('other');
254 $out .= ' ';
255 $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
256 } else {
257 $out .= ' ('.$langs->trans("UploadDisabled").')';
258 }
259
260 print $out;
261
262 print '</div>';
263 if (getDolGlobalString("GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED")) {
264 $geoipfile = getDolGlobalString("GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED");
265 $diroffile = getMultidirOutput(null, 'geoipmaxmind');
266 if (file_exists($diroffile.'/'.$geoipfile)) {
267 $file = dol_dir_list($diroffile, 'files', 0, $geoipfile);
268 print ' ';
269 print '<div class="inline-block valignmiddle marginrightonly"><a href="'.$documenturl.'?modulepart='.$modulepart.'&file='.urlencode($geoipfile).'">'.$geoipfile.'</a>'.$formfile->showPreview($file[0], $modulepart, $geoipfile, 0, '');
270 print '<div class="inline-block valignmiddle marginrightonly"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=removetermsofsale&modulepart='.$modulepart.'&token='.newToken().'">'.img_delete($langs->trans("Delete"), '', 'marginleftonly').'</a></div>';
271 }
272 }
273
274 print '</div>';
275}
276
277print '</td><td>';
278if (getDolGlobalString('GEOIP_VERSION') == 'php') {
279 print '<span class="opacitymedium">';
280 print $langs->trans("Example").'<br>';
281 print '/usr/local/share/GeoIP/GeoIP.dat<br>
282/usr/share/GeoIP/GeoIP.dat<br>
283/usr/share/GeoIP/GeoLite2-Country.mmdb';
284 print '</span>';
285}
286print '</td></tr>';
287
288print '</table>';
289print '</div>';
290
291print '<center>';
292print '<input type="submit" class="button button-edit" value="'.$langs->trans("Save").'">';
293print '</center>';
294
295print "</form>\n";
296
297print '<br>';
298
299print '<div class="hideonsmartphone info">';
300if (getDolGlobalString('GEOIP_VERSION') == 'php') {
301 print $langs->trans("NoteOnPathLocation").'<br>';
302}
303
304$url1 = 'http://www.maxmind.com/en/city?rId=awstats';
305$textoshow = $langs->trans("YouCanDownloadFreeDatFileTo", '{s1}');
306$textoshow = str_replace('{s1}', '<a href="'.$url1.'" target="_blank" rel="noopener noreferrer external">'.$url1.'</a>', $textoshow);
307print $textoshow;
308
309print '<br>';
310
311$url2 = 'http://www.maxmind.com/en/city?rId=awstats';
312$textoshow = $langs->trans("YouCanDownloadAdvancedDatFileTo", '{s1}');
313$textoshow = str_replace('{s1}', '<a href="'.$url2.'" target="_blank" rel="noopener noreferrer external">'.$url2.'</a>', $textoshow);
314print $textoshow;
315
316print '</div>';
317
318if ($geoip) {
319 print '<br>';
320
321 print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
322 print '<input type="hidden" name="token" value="'.newToken().'">';
323
324 $ip = '24.24.24.24';
325
326 print load_fiche_titre($langs->trans("TestGeoIPResult", $ip));
327
328 print $ip.' -> ';
329 $result = dol_print_ip($ip, 1);
330 if ($result) {
331 print $result;
332 } else {
333 print $langs->trans("Error");
334 }
335
336 $ip = '2a01:e0a:7e:4a60:429a:23ff:f7b8:dc8a'; // should be France
337 print '<br>'.$ip.' -> ';
338 $result = dol_print_ip($ip, 1);
339 if ($result) {
340 print $result;
341 } else {
342 print $langs->trans("Error");
343 }
344
345
346 /* We disable this test because dol_print_ip need an ip as input
347 $ip='www.google.com';
348 print '<br>'.$ip.' -> ';
349 $result=dol_print_ip($ip,1);
350 if ($result) print $result;
351 else print $langs->trans("Error");
352 */
353 //var_dump($_SERVER);
354 $ip = getUserRemoteIP();
355 //$ip='91.161.249.43';
356 $isip = is_ip($ip);
357 if ($isip == 1) {
358 print '<br>'.$langs->trans("CurrentIP").': '.$ip.' -> ';
359 $result = dol_print_ip($ip, 1);
360 if ($result) {
361 print $result;
362 } else {
363 print $langs->trans("Error");
364 }
365 } else {
366 print '<br>'.($isip == 2 ? $langs->trans("CurrentIP").': ' : '').$ip.' -> ';
367 $result = dol_print_ip($ip, 1);
368 if ($result) {
369 print $result;
370 } else {
371 print $langs->trans("NotAPublicIp");
372 }
373 }
374
375 $ip = GETPOST("iptotest");
376 print '<br><input type="text class="width100" name="iptotest" id="iptotest" placeholder="'.dol_escape_htmltag($langs->trans("EnterAnIP")).'" value="'.$ip.'">';
377 print '<input type="submit" class="width40 button small smallpaddingimp" value=" -> ">';
378 if ($ip) {
379 $result = dol_print_ip($ip, 1);
380 if ($result) {
381 print $result;
382 } else {
383 print $langs->trans("Error");
384 }
385 }
386
387 print '</form>';
388
389 $geoip->close();
390}
391
392// End of page
393llxFooter();
394$db->close();
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage GeoIP conversion Usage: $geoip=new GeoIP('country',$datfile); $geoip->getCountryCodeF...
Class to offer components to list and upload files.
Class to manage generation of HTML components Only common components must be here.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:64
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $keyforsourcefile='addedfile', $upload_dir='', $mode=0)
Check validity of a file upload from an GUI page, and move it to its final destination.
is_ip($ip)
This function evaluates a string that should be a valid IPv4 Note: For ip 169.254....
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
dol_print_ip($ip, $mode=0, $showname=0)
Return an IP formatted to be shown on screen.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
if(!function_exists( 'utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists( 'str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists( 'str_contains')) getMultidirOutput($object, $module='', $forobject=0, $mode='output')
Return the full path of the directory where a module (or an object of a module) stores its files.
getUserRemoteIP($trusted=0)
Return the real IP of remote user.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='')
Show information in HTML for admin users or standard users.
getMaxFileSizeArray()
Return the max allowed for file upload.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.