Exemplo n.º 1
0
 public function onAfterInitialise()
 {
     $ip = AtsystemUtilFilter::getIp();
     $continents = $this->cparams->getValue('geoblockcontinents', '');
     $continents = empty($continents) ? array() : explode(',', $continents);
     $countries = $this->cparams->getValue('geoblockcountries', '');
     $countries = empty($countries) ? array() : explode(',', $countries);
     $geoip = new AkeebaGeoipProvider();
     $country = $geoip->getCountryCode($ip);
     $continent = $geoip->getContinent($ip);
     if (empty($country)) {
         $country = '(unknown country)';
     }
     if (empty($continent)) {
         $continent = '(unknown continent)';
     }
     if ($continent && !empty($continents) && in_array($continent, $continents)) {
         $extraInfo = 'Continent : ' . $continent;
         $this->exceptionsHandler->blockRequest('geoblocking', null, $extraInfo);
     }
     if ($country && !empty($countries) && in_array($country, $countries)) {
         $extraInfo = 'Country : ' . $country;
         $this->exceptionsHandler->blockRequest('geoblocking', null, $extraInfo);
     }
 }
Exemplo n.º 2
0
 public function updategeoip()
 {
     if ($this->csrfProtection) {
         $this->_csrfProtection();
     }
     // Load the GeoIP library if it's not already loaded
     if (!class_exists('AkeebaGeoipProvider')) {
         if (@file_exists(JPATH_PLUGINS . '/system/akgeoip/lib/akgeoip.php')) {
             if (@(include_once JPATH_PLUGINS . '/system/akgeoip/lib/vendor/autoload.php')) {
                 @(include_once JPATH_PLUGINS . '/system/akgeoip/lib/akgeoip.php');
             }
         }
     }
     $geoip = new AkeebaGeoipProvider();
     $result = $geoip->updateDatabase();
     $url = 'index.php?option=com_admintools';
     if ($result === true) {
         $msg = JText::_('ATOOLS_GEOBLOCK_MSG_DOWNLOADEDGEOIPDATABASE');
         $this->setRedirect($url, $msg);
     } else {
         $this->setRedirect($url, $result, 'error');
     }
 }
Exemplo n.º 3
0
 /**
  * Returns the country of the current user using GeoIP detection, as long as we can get their IP from the server,
  * the GeoIP Provider plugin is installed and returns results for that IP.
  *
  * @return  string  The country code or "XX" when no detection was possible.
  */
 private function getCountryFromGeoIP()
 {
     $country = 'XX';
     // If the GeoIP provider is not loaded return "XX" (no country detected)
     if (!class_exists('AkeebaGeoipProvider')) {
         return $country;
     }
     // Get the IP from the server
     $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
     // If we have a newer FOF version, use it to get the correct IP address of the client
     if (class_exists('F0FUtilsIp')) {
         $ip = F0FUtilsIp::getIp();
     }
     // Use GeoIP to detect the country
     $geoip = new AkeebaGeoipProvider();
     $country = $geoip->getCountryCode($ip);
     // If detection failed, return "XX" (no country detected)
     if (empty($country)) {
         $country = 'XX';
     }
     return $country;
 }
