Exemplo n.º 1
0
 public function check(User_Model_User $user)
 {
     // No CLI
     if ('cli' === PHP_SAPI) {
         return;
     }
     // Prepare
     $id = (int) $user->getIdentity();
     // Get ip address
     $db = $this->getAdapter();
     $ipObj = new Engine_IP();
     $ipExpr = new Zend_Db_Expr($db->quoteInto('UNHEX(?)', bin2hex($ipObj->toBinary())));
     // Run update first
     $count = $this->update(array('active' => date('Y-m-d H:i:s')), array('user_id = ?' => $id, 'ip = ?' => $ipExpr, 'active > ?' => new Zend_Db_Expr('DATE_SUB(NOW(),INTERVAL 20 MINUTE)')));
     // Run insert if update doesn't do anything
     if ($count < 1) {
         if ($this->getAdapter() instanceof Zend_Db_Adapter_Mysqli || $this->getAdapter() instanceof Engine_Db_Adapter_Mysql || $this->getAdapter() instanceof Zend_Db_Adapter_Pdo_Mysql) {
             $sql = 'INSERT IGNORE INTO `' . $this->info('name') . '` (`user_id`, `ip`, `active`) VALUES (?, UNHEX(?), ?)';
             $sql = $this->getAdapter()->quoteInto($sql, $id, null, 1);
             $sql = $this->getAdapter()->quoteInto($sql, bin2hex($ipObj->toBinary()), null, 1);
             $sql = $this->getAdapter()->quoteInto($sql, date('Y-m-d H:i:s'), null, 1);
             $this->getAdapter()->query($sql);
         } else {
             $this->insert(array('user_id' => $id, 'ip' => $ipExpr, 'active' => date('Y-m-d H:i:s')));
         }
     }
     return $this;
 }
Exemplo n.º 2
0
 protected function addAdditionalElements()
 {
     // Init info
     $this->addElement('Select', 'type', array('label' => '*Type of ban', 'multiOptions' => array('0' => 'Email', '1' => 'Username', '2' => 'Ip'), 'onchange' => "updateTextFields()", 'value' => $this->_type));
     $user = Engine_Api::_()->user()->getViewer();
     //ADD AUTH STUFF HERE
     // Init Email
     $this->addElement('Textarea', 'email', array('label' => '*Email Address Ban', 'description' => 'YNBANMEM_FORM_EMAILBANS_DESCRIPTION'));
     $this->email->getDecorator("Description")->setOption("placement", "append");
     // Init Username
     // Init Email
     $this->addElement('Textarea', 'username', array('label' => '*Username Address Ban', 'description' => 'YNBANMEM_FORM_USERNAMEBANS_DESCRIPTION'));
     $this->username->getDecorator("Description")->setOption("placement", "append");
     $translator = $this->getTranslator();
     if ($translator) {
         $description = sprintf($translator->translate('YNBANMEM_FORM_IPBANS_DESCRIPTION'), Engine_IP::normalizeAddress(Engine_IP::getRealRemoteAddress()));
     } else {
         $description = 'YNBANMEM_FORM_IPBANS_DESCRIPTION';
     }
     // Init Ip
     $this->addElement('Textarea', 'ip', array('label' => '*IP Address Ban', 'description' => $description));
     $this->ip->getDecorator("Description")->setOption("placement", "append");
     // init Email Message
     $value = "Your account has been banned.";
     $this->addElement('textarea', 'email_message', array('label' => '*Message', 'style' => 'width: 430px; height: 200px', 'value' => $value));
     $this->email_message->getDecorator("Description")->setOption("placement", "append");
 }
Exemplo n.º 3
0
 public function init()
 {
     $maindescription = $this->getTranslator()->translate('Social networks are often the target of aggressive spam tactics. This most often comes in the form of fake user accounts and spam in comments. On this page, you can manage various anti-spam and censorship features. Note: To turn on the signup image verification feature (a popular anti-spam tool), see the Signup Progress page. <br>');
     $settings = Engine_Api::_()->getApi('settings', 'core');
     if ($settings->getSetting('user.support.links', 0) == 1) {
         $moreinfo = $this->getTranslator()->translate('More Info: <a href="%1$s" target="_blank"> KB Article</a>');
     } else {
         $moreinfo = $this->getTranslator()->translate('');
     }
     $maindescription = vsprintf($maindescription . $moreinfo, array('http://support.socialengine.com/questions/183/Admin-Panel-Settings-Spam-and-Banning-Tools'));
     // Decorators
     $this->loadDefaultDecorators();
     $this->getDecorator('Description')->setOption('escape', false);
     // Set form attributes
     //$this->setTitle('Spam & Banning Tools');
     $this->setDescription($maindescription);
     // init ip-range ban
     $translator = $this->getTranslator();
     if ($translator) {
         $description = sprintf($translator->translate('CORE_FORM_ADMIN_SETTINGS_SPAM_IPBANS_DESCRIPTION'), Engine_IP::normalizeAddress(Engine_IP::getRealRemoteAddress()));
     } else {
         $description = 'CORE_FORM_ADMIN_SETTINGS_SPAM_IPBANS_DESCRIPTION';
     }
     $this->addElement('Textarea', 'bannedips', array('label' => 'IP Address Ban', 'description' => $description));
     // init email bans
     $this->addElement('Textarea', 'bannedemails', array('label' => 'Email Address Ban', 'description' => 'CORE_FORM_ADMIN_SETTINGS_SPAM_EMAILBANS_DESCRIPTION'));
     // init username bans
     $this->addElement('Textarea', 'bannedusernames', array('label' => 'Profile Address Ban', 'description' => 'CORE_FORM_ADMIN_SETTINGS_SPAM_USERNAMEBANS_DESCRIPTION'));
     // init censored words
     $this->addElement('Textarea', 'bannedwords', array('label' => 'Censored Words', 'description' => 'CORE_FORM_ADMIN_SETTINGS_SPAM_CENSOR_DESCRIPTION'));
     $this->addElement('Radio', 'signup', array('label' => 'Require new users to enter validation code when signing up?', 'multiOptions' => $this->_captcha_options, 'value' => 0));
     $this->addElement('Radio', 'invite', array('label' => 'Require users to enter validation code when inviting others?', 'multiOptions' => $this->_captcha_options, 'value' => 0));
     $this->addElement('Radio', 'login', array('label' => 'Require users to enter validation code when signing in?', 'multiOptions' => $this->_captcha_options, 'value' => 0));
     $this->addElement('Radio', 'contact', array('label' => 'Require users to enter validation code when using the contact form?', 'multiOptions' => array(2 => 'Yes, make everyone complete the CAPTCHA form.', 1 => 'Yes, make visitors complete CAPTCHA, but members are exempt.', 0 => 'No, do not show a CAPTCHA form to anyone.'), 'value' => 0));
     // init profile
     $this->addElement('Radio', 'comment', array('label' => 'Require users to enter validation code when commenting?', 'multiOptions' => $this->_captcha_options, 'value' => 0));
     // recaptcha
     if ($translator) {
         $description = sprintf($translator->translate('You can obtain API credentials at: %1$s'), $this->getView()->htmlLink('https://www.google.com/recaptcha', 'https://www.google.com/recaptcha'));
     } else {
         $description = null;
     }
     $this->addElement('Text', 'recaptchapublic', array('label' => 'ReCaptcha Public Key', 'description' => $description, 'filters' => array('StringTrim')));
     $this->getElement('recaptchapublic')->getDecorator('Description')->setOption('escape', false);
     $this->addElement('Text', 'recaptchaprivate', array('label' => 'ReCaptcha Private Key', 'description' => $description, 'filters' => array('StringTrim')));
     $this->getElement('recaptchaprivate')->getDecorator('Description')->setOption('escape', false);
     // tokens
     //    $this->addElement('Radio', 'tokens', array(
     //      'label' => 'Use Tokens?',
     //      'multiOptions' => array(
     //        1 => 'Yes, use security tokens.',
     //        0 => 'No, do not use security tokens.',
     //      ),
     //    ));
     // comment html
     $this->addElement('Text', 'commenthtml', array('label' => 'Allow HTML in Comments?', 'description' => 'CORE_ADMIN_FORM_SETTINGS_SPAM_COMMENTHTML_DESCRIPTION'));
     // init submit
     $this->addElement('Button', 'submit', array('label' => 'Save Changes', 'type' => 'submit', 'ignore' => true));
 }
