Exemplo n.º 1
0
 /**
  * Upgrade to to the next version
  */
 public function upgrade()
 {
     $WEBTREES_EMAIL = 'webtrees-noreply@' . preg_replace('/^www\\./i', '', Filter::server('SERVER_NAME'));
     // Default settings for new trees.  No defaults for:
     // imported, title, CONTACT_USER_ID, WEBMASTER_USER_ID
     // The following settings have defaults, but may need overwriting:
     // LANGUAGE, SURNAME_TRADITION
     Database::prepare("INSERT IGNORE INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value) VALUES" . "(-1, 'ADVANCED_NAME_FACTS', 'NICK,_AKA')," . "(-1, 'ADVANCED_PLAC_FACTS', '')," . "(-1, 'ALLOW_THEME_DROPDOWN', '1')," . "(-1, 'CALENDAR_FORMAT', 'gregorian')," . "(-1, 'CHART_BOX_TAGS', '')," . "(-1, 'COMMON_NAMES_ADD', '')," . "(-1, 'COMMON_NAMES_REMOVE', '')," . "(-1, 'COMMON_NAMES_THRESHOLD', '40')," . "(-1, 'DEFAULT_PEDIGREE_GENERATIONS', '4')," . "(-1, 'EXPAND_RELATIVES_EVENTS', '0')," . "(-1, 'EXPAND_SOURCES', '0')," . "(-1, 'FAM_FACTS_ADD', 'CENS,MARR,RESI,SLGS,MARR_CIVIL,MARR_RELIGIOUS,MARR_PARTNERS,RESN')," . "(-1, 'FAM_FACTS_QUICK', 'MARR,DIV,_NMR')," . "(-1, 'FAM_FACTS_UNIQUE', 'NCHI,MARL,DIV,ANUL,DIVF,ENGA,MARB,MARC,MARS')," . "(-1, 'FAM_ID_PREFIX', 'F')," . "(-1, 'FORMAT_TEXT', 'markdown')," . "(-1, 'FULL_SOURCES', '0')," . "(-1, 'GEDCOM_ID_PREFIX', 'I')," . "(-1, 'GEDCOM_MEDIA_PATH', '')," . "(-1, 'GENERATE_UIDS', '0')," . "(-1, 'HIDE_GEDCOM_ERRORS', '1')," . "(-1, 'HIDE_LIVE_PEOPLE', '1')," . "(-1, 'INDI_FACTS_ADD', 'AFN,BIRT,DEAT,BURI,CREM,ADOP,BAPM,BARM,BASM,BLES,CHRA,CONF,FCOM,ORDN,NATU,EMIG,IMMI,CENS,PROB,WILL,GRAD,RETI,DSCR,EDUC,IDNO,NATI,NCHI,NMR,OCCU,PROP,RELI,RESI,SSN,TITL,BAPL,CONL,ENDL,SLGC,_MILI,ASSO,RESN')," . "(-1, 'INDI_FACTS_QUICK', 'BIRT,BURI,BAPM,CENS,DEAT,OCCU,RESI')," . "(-1, 'INDI_FACTS_UNIQUE', '')," . "(-1, 'KEEP_ALIVE_YEARS_BIRTH', '')," . "(-1, 'KEEP_ALIVE_YEARS_DEATH', '')," . "(-1, 'LANGUAGE', 'en-US')," . "(-1, 'MAX_ALIVE_AGE', '120')," . "(-1, 'MAX_DESCENDANCY_GENERATIONS', '15')," . "(-1, 'MAX_PEDIGREE_GENERATIONS', '10')," . "(-1, 'MEDIA_DIRECTORY', 'media/')," . "(-1, 'MEDIA_ID_PREFIX', 'M')," . "(-1, 'MEDIA_UPLOAD', :MEDIA_UPLOAD)," . "(-1, 'META_DESCRIPTION', '')," . "(-1, 'META_TITLE', :META_TITLE)," . "(-1, 'NOTE_FACTS_ADD', 'SOUR,RESN')," . "(-1, 'NOTE_FACTS_QUICK', '')," . "(-1, 'NOTE_FACTS_UNIQUE', '')," . "(-1, 'NOTE_ID_PREFIX', 'N')," . "(-1, 'NO_UPDATE_CHAN', '0')," . "(-1, 'PEDIGREE_FULL_DETAILS', '1')," . "(-1, 'PEDIGREE_LAYOUT', '1')," . "(-1, 'PEDIGREE_ROOT_ID', '')," . "(-1, 'PEDIGREE_SHOW_GENDER', '0')," . "(-1, 'PREFER_LEVEL2_SOURCES', '1')," . "(-1, 'QUICK_REQUIRED_FACTS', 'BIRT,DEAT')," . "(-1, 'QUICK_REQUIRED_FAMFACTS', 'MARR')," . "(-1, 'REPO_FACTS_ADD', 'PHON,EMAIL,FAX,WWW,RESN')," . "(-1, 'REPO_FACTS_QUICK', '')," . "(-1, 'REPO_FACTS_UNIQUE', 'NAME,ADDR')," . "(-1, 'REPO_ID_PREFIX', 'R')," . "(-1, 'REQUIRE_AUTHENTICATION', '0')," . "(-1, 'SAVE_WATERMARK_IMAGE', '0')," . "(-1, 'SAVE_WATERMARK_THUMB', '0')," . "(-1, 'SHOW_AGE_DIFF', '0')," . "(-1, 'SHOW_COUNTER', '1')," . "(-1, 'SHOW_DEAD_PEOPLE', :SHOW_DEAD_PEOPLE)," . "(-1, 'SHOW_EST_LIST_DATES', '0')," . "(-1, 'SHOW_FACT_ICONS', '1')," . "(-1, 'SHOW_GEDCOM_RECORD', '0')," . "(-1, 'SHOW_HIGHLIGHT_IMAGES', '1')," . "(-1, 'SHOW_LDS_AT_GLANCE', '0')," . "(-1, 'SHOW_LEVEL2_NOTES', '1')," . "(-1, 'SHOW_LIVING_NAMES', :SHOW_LIVING_NAMES)," . "(-1, 'SHOW_MEDIA_DOWNLOAD', '0')," . "(-1, 'SHOW_NO_WATERMARK', :SHOW_NO_WATERMARK)," . "(-1, 'SHOW_PARENTS_AGE', '1')," . "(-1, 'SHOW_PEDIGREE_PLACES', '9')," . "(-1, 'SHOW_PEDIGREE_PLACES_SUFFIX', '0')," . "(-1, 'SHOW_PRIVATE_RELATIONSHIPS', '1')," . "(-1, 'SHOW_RELATIVES_EVENTS', '_BIRT_CHIL,_BIRT_SIBL,_MARR_CHIL,_MARR_PARE,_DEAT_CHIL,_DEAT_PARE,_DEAT_GPAR,_DEAT_SIBL,_DEAT_SPOU')," . "(-1, 'SOURCE_ID_PREFIX', 'S')," . "(-1, 'SOUR_FACTS_ADD', 'NOTE,REPO,SHARED_NOTE,RESN')," . "(-1, 'SOUR_FACTS_QUICK', 'TEXT,NOTE,REPO')," . "(-1, 'SOUR_FACTS_UNIQUE', 'AUTH,ABBR,TITL,PUBL,TEXT')," . "(-1, 'SUBLIST_TRIGGER_I', '200')," . "(-1, 'SURNAME_LIST_STYLE', 'style2')," . "(-1, 'SURNAME_TRADITION', 'paternal')," . "(-1, 'THUMBNAIL_WIDTH', '100')," . "(-1, 'USE_RIN', '0')," . "(-1, 'USE_SILHOUETTE', '1')," . "(-1, 'WATERMARK_THUMB', '0')," . "(-1, 'WEBTREES_EMAIL', :WEBTREES_EMAIL)," . "(-1, 'WORD_WRAPPED_NOTES', '0')")->execute(array('MEDIA_UPLOAD' => Auth::PRIV_USER, 'META_TITLE' => WT_WEBTREES, 'SHOW_DEAD_PEOPLE' => Auth::PRIV_PRIVATE, 'SHOW_LIVING_NAMES' => Auth::PRIV_USER, 'SHOW_NO_WATERMARK' => Auth::PRIV_USER, 'WEBTREES_EMAIL' => $WEBTREES_EMAIL));
     // Previous versions of webtrees allowed this setting to be empty.
     Database::prepare("DELETE FROM `##gedcom_setting` WHERE setting_name  ='WEBTREES_EMAIL' AND setting_value = ''")->execute();
     Database::prepare("INSERT IGNORE INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" . " SELECT gedcom_id, 'WEBTREES_EMAIL', :WEBTREES_EMAIL" . " FROM `##gedcom` WHERE gedcom_id > 0")->execute(array('WEBTREES_EMAIL' => $WEBTREES_EMAIL));
     // Default restrictions
     Database::prepare("INSERT IGNORE INTO `##default_resn` (gedcom_id, tag_type, resn) VALUES " . "(-1, 'SSN', 'confidential')," . "(-1, 'SOUR', 'privacy')," . "(-1, 'REPO', 'privacy')," . "(-1, 'SUBM', 'confidential')," . "(-1, 'SUBN', 'confidential')")->execute();
 }