Exemplo n.º 4
0
 /**
  * Sends an email upon accessing an administrator page other than the login screen
  */
 public function onAfterInitialise()
 {
     $user = JFactory::getUser();
     // Check if the session flag is set (avoid sending thousands of emails!)
     $session = JFactory::getSession();
     $flag = $session->get('waf.loggedin', 0, 'plg_admintools');
     if ($flag == 1) {
         return;
     }
     // Load the component's administrator translation files
     $jlang = JFactory::getLanguage();
     $jlang->load('com_admintools', JPATH_ADMINISTRATOR, 'en-GB', true);
     $jlang->load('com_admintools', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
     $jlang->load('com_admintools', JPATH_ADMINISTRATOR, null, true);
     // Get the username
     $username = $user->username;
     // Get the site name
     $config = JFactory::getConfig();
     if (version_compare(JVERSION, '3.0', 'ge')) {
         $sitename = $config->get('sitename');
     } else {
         $sitename = $config->getValue('config.sitename');
     }
     // Get the IP address
     $ip = AtsystemUtilFilter::getIp();
     if (strpos($ip, '::') === 0 && strstr($ip, '.') !== false) {
         $ip = substr($ip, strrpos($ip, ':') + 1);
     }
     $country = '';
     $continent = '';
     if (class_exists('AkeebaGeoipProvider')) {
         $geoip = new AkeebaGeoipProvider();
         $country = $geoip->getCountryCode($ip);
         $continent = $geoip->getContinent($ip);
     }
     if (empty($country)) {
         $country = '(unknown country)';
     }
     if (empty($continent)) {
         $continent = '(unknown continent)';
     }
     // Construct the replacement table
     $substitutions = array('[SITENAME]' => $sitename, '[USERNAME]' => $username, '[IP]' => $ip, '[UASTRING]' => $_SERVER['HTTP_USER_AGENT'], '[COUNTRY]' => $country, '[CONTINENT]' => $continent);
     $subject = JText::_('ATOOLS_LBL_WAF_EMAILADMINLOGIN_SUBJECT_21');
     $body = JText::_('ATOOLS_LBL_WAF_EMAILADMINLOGIN_BODY_21');
     foreach ($substitutions as $k => $v) {
         $subject = str_replace($k, $v, $subject);
         $body = str_replace($k, $v, $body);
     }
     // Send the email
     $mailer = JFactory::getMailer();
     $mailfrom = $config->get('mailfrom');
     $fromname = $config->get('fromname');
     $recipients = explode(',', $this->cparams->getValue('emailonadminlogin', ''));
     $recipients = array_map('trim', $recipients);
     foreach ($recipients as $recipient) {
         $mailer->setSender(array($mailfrom, $fromname));
         $mailer->addRecipient($recipient);
         $mailer->setSubject($subject);
         $mailer->setBody($body);
         $mailer->Send();
     }
     // Set the flag to prevent sending more emails
     $session->set('waf.loggedin', 1, 'plg_admintools');
 }
Exemplo n.º 5
0
 /**
  * Processes the form data and creates a new subscription
  */
 public function createNewSubscription()
 {
     // Fetch state and validation variables
     $this->setState('opt', '');
     $state = $this->getStateVariables();
     $validation = $this->getValidation();
     // Mark this subscription attempt in the session
     JFactory::getSession()->set('apply_validation.' . $state->id, 1, 'com_akeebasubs');
     // Step #1.a. Check that the form is valid
     // ----------------------------------------------------------------------
     $isValid = $this->isValid();
     if (!$isValid) {
         return false;
     }
     // Step #1.b. Check that the subscription level is allowed
     // ----------------------------------------------------------------------
     // Is this actually an allowed subscription level?
     $allowedLevels = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->only_once(1)->enabled(1)->getItemList();
     $allowed = false;
     if (count($allowedLevels)) {
         foreach ($allowedLevels as $l) {
             if ($l->akeebasubs_level_id == $state->id) {
                 $allowed = true;
                 break;
             }
         }
     }
     if (!$allowed) {
         return false;
     }
     // Fetch the level's object, used later on
     $level = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->getItem($state->id);
     // Step #2. Check that the payment plugin exists or return false
     // ----------------------------------------------------------------------
     $plugins = $this->getPaymentPlugins();
     $found = false;
     if (!empty($plugins)) {
         foreach ($plugins as $plugin) {
             if ($plugin->name == $state->paymentmethod) {
                 $found = true;
                 break;
             }
         }
     }
     if (!$found) {
         return false;
     }
     // Reset the session flag, so that future registrations will merge the
     // data from the database
     JFactory::getSession()->set('firstrun', true, 'com_akeebasubs');
     // Step #2.b. Apply block rules in the Professional release
     // ----------------------------------------------------------------------
     if (F0FModel::getTmpInstance('Blockrules', 'AkeebasubsModel')->isBlocked($state)) {
         throw new Exception(JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 403);
     }
     // Step #3. Create or update a user record
     // ----------------------------------------------------------------------
     $user = JFactory::getUser();
     $this->setState('user', $user);
     $userIsSaved = $this->updateUserInfo(true, $level);
     if (!$userIsSaved) {
         return false;
     } else {
         $user = $this->getState('user', $user);
     }
     // Store the user's ID in the session
     $session = JFactory::getSession();
     $session->set('subscribes.user_id', $user->id, 'com_akeebasubs');
     // Step #4. Create or add user extra fields
     // ----------------------------------------------------------------------
     // Find an existing record
     $dummy = $this->saveCustomFields();
     // Step #5. Check for existing subscription records and calculate the subscription expiration date
     // ----------------------------------------------------------------------
     // First, the question: is this level part of a group?
     $haveLevelGroup = false;
     if ($level->akeebasubs_levelgroup_id > 0) {
         // Is the level group published?
         $levelGroup = F0FModel::getTmpInstance('Levelgroups', 'AkeebasubsModel')->getItem($level->akeebasubs_levelgroup_id);
         if ($levelGroup instanceof F0FTable) {
             $haveLevelGroup = $levelGroup->enabled;
         }
     }
     if ($haveLevelGroup) {
         // We have a level group. Get all subscriptions for all levels in
         // the group.
         $subscriptions = array();
         $levelsInGroup = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->levelgroup($level->akeebasubs_levelgroup_id)->getList(true);
         foreach ($levelsInGroup as $l) {
             $someSubscriptions = F0FModel::getTmpInstance('Subscriptions', 'AkeebasubsModel')->user_id($user->id)->level($l->akeebasubs_level_id)->paystate('C')->getList(true);
             if (count($someSubscriptions)) {
                 $subscriptions = array_merge($subscriptions, $someSubscriptions);
             }
         }
     } else {
         // No level group found. Get subscriptions on the same level.
         $subscriptions = F0FModel::getTmpInstance('Subscriptions', 'AkeebasubsModel')->user_id($user->id)->level($state->id)->paystate('C')->getList(true);
     }
     $jNow = new JDate();
     $now = $jNow->toUnix();
     $mNow = $jNow->toSql();
     if (empty($subscriptions)) {
         $startDate = $now;
     } else {
         $startDate = $now;
         foreach ($subscriptions as $row) {
             // Only take into account paid-for subscriptions
             if ($row->state != 'C') {
                 continue;
             }
             // Calculate the expiration date
             $jDate = new JDate($row->publish_down);
             $expiryDate = $jDate->toUnix();
             // If the subscription expiration date is earlier than today, ignore it
             if ($expiryDate < $now) {
                 continue;
             }
             // If the previous subscription's expiration date is later than the current start date,
             // update the start date to be one second after that.
             if ($expiryDate > $startDate) {
                 $startDate = $expiryDate + 1;
             }
             // Also mark the old subscription as "communicated". We don't want
             // to spam our users with subscription renewal notices or expiration
             // notification after they have effectively renewed!
             F0FModel::getTmpInstance('Subscriptions', 'AkeebasubsModel')->setId($row->akeebasubs_subscription_id)->getItem()->save(array('contact_flag' => 3));
         }
     }
     // Step #6. Create a new subscription record
     // ----------------------------------------------------------------------
     $nullDate = JFactory::getDbo()->getNullDate();
     $level = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->setId($state->id)->getItem();
     if ($level->forever) {
         $jStartDate = new JDate();
         $endDate = '2038-01-01 00:00:00';
     } elseif (!is_null($level->fixed_date) && $level->fixed_date != $nullDate) {
         $jStartDate = new JDate();
         $endDate = $level->fixed_date;
     } else {
         $jStartDate = new JDate($startDate);
         // Subscription duration (length) modifiers, via plugins
         $duration_modifier = 0;
         JLoader::import('joomla.plugin.helper');
         JPluginHelper::importPlugin('akeebasubs');
         $app = JFactory::getApplication();
         $jResponse = $app->triggerEvent('onValidateSubscriptionLength', array($state));
         if (is_array($jResponse) && !empty($jResponse)) {
             foreach ($jResponse as $pluginResponse) {
                 if (empty($pluginResponse)) {
                     continue;
                 }
                 $duration_modifier += $pluginResponse;
             }
         }
         // Calculate the effective duration
         $duration = (int) $level->duration + $duration_modifier;
         if ($duration <= 0) {
             $duration = 0;
         }
         $duration = $duration * 3600 * 24;
         $endDate = $startDate + $duration;
     }
     $mStartDate = $jStartDate->toSql();
     $jEndDate = new JDate($endDate);
     $mEndDate = $jEndDate->toSql();
     // Store the price validation's "oldsub" and "expiration" keys in
     // the subscriptions subcustom array
     $subcustom = $state->subcustom;
     if (empty($subcustom)) {
         $subcustom = array();
     } elseif (is_object($subcustom)) {
         $subcustom = (array) $subcustom;
     }
     $priceValidation = $this->validatePrice();
     $subcustom['fixdates'] = array('oldsub' => $priceValidation->oldsub, 'allsubs' => $priceValidation->allsubs, 'expiration' => $priceValidation->expiration);
     // Serialise custom subscription parameters
     $custom_subscription_params = json_encode($subcustom);
     // Get the IP address
     $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
     if (class_exists('F0FUtilsIp', true)) {
         $ip = F0FUtilsIp::getIp();
     }
     // Get the country from the IP address if the Akeeba GeoIP Provider Plugin is installed and activated
     $ip_country = '(Unknown)';
     if (class_exists('AkeebaGeoipProvider')) {
         $geoip = new AkeebaGeoipProvider();
         $ip_country = $geoip->getCountryName($ip);
         if (empty($ip_country)) {
             $ip_country = '(Unknown)';
         }
     }
     // Setup the new subscription
     $data = array('akeebasubs_subscription_id' => null, 'user_id' => $user->id, 'akeebasubs_level_id' => $state->id, 'publish_up' => $mStartDate, 'publish_down' => $mEndDate, 'notes' => '', 'enabled' => $validation->price->gross < 0.01 ? 1 : 0, 'processor' => $validation->price->gross < 0.01 ? 'none' : $state->paymentmethod, 'processor_key' => $validation->price->gross < 0.01 ? $this->_uuid(true) : '', 'state' => $validation->price->gross < 0.01 ? 'C' : 'N', 'net_amount' => $validation->price->net - $validation->price->discount, 'tax_amount' => $validation->price->tax, 'gross_amount' => $validation->price->gross, 'recurring_amount' => $validation->price->recurring, 'tax_percent' => $validation->price->taxrate, 'created_on' => $mNow, 'params' => $custom_subscription_params, 'ip' => $ip, 'ip_country' => $ip_country, 'akeebasubs_coupon_id' => $validation->price->couponid, 'akeebasubs_upgrade_id' => $validation->price->upgradeid, 'contact_flag' => 0, 'prediscount_amount' => $validation->price->net, 'discount_amount' => $validation->price->discount, 'first_contact' => '0000-00-00 00:00:00', 'second_contact' => '0000-00-00 00:00:00', 'akeebasubs_affiliate_id' => 0, 'affiliate_comission' => 0);
     $subscription = F0FModel::getTmpInstance('Subscriptions', 'AkeebasubsModel')->getTable();
     $subscription->reset();
     $subscription->akeebasubs_subscription_id = 0;
     $subscription->_dontCheckPaymentID = true;
     $result = $subscription->save($data);
     $this->_item = $subscription;
     // Step #7. Hit the coupon code, if a coupon is indeed used
     // ----------------------------------------------------------------------
     if ($validation->price->couponid) {
         F0FModel::getTmpInstance('Coupons', 'AkeebasubsModel')->setId($validation->price->couponid)->getItem()->hit();
     }
     // Step #8. Clear the session
     // ----------------------------------------------------------------------
     $session = JFactory::getSession();
     $session->set('validation_cache_data', null, 'com_akeebasubs');
     $session->set('apply_validation.' . $state->id, null, 'com_akeebasubs');
     // Step #9. Call the specific plugin's onAKPaymentNew() method and get the redirection URL,
     //          or redirect immediately on auto-activated subscriptions
     // ----------------------------------------------------------------------
     if ($subscription->gross_amount != 0) {
         // Non-zero charges; use the plugins
         $app = JFactory::getApplication();
         $jResponse = $app->triggerEvent('onAKPaymentNew', array($state->paymentmethod, $user, $level, $subscription));
         if (empty($jResponse)) {
             return false;
         }
         foreach ($jResponse as $response) {
             if ($response === false) {
                 continue;
             }
             $this->paymentForm = $response;
         }
     } else {
         // Zero charges. First apply subscription replacement
         if (!class_exists('plgAkpaymentAbstract')) {
             require_once JPATH_ADMINISTRATOR . '/components/com_akeebasubs/assets/akpayment.php';
         }
         $updates = array();
         plgAkpaymentAbstract::fixSubscriptionDates($subscription, $updates);
         if (!empty($updates)) {
             $result = $subscription->save($updates);
             $this->_item = $subscription;
         }
         // and then just redirect
         $app = JFactory::getApplication();
         $slug = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->setId($subscription->akeebasubs_level_id)->getItem()->slug;
         $app->redirect(str_replace('&amp;', '&', JRoute::_('index.php?option=com_akeebasubs&layout=default&view=message&slug=' . $slug . '&layout=order&subid=' . $subscription->akeebasubs_subscription_id)));
         return false;
     }
     // Return true
     // ----------------------------------------------------------------------
     return true;
 }
Exemplo n.º 6
0
 /**
  * Checks if an IP address should be automatically banned for raising too many security exceptions over a predefined
  * time period.
  *
  * @param   string $reason The reason of the ban
  *
  * @return  void
  */
 public function autoBan($reason = 'other')
 {
     // We need to be able to get our own IP, right?
     if (!function_exists('inet_pton')) {
         return;
     }
     // Get the IP
     $ip = AtsystemUtilFilter::getIp();
     // No point continuing if we can't get an address, right?
     if (empty($ip) || $ip == '0.0.0.0') {
         return;
     }
     // Check for repeat offenses
     $db = JFactory::getDBO();
     $strikes = $this->cparams->getValue('tsrstrikes', 3);
     $numfreq = $this->cparams->getValue('tsrnumfreq', 1);
     $frequency = $this->cparams->getValue('tsrfrequency', 'hour');
     $mindatestamp = 0;
     switch ($frequency) {
         case 'second':
             break;
         case 'minute':
             $numfreq *= 60;
             break;
         case 'hour':
             $numfreq *= 3600;
             break;
         case 'day':
             $numfreq *= 86400;
             break;
         case 'ever':
             $mindatestamp = 946706400;
             // January 1st, 2000
             break;
     }
     JLoader::import('joomla.utilities.date');
     $jNow = new JDate();
     if ($mindatestamp == 0) {
         $mindatestamp = $jNow->toUnix() - $numfreq;
     }
     $jMinDate = new JDate($mindatestamp);
     $minDate = $jMinDate->toSql();
     $sql = $db->getQuery(true)->select('COUNT(*)')->from($db->qn('#__admintools_log'))->where($db->qn('logdate') . ' >= ' . $db->q($minDate))->where($db->qn('ip') . ' = ' . $db->q($ip));
     $db->setQuery($sql);
     try {
         $numOffenses = $db->loadResult();
     } catch (Exception $e) {
         $numOffenses = 0;
     }
     if ($numOffenses < $strikes) {
         return;
     }
     // Block the IP
     $myIP = @inet_pton($ip);
     if ($myIP === false) {
         return;
     }
     $myIP = inet_ntop($myIP);
     $until = $jNow->toUnix();
     $numfreq = $this->cparams->getValue('tsrbannum', 1);
     $frequency = $this->cparams->getValue('tsrbanfrequency', 'hour');
     switch ($frequency) {
         case 'second':
             $until += $numfreq;
             break;
         case 'minute':
             $numfreq *= 60;
             $until += $numfreq;
             break;
         case 'hour':
             $numfreq *= 3600;
             $until += $numfreq;
             break;
         case 'day':
             $numfreq *= 86400;
             $until += $numfreq;
             break;
         case 'ever':
             $until = 2145938400;
             // January 1st, 2038 (mind you, UNIX epoch runs out on January 19, 2038!)
             break;
     }
     JLoader::import('joomla.utilities.date');
     $jMinDate = new JDate($until);
     $minDate = $jMinDate->toSql();
     $record = (object) array('ip' => $myIP, 'reason' => $reason, 'until' => $minDate);
     // If I'm here it means that we have to ban the user. Let's see if this is a simple autoban or
     // we have to issue a permaban as a result of several attacks
     if ($this->cparams->getValue('permaban', 0)) {
         // Ok I have to check the number of autoban
         $query = $db->getQuery(true)->select('COUNT(*)')->from($db->qn('#__admintools_ipautobanhistory'))->where($db->qn('ip') . ' = ' . $db->q($myIP));
         try {
             $bans = $db->setQuery($query)->loadResult();
         } catch (Exception $e) {
             $bans = 0;
         }
         $limit = (int) $this->cparams->getValue('permabannum', 0);
         if ($limit && $bans >= $limit) {
             $block = (object) array('ip' => $myIP, 'description' => 'IP automatically blocked after being banned automatically ' . $bans . ' times');
             $db->insertObject('#__admintools_ipblock', $block);
         }
     }
     $db->insertObject('#__admintools_ipautoban', $record);
     // Send an optional email
     if ($this->cparams->getValue('emailafteripautoban', '')) {
         // Load the component's administrator translation files
         $jlang = JFactory::getLanguage();
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, 'en-GB', true);
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, null, true);
         // Get the site name
         $config = JFactory::getConfig();
         $sitename = $config->get('sitename');
         $country = '';
         $continent = '';
         if (class_exists('AkeebaGeoipProvider')) {
             $geoip = new AkeebaGeoipProvider();
             $country = $geoip->getCountryCode($ip);
             $continent = $geoip->getContinent($ip);
         }
         if (empty($country)) {
             $country = '(unknown country)';
         }
         if (empty($continent)) {
             $continent = '(unknown continent)';
         }
         $uri = JURI::getInstance();
         $url = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port', 'path', 'query', 'fragment'));
         $ip_link = $this->cparams->getValue('iplookupscheme', 'http') . '://' . $this->cparams->getValue('iplookup', 'ip-lookup.net/index.php?ip={ip}');
         $ip_link = str_replace('{ip}', $ip, $ip_link);
         $substitutions = array('[SITENAME]' => $sitename, '[REASON]' => JText::_('COM_ADMINTOOLS_EMAILTEMPLATE_REASON_IPAUTOBAN'), '[DATE]' => gmdate('Y-m-d H:i:s') . " GMT", '[URL]' => $url, '[USER]' => '', '[IP]' => $ip, '[LOOKUP]' => '<a href="' . $ip_link . '">IP Lookup</a>', '[COUNTRY]' => $country, '[CONTINENT]' => $continent, '[UA]' => $_SERVER['HTTP_USER_AGENT'], '[UNTIL]' => $minDate);
         // Load the component's administrator translation files
         $jlang = JFactory::getLanguage();
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, 'en-GB', true);
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, null, true);
         // Let's get the most suitable email template
         $template = $this->getEmailTemplate('ipautoban');
         // Got no template, the user didn't published any email template, or the template doesn't want us to
         // send a notification email. Anyway, let's stop here.
         if (!$template) {
             return;
         } else {
             $subject = $template[0];
             $body = $template[1];
         }
         foreach ($substitutions as $k => $v) {
             $subject = str_replace($k, $v, $subject);
             $body = str_replace($k, $v, $body);
         }
         // Send the email
         $mailer = JFactory::getMailer();
         $mailfrom = $config->get('mailfrom');
         $fromname = $config->get('fromname');
         $mailer->isHtml(true);
         $mailer->setSender(array($mailfrom, $fromname));
         $mailer->addRecipient($this->cparams->getValue('emailafteripautoban', ''));
         $mailer->setSubject($subject);
         $mailer->setBody($body);
         $mailer->Send();
     }
 }