Exemplo n.º 4
0
 public function onRenderLayoutDefault($event)
 {
     //echo 'banmer';die;
     // Check if visitor is banned by IP
     $addressObject = new Engine_IP();
     $addressBinary = $addressObject->toBinary();
     // Load banned IPs
     $bannedIpTable = Engine_Api::_()->getDbtable('bannedips', 'ynbanmem');
     $bannedIps = $bannedIpTable->select()->query()->fetchAll();
     $bannedId;
     $isBanned = false;
     if (count($bannedIps) > 0) {
         foreach ($bannedIps as $bannedIp) {
             // @todo ipv4->ipv6 transformations
             if (strlen($addressBinary) == strlen($bannedIp['start'])) {
                 if (strcmp($addressBinary, $bannedIp['start']) >= 0 && strcmp($addressBinary, $bannedIp['stop']) <= 0) {
                     $isBanned = true;
                     $bannedId = $bannedIp['banedip_id'];
                     break;
                 }
             }
         }
         // tell them they're banned
         if ($isBanned) {
             $extraInfoTable = Engine_Api::_()->getDbTable('extrainfo', 'ynbanmem');
             //Get extra info
             $extraInfo = $extraInfoTable->getExtraInfo($bannedId, 1);
             //@todo give appropriate forbidden page
             if (!headers_sent()) {
                 header('HTTP/1.0 403 Forbidden');
             }
             if (count($extraInfo) != 0) {
                 die($extraInfo[0]['reason']);
             }
             die('banned');
         }
     }
     $viewer = Engine_Api::_()->user()->getViewer();
     if ($viewer->getIdentity() > 0 && $viewer->username != null && !$viewer->level_id != 1) {
         // Load banned Usernames
         $bannedUsernameTable = Engine_Api::_()->getDbtable('bannedusernames', 'ynbanmem');
         $bannedUsername = $bannedUsernameTable->select()->where('username = ?', $viewer->username)->query()->fetchAll();
         // tell them they're banned
         if (count($bannedUsername) != 0) {
             $extraInfoTable = Engine_Api::_()->getDbTable('extrainfo', 'ynbanmem');
             //Get extra info
             $extraInfo = $extraInfoTable->getExtraInfo($bannedUsername[0]['bannedusername_id'], 0);
             //@todo give appropriate forbidden page
             if (!headers_sent()) {
                 header('HTTP/1.0 403 Forbidden');
             }
             if (count($extraInfo) != 0) {
                 die('banned <br/>' . $extraInfo[0]['reason']);
             }
             die('banned');
         }
         // Load banned emails
         $bannedEmailTable = Engine_Api::_()->getDbtable('bannedemails', 'ynbanmem');
         $bannedEmail = $bannedEmailTable->select()->where('email = ?', $viewer->email)->query()->fetchAll();
         //echo $viewer -> email;die;
         // tell them they're banned
         if (count($bannedEmail) != 0) {
             $extraInfoTable = Engine_Api::_()->getDbTable('extrainfo', 'ynbanmem');
             //Get extra info
             $extraInfo = $extraInfoTable->getExtraInfo($bannedEmail[0]['bannedemail_id'], 2);
             //@todo give appropriate forbidden page
             if (!headers_sent()) {
                 header('HTTP/1.0 403 Forbidden');
             }
             if (count($extraInfo) != 0) {
                 die('banned <br/>' . $extraInfo[0]['reason']);
             }
             //die('banned');
         }
     }
 }
Exemplo n.º 5
0
 public function activateAction()
 {
     $this->_helper->layout->setLayout('default-simple');
     $user = Engine_Api::_()->core()->getSubject();
     if (!$user->deactive) {
         return $this->_forward('success', 'utility', 'core', array('messages' => array(Zend_Registry::get('Zend_Translate')->_('Your request is invalid.')), 'redirect' => $this->getFrontController()->getRouter()->assemble(array('action' => 'home'), 'user_general', true)));
     }
     // Form
     $this->view->form = $form = new User_Form_Settings_Active();
     if (!$this->getRequest()->isPost()) {
         return;
     }
     if (!$form->isValid($this->getRequest()->getPost())) {
         return;
     }
     // Process
     $db = Engine_Api::_()->getDbtable('users', 'user')->getAdapter();
     $db->beginTransaction();
     try {
         $user->user_id = $user->deactive;
         $user->deactive = 0;
         $user->save();
         $db->commit();
     } catch (Exception $e) {
         $db->rollBack();
         throw $e;
     }
     Zend_Auth::getInstance()->getStorage()->write($user->user_id);
     Engine_Api::_()->user()->setViewer();
     // Register login
     $loginTable = Engine_Api::_()->getDbtable('logins', 'user');
     $ipObj = new Engine_IP();
     $ipExpr = new Zend_Db_Expr($db->quoteInto('UNHEX(?)', bin2hex($ipObj->toBinary())));
     $loginTable->insert(array('user_id' => $user->getIdentity(), 'email' => $user->email, 'ip' => $ipExpr, 'timestamp' => new Zend_Db_Expr('NOW()'), 'state' => 'success', 'active' => true));
     $_SESSION['login_id'] = $login_id = $loginTable->getAdapter()->lastInsertId();
     // Increment sign-in count
     Engine_Api::_()->getDbtable('statistics', 'core')->increment('user.logins');
     // Test activity @todo remove
     $viewer = Engine_Api::_()->user()->getViewer();
     if ($viewer->getIdentity()) {
         $viewer->lastlogin_date = date("Y-m-d H:i:s");
         if ('cli' !== PHP_SAPI) {
             $viewer->lastlogin_ip = $ipExpr;
         }
         $viewer->save();
         Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $viewer, 'login');
     }
     // Assign sid to view for json context
     $this->view->status = true;
     $this->view->message = Zend_Registry::get('Zend_Translate')->_('Login successful');
     $this->view->sid = Zend_Session::getId();
     $this->view->sname = Zend_Session::getOptions('name');
     // Run post login hook
     $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('onUserLoginAfter', $viewer);
     // Do redirection only if normal context
     if (null === $this->_helper->contextSwitch->getCurrentContext()) {
         // Redirect by form
         $uri = $form->getValue('return_url');
         if ($uri) {
             if (substr($uri, 0, 3) == '64-') {
                 $uri = base64_decode(substr($uri, 3));
             }
             return $this->_redirect($uri, array('prependBase' => false));
         }
         // Redirect by session
         $session = new Zend_Session_Namespace('Redirect');
         if (isset($session->uri)) {
             $uri = $session->uri;
             $opts = $session->options;
             $session->unsetAll();
             return $this->_redirect($uri, $opts);
         } else {
             if (isset($session->route)) {
                 $session->unsetAll();
                 return $this->_helper->redirector->gotoRoute($session->params, $session->route, $session->reset);
             }
         }
         // Redirect by hook
         foreach ((array) $event->getResponses() as $response) {
             if (is_array($response)) {
                 if (!empty($response['error']) && !empty($response['message'])) {
                     return $form->addError($response['message']);
                 } else {
                     if (!empty($response['redirect'])) {
                         return $this->_helper->redirector->gotoUrl($response['redirect'], array('prependBase' => false));
                     }
                 }
             }
         }
         // Just redirect to home
         return $this->_helper->redirector->gotoRoute(array('action' => 'home'), 'user_general', true);
     }
 }