Exemplo n.º 2
0
 /**
  * Decode and encrypt a text from base64 compatible with URL use
  *
  * @param string $encrypted Text to decrypt
  * @return string Decrypted text
  */
 public static function decryptFromSafeBase64($encrypted)
 {
     if (!self::isEncryptionCompatible()) {
         throw new \Exception('MCrypt PHP extension is required to use encryption.');
     }
     $key = 'STANDARDKEYIFNOSERVER';
     if (!empty(Filter::server('SERVER_NAME')) && !empty(Filter::server('SERVER_SOFTWARE'))) {
         $key = md5(Filter::server('SERVER_NAME') . Filter::server('SERVER_SOFTWARE'));
     }
     $encrypted = str_replace('-', '+', $encrypted);
     $encrypted = str_replace('_', '/', $encrypted);
     $encrypted = str_replace('*', '=', $encrypted);
     $encrypted = base64_decode($encrypted);
     if (!$encrypted) {
         throw new \InvalidArgumentException('The encrypted value is not in correct base64 format.');
     }
     if (strlen($encrypted) < self::ENCRYPTION_IV_SIZE) {
         throw new \InvalidArgumentException('The encrypted value does not contain enough characters for the key.');
     }
     $iv_dec = substr($encrypted, 0, self::ENCRYPTION_IV_SIZE);
     $encrypted = substr($encrypted, self::ENCRYPTION_IV_SIZE);
     $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv_dec);
     return preg_replace('~(?:\\000+)$~', '', $decrypted);
 }
Exemplo n.º 3
0
 /**
  * Render the image to the output.
  */
 public function render()
 {
     if (!$this->media || !$this->media->canShow()) {
         Log::addMediaLog('Image Builder error: >' . I18N::translate('Missing or private media object.'));
         $this->renderError();
     }
     $serverFilename = $this->media->getServerFilename();
     if (!file_exists($serverFilename)) {
         Log::addMediaLog('Image Builder error: >' . I18N::translate('The media object does not exist.') . '< for path >' . $serverFilename . '<');
         $this->renderError();
     }
     $mimetype = $this->media->mimeType();
     $imgsize = $this->media->getImageAttributes();
     $filetime = $this->media->getFiletime();
     $filetimeHeader = gmdate('D, d M Y H:i:s', $filetime) . ' GMT';
     $expireHeader = gmdate('D, d M Y H:i:s', WT_TIMESTAMP + $this->getExpireOffset()) . ' GMT';
     $type = Functions::isImageTypeSupported($imgsize['ext']);
     $usewatermark = false;
     // if this image supports watermarks and the watermark module is intalled...
     if ($type) {
         $usewatermark = $this->isShowWatermark();
     }
     // determine whether we have enough memory to watermark this image
     if ($usewatermark) {
         if (!FunctionsMedia::hasMemoryForImage($serverFilename)) {
             // not enough memory to watermark this file
             $usewatermark = false;
         }
     }
     $etag = $this->media->getEtag();
     // parse IF_MODIFIED_SINCE header from client
     $if_modified_since = 'x';
     if (!empty(Filter::server('HTTP_IF_MODIFIED_SINCE'))) {
         $if_modified_since = preg_replace('/;.*$/', '', Filter::server('HTTP_IF_MODIFIED_SINCE'));
     }
     // parse IF_NONE_MATCH header from client
     $if_none_match = 'x';
     if (!empty(Filter::server('HTTP_IF_NONE_MATCH'))) {
         $if_none_match = str_replace('"', '', Filter::server('HTTP_IF_NONE_MATCH'));
     }
     // add caching headers.  allow browser to cache file, but not proxy
     header('Last-Modified: ' . $filetimeHeader);
     header('ETag: "' . $etag . '"');
     header('Expires: ' . $expireHeader);
     header('Cache-Control: max-age=' . $this->getExpireOffset() . ', s-maxage=0, proxy-revalidate');
     // if this file is already in the user’s cache, don’t resend it
     // first check if the if_modified_since param matches
     if ($if_modified_since === $filetimeHeader) {
         // then check if the etag matches
         if ($if_none_match === $etag) {
             http_response_code(304);
             return;
         }
     }
     // send headers for the image
     header('Content-Type: ' . $mimetype);
     header('Content-Disposition: filename="' . addslashes(basename($this->media->getFilename())) . '"');
     if ($usewatermark) {
         // generate the watermarked image
         $imCreateFunc = 'imagecreatefrom' . $type;
         $imSendFunc = 'image' . $type;
         if (function_exists($imCreateFunc) && function_exists($imSendFunc)) {
             $im = $imCreateFunc($serverFilename);
             $im = $this->applyWatermark($im);
             // send the image
             $imSendFunc($im);
             imagedestroy($im);
             return;
         } else {
             // this image is defective.  log it
             Log::addMediaLog('Image Builder error: >' . I18N::translate('This media file is broken and cannot be watermarked.') . '< in file >' . $serverFilename . '< memory used: ' . memory_get_usage());
         }
     }
     // determine filesize of image (could be original or watermarked version)
     $filesize = filesize($serverFilename);
     // set content-length header, send file
     header('Content-Length: ' . $filesize);
     // Some servers disable fpassthru() and readfile()
     if (function_exists('readfile')) {
         readfile($serverFilename);
     } else {
         $fp = fopen($serverFilename, 'rb');
         if (function_exists('fpassthru')) {
             fpassthru($fp);
         } else {
             while (!feof($fp)) {
                 echo fread($fp, 65536);
             }
         }
         fclose($fp);
     }
 }
