dolibarr 25.0.0-alpha
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"));
49
50$action = GETPOST('action', 'aZ09');
51
52if (!getDolGlobalString("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 $langs->load('errors');
74 setEventMessages($langs->trans("ErrorFileMustHaveFormat", '.dat|.mmdb'), null, 'errors');
75 $error++;
76 }
77
78 if (!$error) {
79 $res2 = dolibarr_set_const($db, "GEOIPMAXMIND_COUNTRY_DATAFILE", $gimcdf, 'chaine', 0, '', $conf->entity);
80 if (!($res2 > 0)) {
81 $error++;
82 }
83 }
84 }
85 } else {
86 $gimcdf = GETPOST("GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED");
87 if ($gimcdf && !preg_match('/\.(dat|mmdb)$/', $gimcdf)) {
88 $langs->load('errors');
89 setEventMessages($langs->trans("ErrorFileMustHaveFormat", '.dat|.mmdb'), null, 'errors');
90 $error++;
91 }
92
93 if (!$error) {
94 $varname = 'GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED';
95 if (isset($_FILES[$varname]) && $_FILES[$varname]["name"]) {
96 $diroffile = getMultidirOutput(null, 'geoipmaxmind');
97 if ($diroffile) {
98 $dirforterms = $diroffile.'/';
99 $original_file = $_FILES[$varname]["name"];
100 // @phan-suppress-next-line PhanTypeInvalidDimOffset
101 $result = dol_move_uploaded_file($_FILES[$varname]["tmp_name"], $dirforterms.$original_file, 1, 0, $_FILES[$varname]['error']);
102 if ((int) $result > 0) {
103 dolibarr_set_const($db, $varname, $original_file, 'chaine', 0, '', $conf->entity);
104 } else {
105 $error++;
106 setEventMessages($langs->trans("Error").' '.$langs->transnoentitiesnoconv((string) $result), null, 'errors');
107 }
108 }
109 }
110 }
111 }
112
113 if (!$error) {
114 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
115 } else {
116 //setEventMessages($langs->trans("Error"), null, 'errors');
117 }
118}
119
120$documenturl = getDolGlobalString('DOL_URL_ROOT_DOCUMENT_PHP', DOL_URL_ROOT.'/document.php');
121
122
123/*
124 * View
125 */
126
127$form = new Form($db);
128$formfile = new FormFile($db);
129
130llxHeader('', '', '', '', 0, 0, '', '', '', 'mod-admin page-geoipmaxmind');
131
132$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>';
133
134print load_fiche_titre($langs->trans("GeoIPMaxmindSetup"), $linkback, 'title_setup');
135print '<br>';
136
137$version = '';
138$geoip = '';
139if (getDolGlobalString('GEOIP_VERSION') == 'php') {
140 $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
141} else {
142 $diroffile = getMultidirOutput(null, 'geoipmaxmind');
143 $datafile = $diroffile . '/' . getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED');
144}
145if ($datafile) {
146 $geoip = new DolGeoIP('country', $datafile);
147}
148
149// Mode
150print '<form action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data" method="post" spellcheck="false">';
151print '<input type="hidden" name="token" value="'.newToken().'">';
152print '<input type="hidden" name="action" value="set">';
153
154print '<div class="div-table-responsive-no-min">';
155print '<table class="noborder centpercent">';
156print '<tr class="liste_titre">';
157print '<td>'.$langs->trans("Parameter").'</td><td></td>';
158print '<td class="right"></td>';
159print "</tr>\n";
160
161// Lib version
162print '<tr class="oddeven"><td>'.$langs->trans("GeoIPLibVersion").'</td>';
163print '<td>';
164$arrayofvalues = array('php' => 'Native PHP functions', '1' => 'Embedded GeoIP v1', '2' => 'Embedded GeoIP v2');
165print $form->selectarray('geoipversion', $arrayofvalues, getDolGlobalString('GEOIP_VERSION', '2'));
166if (getDolGlobalString('GEOIP_VERSION') == 'php') {
167 if ($geoip) {
168 $version = $geoip->getVersion();
169 }
170 if ($version) {
171 print '<br>'.$langs->trans("Version").': '.$version;
172 }
173}
174print '</td>';
175print '<td>';
176print '</td></tr>';
177
178// Path to database file
179print '<tr class="oddeven"><td>'.$langs->trans("PathToGeoIPMaxmindCountryDataFile").'</td>';
180print '<td>';
181if (getDolGlobalString('GEOIP_VERSION') == 'php') {
182 $gimcdf = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
183
184 if (function_exists('geoip_db_filename')) {
185 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>';
186 }
187 print '<input type="text" class="minwidth200" name="GEOIPMAXMIND_COUNTRY_DATAFILE" value="'.dol_escape_htmltag(getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE')).'">';
188 if (!file_exists(str_replace('DOL_DATA_ROOT', DOL_DATA_ROOT, $gimcdf))) {
189 $langs->load('errors');
190 print '<div class="error">'.$langs->trans("ErrorFileNotFound", $gimcdf).'</div>';
191 }
192} else {
193 $modulepart = 'geoipmaxmind';
194 print '<div class="inline-block nobordernopadding valignmiddle "><div class="inline-block marginrightonly">';
195 $maxfilesizearray = getMaxFileSizeArray();
196 $maxmin = $maxfilesizearray['maxmin'];
197 if ($maxmin > 0) {
198 print '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
199 }
200 print '<input type="file" class="flat minwidth100 maxwidthinputfileonsmartphone" name="GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED" id="GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED">';
201
202 // TODO Move this into a function $out = getHelpOnUploadMax();
203 $out = '';
204 if (getDolGlobalString('MAIN_UPLOAD_DOC')) {
205 $max = getDolGlobalString('MAIN_UPLOAD_DOC'); // In Kb
206 $maxphp = @ini_get('upload_max_filesize'); // In unknown
207 if (preg_match('/k$/i', $maxphp)) {
208 $maxphp = preg_replace('/k$/i', '', $maxphp);
209 $maxphp = (int) $maxphp * 1;
210 }
211 if (preg_match('/m$/i', $maxphp)) {
212 $maxphp = preg_replace('/m$/i', '', $maxphp);
213 $maxphp = (int) $maxphp * 1024;
214 }
215 if (preg_match('/g$/i', $maxphp)) {
216 $maxphp = preg_replace('/g$/i', '', $maxphp);
217 $maxphp = (int) $maxphp * 1024 * 1024;
218 }
219 if (preg_match('/t$/i', $maxphp)) {
220 $maxphp = preg_replace('/t$/i', '', $maxphp);
221 $maxphp = (int) $maxphp * 1024 * 1024 * 1024;
222 }
223 $maxphp2 = @ini_get('post_max_size'); // In unknown
224 if (preg_match('/k$/i', $maxphp2)) {
225 $maxphp2 = preg_replace('/k$/i', '', $maxphp2);
226 $maxphp2 = (int) $maxphp2 * 1;
227 }
228 if (preg_match('/m$/i', $maxphp2)) {
229 $maxphp2 = preg_replace('/m$/i', '', $maxphp2);
230 $maxphp2 = (int) $maxphp2 * 1024;
231 }
232 if (preg_match('/g$/i', $maxphp2)) {
233 $maxphp2 = preg_replace('/g$/i', '', $maxphp2);
234 $maxphp2 = (int) $maxphp2 * 1024 * 1024;
235 }
236 if (preg_match('/t$/i', $maxphp2)) {
237 $maxphp2 = preg_replace('/t$/i', '', $maxphp2);
238 $maxphp2 = (int) $maxphp2 * 1024 * 1024 * 1024;
239 }
240 // Now $max and $maxphp and $maxphp2 are in Kb
241 $maxmin = $max;
242 $maxphptoshow = $maxphptoshowparam = '';
243 if ($maxphp > 0) {
244 $maxmin = min($max, $maxphp);
245 $maxphptoshow = $maxphp;
246 $maxphptoshowparam = 'upload_max_filesize';
247 }
248 if ($maxphp2 > 0) {
249 $maxmin = min($max, $maxphp2);
250 if ($maxphp2 < $maxphp) {
251 $maxphptoshow = $maxphp2;
252 $maxphptoshowparam = 'post_max_size';
253 }
254 }
255
256 $langs->load('other');
257 $out .= ' ';
258 $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
259 } else {
260 $out .= ' ('.$langs->trans("UploadDisabled").')';
261 }
262
263 print $out;
264
265 print '</div>';
266 if (getDolGlobalString("GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED")) {
267 $geoipfile = getDolGlobalString("GEOIPMAXMIND_COUNTRY_DATAFILE_EMBEDDED");
268 $diroffile = getMultidirOutput(null, 'geoipmaxmind');
269 if (file_exists($diroffile.'/'.$geoipfile)) {
270 $file = dol_dir_list($diroffile, 'files', 0, $geoipfile);
271 print ' ';
272 print '<div class="inline-block valignmiddle marginrightonly"><a href="'.$documenturl.'?modulepart='.$modulepart.'&file='.urlencode($geoipfile).'">'.$geoipfile.'</a>'.$formfile->showPreview($file[0], $modulepart, $geoipfile, 0, '');
273 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>';
274 }
275 }
276
277 print '</div>';
278}
279
280print '</td><td>';
281if (getDolGlobalString('GEOIP_VERSION') == 'php') {
282 print '<span class="opacitymedium">';
283 print $langs->trans("Example").'<br>';
284 print '/usr/local/share/GeoIP/GeoIP.dat<br>
285/usr/share/GeoIP/GeoIP.dat<br>
286/usr/share/GeoIP/GeoLite2-Country.mmdb';
287 print '</span>';
288}
289print '</td></tr>';
290
291print '</table>';
292print '</div>';
293
294print '<center>';
295print '<input type="submit" class="button button-edit" value="'.$langs->trans("Save").'">';
296print '</center>';
297
298print "</form>\n";
299
300print '<br>';
301
302print '<div class="hideonsmartphone info">';
303if (getDolGlobalString('GEOIP_VERSION') == 'php') {
304 print $langs->trans("NoteOnPathLocation").'<br>';
305}
306
307$url1 = 'http://www.maxmind.com/en/city?rId=awstats';
308$textoshow = $langs->trans("YouCanDownloadFreeDatFileTo", '{s1}');
309$textoshow = str_replace('{s1}', '<a href="'.$url1.'" target="_blank" rel="noopener noreferrer external">'.$url1.'</a>', $textoshow);
310print $textoshow;
311
312print '<br>';
313
314$url2 = 'http://www.maxmind.com/en/city?rId=awstats';
315$textoshow = $langs->trans("YouCanDownloadAdvancedDatFileTo", '{s1}');
316$textoshow = str_replace('{s1}', '<a href="'.$url2.'" target="_blank" rel="noopener noreferrer external">'.$url2.'</a>', $textoshow);
317print $textoshow;
318
319print '</div>';
320
321if ($geoip) {
322 print '<br>';
323
324 print '<form action="'.$_SERVER["PHP_SELF"].'" method="post" spellcheck="false">';
325 print '<input type="hidden" name="token" value="'.newToken().'">';
326
327 $ip = '24.24.24.24';
328
329 print load_fiche_titre($langs->trans("TestGeoIPResult", $ip));
330
331 print $ip.' -> ';
332 $result = dol_print_ip($ip, 1);
333 if ($result) {
334 print $result;
335 } else {
336 print $langs->trans("Error");
337 }
338
339 $ip = '2a01:e0a:7e:4a60:429a:23ff:f7b8:dc8a'; // should be France
340 print '<br>'.$ip.' -> ';
341 $result = dol_print_ip($ip, 1);
342 if ($result) {
343 print $result;
344 } else {
345 print $langs->trans("Error");
346 }
347
348
349 /* We disable this test because dol_print_ip need an ip as input
350 $ip='www.google.com';
351 print '<br>'.$ip.' -> ';
352 $result=dol_print_ip($ip,1);
353 if ($result) print $result;
354 else print $langs->trans("Error");
355 */
356 //var_dump($_SERVER);
357 $ip = getUserRemoteIP();
358 //$ip='91.161.249.43';
359 $isip = is_ip($ip);
360 if ($isip == 1) {
361 print '<br>'.$langs->trans("CurrentIP").': '.$ip.' -> ';
362 $result = dol_print_ip($ip, 1);
363 if ($result) {
364 print $result;
365 } else {
366 print $langs->trans("Error");
367 }
368 } else {
369 print '<br>'.($isip == 2 ? $langs->trans("CurrentIP").': ' : '').$ip.' -> ';
370 $result = dol_print_ip($ip, 1);
371 if ($result) {
372 print $result;
373 } else {
374 print $langs->trans("NotAPublicIp");
375 }
376 }
377
378 $ip = GETPOST("iptotest");
379 print '<br><input type="text class="width100" name="iptotest" id="iptotest" placeholder="'.dol_escape_htmltag($langs->trans("EnterAnIP")).'" value="'.$ip.'">';
380 print '<input type="submit" class="width40 button small smallpaddingimp" value=" -> ">';
381 if ($ip) {
382 $result = dol_print_ip($ip, 1);
383 if ($result) {
384 print $result;
385 } else {
386 print $langs->trans("Error");
387 }
388 }
389
390 print '</form>';
391
392 $geoip->close();
393}
394
395// End of page
396llxFooter();
397$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
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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:66
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....
dol_print_ip($ip, $mode=0, $showname=0)
Return an IP formatted to be shown on screen.
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.
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, $nodefault=0)
Return value of a param into GET or POST supervariable.
getUserRemoteIP($trusted=0)
Return the real IP of remote user.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='', $cssfordropdown='info_admin')
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.