Exemplo n.º 6
0
 public function normalizeAddressArray($addresses)
 {
     $data = array();
     foreach ($addresses as $address) {
         if (is_string($address)) {
             $start = Engine_IP::normalizeAddressToBinary($address);
             $stop = Engine_IP::normalizeAddressToBinary($address);
         } else {
             if (is_array($address)) {
                 $start = Engine_IP::normalizeAddressToBinary($address[0]);
                 $stop = Engine_IP::normalizeAddressToBinary($address[1]);
             } else {
                 continue;
             }
         }
         $data[bin2hex($start) . '-' . bin2hex($stop)] = array('start' => $start, 'stop' => $stop);
     }
     return $data;
 }
Exemplo n.º 7
0
 public function janrainAction()
 {
     // Exit if no token is posted
     if (!($token = $this->_getParam('token'))) {
         return $this->_helper->redirector->gotoRoute(array(), 'default', true);
     }
     // Get settings
     $settings = Engine_Api::_()->getDbtable('settings', 'core');
     $janrainSettings = $settings->core_janrain;
     if (empty($janrainSettings['key']) || empty($janrainSettings['enable']) || $janrainSettings['enable'] == 'none') {
         return $this->_helper->redirector->gotoRoute(array(), 'default', true);
     }
     // Get info
     $viewer = Engine_Api::_()->user()->getViewer();
     $janrainTable = Engine_Api::_()->getDbtable('janrain', 'user');
     $db = Engine_Db_Table::getDefaultAdapter();
     $ipObj = new Engine_IP();
     $ipExpr = new Zend_Db_Expr($db->quoteInto('UNHEX(?)', bin2hex($ipObj->toBinary())));
     $log = Zend_Registry::get('Zend_Log');
     // Call auth_info
     $post_data = array('token' => $token, 'apiKey' => $janrainSettings['key'], 'format' => 'json', 'extended' => 'false');
     //Extended is not available to Basic.
     $curl = curl_init();
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($curl, CURLOPT_URL, 'https://rpxnow.com/api/v2/auth_info');
     curl_setopt($curl, CURLOPT_POST, true);
     curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
     curl_setopt($curl, CURLOPT_HEADER, false);
     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($curl, CURLOPT_FAILONERROR, true);
     $result = curl_exec($curl);
     if ($result == false) {
         $log->log('Janrain Error' . PHP_EOL . 'Curl error: ' . curl_error($curl) . PHP_EOL . 'HTTP code: ' . curl_errno($curl) . PHP_EOL . var_export($post_data, true), Zend_Log::DEBUG);
         return $this->_helper->redirector->gotoRoute(array(), 'default', true);
     }
     curl_close($curl);
     // Decode json
     $auth_info = Zend_Json::decode($result, true);
     if ($auth_info['stat'] !== 'ok') {
         $log->log('Janrain Error' . PHP_EOL . var_export($result, true) . PHP_EOL . var_export($auth_info, true), Zend_Log::DEBUG);
         return $this->_helper->redirector->gotoRoute(array(), 'default', true);
     }
     $profile = $auth_info['profile'];
     if (!empty($auth_info['merged_poco'])) {
         $profile['merged_poco'] = $auth_info['merged_poco'];
     }
     $identifier = $profile['identifier'];
     $provider = $profile['providerName'];
     // Check if already exists
     $info = $janrainTable->select()->from($janrainTable)->where('identifier = ?', $identifier)->limit(1)->query()->fetch();
     if ($info) {
         if ($viewer->getIdentity()) {
             // Already associated
             $this->view->error = 'That account has already been connected to ' . 'another member on this site.';
         } else {
             // Sign-in
             Zend_Auth::getInstance()->getStorage()->write($info['user_id']);
             // Register login
             $viewer = Engine_Api::_()->getItem('user', $info['user_id']);
             $viewer->lastlogin_date = date("Y-m-d H:i:s");
             if ('cli' !== PHP_SAPI) {
                 $viewer->lastlogin_ip = $ipExpr;
                 Engine_Api::_()->getDbtable('logins', 'user')->insert(array('user_id' => $info['user_id'], 'ip' => $ipExpr, 'timestamp' => new Zend_Db_Expr('NOW()'), 'state' => 'success', 'source' => 'janrain'));
             }
             $viewer->save();
             // Redirect
             return $this->_helper->redirector->gotoRoute(array(), 'default', true);
         }
     } else {
         if ($viewer->getIdentity()) {
             // Connect
             $janrainTable->insert(array('user_id' => $viewer->getIdentity(), 'identifier' => $identifier, 'provider' => $provider, 'token' => $token));
             // Redirect
             return $this->_helper->redirector->gotoRoute(array(), 'default', true);
         } else {
             // Sign-up
             $_SESSION['janrain_signup'] = true;
             $_SESSION['janrain_signup_info'] = $profile;
             $_SESSION['janrain_signup_token'] = $token;
             return $this->_helper->redirector->gotoRoute(array(), 'user_signup', true);
         }
     }
 }
Exemplo n.º 8
0
 protected function _insert()
 {
     $settings = Engine_Api::_()->getApi('settings', 'core');
     // These need to be done first so the hook can see them
     $this->level_id = Engine_Api::_()->getItemTable('authorization_level')->getDefaultLevel()->level_id;
     $this->approved = (int) ($settings->getSetting('user.signup.approve', 1) == 1);
     $this->verified = (int) ($settings->getSetting('user.signup.verifyemail', 1) < 2);
     $this->enabled = $this->approved && $this->verified;
     $this->search = true;
     if (empty($this->_modifiedFields['timezone'])) {
         $this->timezone = $settings->getSetting('core.locale.timezone', 'America/Los_Angeles');
     }
     if (empty($this->_modifiedFields['locale'])) {
         $this->locale = $settings->getSetting('core.locale.locale', 'auto');
     }
     if (empty($this->_modifiedFields['language'])) {
         $this->language = $settings->getSetting('core.locale.language', 'en_US');
     }
     if ('cli' !== PHP_SAPI) {
         // No CLI
         // Get ip address
         $db = $this->getTable()->getAdapter();
         $ipObj = new Engine_IP();
         $ipExpr = new Zend_Db_Expr($db->quoteInto('UNHEX(?)', bin2hex($ipObj->toBinary())));
         $this->creation_ip = $ipExpr;
     }
     // Set defaults, process etc
     $this->salt = (string) rand(1000000, 9999999);
     if (!empty($this->password)) {
         $this->password = md5($settings->getSetting('core.secret', 'staticSalt') . $this->password . $this->salt);
     } else {
         $this->password = '';
     }
     // The hook will be called here
     parent::_insert();
 }