Exemplo n.º 4
0
    /**
     * Places administration.
     */
    private function adminPlaces()
    {
        global $WT_TREE;
        $action = Filter::get('action');
        $parent = Filter::get('parent');
        $inactive = Filter::getBool('inactive');
        $deleteRecord = Filter::get('deleteRecord');
        if (!isset($parent)) {
            $parent = 0;
        }
        $controller = new PageController();
        $controller->restrictAccess(Auth::isAdmin());
        if ($action == 'ExportFile' && Auth::isAdmin()) {
            $tmp = $this->placeIdToHierarchy($parent);
            $maxLevel = $this->getHighestLevel();
            if ($maxLevel > 8) {
                $maxLevel = 8;
            }
            $tmp[0] = 'places';
            $outputFileName = preg_replace('/[:;\\/\\\\(\\)\\{\\}\\[\\] $]/', '_', implode('-', $tmp)) . '.csv';
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . $outputFileName . '"');
            echo '"', I18N::translate('Level'), '";"', I18N::translate('Country'), '";';
            if ($maxLevel > 0) {
                echo '"', I18N::translate('State'), '";';
            }
            if ($maxLevel > 1) {
                echo '"', I18N::translate('County'), '";';
            }
            if ($maxLevel > 2) {
                echo '"', I18N::translate('City'), '";';
            }
            if ($maxLevel > 3) {
                echo '"', I18N::translate('Place'), '";';
            }
            if ($maxLevel > 4) {
                echo '"', I18N::translate('Place'), '";';
            }
            if ($maxLevel > 5) {
                echo '"', I18N::translate('Place'), '";';
            }
            if ($maxLevel > 6) {
                echo '"', I18N::translate('Place'), '";';
            }
            if ($maxLevel > 7) {
                echo '"', I18N::translate('Place'), '";';
            }
            echo '"', I18N::translate('Longitude'), '";"', I18N::translate('Latitude'), '";';
            echo '"', I18N::translate('Zoom level'), '";"', I18N::translate('Icon'), '";', WT_EOL;
            $this->outputLevel($parent);
            return;
        }
        $controller->setPageTitle(I18N::translate('Google Maps™'))->pageHeader();
        ?>
		<ol class="breadcrumb small">
			<li><a href="admin.php"><?php 
        echo I18N::translate('Control panel');
        ?>
</a></li>
			<li><a href="admin_modules.php"><?php 
        echo I18N::translate('Module administration');
        ?>
</a></li>
			<li class="active"><?php 
        echo $controller->getPageTitle();
        ?>