Exemplo n.º 7
0
 /**
  * Logs security exceptions
  *
  * @param string $reason                   Block reason code
  * @param string $extraLogInformation      Extra information to be written to the text log file
  * @param string $extraLogTableInformation Extra information to be written to the extradata field of the log table (useful for JSON format)
  *
  * @return bool
  */
 public function logBreaches($reason, $extraLogInformation = '', $extraLogTableInformation = '')
 {
     $reasons_nolog = $this->cparams->getValue('reasons_nolog', 'geoblocking');
     $reasons_noemail = $this->cparams->getValue('reasons_noemail', 'geoblocking');
     $whitelist_domains = $this->cparams->getValue('whitelist_domains', '.googlebot.com,.search.msn.com');
     $reasons_nolog = explode(',', $reasons_nolog);
     $reasons_noemail = explode(',', $reasons_noemail);
     $whitelist_domains = explode(',', $whitelist_domains);
     // === SANITY CHECK - BEGIN ===
     // Get our IP address
     $ip = AtsystemUtilFilter::getIp();
     if (strpos($ip, '::') === 0 && strstr($ip, '.') !== false) {
         $ip = substr($ip, strrpos($ip, ':') + 1);
     }
     // No point continuing if we can't get an address, right?
     if (empty($ip) || $ip == '0.0.0.0') {
         return false;
     }
     // Make sure it's not an IP in the safe list
     $safeIPs = $this->cparams->getValue('neverblockips', '');
     if (!empty($safeIPs)) {
         $safeIPs = explode(',', $safeIPs);
         if (!empty($safeIPs)) {
             if (AtsystemUtilFilter::IPinList($safeIPs)) {
                 return false;
             }
         }
     }
     // Make sure we don't have a list in the administrator white list
     if ($this->cparams->getValue('ipwl', 0) == 1) {
         $db = JFactory::getDBO();
         $sql = $db->getQuery(true)->select($db->qn('ip'))->from($db->qn('#__admintools_adminiplist'));
         $db->setQuery($sql);
         try {
             if (version_compare(JVERSION, '3.0', 'ge')) {
                 $ipTable = $db->loadColumn();
             } else {
                 $ipTable = $db->loadResultArray();
             }
         } catch (Exception $e) {
             $ipTable = null;
         }
         if (!empty($ipTable)) {
             if (AtsystemUtilFilter::IPinList($ipTable)) {
                 return false;
             }
         }
     }
     // Make sure this IP doesn't resolve to a whitelisted domain
     if (!empty($whitelist_domains)) {
         $remote_domain = @gethostbyaddr($ip);
         if (!empty($remote_domain)) {
             foreach ($whitelist_domains as $domain) {
                 $domain = trim($domain);
                 if (strrpos($remote_domain, $domain) !== false) {
                     return true;
                 }
             }
         }
     }
     // === SANITY CHECK - END ===
     // DO I have any kind of log? Let's get some extra info
     if ($this->cparams->getValue('logbreaches', 0) && !in_array($reason, $reasons_nolog) || $this->cparams->getValue('emailbreaches', '') && !in_array($reason, $reasons_noemail)) {
         $uri = JURI::getInstance();
         $url = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port', 'path', 'query', 'fragment'));
         JLoader::import('joomla.utilities.date');
         $date = new JDate();
         $user = JFactory::getUser();
         if ($user->guest) {
             $username = '******';
         } else {
             $username = $user->username . ' (' . $user->name . ' <' . $user->email . '>)';
         }
         $country = '';
         $continent = '';
         if (class_exists('AkeebaGeoipProvider')) {
             $geoip = new AkeebaGeoipProvider();
             $country = $geoip->getCountryCode($ip);
             $continent = $geoip->getContinent($ip);
         }
         if (empty($country)) {
             $country = '(unknown country)';
         }
         if (empty($continent)) {
             $continent = '(unknown continent)';
         }
     }
     if ($this->cparams->getValue('logbreaches', 0) && !in_array($reason, $reasons_nolog)) {
         // Logging to file
         $config = JFactory::getConfig();
         if (version_compare(JVERSION, '3.0', 'ge')) {
             $logpath = $config->get('log_path');
         } else {
             $logpath = $config->getValue('log_path');
         }
         $fname = $logpath . DIRECTORY_SEPARATOR . 'admintools_breaches.log';
         // -- Check the file size. If it's over 1Mb, archive and start a new log.
         if (@file_exists($fname)) {
             $fsize = filesize($fname);
             if ($fsize > 1048756) {
                 if (@file_exists($fname . '.1')) {
                     unlink($fname . '.1');
                 }
                 @copy($fname, $fname . '.1');
                 @unlink($fname);
             }
         }
         // -- Log the exception
         $fp = @fopen($fname, 'at');
         if ($fp !== false) {
             fwrite($fp, str_repeat('-', 79) . "\n");
             fwrite($fp, "Blocking reason: " . $reason . "\n" . str_repeat('-', 79) . "\n");
             fwrite($fp, 'Date/time : ' . gmdate('Y-m-d H:i:s') . " GMT\n");
             fwrite($fp, 'URL       : ' . $url . "\n");
             fwrite($fp, 'User      : '******'IP        : ' . $ip . "\n");
             fwrite($fp, 'Country   : ' . $country . "\n");
             fwrite($fp, 'Continent : ' . $continent . "\n");
             fwrite($fp, 'UA        : ' . $_SERVER['HTTP_USER_AGENT'] . "\n");
             if (!empty($extraLogInformation)) {
                 fwrite($fp, $extraLogInformation . "\n");
             }
             fwrite($fp, "\n\n");
             fclose($fp);
         }
         // ...and write a record to the log table
         $db = JFactory::getDBO();
         $logEntry = (object) array('logdate' => $date->toSql(), 'ip' => $ip, 'url' => $url, 'reason' => $reason, 'extradata' => $extraLogTableInformation);
         try {
             $db->insertObject('#__admintools_log', $logEntry);
         } catch (Exception $e) {
             // Do nothing if the query fails
         }
     }
     $emailbreaches = $this->cparams->getValue('emailbreaches', '');
     if (!empty($emailbreaches) && !in_array($reason, $reasons_noemail)) {
         // Load the component's administrator translation files
         $jlang = JFactory::getLanguage();
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, 'en-GB', true);
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, null, true);
         // Get the site name
         $config = JFactory::getConfig();
         if (version_compare(JVERSION, '3.0', 'ge')) {
             $sitename = $config->get('sitename');
         } else {
             $sitename = $config->getValue('config.sitename');
         }
         // Create a link to lookup the IP
         $ip_link = $this->cparams->getValue('iplookupscheme', 'http') . '://' . $this->cparams->getValue('iplookup', 'ip-lookup.net/index.php?ip={ip}');
         $ip_link = str_replace('{ip}', $ip, $ip_link);
         // Get the reason in human readable format
         $txtReason = JText::_('ATOOLS_LBL_REASON_' . strtoupper($reason));
         // Get extra information
         if ($extraLogTableInformation) {
             list($logReason, ) = explode('|', $extraLogTableInformation);
             $txtReason .= " ({$logReason})";
         }
         // Send the email
         $mailer = JFactory::getMailer();
         if (version_compare(JVERSION, '3.0', 'ge')) {
             $mailfrom = $config->get('mailfrom');
             $fromname = $config->get('fromname');
         } else {
             $mailfrom = $config->getValue('config.mailfrom');
             $fromname = $config->getValue('config.fromname');
         }
         // Let's get the most suitable email template
         $template = $this->getEmailTemplate($reason);
         // Got no template, the user didn't published any email template, or the template doesn't want us to
         // send a notification email. Anyway, let's stop here
         if (!$template) {
             return true;
         } else {
             $subject = $template[0];
             $body = $template[1];
         }
         $tokens = array('[SITENAME]' => $sitename, '[REASON]' => $txtReason, '[DATE]' => gmdate('Y-m-d H:i:s') . " GMT", '[URL]' => $url, '[USER]' => $username, '[IP]' => $ip, '[LOOKUP]' => '<a href="' . $ip_link . '">IP Lookup</a>', '[COUNTRY]' => $country, '[CONTINENT]' => $continent, '[UA]' => $_SERVER['HTTP_USER_AGENT']);
         $subject = str_replace(array_keys($tokens), array_values($tokens), $subject);
         $body = str_replace(array_keys($tokens), array_values($tokens), $body);
         $recipients = explode(',', $emailbreaches);
         $recipients = array_map('trim', $recipients);
         foreach ($recipients as $recipient) {
             $mailer->isHtml(true);
             $mailer->setSender(array($mailfrom, $fromname));
             $mailer->addRecipient($recipient);
             $mailer->setSubject($subject);
             $mailer->setBody($body);
             $mailer->Send();
         }
     }
     return true;
 }
Exemplo n.º 8
0
 public function check()
 {
     if (empty($this->user_id)) {
         $user = $this->container->platform->getUser();
         $this->user_id = $user->id;
     }
     if (empty($this->item_id)) {
         // Yeah, I know, the Model shouldn't access the input directly but this saves us a lot of code in the
         // front-end models where we're logging downloads.
         $this->item_id = $this->input->getInt('id', 0);
     }
     if (empty($this->accessed_on) || $this->accessed_on == '0000-00-00 00:00:00') {
         \JLoader::import('joomla.utilities.date');
         $date = new \JDate();
         $this->accessed_on = $date->toSql();
     }
     if (empty($this->referer)) {
         if (isset($_SERVER['HTTP_REFERER'])) {
             $this->referer = $_SERVER['HTTP_REFERER'];
         }
     }
     if (empty($this->ip)) {
         $this->ip = Ip::getIp();
         if (class_exists('\\AkeebaGeoipProvider')) {
             $geoip = new \AkeebaGeoipProvider();
             $this->country = $geoip->getCountryCode($this->ip);
         }
     }
     return parent::check();
 }