Exemplo n.º 9
0
 public function ajaxRenderAdsAction()
 {
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender(TRUE);
     $params = array();
     $params['content_id'] = $content_id = $this->_getParam('content_id');
     $viewer = Engine_Api::_()->user()->getViewer();
     $tableHiddens = Engine_Api::_()->getItemTable('ynsocialads_hidden');
     $tableAdBlock = Engine_Api::_()->getItemTable('ynsocialads_adblock');
     $adBlock = $tableAdBlock->fetchRow($tableAdBlock->select()->where('content_id = ?', $content_id));
     $ads_limit = $adBlock->ads_limit;
     if ($viewer->getIdentity()) {
         $items = Engine_Api::_()->getItemTable('ynsocialads_ad')->getAdsRender($params, $viewer->getIdentity(), 'yes');
     } else {
         // Get ip address
         $db = Engine_Db_Table::getDefaultAdapter();
         $ipObj = new Engine_IP();
         $ipExpr = new Zend_Db_Expr($db->quoteInto('UNHEX(?)', bin2hex($ipObj->toBinary())));
         $items = Engine_Api::_()->getItemTable('ynsocialads_ad')->getAdsRender($params, $ipExpr, 'no');
     }
     $arr = array();
     foreach ($items as $item) {
         if ($item->isAudience($viewer->getIdentity())) {
             $package = $item->getPackage();
             $base_order = 0;
             switch ($package->benefit_type) {
                 case 'click':
                     $base_order = $item->click_count / $item->benefit_total;
                     break;
                 case 'impression':
                     $base_order = $item->impressions_count / $item->benefit_total;
                     break;
                 case 'day':
                     $start_date = new DateTime($item->start_date);
                     $now = new DateTime();
                     $diff = date_diff($start_date, $now);
                     $base_order = $diff->format('%a') / $item->benefit_total;
                     break;
             }
             $user_id = $item->user_id;
             $ad_id = $item->getIdentity();
             $id = $item->ad_id;
             $arr[$id] = $base_order;
         }
     }
     asort($arr);
     $arr_ads = array();
     $count = 0;
     foreach ($arr as $key => $value) {
         if ($count >= $ads_limit) {
             break;
         }
         $item = Engine_Api::_()->getItem('ynsocialads_ad', $key);
         $arr_ads[] = $item;
         //update view
         $tableStatisticTable = Engine_Api::_()->getItemTable('ynsocialads_statistic');
         $tableTrackTable = Engine_Api::_()->getItemTable('ynsocialads_track');
         $date = new DateTime();
         $item->last_view = $date->getTimestamp();
         $today = date("Y-m-d");
         //check if user login
         if ($viewer->getIdentity()) {
             // check if user has not view ad yet -> add reach count
             if (!$tableStatisticTable->checkUniqueViewByUserId($viewer->getIdentity(), $key, 'impression')) {
                 $item->reaches_count = $item->reaches_count + 1;
                 $item->impressions_count = $item->impressions_count + 1;
                 if ($track = $tableTrackTable->checkExistTrack($today, $key)) {
                     $track->reaches = $track->reaches + 1;
                     $track->impressions = $track->impressions + 1;
                     $track->save();
                 } else {
                     $track = $tableTrackTable->createRow();
                     $track->date = $today;
                     $track->ad_id = $key;
                     $track->reaches = 1;
                     $track->impressions = 1;
                     $track->save();
                 }
             } else {
                 $item->impressions_count = $item->impressions_count + 1;
                 if ($track = $tableTrackTable->checkExistTrack($today, $key)) {
                     $track->impressions = $track->impressions + 1;
                     $track->save();
                 } else {
                     $track = $tableTrackTable->createRow();
                     $track->date = $today;
                     $track->ad_id = $key;
                     $track->impressions = 1;
                     $track->save();
                 }
             }
             //update view statistic
             $stats = $tableStatisticTable->createRow();
             $stats->user_id = $viewer->getIdentity();
             $stats->timestamp = date('Y-m-d H:i:s');
             $stats->type = 'impression';
             $stats->ad_id = $key;
             $stats->save();
         } else {
             // Get ip address
             $db = Engine_Db_Table::getDefaultAdapter();
             $ipObj = new Engine_IP();
             $ipExpr = new Zend_Db_Expr($db->quoteInto('UNHEX(?)', bin2hex($ipObj->toBinary())));
             if (!$tableStatisticTable->checkUniqueViewByIP($ipExpr, $key, 'impression')) {
                 $item->reaches_count = $item->reaches_count + 1;
                 $item->impressions_count = $item->impressions_count + 1;
                 if ($track = $tableTrackTable->checkExistTrack($today, $key)) {
                     $track->reaches = $track->reaches + 1;
                     $track->impressions = $track->impressions + 1;
                     $track->save();
                 } else {
                     $track = $tableTrackTable->createRow();
                     $track->date = $today;
                     $track->ad_id = $key;
                     $track->reaches = 1;
                     $track->impressions = 1;
                     $track->save();
                 }
             } else {
                 $item->impressions_count = $item->impressions_count + 1;
                 if ($track = $tableTrackTable->checkExistTrack($today, $key)) {
                     $track->impressions = $track->impressions + 1;
                     $track->save();
                 } else {
                     $track = $tableTrackTable->createRow();
                     $track->date = $today;
                     $track->ad_id = $key;
                     $track->impressions = 1;
                     $track->save();
                 }
             }
             //update view statistic
             $stats = $tableStatisticTable->createRow();
             $stats->IP = $ipExpr;
             $stats->timestamp = date('Y-m-d H:i:s');
             $stats->type = 'impression';
             $stats->ad_id = $key;
             $stats->save();
         }
         $item->save();
         $count++;
     }
     echo $this->view->partial(Ynsocialads_Api_Core::partialViewFullPath('_blockRenderView.tpl'), array('ads' => $arr_ads, 'content_id' => $content_id, 'viewer' => $viewer));
 }