</li>
		</ol>

		<ul class="nav nav-tabs nav-justified" role="tablist">
			<li role="presentation">
				<a href="?mod=googlemap&amp;mod_action=admin_config" role="tab">
					<?php 
        echo I18N::translate('Google Maps™ preferences');
        ?>
				</a>
			</li>
			<li role="presentation" class="active">
				<a href="#">
					<?php 
        echo I18N::translate('Geographic data');
        ?>
				</a>
			</li>
			<li role="presentation">
				<a href="?mod=googlemap&amp;mod_action=admin_placecheck">
					<?php 
        echo I18N::translate('Place check');
        ?>
				</a>
			</li>
		</ul>
		<?php 
        if ($action == 'ImportGedcom') {
            echo '<h2>' . I18N::translate('Geographic data') . '</h2>';
            $placelist = array();
            $j = 0;
            $gedcom_records = Database::prepare("SELECT i_gedcom FROM `##individuals` WHERE i_file=? UNION ALL SELECT f_gedcom FROM `##families` WHERE f_file=?")->execute(array($WT_TREE->getTreeId(), $WT_TREE->getTreeId()))->fetchOneColumn();
            foreach ($gedcom_records as $gedrec) {
                $i = 1;
                $placerec = Functions::getSubRecord(2, '2 PLAC', $gedrec, $i);
                while (!empty($placerec)) {
                    if (preg_match("/2 PLAC (.+)/", $placerec, $match)) {
                        $placelist[$j] = array();
                        $placelist[$j]['place'] = trim($match[1]);
                        if (preg_match("/4 LATI (.*)/", $placerec, $match)) {
                            $placelist[$j]['lati'] = trim($match[1]);
                            if ($placelist[$j]['lati'][0] != 'N' && $placelist[$j]['lati'][0] != 'S') {
                                if ($placelist[$j]['lati'] < 0) {
                                    $placelist[$j]['lati'][0] = 'S';
                                } else {
                                    $placelist[$j]['lati'] = 'N' . $placelist[$j]['lati'];
                                }
                            }
                        } else {
                            $placelist[$j]['lati'] = null;
                        }
                        if (preg_match("/4 LONG (.*)/", $placerec, $match)) {
                            $placelist[$j]['long'] = trim($match[1]);
                            if ($placelist[$j]['long'][0] != 'E' && $placelist[$j]['long'][0] != 'W') {
                                if ($placelist[$j]['long'] < 0) {
                                    $placelist[$j]['long'][0] = 'W';
                                } else {
                                    $placelist[$j]['long'] = 'E' . $placelist[$j]['long'];
                                }
                            }
                        } else {
                            $placelist[$j]['long'] = null;
                        }
                        $j = $j + 1;
                    }
                    $i = $i + 1;
                    $placerec = Functions::getSubRecord(2, '2 PLAC', $gedrec, $i);
                }
            }
            asort($placelist);
            $prevPlace = '';
            $prevLati = '';
            $prevLong = '';
            $placelistUniq = array();
            $j = 0;
            foreach ($placelist as $k => $place) {
                if ($place['place'] != $prevPlace) {
                    $placelistUniq[$j] = array();
                    $placelistUniq[$j]['place'] = $place['place'];
                    $placelistUniq[$j]['lati'] = $place['lati'];
                    $placelistUniq[$j]['long'] = $place['long'];
                    $j = $j + 1;
                } elseif ($place['place'] == $prevPlace && ($place['lati'] != $prevLati || $place['long'] != $prevLong)) {
                    if ($placelistUniq[$j - 1]['lati'] == 0 || $placelistUniq[$j - 1]['long'] == 0) {
                        $placelistUniq[$j - 1]['lati'] = $place['lati'];
                        $placelistUniq[$j - 1]['long'] = $place['long'];
                    } elseif ($place['lati'] != '0' || $place['long'] != '0') {
                        echo 'Difference: previous value = ', $prevPlace, ', ', $prevLati, ', ', $prevLong, ' current = ', $place['place'], ', ', $place['lati'], ', ', $place['long'], '<br>';
                    }
                }
                $prevPlace = $place['place'];
                $prevLati = $place['lati'];
                $prevLong = $place['long'];
            }
            $highestIndex = $this->getHighestIndex();
            $default_zoom_level = array(4, 7, 10, 12);
            foreach ($placelistUniq as $k => $place) {
                $parent = preg_split('/ *, */', $place['place']);
                $parent = array_reverse($parent);
                $parent_id = 0;
                $num_parent = count($parent);
                for ($i = 0; $i < $num_parent; $i++) {
                    if (!isset($default_zoom_level[$i])) {
                        $default_zoom_level[$i] = $default_zoom_level[$i - 1];
                    }
                    $escparent = $parent[$i];
                    if ($escparent == '') {
                        $escparent = 'Unknown';
                    }
                    $row = Database::prepare("SELECT pl_id, pl_long, pl_lati, pl_zoom FROM `##placelocation` WHERE pl_level=? AND pl_parent_id=? AND pl_place LIKE ?")->execute(array($i, $parent_id, $escparent))->fetchOneRow();
                    if ($i < $num_parent - 1) {
                        // Create higher-level places, if necessary
                        if (empty($row)) {
                            $highestIndex++;
                            Database::prepare("INSERT INTO `##placelocation` (pl_id, pl_parent_id, pl_level, pl_place, pl_zoom) VALUES (?, ?, ?, ?, ?)")->execute(array($highestIndex, $parent_id, $i, $escparent, $default_zoom_level[$i]));
                            echo Filter::escapeHtml($escparent), '<br>';
                            $parent_id = $highestIndex;
                        } else {
                            $parent_id = $row->pl_id;
                        }
                    } else {
                        // Create lowest-level place, if necessary
                        if (empty($row->pl_id)) {
                            $highestIndex++;
                            Database::prepare("INSERT INTO `##placelocation` (pl_id, pl_parent_id, pl_level, pl_place, pl_long, pl_lati, pl_zoom) VALUES (?, ?, ?, ?, ?, ?, ?)")->execute(array($highestIndex, $parent_id, $i, $escparent, $place['long'], $place['lati'], $default_zoom_level[$i]));
                            echo Filter::escapeHtml($escparent), '<br>';
                        } else {
                            if (empty($row->pl_long) && empty($row->pl_lati) && $place['lati'] != '0' && $place['long'] != '0') {
                                Database::prepare("UPDATE `##placelocation` SET pl_lati=?, pl_long=? WHERE pl_id=?")->execute(array($place['lati'], $place['long'], $row->pl_id));
                                echo Filter::escapeHtml($escparent), '<br>';
                            }
                        }
                    }
                }
            }
            $parent = 0;
        }
        if ($action === 'ImportFile') {
            echo '<h2>' . I18N::translate('Upload geographic data') . '</h2>';
            $placefiles = $this->findFiles(WT_MODULES_DIR . 'googlemap/extra');
            sort($placefiles);
            ?>
		<form class="form-horizontal" method="post" enctype="multipart/form-data" id="importfile" name="importfile" action="module.php?mod=googlemap&amp;mod_action=admin_places&amp;action=ImportFile2">

			<!-- PLACES FILE -->
			<div class="form-group">
				<label class="control-label col-sm-4" for="placesfile">
					<?php 
            echo I18N::translate('A file on your computer');
            ?>
				</label>
				<div class="col-sm-8">
					<div class="btn btn-default">
					<input id="placesfile" type="file" name="placesfile">
					</div>
				</div>
			</div>

			<!-- LOCAL FILE -->
			<div class="form-group">
				<label class="control-label col-sm-4" for="localfile">
					<?php 
            echo I18N::translate('A file on the server');
            ?>
				</label>
				<div class="col-sm-8">
					<div class="input-group">
						<span class="input-group-addon">
							<?php 
            echo WT_MODULES_DIR . 'googlemap/extra/';
            ?>
						</span>
						<?php 
            foreach ($placefiles as $p => $placefile) {
                unset($placefiles[$p]);
                $p = Filter::escapeHtml($placefile);
                if (substr($placefile, 0, 1) == "/") {
                    $placefiles[$p] = substr($placefile, 1);
                } else {
                    $placefiles[$p] = $placefile;
                }
            }
            echo FunctionsEdit::selectEditControl('localfile', $placefiles, '', '', 'class="form-control"');
            ?>
					</div>
				</div>
			</div>

			<!-- CLEAR DATABASE -->
			<fieldset class="form-group">
				<legend class="control-label col-sm-4">
					<?php 
            echo I18N::translate('Delete all existing geographic data before importing the file.');
            ?>
				</legend>
				<div class="col-sm-8">
					<?php 
            echo FunctionsEdit::editFieldYesNo('cleardatabase', 0, 'class="radio-inline"');
            ?>
				</div>
			</fieldset>

			<!-- UPDATE ONLY -->
			<fieldset class="form-group">
				<legend class="control-label col-sm-4">
					<?php 
            echo I18N::translate('Do not create new locations, just import coordinates for existing locations.');
            ?>
				</legend>
				<div class="col-sm-8">
					<?php 
            echo FunctionsEdit::editFieldYesNo('updateonly', 0, 'class="radio-inline"');
            ?>
				</div>
			</fieldset>

			<!-- OVERWRITE DATA -->
			<fieldset class="form-group">
				<legend class="control-label col-sm-4">
					<?php 
            echo I18N::translate('Overwrite existing coordinates.');
            ?>
				</legend>
				<div class="col-sm-8">
					<?php 
            echo FunctionsEdit::editFieldYesNo('overwritedata', 0, 'class="radio-inline"');
            ?>
				</div>
			</fieldset>

			<!-- SAVE BUTTON -->
			<div class="form-group">
				<div class="col-sm-offset-4 col-sm-8">
					<button type="submit" class="btn btn-primary">
						<i class="fa fa-check"></i>
						<?php 
            echo I18N::translate('continue');
            ?>
					</button>
				</div>
			</div>
		</form>
		<?php 
            return;
        }
        if ($action === 'ImportFile2') {
            echo '<h2>' . I18N::translate('Geographic data') . '</h2>';
            $country_names = array();
            $stats = new Stats($WT_TREE);
            foreach ($stats->iso3166() as $key => $value) {
                $country_names[$key] = I18N::translate($key);
            }
            if (Filter::postBool('cleardatabase')) {
                Database::exec("DELETE FROM `##placelocation` WHERE 1=1");
            }
            if (!empty($_FILES['placesfile']['tmp_name'])) {
                $lines = file($_FILES['placesfile']['tmp_name']);
            } elseif (!empty($_REQUEST['localfile'])) {
                $lines = file(WT_MODULES_DIR . 'googlemap/extra' . $_REQUEST['localfile']);
            }
            // Strip BYTE-ORDER-MARK, if present
            if (!empty($lines[0]) && substr($lines[0], 0, 3) === WT_UTF8_BOM) {
                $lines[0] = substr($lines[0], 3);
            }
            asort($lines);
            $highestIndex = $this->getHighestIndex();
            $placelist = array();
            $j = 0;
            $maxLevel = 0;
            foreach ($lines as $p => $placerec) {
                $fieldrec = explode(';', $placerec);
                if ($fieldrec[0] > $maxLevel) {
                    $maxLevel = $fieldrec[0];
                }
            }
            $fields = count($fieldrec);
            $set_icon = true;
            if (!is_dir(WT_MODULES_DIR . 'googlemap/places/flags/')) {
                $set_icon = false;
            }
            foreach ($lines as $p => $placerec) {
                $fieldrec = explode(';', $placerec);
                if (is_numeric($fieldrec[0]) && $fieldrec[0] <= $maxLevel) {
                    $placelist[$j] = array();
                    $placelist[$j]['place'] = '';
                    for ($ii = $fields - 4; $ii > 1; $ii--) {
                        if ($fieldrec[0] > $ii - 2) {
                            $placelist[$j]['place'] .= $fieldrec[$ii] . ',';
                        }
                    }
                    foreach ($country_names as $countrycode => $countryname) {
                        if ($countrycode == strtoupper($fieldrec[1])) {
                            $fieldrec[1] = $countryname;
                            break;
                        }
                    }
                    $placelist[$j]['place'] .= $fieldrec[1];
                    $placelist[$j]['long'] = $fieldrec[$fields - 4];
                    $placelist[$j]['lati'] = $fieldrec[$fields - 3];
                    $placelist[$j]['zoom'] = $fieldrec[$fields - 2];
                    if ($set_icon) {
                        $placelist[$j]['icon'] = trim($fieldrec[$fields - 1]);
                    } else {
                        $placelist[$j]['icon'] = '';
                    }
                    $j = $j + 1;
                }
            }
            $prevPlace = '';
            $prevLati = '';
            $prevLong = '';
            $placelistUniq = array();
            $j = 0;
            foreach ($placelist as $k => $place) {
                if ($place['place'] != $prevPlace) {
                    $placelistUniq[$j] = array();
                    $placelistUniq[$j]['place'] = $place['place'];
                    $placelistUniq[$j]['lati'] = $place['lati'];
                    $placelistUniq[$j]['long'] = $place['long'];
                    $placelistUniq[$j]['zoom'] = $place['zoom'];
                    $placelistUniq[$j]['icon'] = $place['icon'];
                    $j = $j + 1;
                } elseif ($place['place'] == $prevPlace && ($place['lati'] != $prevLati || $place['long'] != $prevLong)) {
                    if ($placelistUniq[$j - 1]['lati'] == 0 || $placelistUniq[$j - 1]['long'] == 0) {
                        $placelistUniq[$j - 1]['lati'] = $place['lati'];
                        $placelistUniq[$j - 1]['long'] = $place['long'];
                        $placelistUniq[$j - 1]['zoom'] = $place['zoom'];
                        $placelistUniq[$j - 1]['icon'] = $place['icon'];
                    } elseif ($place['lati'] != '0' || $place['long'] != '0') {
                        echo 'Difference: previous value = ', $prevPlace, ', ', $prevLati, ', ', $prevLong, ' current = ', $place['place'], ', ', $place['lati'], ', ', $place['long'], '<br>';
                    }
                }
                $prevPlace = $place['place'];
                $prevLati = $place['lati'];
                $prevLong = $place['long'];
            }
            $default_zoom_level = array();
            $default_zoom_level[0] = 4;
            $default_zoom_level[1] = 7;
            $default_zoom_level[2] = 10;
            $default_zoom_level[3] = 12;
            foreach ($placelistUniq as $k => $place) {
                $parent = explode(',', $place['place']);
                $parent = array_reverse($parent);
                $parent_id = 0;
                $num_parent = count($parent);
                for ($i = 0; $i < $num_parent; $i++) {
                    $escparent = $parent[$i];
                    if ($escparent == '') {
                        $escparent = 'Unknown';
                    }
                    $row = Database::prepare("SELECT pl_id, pl_long, pl_lati, pl_zoom, pl_icon FROM `##placelocation` WHERE pl_level=? AND pl_parent_id=? AND pl_place LIKE ? ORDER BY pl_place")->execute(array($i, $parent_id, $escparent))->fetchOneRow();
                    if (empty($row)) {
                        // this name does not yet exist: create entry
                        if (!Filter::postBool('updateonly')) {
                            $highestIndex = $highestIndex + 1;
                            if ($i + 1 == $num_parent) {
                                $zoomlevel = $place['zoom'];
                            } elseif (isset($default_zoom_level[$i])) {
                                $zoomlevel = $default_zoom_level[$i];
                            } else {
                                $zoomlevel = $this->getSetting('GM_MAX_ZOOM');
                            }
                            if ($place['lati'] == '0' || $place['long'] == '0' || $i + 1 < $num_parent) {
                                Database::prepare("INSERT INTO `##placelocation` (pl_id, pl_parent_id, pl_level, pl_place, pl_zoom, pl_icon) VALUES (?, ?, ?, ?, ?, ?)")->execute(array($highestIndex, $parent_id, $i, $escparent, $zoomlevel, $place['icon']));
                            } else {
                                //delete leading zero
                                $pl_lati = str_replace(array('N', 'S', ','), array('', '-', '.'), $place['lati']);
                                $pl_long = str_replace(array('E', 'W', ','), array('', '-', '.'), $place['long']);
                                if ($pl_lati >= 0) {
                                    $place['lati'] = 'N' . abs($pl_lati);
                                } elseif ($pl_lati < 0) {
                                    $place['lati'] = 'S' . abs($pl_lati);
                                }
                                if ($pl_long >= 0) {
                                    $place['long'] = 'E' . abs($pl_long);
                                } elseif ($pl_long < 0) {
                                    $place['long'] = 'W' . abs($pl_long);
                                }
                                Database::prepare("INSERT INTO `##placelocation` (pl_id, pl_parent_id, pl_level, pl_place, pl_long, pl_lati, pl_zoom, pl_icon) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")->execute(array($highestIndex, $parent_id, $i, $escparent, $place['long'], $place['lati'], $zoomlevel, $place['icon']));
                            }
                            $parent_id = $highestIndex;
                        }
                    } else {
                        $parent_id = $row->pl_id;
                        if (Filter::postBool('overwritedata') && $i + 1 == count($parent)) {
                            Database::prepare("UPDATE `##placelocation` SET pl_lati = ?, pl_long = ?, pl_zoom = ?, pl_icon = ? WHERE pl_id = ?")->execute(array($place['lati'], $place['long'], $place['zoom'], $place['icon'], $parent_id));
                        } else {
                            // Update only if existing data is missing
                            if (!$row->pl_long && !$row->pl_lati) {
                                Database::prepare("UPDATE `##placelocation` SET pl_lati = ?, pl_long = ? WHERE pl_id = ?")->execute(array($place['lati'], $place['long'], $parent_id));
                            }
                            if (!$row->pl_icon && $place['icon']) {
                                Database::prepare("UPDATE `##placelocation` SET pl_icon = ? WHERE pl_id = ?")->execute(array($place['icon'], $parent_id));
                            }
                        }
                    }
                }
            }
            $parent = 0;
        }
        if ($action == 'DeleteRecord') {
            echo '<h2>' . I18N::translate('Geographic data') . '</h2>';
            $exists = Database::prepare("SELECT 1 FROM `##placelocation` WHERE pl_parent_id=?")->execute(array($deleteRecord))->fetchOne();
            if (!$exists) {
                Database::prepare("DELETE FROM `##placelocation` WHERE pl_id=?")->execute(array($deleteRecord));
            } else {
                echo '<table class="facts_table"><tr><td>', I18N::translate('Location not removed: this location contains sub-locations'), '</td></tr></table>';
            }
        }
        ?>
		<script>
		function updateList(inactive) {
			window.location.href='<?php 
        if (strstr(Filter::server('REQUEST_URI'), '&inactive', true)) {
            $uri = strstr(Filter::server('REQUEST_URI'), '&inactive', true);
        } else {
            $uri = Filter::server('REQUEST_URI');
        }
        echo $uri, '&inactive=';
        ?>
'+inactive;
		}

		function edit_place_location(placeid) {
			window.open('module.php?mod=googlemap&mod_action=places_edit&action=update&placeid='+placeid, '_blank', gmap_window_specs);
			return false;
		}

		function add_place_location(placeid) {
			window.open('module.php?mod=googlemap&mod_action=places_edit&action=add&placeid='+placeid, '_blank', gmap_window_specs);
			return false;
		}

		function delete_place(placeid) {
			var answer=confirm('<?php 
        echo I18N::translate('Remove this location?');
        ?>
');
			if (answer == true) {
				window.location = '<?php 
        echo Functions::getQueryUrl(array('action' => 'DeleteRecord'));
        ?>
&action=DeleteRecord&deleteRecord=' + placeid;
			}
		}
		</script>
		<p id="gm_breadcrumb">
			<?php 
        $where_am_i = $this->placeIdToHierarchy($parent);
        foreach (array_reverse($where_am_i, true) as $id => $place) {
            if ($id == $parent) {
                if ($place != 'Unknown') {
                    echo Filter::escapeHtml($place);
                } else {
                    echo I18N::translate('unknown');
                }
            } else {
                echo '<a href="module.php?mod=googlemap&mod_action=admin_places&parent=', $id, '&inactive=', $inactive, '">';
                if ($place != 'Unknown') {
                    echo Filter::escapeHtml($place), '</a>';
                } else {
                    echo I18N::translate('unknown'), '</a>';
                }
            }
            echo ' - ';
        }
        ?>
			<a href="module.php?mod=googlemap&mod_action=admin_places&parent=0&inactive=', $inactive, '"><?php 
        echo I18N::translate('Top level');
        ?>
</a>
		</p>

		<form class="form-inline" name="active" method="post" action="module.php?mod=googlemap&mod_action=admin_places&parent=', $parent, '&inactive=', $inactive, '">
			<div class="checkbox">
				<label for="inactive">
				   <?php 
        echo FunctionsEdit::checkbox('inactive', $inactive, 'onclick="updateList(this.checked)"');
        ?>
				   <?php 
        echo I18N::translate('Show inactive places');
        ?>
				</label>
			</div>
			<p class="small text-muted">
				<?php 
        echo I18N::translate('By default, the list shows only those places which can be found in your family trees. You may have details for other places, such as those imported in bulk from an external file. Selecting this option will show all places, including ones that are not currently used.');
        ?>
				<?php 
        echo I18N::translate('If you have a large number of inactive places, it can be slow to generate the list.');
        ?>
			</p>
		</form>

		<?php 
        $placelist = $this->getPlaceListLocation($parent, $inactive);
        echo '<div class="gm_plac_edit">';
        echo '<table class="table table-bordered table-condensed table-hover"><tr>';
        echo '<th>', GedcomTag::getLabel('PLAC'), '</th>';
        echo '<th>', GedcomTag::getLabel('LATI'), '</th>';
        echo '<th>', GedcomTag::getLabel('LONG'), '</th>';
        echo '<th>', I18N::translate('Zoom level'), '</th>';
        echo '<th>', I18N::translate('Icon'), '</th>';
        echo '<th>';
        echo I18N::translate('Edit'), '</th><th>', I18N::translate('Delete'), '</th></tr>';
        if (count($placelist) == 0) {
            echo '<tr><td colspan="7">', I18N::translate('No places found'), '</td></tr>';
        }
        foreach ($placelist as $place) {
            echo '<tr><td><a href="module.php?mod=googlemap&mod_action=admin_places&parent=', $place['place_id'], '&inactive=', $inactive, '">';
            if ($place['place'] != 'Unknown') {
                echo Filter::escapeHtml($place['place']), '</a></td>';
            } else {
                echo I18N::translate('unknown'), '</a></td>';
            }
            echo '<td>', $place['lati'], '</td>';
            echo '<td>', $place['long'], '</td>';
            echo '<td>', $place['zoom'], '</td>';
            echo '<td>';
            if ($place['icon']) {
                echo '<img src="', WT_STATIC_URL, WT_MODULES_DIR, 'googlemap/', $place['icon'], '" width="25" height="15">';
            } else {
                if ($place['lati'] || $place['long']) {
                    echo '<img src="', WT_STATIC_URL, WT_MODULES_DIR, 'googlemap/images/mm_20_red.png">';
                } else {
                    echo '<img src="', WT_STATIC_URL, WT_MODULES_DIR, 'googlemap/images/mm_20_yellow.png">';
                }
            }
            echo '</td>';
            echo '<td class="narrow"><a href="#" onclick="edit_place_location(', $place['place_id'], ');return false;" class="icon-edit" title="', I18N::translate('Edit'), '"></a></td>';
            $noRows = Database::prepare("SELECT COUNT(pl_id) FROM `##placelocation` WHERE pl_parent_id=?")->execute(array($place['place_id']))->fetchOne();
            if ($noRows == 0) {
                ?>
				<td><a href="#" onclick="delete_place(<?php 
                echo $place['place_id'];
                ?>
);return false;" class="icon-delete" title="<?php 
                echo I18N::translate('Remove');
                ?>
"></a></td>
		<?php 
            } else {
                ?>
				<td><i class="icon-delete-grey"></i></td>
		<?php 
            }
            ?>
			</tr>
			<?php 
        }
        ?>
		</table>
		</div>

		<hr>
		<form class="form-horizontal" action="?" onsubmit="add_place_location(this.parent_id.options[this.parent_id.selectedIndex].value); return false;">
			<div class="form-group">
				<label class="form-control-static col-sm-4" for="parent_id">
					<?php 
        echo I18N::translate('Add a geographic location');
        ?>
				</label>
				<div class="col-sm-8">
					<div class="col-sm-6">
						<?php 
        echo FunctionsEdit::selectEditControl('parent_id', $where_am_i, I18N::translate('Top level'), $parent, 'class="form-control"');
        ?>
					</div>
					<button type="submit" class="btn btn-default">
						<i class="fa fa-plus"></i>
						<?php 
        echo I18N::translate('add');
        ?>
					</button>
				</div>
			</div>
		</form>

		<form class="form-horizontal" action="module.php" method="get">
			<input type="hidden" name="mod" value="googlemap">
			<input type="hidden" name="mod_action" value="admin_places">
			<input type="hidden" name="action" value="ImportGedcom">
			<div class="form-group">
				<label class="form-control-static col-sm-4" for="ged">
					<?php 
        echo I18N::translate('Import all places from a family tree');
        ?>
				</label>
				<div class="col-sm-8">
					<div class="col-sm-6">
						<?php 
        echo FunctionsEdit::selectEditControl('ged', Tree::getNameList(), null, $WT_TREE->getName(), 'class="form-control"');
        ?>
					</div>
					<button type="submit" class="btn btn-default">
						<i class="fa fa-upload"></i>
						<?php 
        echo I18N::translate('import');
        ?>
					</button>
				</div>
			</div>
		</form>

		<form class="form-horizontal" action="module.php" method="get">
			<input type="hidden" name="mod" value="googlemap">
			<input type="hidden" name="mod_action" value="admin_places">
			<input type="hidden" name="action" value="ImportFile">
			<div class="form-group">
				<label class="form-control-static col-sm-4">
					<?php 
        echo I18N::translate('Upload geographic data');
        ?>
				</label>
				<div class="col-sm-8">
					<div class="col-sm-6">
						<button type="submit" class="btn btn-default">
							<i class="fa fa-upload"></i>
							<?php 
        echo I18N::translate('upload');
        ?>
						</button>
					</div>
				</div>
			</div>
		</form>

		<form class="form-horizontal" action="module.php" method="get">
			<input type="hidden" name="mod" value="googlemap">
			<input type="hidden" name="mod_action" value="admin_places">
			<input type="hidden" name="action" value="ExportFile">
			<div class="form-group">
				<label class="form-control-static col-sm-4">
					<?php 
        echo I18N::translate('Download geographic data');
        ?>
				</label>
				<div class="col-sm-8">
					<div class="col-sm-6">
						<?php 
        echo FunctionsEdit::selectEditControl('parent', $where_am_i, I18N::translate('All'), $WT_TREE->getTreeId(), 'class="form-control"');
        ?>
					</div>
					<button type="submit" class="btn btn-default">
						<i class="fa fa-download"></i>
						<?php 
        echo I18N::translate('download');
        ?>
					</button>
				</div>
			</div>
		</form>
		<?php 
    }
