/**
* Displays the login page
* @param object $formModel
* @param bool $isMobile Whether this was called from mobile site controller
*/
public function login(LoginForm $model, $isMobile = false)
{
$model->attributes = $_POST['LoginForm'];
// get user input data
Session::cleanUpSessions();
$ip = $this->owner->getRealIp();
$userModel = $model->getUser();
$isRealUser = $userModel instanceof User;
$effectiveUsername = $isRealUser ? $userModel->username : $model->username;
$isActiveUser = $isRealUser && $userModel->status == User::STATUS_ACTIVE;
/* increment count on every session with this user/IP, to prevent brute force attacks
using session_id spoofing or whatever */
Yii::app()->db->createCommand('UPDATE x2_sessions SET status=status-1,lastUpdated=:time WHERE user=:name AND
CAST(IP AS CHAR)=:ip AND status BETWEEN -2 AND 0')->bindValues(array(':time' => time(), ':name' => $effectiveUsername, ':ip' => $ip))->execute();
$activeUser = Yii::app()->db->createCommand()->select('username')->from('x2_users')->where('username=:name AND status=1', array(':name' => $model->username))->limit(1)->queryScalar();
// get the correctly capitalized username
if (isset($_SESSION['sessionId'])) {
$sessionId = $_SESSION['sessionId'];
} else {
$sessionId = $_SESSION['sessionId'] = session_id();
}
$session = X2Model::model('Session')->findByPk($sessionId);
/* get the number of failed login attempts from this IP within timeout interval. If the
number of login attempts exceeds maximum, display captcha */
$badAttemptsRefreshTimeout = 900;
$maxFailedLoginAttemptsPerIP = 100;
$maxLoginsBeforeCaptcha = 5;
$this->pruneTimedOutBans($badAttemptsRefreshTimeout);
$failedLoginRecord = FailedLogins::model()->findActiveByIp($ip);
$badAttemptsWithThisIp = $failedLoginRecord ? $failedLoginRecord->attempts : 0;
if ($badAttemptsWithThisIp >= $maxFailedLoginAttemptsPerIP) {
$this->recordFailedLogin($ip);
throw new CHttpException(403, Yii::t('app', 'You are not authorized to use this application'));
}
// if this client has already tried to log in, increment their attempt count
if ($session === null) {
$session = new Session();
$session->id = $sessionId;
$session->user = $model->getSessionUserName();
$session->lastUpdated = time();
$session->status = 0;
$session->IP = $ip;
} else {
$session->lastUpdated = time();
$session->user = $model->getSessionUserName();
}
if ($isActiveUser === false) {
$model->verifyCode = '';
// clear captcha code
$model->validate();
// validate captcha if it's being used
$this->recordFailedLogin($ip);
$session->save();
if ($badAttemptsWithThisIp + 1 >= $maxFailedLoginAttemptsPerIP) {
throw new CHttpException(403, Yii::t('app', 'You are not authorized to use this application'));
} else {
if ($badAttemptsWithThisIp >= $maxLoginsBeforeCaptcha - 1) {
$model->useCaptcha = true;
$model->setScenario('loginWithCaptcha');
$session->status = -2;
}
}
} else {
if ($model->validate() && $model->login()) {
// user successfully logged in
if ($model->rememberMe) {
foreach (array('username', 'rememberMe') as $attr) {
// Expires in 30 days
AuxLib::setCookie(CHtml::resolveName($model, $attr), $model->{$attr}, 2592000);
}
} else {
foreach (array('username', 'rememberMe') as $attr) {
// Remove the cookie if they unchecked the box
AuxLib::clearCookie(CHtml::resolveName($model, $attr));
}
}
// We're not using the isAdmin parameter of the application
// here because isAdmin in this context hasn't been set yet.
$isAdmin = Yii::app()->user->checkAccess('AdminIndex');
if ($isAdmin && !$isMobile) {
$this->owner->attachBehavior('updaterBehavior', new UpdaterBehavior());
$this->owner->checkUpdates();
// check for updates if admin
} else {
Yii::app()->session['versionCheck'] = true;
}
// ...or don't
$session->status = 1;
$session->save();
SessionLog::logSession($model->username, $sessionId, 'login');
$_SESSION['playLoginSound'] = true;
if (YII_UNIT_TESTING && defined('X2_DEBUG_EMAIL') && X2_DEBUG_EMAIL) {
Yii::app()->session['debugEmailWarning'] = 1;
}
// if ( isset($_POST['themeName']) ) {
//.........这里部分代码省略.........
/**
* Returns true if the file is safe to upload.
*
* Will use fileinfo if available for determining mime type of the uploaded file.
* @param array $file
*/
public function checkFilename($filename)
{
if (preg_match(self::EXT_BLACKLIST, $filename, $match)) {
AuxLib::debugLog('Throwing exception for array: ' . var_export($_FILES, 1));
throw new CHttpException(403, Yii::t('app', 'Forbidden file type: {ext}', array('{ext}' => $match['ext'])));
}
}
/**
* Create new list from selection then mass add to newly created list
*/
public function testExecute()
{
TestingAuxLib::suLogin('admin');
X2List::model()->deleteAllByAttributes(array('name' => 'test'));
$newList = new NewListFromSelection();
$addToList = new MassAddToList();
// create new list with 2 records
$_POST['modelType'] = 'Contacts';
$_POST['listName'] = 'test';
$_SERVER['REQUEST_METHOD'] = 'POST';
$_SERVER['SERVER_NAME'] = 'localhost';
Yii::app()->controller = new ContactsController('contacts', new ContactsModule('contacts', null));
$gvSelection = range(1, 2);
AuxLib::debugLogR($newList->execute($gvSelection));
$getFlashes = TestingAuxLib::setPublic('NewListFromSelection', 'getFlashes');
AuxLib::debugLogR($getFlashes());
$list = X2List::model()->findByAttributes(array('name' => 'test'));
$itemIds = $list->queryCommand(true)->select('id')->queryColumn();
$this->assertEquals(array(1, 2), $itemIds);
// add the rest of the contacts to the newly created list
unset($_POST['modelType']);
unset($_POST['listName']);
$_POST['listId'] = $list->id;
$gvSelection = range(3, 24);
$addToList->execute($gvSelection);
$itemIds = $list->queryCommand(true)->select('id')->queryColumn();
$this->assertEquals(range(1, 24), $itemIds);
}
/**
* Deletes a web form record with the specified id
* @param int $id
*/
public function actionDeleteWebForm($id)
{
$model = WebForm::model()->findByPk($id);
$name = $model->name;
$success = false;
if ($model) {
$success = $model->delete();
}
AuxLib::ajaxReturn($success, Yii::t('app', "Deleted '{$name}'"), Yii::t('app', 'Unable to delete web form'));
}
public function run()
{
$hiddenTags = json_decode(Yii::app()->params->profile->hiddenTags, true);
$params = array();
if (count($hiddenTags) > 0) {
$tagParams = AuxLib::bindArray($hiddenTags);
$params = array_merge($params, $tagParams);
$str1 = " AND tag NOT IN (" . implode(',', array_keys($tagParams)) . ")";
} else {
$str1 = "";
}
$myTags = Yii::app()->db->createCommand()->select('COUNT(*) AS count, tag')->from('x2_tags')->where('taggedBy=:user AND tag IS NOT NULL' . $str1, array_merge($params, array(':user' => Yii::app()->user->getName())))->group('tag')->order('count DESC')->limit(20)->queryAll();
$allTags = Yii::app()->db->createCommand()->select('COUNT(*) AS count, tag')->from('x2_tags')->group('tag')->where('tag IS NOT NULL' . $str1, $params)->order('count DESC')->limit(20)->queryAll();
// $myTags=Tags::model()->findAllBySql("SELECT *, COUNT(*) as num FROM x2_tags WHERE taggedBy='".Yii::app()->user->getName()."' GROUP BY tag ORDER BY num DESC LIMIT 20");
// $allTags=Tags::model()->findAllBySql("SELECT *, COUNT(*) as num FROM x2_tags GROUP BY tag ORDER BY num DESC LIMIT 20");
$this->render('tagCloud', array('myTags' => $myTags, 'allTags' => $allTags, 'showAllUsers' => Yii::app()->params->profile->tagsShowAllUsers));
}
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact X2Engine, Inc. P.O. Box 66752, Scotts Valley,
* California 95067, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* X2Engine" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by X2Engine".
*****************************************************************************************/
/*
Public/private profile page. If the requested profile belongs to the current user, profile widgets
get displayed in addition to the activity feed/profile information sections.
*/
Yii::app()->clientScript->registerCssFiles('profileCombinedCss', array('profile.css', 'activityFeed.css', '../../../js/multiselect/css/ui.multiselect.css'));
Yii::app()->clientScript->registerResponsiveCssFile(Yii::app()->getTheme()->getBaseUrl() . '/css/responsiveActivityFeed.css');
AuxLib::registerPassVarsToClientScriptScript('x2.profile', array('isMyProfile' => $isMyProfile ? 'true' : 'false'), 'profileScript');
$this->renderPartial('_activityFeed', array('dataProvider' => $dataProvider, 'profileId' => $model->id, 'users' => $users, 'lastEventId' => $lastEventId, 'firstEventId' => $firstEventId, 'lastTimestamp' => $lastTimestamp, 'stickyDataProvider' => $stickyDataProvider, 'userModels' => $userModels, 'isMyProfile' => $isMyProfile));
/**
* Gets a list of names of all users having a group in common with a user.
*
* @param integer $userId User's ID
* @param boolean $cache Whether to cache or not
* @return array
*/
public static function getGroupmates($userId, $cache = true)
{
if ($cache === true && ($groupmates = Yii::app()->cache->get('user_groupmates')) !== false) {
if (isset($groupmates[$userId])) {
return $groupmates[$userId];
}
} else {
$groupmates = array();
}
$userGroups = self::getUserGroups($userId, $cache);
$groupmates[$userId] = array();
if (!empty($userGroups)) {
$groupParam = AuxLib::bindArray($userGroups, 'gid_');
$inGroup = AuxLib::arrToStrList(array_keys($groupParam));
$groupmates[$userId] = Yii::app()->db->createCommand()->select('DISTINCT(gtu.username)')->from(GroupToUser::model()->tableName() . ' gtu')->join(User::model()->tableName() . ' u', 'gtu.userId=u.id AND gtu.groupId IN ' . $inGroup, $groupParam)->queryColumn();
}
if ($cache === true) {
Yii::app()->cache->set('user_groupmates', $groupmates, 259200);
}
return $groupmates[$userId];
}
开发者ID:dsyman2,项目名称:X2CRM,代码行数:28,代码来源:Groups.php
示例14: getItems2
/**
* Improved version of getItems which enables use of empty search string, pagination, and
* configurable option values/names.
* @param string $prefix name prefix of items to retrieve
* @param int $page page number of results to retrieve
* @param int $limit max number of results to retrieve
* @param string|array $valueAttr attribute(s) used to popuplate the option values. If an
* array is passed, value will composed of values of each of the attributes specified, joined
* by commas
* @param string $nameAttr attribute used to popuplate the option names
* @return array name, value pairs
*/
public function getItems2($prefix = '', $page = 0, $limit = 20, $valueAttr = 'name', $nameAttr = 'name')
{
$modelClass = get_class($this->owner);
$model = CActiveRecord::model($modelClass);
$table = $model->tableName();
$offset = intval($page) * intval($limit);
AuxLib::coerceToArray($valueAttr);
$modelClass::checkThrowAttrError(array_merge($valueAttr, array($nameAttr)));
$params = array();
if ($prefix !== '') {
$params[':prefix'] = $prefix . '%';
}
$offset = abs((int) $offset);
$limit = abs((int) $limit);
$command = Yii::app()->db->createCommand("\n SELECT " . implode(',', $valueAttr) . ", {$nameAttr} as __name\n FROM {$table}\n WHERE " . ($prefix === '' ? '1=1' : $nameAttr . ' LIKE :prefix') . "\n ORDER BY __name\n LIMIT {$offset}, {$limit}\n ");
$rows = $command->queryAll(true, $params);
$items = array();
foreach ($rows as $row) {
$name = $row['__name'];
unset($row['__name']);
$items[] = array($name, $row);
}
return $items;
}
* You can contact X2Engine, Inc. P.O. Box 66752, Scotts Valley,
* California 95067, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* X2Engine" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by X2Engine".
*****************************************************************************************/
/**
* Used by inline workflow widget to render the funnel
*/
if (AuxLib::isIE8()) {
Yii::app()->clientScript->registerScriptFile(Yii::app()->getBaseUrl() . '/js/jqplot/excanvas.js');
}
if ($this->id !== 'Workflow') {
$assetsUrl = Yii::app()->assetManager->publish(Yii::getPathOfAlias('application.modules.workflow.assets'), false, -1, YII_DEBUG ? true : null);
} else {
$assetsUrl = $this->module->assetsUrl;
}
Yii::app()->clientScript->registerScriptFile($assetsUrl . '/js/X2Geometry.js', CClientScript::POS_END);
Yii::app()->clientScript->registerScriptFile($assetsUrl . '/js/BaseFunnel.js', CClientScript::POS_END);
Yii::app()->clientScript->registerScriptFile($assetsUrl . '/js/InlineFunnel.js', CClientScript::POS_END);
Yii::app()->clientScript->registerScript('_funnelJS', "\n\nx2.inlineFunnel = new x2.InlineFunnel ({\n workflowStatus: " . CJSON::encode($workflowStatus) . ",\n translations: " . CJSON::encode(array('Completed' => Yii::t('workflow', 'Completed'), 'Started' => Yii::t('workflow', 'Started'), 'Details' => Yii::t('workflow', 'Details'), 'Revert Stage' => Yii::t('workflow', 'Revert Stage'), 'Complete Stage' => Yii::t('workflow', 'Complete Stage'), 'Start' => Yii::t('workflow', 'Start'), 'noRevertPermissions' => Yii::t('workflow', 'You do not have permission to revert this stage.'), 'noCompletePermissions' => Yii::t('workflow', 'You do not have permission to complete this stage.'))) . ",\n stageCount: " . $stageCount . ",\n containerSelector: '#funnel-container',\n colors: " . CJSON::encode($colors) . ",\n revertButtonUrl: '" . Yii::app()->theme->getBaseUrl() . "/images/icons/Uncomplete.png',\n completeButtonUrl: '" . Yii::app()->theme->getBaseUrl() . "/images/icons/Complete.png',\n stageNames: " . CJSON::encode(Workflow::getStageNames($workflowStatus)) . ",\n stagePermissions: " . CJSON::encode(Workflow::getStagePermissions($workflowStatus)) . ",\n uncompletionPermissions: " . CJSON::encode(Workflow::getStageUncompletionPermissions($workflowStatus)) . ",\n stagesWhichRequireComments: " . CJSON::encode(Workflow::getStageCommentRequirements($workflowStatus)) . "\n});\n\n", CClientScript::POS_END);
?>
<div id='funnel-container'></div>
请发表评论