Exemplo n.º 10
0
 public function spamAction()
 {
     // Get navigation
     $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('core_admin_banning', array(), 'core_admin_banning_general');
     // Get form
     $this->view->form = $form = new Core_Form_Admin_Settings_Spam();
     // Get db
     $db = Engine_Db_Table::getDefaultAdapter();
     // Populate some settings
     $settings = Engine_Api::_()->getApi('settings', 'core');
     $config = (array) $settings->core_spam;
     // Load all IPs
     $bannedIpsTable = Engine_Api::_()->getDbtable('BannedIps', 'core');
     $bannedIps = array();
     foreach ($bannedIpsTable->getAddresses() as $bannedIp) {
         if (is_array($bannedIp)) {
             $bannedIps[] = join(' - ', $bannedIp);
         } else {
             if (is_string($bannedIp)) {
                 $bannedIps[] = $bannedIp;
             }
         }
     }
     $config['bannedips'] = join("\n", $bannedIps);
     // Load all emails
     $bannedEmailsTable = Engine_Api::_()->getDbtable('BannedEmails', 'core');
     $bannedEmails = $bannedEmailsTable->getEmails();
     $config['bannedemails'] = join("\n", $bannedEmails);
     // Load all usernames
     $bannedUsernamesTable = Engine_Api::_()->getDbtable('BannedUsernames', 'core');
     $bannedUsernames = $bannedUsernamesTable->getUsernames();
     $config['bannedusernames'] = join("\n", $bannedUsernames);
     // Load all words
     $bannedWordsTable = Engine_Api::_()->getDbtable('BannedWords', 'core');
     $bannedWords = $bannedWordsTable->getWords();
     $config['bannedwords'] = join("\n", $bannedWords);
     // Populate
     if (_ENGINE_ADMIN_NEUTER) {
         $config['recaptchapublic'] = '**********';
         $config['recaptchaprivate'] = '**********';
     }
     $form->populate($config);
     if (!$this->getRequest()->isPost()) {
         return;
     }
     if (!$form->isValid($this->getRequest()->getPost())) {
         return;
     }
     // Process
     $db = Engine_Api::_()->getDbtable('settings', 'core')->getAdapter();
     $db->beginTransaction();
     $values = $form->getValues();
     // Build banned IPs
     $bannedIpsNew = preg_split('/\\s*[,\\n]+\\s*/', $values['bannedips']);
     foreach ($bannedIpsNew as &$bannedIpNew) {
         if (false !== strpos($bannedIpNew, '-')) {
             $bannedIpNew = preg_split('/\\s*-\\s*/', $bannedIpNew, 2);
         } else {
             if (false != strpos($bannedIpNew, '*')) {
                 $tmp = $bannedIpNew;
                 if (false != strpos($tmp, ':')) {
                     $bannedIpNew = array(str_replace('*', '0', $tmp), str_replace('*', 'ffff', $tmp));
                 } else {
                     $bannedIpNew = array(str_replace('*', '0', $tmp), str_replace('*', '255', $tmp));
                 }
             }
         }
     }
     // Check if they are banning their own address
     if ($bannedIpsTable->isAddressBanned(Engine_IP::getRealRemoteAddress(), $bannedIpsTable->normalizeAddressArray($bannedIpsNew))) {
         return $form->addError('One of the IP addresses or IP address ranges you entered contains your own IP address.');
     }
     if (!empty($values['recaptchapublic']) && !empty($values['recaptchaprivate'])) {
         $recaptcha = new Zend_Service_ReCaptcha($values['recaptchapublic'], $values['recaptchaprivate']);
         try {
             $resp = $recaptcha->verify('test', 'test');
             //        if( false === stripos($resp, 'error') ) {
             //          return $form->addError('ReCaptcha Key Invalid: ' . $resp);
             //        }
             if (in_array($err = $resp->getErrorCode(), array('invalid-site-private-key', 'invalid-site-public-key'))) {
                 return $form->addError('ReCaptcha Error: ' . $err);
             }
             // Validate public key
             $httpClient = new Zend_Http_Client();
             $httpClient->setUri('http://www.google.com/recaptcha/api/challenge');
             $httpClient->setParameterGet('k', $values['recaptchapublic']);
             $resp = $httpClient->request('GET');
             if (false !== stripos($resp->getBody(), 'Input error')) {
                 return $form->addError('ReCaptcha Error: ' . str_replace(array("document.write('", "\\n');"), array('', ''), $resp->getBody()));
             }
         } catch (Exception $e) {
             return $form->addError('ReCaptcha Key Invalid: ' . $e->getMessage());
         }
         $values['recaptchaenabled'] = true;
     } else {
         $values['recaptchaenabled'] = false;
     }
     try {
         if (!empty($bannedIpNew)) {
             // Save Banned IPs
             $bannedIpsTable->setAddresses($bannedIpsNew);
             unset($values['bannedips']);
         }
         // Save Banned Emails
         $bannedEmailsNew = preg_split('/\\s*[,\\n]+\\s*/', $values['bannedemails']);
         $bannedEmailsTable->setEmails($bannedEmailsNew);
         unset($values['bannedemails']);
         // Save Banned Usernames
         $bannedUsernamesNew = preg_split('/\\s*[,\\n]+\\s*/', $values['bannedusernames']);
         $bannedUsernamesTable->setUsernames($bannedUsernamesNew);
         unset($values['bannedusernames']);
         // Save Banned Words
         $bannedWordsNew = preg_split('/\\s*[,\\n]+\\s*/', $values['bannedwords']);
         $bannedWordsTable->setWords($bannedWordsNew);
         unset($values['bannedwords']);
         // Save other settings
         $settings->core_spam = $values;
         $db->commit();
         $form->addNotice('Your changes have been saved.');
     } catch (Exception $e) {
         $db->rollback();
         throw $e;
     }
 }
Exemplo n.º 11
0
 protected function _initBannedIps()
 {
     // No CLI
     if ('cli' === PHP_SAPI) {
         return;
     }
     // Check if visitor is banned by IP
     $addressObject = new Engine_IP();
     $addressBinary = $addressObject->toBinary();
     // Load banned IPs
     $db = $this->getContainer()->db;
     $bannedIps = $db->select()->from('engine4_core_bannedips')->query()->fetchAll();
     $isBanned = false;
     foreach ($bannedIps as $bannedIp) {
         // @todo ipv4->ipv6 transformations
         if (strlen($addressBinary) == strlen($bannedIp['start'])) {
             if (strcmp($addressBinary, $bannedIp['start']) >= 0 && strcmp($addressBinary, $bannedIp['stop']) <= 0) {
                 $isBanned = true;
                 break;
             }
         }
     }
     // tell them they're banned
     if ($isBanned) {
         //@todo give appropriate forbidden page
         if (!headers_sent()) {
             header('HTTP/1.0 403 Forbidden');
         }
         die('banned');
     }
 }
 public function indexAction()
 {
     $this->view->formFilter = $formFilter = new User_Form_Admin_Manage_Login();
     $table = Engine_Api::_()->getDbtable('users', 'user');
     $select = $table->select();
     // Process form
     $values = array();
     if ($formFilter->isValid($this->_getAllParams())) {
         $values = $formFilter->getValues();
     }
     foreach ($values as $key => $value) {
         if (null === $value) {
             unset($values[$key]);
         }
     }
     $values = array_merge(array('order' => 'timestamp', 'order_direction' => 'DESC'), $values);
     $this->view->assign($values);
     // Get navigation
     $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('core_admin_banning', array(), 'user_admin_banning_logins');
     // Get select
     $table = Engine_Api::_()->getDbtable('logins', 'user');
     $select = $table->select();
     $select->order((!empty($values['order']) ? $values['order'] : 'user_id') . ' ' . (!empty($values['order_direction']) ? $values['order_direction'] : 'DESC'));
     if (!empty($values['username'])) {
         $usersTable = Engine_Api::_()->getDbtable('users', 'user');
         $usersSelect = $usersTable->select()->from($usersTable, 'user_id')->where('username LIKE ?', '%' . $values['username'] . '%');
         $select->where('user_id IN ?', $usersSelect);
     }
     if (!empty($values['email'])) {
         $select->where('email LIKE ?', '%' . $values['email'] . '%');
     }
     if (!empty($values['ip'])) {
         $ipObj = new Engine_IP($values['ip']);
         $select->where('ip = ?', $ipObj->toBinary());
     }
     if (!empty($values['state']) && $values['state'] != -1) {
         $select->where('state = ?', $values['state']);
     }
     if (!empty($values['source']) && $values['source'] != -1) {
         $select->where('source = ?', $values['source']);
     }
     // Filter out junk
     $valuesCopy = array_filter($values);
     // Get paginator
     $this->view->paginator = $paginator = Zend_Paginator::factory($select);
     $paginator->setItemCountPerPage(50);
     $paginator->setCurrentPageNumber($this->_getParam('page', 1));
     $this->view->formValues = $valuesCopy;
     // Preload users
     $identities = array();
     foreach ($paginator as $item) {
         if (!empty($item->user_id)) {
             $identities[] = $item->user_id;
         }
     }
     $identities = array_unique($identities);
     $users = array();
     if (!empty($identities)) {
         foreach (Engine_Api::_()->getItemMulti('user', $identities) as $user) {
             $users[$user->getIdentity()] = $user;
         }
     }
     $this->view->users = $users;
 }