Exemplo n.º 5
0
switch ($rule) {
    case 'allow':
        $SEARCH_SPIDER = false;
        break;
    case 'deny':
        http_response_code(403);
        exit;
    case 'robot':
    case 'unknown':
        // Search engines don’t send cookies, and so create a new session with every visit.
        // Make sure they always use the same one
        Session::setId('search-engine-' . str_replace('.', '-', WT_CLIENT_IP));
        $SEARCH_SPIDER = true;
        break;
    case '':
        Database::prepare("INSERT INTO `##site_access_rule` (ip_address_start, ip_address_end, user_agent_pattern, comment) VALUES (IFNULL(INET_ATON(?), 0), IFNULL(INET_ATON(?), 4294967295), ?, '')")->execute(array(WT_CLIENT_IP, WT_CLIENT_IP, Filter::server('HTTP_USER_AGENT', null, '')));
        $SEARCH_SPIDER = true;
        break;
}
// Store our session data in the database.
session_set_save_handler(function () {
    return true;
}, function () {
    return true;
}, function ($id) {
    return Database::prepare("SELECT session_data FROM `##session` WHERE session_id=?")->execute(array($id))->fetchOne();
}, function ($id, $data) {
    // Only update the session table once per minute, unless the session data has actually changed.
    Database::prepare("INSERT INTO `##session` (session_id, user_id, ip_address, session_data, session_time)" . " VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP - SECOND(CURRENT_TIMESTAMP))" . " ON DUPLICATE KEY UPDATE" . " user_id      = VALUES(user_id)," . " ip_address   = VALUES(ip_address)," . " session_data = VALUES(session_data)," . " session_time = CURRENT_TIMESTAMP - SECOND(CURRENT_TIMESTAMP)")->execute(array($id, (int) Auth::id(), WT_CLIENT_IP, $data));
    return true;
}, function ($id) {
Exemplo n.º 6
0
/**
 * https://php.net/http_response_code
 *
 * @param string|null $code
 *
 * @link https://php.net/http_response_code
 *
 * @return int|null
 */
function http_response_code($code = null)
{
    static $http_response_code = 200;
    if ($code !== null) {
        switch ($code) {
            case 100:
                $text = 'Continue';
                break;
            case 101:
                $text = 'Switching Protocols';
                break;
            case 200:
                $text = 'OK';
                break;
            case 201:
                $text = 'Created';
                break;
            case 202:
                $text = 'Accepted';
                break;
            case 203:
                $text = 'Non-Authoritative Information';
                break;
            case 204:
                $text = 'No Content';
                break;
            case 205:
                $text = 'Reset Content';
                break;
            case 206:
                $text = 'Partial Content';
                break;
            case 300:
                $text = 'Multiple Choices';
                break;
            case 301:
                $text = 'Moved Permanently';
                break;
            case 302:
                $text = 'Moved Temporarily';
                break;
            case 303:
                $text = 'See Other';
                break;
            case 304:
                $text = 'Not Modified';
                break;
            case 305:
                $text = 'Use Proxy';
                break;
            case 400:
                $text = 'Bad Request';
                break;
            case 401:
                $text = 'Unauthorized';
                break;
            case 402:
                $text = 'Payment Required';
                break;
            case 403:
                $text = 'Forbidden';
                break;
            case 404:
                $text = 'Not Found';
                break;
            case 405:
                $text = 'Method Not Allowed';
                break;
            case 406:
                $text = 'Not Acceptable';
                break;
            case 407:
                $text = 'Proxy Authentication Required';
                break;
            case 408:
                $text = 'Request Time-out';
                break;
            case 409:
                $text = 'Conflict';
                break;
            case 410:
                $text = 'Gone';
                break;
            case 411:
                $text = 'Length Required';
                break;
            case 412:
                $text = 'Precondition Failed';
                break;
            case 413:
                $text = 'Request Entity Too Large';
                break;
            case 414:
                $text = 'Request-URI Too Large';
                break;
            case 415:
                $text = 'Unsupported Media Type';
                break;
            case 500:
                $text = 'Internal Server Error';
                break;
            case 501:
                $text = 'Not Implemented';
                break;
            case 502:
                $text = 'Bad Gateway';
                break;
            case 503:
                $text = 'Service Unavailable';
                break;
            case 504:
                $text = 'Gateway Time-out';
                break;
            case 505:
                $text = 'HTTP Version not supported';
                break;
            default:
                throw new \DomainException();
        }
        $http_response_code = $code;
        $protocol = Filter::server('SERVER_PROTOCOL', null, 'HTTP/1.0');
        header($protocol . ' ' . $code . ' ' . $text);
    }
    return $http_response_code;
}
Exemplo n.º 7
0
use PDO;
define('WT_SCRIPT_NAME', 'admin_site_access.php');
require './includes/session.php';
$rules_display = array('unknown' => I18N::translate('unknown'), 'allow' => I18N::translate('allow'), 'deny' => I18N::translate('deny'), 'robot' => I18N::translate('robot'));
$rules_edit = array('unknown' => I18N::translate('unknown'), 'allow' => I18N::translate('allow'), 'deny' => I18N::translate('deny'), 'robot' => I18N::translate('robot'));
// Form actions
switch (Filter::post('action')) {
    case 'save':
        if (Filter::checkCsrf()) {
            $site_access_rule_id = Filter::postInteger('site_access_rule_id');
            $ip_address_start = Filter::post('ip_address_start', WT_REGEX_IPV4);
            $ip_address_end = Filter::post('ip_address_end', WT_REGEX_IPV4);
            $user_agent_pattern = Filter::post('user_agent_pattern');
            $rule = Filter::post('rule', 'allow|deny|robot');
            $comment = Filter::post('comment');
            $user_agent_string = Filter::server('HTTP_USER_AGENT');
            $ip_address = WT_CLIENT_IP;
            if ($ip_address_start !== null && $ip_address_end !== null && $user_agent_pattern !== null && $rule !== null) {
                // This doesn't work with named placeholders.  The :user_agent_string parameter is not recognised...
                $oops = $rule !== 'allow' && Database::prepare("SELECT INET_ATON(:ip_address) BETWEEN INET_ATON(:ip_address_start) AND INET_ATON(:ip_address_end)" . " AND :user_agent_string LIKE :user_agent_pattern")->execute(array('ip_address' => $ip_address, 'ip_address_start' => $ip_address_start, 'ip_address_end' => $ip_address_end, 'user_agent_string' => $user_agent_string, 'user_agent_pattern' => $user_agent_pattern))->fetchOne();
                if ($oops) {
                    FlashMessages::addMessage(I18N::translate('You cannot create a rule which would prevent yourself from accessing the website.'), 'danger');
                } elseif ($site_access_rule_id === null) {
                    Database::prepare("INSERT INTO `##site_access_rule` (ip_address_start, ip_address_end, user_agent_pattern, rule, comment) VALUES (INET_ATON(:ip_address_start), INET_ATON(:ip_address_end), :user_agent_pattern, :rule, :comment)")->execute(array('ip_address_start' => $ip_address_start, 'ip_address_end' => $ip_address_end, 'user_agent_pattern' => $user_agent_pattern, 'rule' => $rule, 'comment' => $comment));
                    FlashMessages::addMessage(I18N::translate('The website access rule has been created.'), 'success');
                } else {
                    Database::prepare("UPDATE `##site_access_rule` SET ip_address_start = INET_ATON(:ip_address_start), ip_address_end = INET_ATON(:ip_address_end), user_agent_pattern = :user_agent_pattern, rule = :rule, comment = :comment WHERE site_access_rule_id = :site_access_rule_id")->execute(array('ip_address_start' => $ip_address_start, 'ip_address_end' => $ip_address_end, 'user_agent_pattern' => $user_agent_pattern, 'rule' => $rule, 'comment' => $comment, 'site_access_rule_id' => $site_access_rule_id));
                    FlashMessages::addMessage(I18N::translate('The website access rule has been updated.'), 'success');
                }
            }
        }