Exemplo n.º 13
0
 public function addAction()
 {
     // Get navigation
     $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('ynbanmem_main');
     if (count($this->view->navigation) == 1) {
         $this->view->navigation = null;
     }
     // Check auth
     $viewer = Engine_Api::_()->user()->getViewer();
     if (!$this->_helper->requireUser()->isValid()) {
         return;
     }
     if (!$this->_helper->requireAuth()->setAuthParams('ynbanmem', null, 'add')->isValid()) {
         return;
     }
     // Make params
     $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('ynbanmem_main', array(), 'ynbanmem_main_add');
     // Make form
     $this->view->form = $form = new Ynbanmem_Form_Add(array('type' => $this->_getParam('type', 0)));
     //  Get data if the request come from profile page
     $id = $this->_getParam('id', null);
     if ($id != "") {
         $user = Engine_Api::_()->getItem('user', $id);
         $form->populate(array('email' => $user->email));
     }
     if (!$this->getRequest()->isPost()) {
         return;
     }
     $post = $this->getRequest()->getPost();
     if (!$form->isValid($post)) {
         return;
     }
     $db = Engine_Db_Table::getDefaultAdapter();
     $db->beginTransaction();
     $flag = true;
     // Process
     $bannedUsernamesTable = Engine_Api::_()->getDbTable('bannedusernames', 'ynbanmem');
     $bannedIpsTable = Engine_Api::_()->getDbTable('bannedips', 'ynbanmem');
     $bannedEmailsTable = Engine_Api::_()->getDbTable('bannedemails', 'ynbanmem');
     $extraInfoTable = Engine_Api::_()->getDbTable('extrainfo', 'ynbanmem');
     $userTable = Engine_Api::_()->getDbTable('users', 'user');
     try {
         $values = $form->getValues();
         $values['admin'] = Engine_Api::_()->user()->getViewer()->getIdentity();
         //Get expiry date
         if (strtotime($values['expiry_date']) > 0) {
             // Convert times
             $oldTz = date_default_timezone_get();
             date_default_timezone_set($viewer->timezone);
             $expiry_date = strtotime($values['expiry_date']);
             $now = strtotime(date('Y-m-d H:i:s'));
             date_default_timezone_set($oldTz);
             $values['expiry_date'] = date('Y-m-d H:i:s', $expiry_date);
             if ($expiry_date <= $now) {
                 $form->getElement('expiry_date')->addError('Expiry Date should be greater than Current Time!');
                 return;
             }
         } else {
             $values['expiry_date'] = "0000-00-00 00:00:00";
         }
         $info = $values;
         $info['email_message'] = trim($values['email_message']);
         switch ($values['type']) {
             // Ban username
             case 1:
                 if ($values['username'] == "") {
                     $form->getElement('username')->addError('Please complete this field - it is required.');
                     return;
                 }
                 $info['type'] = 0;
                 // Username
                 $bannedUsernamesNew = preg_split('/\\s*[,\\n]+\\s*/', $values['username']);
                 foreach ($bannedUsernamesNew as $newUsername) {
                     $user = $userTable->select()->where('username = ?', $newUsername)->query()->fetchAll();
                     if (count($user) == 0 || $user[0]['level_id'] == 1 || $viewer->username == $user[0]['username']) {
                         $form->getElement('username')->addError('There is not any users relate to this username or the usernames you entered contains your own username or admin username.');
                         return;
                     }
                 }
                 $bannedUsernamesTable->setBannedUsernames($bannedUsernamesNew, $info);
                 $form->addNotice('Your changes have been saved.');
                 unset($values['bannedusernames']);
                 break;
             case 2:
                 if ($values['ip'] == "") {
                     $form->getElement('ip')->addError('Please complete this field - it is required.');
                     return;
                 }
                 $info['type'] = 1;
                 // Ip
                 // Build banned IPs
                 try {
                     $bannedIpsNew = preg_split('/\\s*[,\\n]+\\s*/', $values['ip']);
                     foreach ($bannedIpsNew as &$bannedIpNew) {
                         if (false !== strpos($bannedIpNew, '-')) {
                             $bannedIpNew = preg_split('/\\s*-\\s*/', $bannedIpNew, 2);
                         } else {
                             if (false != strpos($bannedIpNew, '*')) {
                                 $tmp = $bannedIpNew;
                                 if (false != strpos($tmp, ':')) {
                                     $bannedIpNew = array(str_replace('*', '0', $tmp), str_replace('*', 'ffff', $tmp));
                                 } else {
                                     $bannedIpNew = array(str_replace('*', '0', $tmp), str_replace('*', '255', $tmp));
                                 }
                             }
                         }
                     }
                 } catch (Exception $e) {
                     $db->rollBack();
                     return $form->addError('');
                 }
                 // Check if they are banning their own address
                 if ($bannedIpsTable->isAddressBanned(Engine_IP::getRealRemoteAddress(), $bannedIpsTable->normalizeAddressArray($bannedIpsNew))) {
                     return $form->addError('One of the IP addresses or IP address ranges you entered contains your own IP address.');
                 }
                 if (!empty($bannedIpNew)) {
                     // Save Banned IPs
                     $bannedIpsTable->setAddresses($bannedIpsNew, $info);
                     unset($values['bannedips']);
                 }
                 $form->addNotice('Your changes have been saved.');
                 break;
                 // Ban Emails
             // Ban Emails
             case 0:
                 if ($values['email'] == "") {
                     $form->getElement('email')->addError('Please complete this field - it is required.');
                     return;
                 }
                 $info['type'] = 2;
                 // Email
                 // Save Banned Emails
                 $bannedEmailsNew = preg_split('/\\s*[,\\n]+\\s*/', $values['email']);
                 foreach ($bannedEmailsNew as $newEmail) {
                     $user = $userTable->select()->where('email = ?', $newEmail)->query()->fetchAll();
                     if (count($user) == 0 || $user[0]['level_id'] == 1 || $viewer->email == $user[0]['email']) {
                         $form->getElement('email')->addError('There is not any users relate to the email(s) or the email(s) you entered contains your own email or admin email.');
                         return;
                     }
                 }
                 $bannedEmailsTable->setEmails($bannedEmailsNew, $info);
                 $form->addNotice('Your changes have been saved.');
                 unset($values['email']);
                 break;
             default:
                 break;
         }
         $db->commit();
         //$form->addNotice('There is not any user relate to this email.');
         switch ($values['type']) {
             // Ban username
             case 1:
                 return $this->_helper->redirector->gotoRoute(array('action' => ''), 'ynbanmem_general', true);
                 break;
             case 2:
                 return $this->_helper->redirector->gotoRoute(array('action' => 'view-ip'), 'ynbanmem_general', true);
                 break;
             case 0:
                 return $this->_helper->redirector->gotoRoute(array('action' => 'view-email'), 'ynbanmem_general', true);
                 break;
         }
         //
         //      Engine_Api::_()->getApi('mail', 'core')->sendSystem($user, 'user_account_approved', array(
         //        'host' => $_SERVER['HTTP_HOST'],
         //        'email' => $user->email,
         //        'date' => time(),
         //        'recipient_title' => $user->getTitle(),
         //        'recipient_link' => $user->getHref(),
         //        'recipient_photo' => $user->getPhotoUrl('thumb.icon'),
         //        'object_link' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array(), 'user_login', true),
         //      ));
     } catch (Exception $e) {
         $db->rollBack();
         throw $e;
     }
 }
Exemplo n.º 14
0
 public function getAddresses()
 {
     $extraInfoTable = Engine_Api::_()->getDbTable('extrainfo', 'ynbanmem');
     $data = $this->select()->from($this, array('banned_id' => 'bannedip_id', 'start', 'stop'))->order('start ASC')->query()->fetchAll();
     $addresses = array();
     foreach ($data as $datum) {
         if ($datum['start'] == $datum['stop']) {
             $startStr = Engine_IP::normalizeAddress($datum['start']);
             $extraInfo = $extraInfoTable->getExtraInfo($datum['banned_id'], 1);
             $bannedip['banned_id'] = $datum['banned_id'];
             $bannedip['start'] = $startStr;
             $bannedip['stop'] = "";
             $bannedip['extra_info'] = $extraInfo;
             //$addresses[] = $startStr . ' - ' . $stopStr;
             if ($startStr) {
                 $addresses[] = $bannedip;
             }
         } else {
             $startStr = Engine_IP::normalizeAddress($datum['start']);
             $stopStr = Engine_IP::normalizeAddress($datum['stop']);
             //Get extra info
             $extraInfo = $extraInfoTable->getExtraInfo($datum['banned_id'], 1);
             $bannedip['banned_id'] = $datum['banned_id'];
             $bannedip['start'] = $startStr;
             $bannedip['stop'] = $stopStr;
             $bannedip['extra_info'] = $extraInfo;
             //$addresses[] = $startStr . ' - ' . $stopStr;
             if ($startStr && $stopStr) {
                 $addresses[] = $bannedip;
             }
         }
     }
     return array_filter($addresses);
 }
Exemplo n.º 15
0
 public function loginAction()
 {
     // Render
     $this->_helper->content->setContentName('user_auth_login')->setEnabled();
     $this->view->form = $form = new User_Form_Login();
     $form->setAction(Zend_Controller_Front::getInstance()->getRouter()->assemble(array(), 'user_login', true));
     $user_id = 0;
     $email = "";
     $skey = self::TEMPORAY_SESSION_LOGIN_ID;
     if (isset($_SESSION[$skey])) {
         $user_id = $_SESSION[$skey];
         unset($_SESSION[$skey]);
     }
     // $email, $password, $remember
     $user_table = Engine_Api::_()->getDbtable('users', 'user');
     // If post exists
     $user = $user_table->find($user_id)->current();
     // Get ip address
     $db = Engine_Db_Table::getDefaultAdapter();
     $ipObj = new Engine_IP();
     $ipExpr = new Zend_Db_Expr($db->quoteInto('UNHEX(?)', bin2hex($ipObj->toBinary())));
     // Check if user exists
     if (empty($user)) {
         $this->view->status = false;
         $this->view->error = Zend_Registry::get('Zend_Translate')->_('No record of a member with that email was found.');
         // Register login
         Engine_Api::_()->getDbtable('logins', 'user')->insert(array('email' => $email, 'ip' => $ipExpr, 'timestamp' => new Zend_Db_Expr('NOW()'), 'state' => 'no-member'));
         return;
     }
     // Check if user is verified and enabled
     if (!$user->enabled) {
         if (!$user->verified) {
             $this->view->status = false;
             $resend_url = $this->_helper->url->url(array('action' => 'resend', 'email' => $email), 'user_signup', true);
             $translate = Zend_Registry::get('Zend_Translate');
             $error = $translate->translate('This account still requires either email verification.');
             $error .= ' ';
             $error .= sprintf($translate->translate('Click <a href="%s">here</a> to resend the email.'), $resend_url);
             $this->view->error = $error;
             $form->getDecorator('errors')->setOption('escape', false);
             $form->addError($error);
             // Register login
             Engine_Api::_()->getDbtable('logins', 'user')->insert(array('user_id' => $user->getIdentity(), 'email' => $email, 'ip' => $ipExpr, 'timestamp' => new Zend_Db_Expr('NOW()'), 'state' => 'disabled'));
             return;
         } else {
             if (!$user->approved) {
                 $this->view->status = false;
                 $translate = Zend_Registry::get('Zend_Translate');
                 $this->view->error = $error = $translate->translate('This account still requires admin approval.');
                 $form->getDecorator('errors')->setOption('escape', false);
                 $form->addError($error);
                 // Register login
                 Engine_Api::_()->getDbtable('logins', 'user')->insert(array('user_id' => $user->getIdentity(), 'email' => $email, 'ip' => $ipExpr, 'timestamp' => new Zend_Db_Expr('NOW()'), 'state' => 'disabled'));
                 return;
             }
         }
         // Should be handled by hooks or payment
     }
     // Handle subscriptions
     if (Engine_Api::_()->hasModuleBootstrap('payment')) {
         // Check for the user's plan
         $subscriptionsTable = Engine_Api::_()->getDbtable('subscriptions', 'payment');
         if (!$subscriptionsTable->check($user)) {
             // Register login
             Engine_Api::_()->getDbtable('logins', 'user')->insert(array('user_id' => $user->getIdentity(), 'email' => $email, 'ip' => $ipExpr, 'timestamp' => new Zend_Db_Expr('NOW()'), 'state' => 'unpaid'));
             // Redirect to subscription page
             $subscriptionSession = new Zend_Session_Namespace('Payment_Subscription');
             $subscriptionSession->unsetAll();
             $subscriptionSession->user_id = $user->getIdentity();
             return $this->_helper->redirector->gotoRoute(array('module' => 'payment', 'controller' => 'subscription', 'action' => 'index'), 'default', true);
         }
     }
     // Register login
     $auth = Zend_Auth::getInstance();
     $auth->getStorage()->write($user->getIdentity());
     // Run pre login hook
     $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('onUserLoginBefore', $user);
     foreach ((array) $event->getResponses() as $response) {
         if (is_array($response)) {
             if (!empty($response['error']) && !empty($response['message'])) {
                 $form->addError($response['message']);
             } else {
                 if (!empty($response['redirect'])) {
                     $this->_helper->redirector->gotoUrl($response['redirect'], array('prependBase' => false));
                 } else {
                     continue;
                 }
             }
             // Register login
             Engine_Api::_()->getDbtable('logins', 'user')->insert(array('user_id' => $user->getIdentity(), 'email' => $email, 'ip' => $ipExpr, 'timestamp' => new Zend_Db_Expr('NOW()'), 'state' => 'third-party'));
             // Return
             return;
         }
     }
     // Register login
     $loginTable = Engine_Api::_()->getDbtable('logins', 'user');
     $loginTable->insert(array('user_id' => $user->getIdentity(), 'email' => $email, 'ip' => $ipExpr, 'timestamp' => new Zend_Db_Expr('NOW()'), 'state' => 'success', 'active' => true));
     $_SESSION['login_id'] = $login_id = $loginTable->getAdapter()->lastInsertId();
     // Increment sign-in count
     Engine_Api::_()->getDbtable('statistics', 'core')->increment('user.logins');
     // Test activity @todo remove
     $viewer = Engine_Api::_()->user()->getViewer();
     if ($viewer->getIdentity()) {
         $viewer->lastlogin_date = date("Y-m-d H:i:s");
         if ('cli' !== PHP_SAPI) {
             $viewer->lastlogin_ip = $ipExpr;
         }
         $viewer->save();
         Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $viewer, 'login');
     }
     // Assign sid to view for json context
     $this->view->status = true;
     $this->view->message = Zend_Registry::get('Zend_Translate')->_('Login successful');
     $this->view->sid = Zend_Session::getId();
     $this->view->sname = Zend_Session::getOptions('name');
     // Run post login hook
     $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('onUserLoginAfter', $viewer);
     // Do redirection only if normal context
     if (null === $this->_helper->contextSwitch->getCurrentContext()) {
         // Redirect by session
         $session = new Zend_Session_Namespace('Redirect');
         if (isset($session->uri)) {
             $uri = $session->uri;
             $opts = $session->options;
             $session->unsetAll();
             return $this->_redirect($uri, $opts);
         } else {
             if (isset($session->route)) {
                 $session->unsetAll();
                 return $this->_helper->redirector->gotoRoute($session->params, $session->route, $session->reset);
             }
         }
         // Redirect by hook
         foreach ((array) $event->getResponses() as $response) {
             if (is_array($response)) {
                 if (!empty($response['error']) && !empty($response['message'])) {
                     return $form->addError($response['message']);
                 } else {
                     if (!empty($response['redirect'])) {
                         return $this->_helper->redirector->gotoUrl($response['redirect'], array('prependBase' => false));
                     }
                 }
             }
         }
         // Just redirect to home
         return $this->_helper->redirector->gotoRoute(array('action' => 'home'), 'user_general', true);
     }
 }
Exemplo n.º 16
0
 public function indexAction()
 {
     // Render
     $this->_helper->content->setEnabled();
     // Get settings
     $settings = Engine_Api::_()->getApi('settings', 'core');
     // If the user is logged in, they can't sign up now can they?
     if (Engine_Api::_()->user()->getViewer()->getIdentity()) {
         return $this->_helper->redirector->gotoRoute(array(), 'default', true);
     }
     $formSequenceHelper = $this->_helper->formSequence;
     foreach (Engine_Api::_()->getDbtable('signup', 'user')->fetchAll() as $row) {
         if ($row->enable == 1) {
             $class = $row->class;
             $formSequenceHelper->setPlugin(new $class(), $row->order);
         }
     }
     // This will handle everything until done, where it will return true
     if (!$this->_helper->formSequence()) {
         return;
     }
     // Get viewer
     $viewer = Engine_Api::_()->user()->getViewer();
     // Run post signup hook
     $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('onUserSignupAfter', $viewer);
     $responses = $event->getResponses();
     if ($responses) {
         foreach ($event->getResponses() as $response) {
             if (is_array($response)) {
                 // Clear login status
                 if (!empty($response['error'])) {
                     Engine_Api::_()->user()->setViewer(null);
                     Engine_Api::_()->user()->getAuth()->getStorage()->clear();
                 }
                 // Redirect
                 if (!empty($response['redirect'])) {
                     return $this->_helper->redirector->gotoUrl($response['redirect'], array('prependBase' => false));
                 }
             }
         }
     }
     // Handle subscriptions
     if (Engine_Api::_()->hasModuleBootstrap('payment')) {
         // Check for the user's plan
         $subscriptionsTable = Engine_Api::_()->getDbtable('subscriptions', 'payment');
         if (!$subscriptionsTable->check($viewer)) {
             // Handle default payment plan
             $defaultSubscription = null;
             try {
                 $subscriptionsTable = Engine_Api::_()->getDbtable('subscriptions', 'payment');
                 if ($subscriptionsTable) {
                     $defaultSubscription = $subscriptionsTable->activateDefaultPlan($viewer);
                     if ($defaultSubscription) {
                         // Re-process enabled?
                         $viewer->enabled = true;
                         $viewer->save();
                     }
                 }
             } catch (Exception $e) {
                 // Silence
             }
             if (!$defaultSubscription) {
                 // Redirect to subscription page, log the user out, and set the user id
                 // in the payment session
                 $subscriptionSession = new Zend_Session_Namespace('Payment_Subscription');
                 $subscriptionSession->user_id = $viewer->getIdentity();
                 Engine_Api::_()->user()->setViewer(null);
                 Engine_Api::_()->user()->getAuth()->getStorage()->clear();
                 if (!empty($subscriptionSession->subscription_id)) {
                     return $this->_helper->redirector->gotoRoute(array('module' => 'payment', 'controller' => 'subscription', 'action' => 'gateway'), 'default', true);
                 } else {
                     return $this->_helper->redirector->gotoRoute(array('module' => 'payment', 'controller' => 'subscription', 'action' => 'index'), 'default', true);
                 }
             }
         }
     }
     // Handle email verification or pending approval
     if (!$viewer->enabled) {
         Engine_Api::_()->user()->setViewer(null);
         Engine_Api::_()->user()->getAuth()->getStorage()->clear();
         $confirmSession = new Zend_Session_Namespace('Signup_Confirm');
         $confirmSession->approved = $viewer->approved;
         $confirmSession->verified = $viewer->verified;
         $confirmSession->enabled = $viewer->enabled;
         return $this->_helper->_redirector->gotoRoute(array('action' => 'confirm'), 'user_signup', true);
     } else {
         Engine_Api::_()->user()->getAuth()->getStorage()->write($viewer->getIdentity());
         Engine_Hooks_Dispatcher::getInstance()->callEvent('onUserEnable', $viewer);
     }
     // Set lastlogin_date here to prevent issues with payment
     if ($viewer->getIdentity()) {
         $viewer->lastlogin_date = date("Y-m-d H:i:s");
         if ('cli' !== PHP_SAPI) {
             $ipObj = new Engine_IP();
             $viewer->lastlogin_ip = $ipObj->toBinary();
         }
         $viewer->save();
     }
     return $this->_helper->_redirector->gotoRoute(array('action' => 'home'), 'user_general', true);
 }
Exemplo n.º 17
0
 public static function setPreferIPv6($flag = true)
 {
     self::$_preferIPv6 = (bool) $flag;
 }