/**
  * Test, if a user cached by login gets removed on clear()
  */
 function test_get_by_login_and_remove()
 {
     $UserCache = new UserCache();
     $this->MockDB->expectCallCount('get_row', 2);
     $this->MockDB->expect('get_row', array(new PatternExpectation('/SELECT \\*\\s+FROM T_users.*login/is'), '*', '*', '*'), 'DB select ok.');
     $UserCache->get_by_login('login');
     $UserCache->clear();
     $UserCache->get_by_login('login');
 }
Exemplo n.º 2
0
 /**
  * Get general info of an issue
  * @param Issue $issue The issue
  * @param bool $isManager if true: show MgrEffortEstim column
  * @param bool $displaySupport If true, display support
  * @return mixed[]
  */
 public static function getIssueGeneralInfo(Issue $issue, $isManager = false, $displaySupport = false)
 {
     $withSupport = true;
     // include support in elapsed & Drift
     $drift = $issue->getDrift($withSupport);
     $issueGeneralInfo = array("issueId" => $issue->getId(), "issueSummary" => htmlspecialchars(preg_replace('![\\t\\r\\n]+!', ' ', $issue->getSummary())), "issueType" => $issue->getType(), "issueDescription" => htmlspecialchars($issue->getDescription()), "projectName" => $issue->getProjectName(), "categoryName" => $issue->getCategoryName(), "issueExtRef" => $issue->getTcId(), 'mantisURL' => Tools::mantisIssueURL($issue->getId(), NULL, true), 'issueURL' => Tools::mantisIssueURL($issue->getId()), 'statusName' => $issue->getCurrentStatusName(), 'priorityName' => $issue->getPriorityName(), 'severityName' => $issue->getSeverityName(), 'handlerName' => UserCache::getInstance()->getUser($issue->getHandlerId())->getName(), "issueEffortTitle" => $issue->getEffortEstim() . ' + ' . $issue->getEffortAdd(), "issueEffort" => $issue->getEffortEstim() + $issue->getEffortAdd(), "issueReestimated" => $issue->getReestimated(), "issueBacklog" => $issue->getBacklog(), "issueDriftColor" => $issue->getDriftColor($drift), "issueDrift" => round($drift, 2), "progress" => round(100 * $issue->getProgress()), 'relationships' => self::getFormattedRelationshipsInfo($issue));
     if ($isManager) {
         $issueGeneralInfo['issueMgrEffortEstim'] = $issue->getMgrEffortEstim();
         $driftMgr = $issue->getDriftMgr($withSupport);
         $issueGeneralInfo['issueDriftMgrColor'] = $issue->getDriftColor($driftMgr);
         $issueGeneralInfo['issueDriftMgr'] = round($driftMgr, 2);
     }
     if ($withSupport) {
         $issueGeneralInfo['issueElapsed'] = $issue->getElapsed();
     } else {
         $issueGeneralInfo['issueElapsed'] = $issue->getElapsed() - $issue->getElapsed(Jobs::JOB_SUPPORT);
     }
     if ($displaySupport) {
         if ($isManager) {
             $driftMgr = $issue->getDriftMgr(!$withSupport);
             $issueGeneralInfo['issueDriftMgrSupportColor'] = $issue->getDriftColor($driftMgr);
             $issueGeneralInfo['issueDriftMgrSupport'] = round($driftMgr, 2);
         }
         $drift = $issue->getDrift(!$withSupport);
         $issueGeneralInfo['issueDriftSupportColor'] = $issue->getDriftColor($drift);
         $issueGeneralInfo['issueDriftSupport'] = round($drift, 2);
     }
     return $issueGeneralInfo;
 }
Exemplo n.º 3
0
 protected function display()
 {
     // Admins only
     if (Tools::isConnectedUser()) {
         $session_user = UserCache::getInstance()->getUser($_SESSION['userid']);
         if ($session_user->isTeamMember(Config::getInstance()->getValue(Config::id_adminTeamId))) {
             $this->smartyHelper->assign('defaultColor', Holidays::$defaultColor);
             if (isset($_POST['hol_color'])) {
                 $formatedDate = Tools::getSecurePOSTStringValue('date');
                 $timestamp = Tools::date2timestamp($formatedDate);
                 $hol_desc = Tools::getSecurePOSTStringValue('hol_desc');
                 $hol_color = Tools::getSecurePOSTStringValue('hol_color');
                 if (!Holidays::save($timestamp, $hol_desc, $hol_color)) {
                     $this->smartyHelper->assign('error', T_("Couldn't add the holiday"));
                 }
             } elseif (isset($_POST['hol_id'])) {
                 $hol_id = Tools::getSecurePOSTIntValue('hol_id');
                 if (!Holidays::delete($hol_id)) {
                     $this->smartyHelper->assign('error', T_("Couldn't remove the holiday"));
                 }
             }
             $this->smartyHelper->assign('holidays', Holidays::getHolidays());
         }
     }
 }
Exemplo n.º 4
0
 /**
  * actionRefreshOperations 
  * 
  * @param int $id - task id
  */
 public function actionRefreshOperations($id)
 {
     UserOperation::updateData();
     // Reset cache
     UserCache::model()->updateAll(array('status' => 0));
     $this->redirect(array('view', 'id' => $id));
 }
Exemplo n.º 5
0
 /**
  *
  * 执行登录检查,如果错误,将返回状态代码403
  *
  * @access public
  * @param 无
  * @return void
  */
 public function execute($request)
 {
     Logger::debug('----- ' . __CLASS__ . ' is started -----');
     // 验证 SessionKey
     $user_id = $request->getRequestParameter(Constants::PARAM_SESSION_KEY);
     $clientSendKey = $request->getRequestParameter(Constants::PARAM_USER_ID);
     $userCache = UserCache::getCacheInstance();
     $serverSaveKey = $userCache->getByKey($user_id, Constants::CURRENT_SESSION_KEY);
     if ($serverSaveKey !== $clientSendKey) {
         Logger::debug('Stopping ' . __CLASS__ . '. caused by: Invalid session key.');
         Logger::debug('server save session key: ', $serverSaveKey);
         Logger::debug('client send session key: ', $clientSendKey);
         $view = new JsonView();
         $view->setValue('result', Constants::RESP_RESULT_ERROR);
         $view->setValue('message', "session key not match");
         $view->display();
         throw new ForbiddenException("Session Key not match.");
     }
     // 登录检查
     /*if( !$authorizer->loginCheck($auth_param) )
       {
           Logger::debug( 'Stopping ' . __CLASS__ . '. caused by: The request not authenticated.' );
           throw new ForbiddenException();
       }*/
     Logger::debug(__CLASS__ . ' is success.');
     Logger::debug('----- ' . __CLASS__ . ' is finished -----');
 }
Exemplo n.º 6
0
Arquivo: logs.php Projeto: fg-ok/codev
 protected function display()
 {
     if (Tools::isConnectedUser()) {
         // Admins only
         $session_user = UserCache::getInstance()->getUser($_SESSION['userid']);
         if ($session_user->isTeamMember(Config::getInstance()->getValue(Config::id_adminTeamId))) {
             if (NULL != Constants::$codevtt_logfile && file_exists(Constants::$codevtt_logfile)) {
                 $nbLinesToDisplay = 1500;
                 $lines = file(Constants::$codevtt_logfile);
                 if (count($lines) > $nbLinesToDisplay) {
                     $offset = count($lines) - $nbLinesToDisplay;
                 } else {
                     $offset = 0;
                 }
                 $logs = array();
                 for ($i = $offset; $i <= $offset + $nbLinesToDisplay, $i < count($lines); $i++) {
                     $logs[$i + 1] = htmlspecialchars($lines[$i], ENT_QUOTES, "UTF-8");
                     #echo "DEBUG $line_num - ".$logs[$line_num]."<br>";
                 }
                 $this->smartyHelper->assign('logs', $logs);
             } else {
                 $this->smartyHelper->assign('error', T_('Sorry, logfile not found:') . ' [' . Constants::$codevtt_logfile . ']');
             }
         } else {
             $this->smartyHelper->assign('error', T_('Sorry, you need to be in the admin-team to access this page.'));
         }
     } else {
         $this->smartyHelper->assign('error', T_('Sorry, you need to be in the admin-team to access this page.'));
     }
 }
Exemplo n.º 7
0
 /**
  * 用户缓存管理单例
  *
  * @access public
  * @param void
  * @return Memcache 单例对象
  */
 private static function getCacheInstance()
 {
     $get_instance = self::$cache_instance;
     if (is_null(self::$cache_instance)) {
         self::$cache_instance = MemcacheManager::instance();
     }
     return self::$cache_instance;
 }
Exemplo n.º 8
0
 public static function getInstance()
 {
     if (self::$instance === null) {
         self::$instance = new self();
         self::$instance->cacheDir = CACHE_DIR_PATH . DS . "user";
     }
     return self::$instance;
 }
Exemplo n.º 9
0
 protected function display()
 {
     if (Tools::isConnectedUser()) {
         // Admins only
         $session_user = UserCache::getInstance()->getUser($_SESSION['userid']);
         if ($session_user->isTeamMember(Config::getInstance()->getValue(Config::id_adminTeamId))) {
             $projectList = $this->getProjectList(false);
             if (isset($_POST['projectid']) && array_key_exists($_POST['projectid'], $projectList)) {
                 $projectid = Tools::getSecurePOSTIntValue('projectid');
                 $_SESSION['projectid'] = $projectid;
             } elseif (isset($_SESSION['projectid']) && array_key_exists($_SESSION['projectid'], $projectList)) {
                 $projectid = $_SESSION['projectid'];
             } else {
                 $projectIds = array_keys($projectList);
                 if (count($projectIds) > 0) {
                     $projectid = $projectIds[0];
                 } else {
                     $projectid = 0;
                 }
             }
             $this->smartyHelper->assign('projects', SmartyTools::getSmartyArray($projectList, $projectid));
             // display current workflow
             if (0 != $projectid) {
                 $clone_projectid = Tools::getSecurePOSTIntValue('clone_projectid', 0);
                 if ($clone_projectid == $projectid || !array_key_exists($clone_projectid, $projectList)) {
                     $clone_projectid = 0;
                 }
                 $action = Tools::getSecurePOSTStringValue('action', '');
                 if ("cloneToProject" == $action) {
                     #echo "Clone $projectid ---> $clone_projectid<br>";
                     $errMsg = Project::cloneAllProjectConfig($projectid, $clone_projectid);
                     $this->smartyHelper->assign('msg', 'Clone to project : ' . $errMsg);
                 } elseif ("cloneFromProject" == $action) {
                     #echo "Clone $clone_projectid ---> $projectid<br>";
                     $errMsg = Project::cloneAllProjectConfig($clone_projectid, $projectid);
                     $this->smartyHelper->assign('msg', 'Clone from project : ' . $errMsg);
                 }
                 unset($projectList[$projectid]);
                 $this->smartyHelper->assign('cloneProjects', SmartyTools::getSmartyArray($projectList, $clone_projectid));
                 $proj = ProjectCache::getInstance()->getProject($projectid);
                 $this->smartyHelper->assign('currentProjectId', $projectid);
                 $this->smartyHelper->assign('defaultProjectId', $clone_projectid);
                 $this->smartyHelper->assign('currentProjectName', $proj->getName());
                 $this->smartyHelper->assign('disabled', 0 == $clone_projectid);
                 $projectsInfo = array();
                 $projectsInfo[] = $this->getProjectInfo($proj, "tabsProject");
                 if (0 != $clone_projectid) {
                     $cproj = ProjectCache::getInstance()->getProject($clone_projectid);
                     $this->smartyHelper->assign('defaultProjectName', $cproj->getName());
                     $projectsInfo[] = $this->getProjectInfo($cproj, "tabsCloneProject");
                 }
                 $this->smartyHelper->assign('projectsInfo', $projectsInfo);
             }
         }
     }
 }
Exemplo n.º 10
0
 protected function display()
 {
     if (Tools::isConnectedUser()) {
         $session_user = UserCache::getInstance()->getUser($_SESSION['userid']);
         // Admins only
         if ($session_user->isTeamMember(Config::getInstance()->getValue(Config::id_adminTeamId))) {
             $this->smartyHelper->assign('access', true);
             $is_modified = Tools::getSecurePOSTStringValue('is_modified', 'false');
             // init
             // 'is_modified' is used because it's not possible to make a difference
             // between an unchecked checkBox and an unset checkbox variable
             if ("false" == $is_modified) {
                 $isBackup = true;
             } else {
                 $isBackup = $_POST['cb_backup'];
             }
             $filename = Tools::getSecurePOSTStringValue('backup_filename', "codevtt_backup_" . date("Ymd") . ".sql");
             $this->smartyHelper->assign('isBackup', $isBackup);
             $this->smartyHelper->assign('filename', $filename);
             if (isset($_POST['cb_backup'])) {
                 $result = true;
                 if ($isBackup) {
                     $result = SqlWrapper::getInstance()->sql_dump($filename) && $this->saveConfigFiles();
                     $this->smartyHelper->assign('backupResult', $result);
                 }
                 $this->smartyHelper->assign('stepOneResult', $result);
                 if ($result) {
                     $prjList = $this->displayProjectsToRemove();
                     $this->smartyHelper->assign('projects', $prjList);
                 }
                 $this->smartyHelper->assign('stepTwoResult', $result);
                 if ($result) {
                     $result = $this->removeCustomFields();
                 }
                 $this->smartyHelper->assign('stepThreeResult', $result);
                 if ($result) {
                     $result = Tools::execSQLscript2("uninstall.sql");
                 }
                 $this->smartyHelper->assign('stepFourResult', $result);
                 if ($result) {
                     $result = $this->deleteConfigFiles();
                 }
                 $this->smartyHelper->assign('stepFiveResult', $result);
                 if ($result) {
                     $result = $this->removeCustomMenuItem('CodevTT');
                 }
                 $this->smartyHelper->assign('stepSixResult', $result);
             } else {
                 Config::setQuiet(true);
                 $this->smartyHelper->assign('codevReportsDir', Constants::$codevOutputDir . DIRECTORY_SEPARATOR . 'reports');
                 Config::setQuiet(false);
                 $this->smartyHelper->assign('is_modified', $is_modified);
             }
         }
     }
 }
Exemplo n.º 11
0
function login($user, $password)
{
    $logger = Logger::getLogger('login');
    // WARN: if logger is LoggerAppenderEcho, then logs will break the login Ajax call !
    try {
        $appenders = $logger->getParent()->getAllAppenders();
        $isLog = true;
        foreach ($appenders as $appender) {
            if ('LoggerAppenderEcho' === get_class($appender)) {
                $isLog = false;
                break;
            }
        }
    } catch (Exception $e) {
        // logs should never break application
        $isLog = false;
    }
    $password = md5($password);
    $formattedUser = SqlWrapper::sql_real_escape_string($user);
    $formattedPass = SqlWrapper::sql_real_escape_string($password);
    $query = "SELECT id, username, realname FROM `mantis_user_table` WHERE username = '******' AND password = '******' AND enabled = 1;";
    $result = SqlWrapper::getInstance()->sql_query($query);
    if ($result && SqlWrapper::getInstance()->sql_num_rows($result) == 1 && ($row_login = SqlWrapper::getInstance()->sql_fetch_object($result))) {
        $_SESSION['userid'] = $row_login->id;
        $_SESSION['username'] = $row_login->username;
        $_SESSION['realname'] = $row_login->realname;
        try {
            $user = UserCache::getInstance()->getUser($row_login->id);
            $locale = $user->getDefaultLanguage();
            if (NULL != $locale) {
                $_SESSION['locale'] = $locale;
            }
            $teamid = $user->getDefaultTeam();
            if (0 != $teamid) {
                $_SESSION['teamid'] = $teamid;
            }
            $projid = $user->getDefaultProject();
            if (0 != $projid) {
                $_SESSION['projectid'] = $projid;
            }
        } catch (Exception $e) {
            if ($isLog && self::$logger->isDebugEnabled()) {
                $logger->debug("could not load preferences for user {$row_login->id}");
            }
        }
        if ($isLog) {
            $ua = Tools::getBrowser();
            $browserStr = $ua['name'] . ' ' . $ua['version'] . ' (' . $ua['platform'] . ')';
            $logger->info('user ' . $row_login->id . ' ' . $row_login->username . ' (' . $row_login->realname . '), Team ' . $user->getDefaultTeam() . ', ' . $browserStr);
        }
        return TRUE;
    } else {
        #$error = 'login failed !';
        return FALSE;
    }
}
Exemplo n.º 12
0
 public static function setSessionKey($user_id, $oldSessionKey)
 {
     // 生成缓存
     $newSessionKey = Util::generateSessionKey($user_id);
     Logger::debug('SessionKey1:' . $oldSessionKey);
     Logger::debug('SessionKey2:' . $newSessionKey);
     UserCache::setByKey($user_id, Constants::PREVIOUS_SESSION_KEY, $oldSessionKey);
     UserCache::setByKey($user_id, Constants::CURRENT_SESSION_KEY, $newSessionKey);
     return $newSessionKey;
 }
Exemplo n.º 13
0
 /**
  * @param Command $command
  * @return mixed[]
  */
 private static function getCommandIssues(Command $command)
 {
     $issueArray = array();
     $issues = $command->getIssueSelection()->getIssueList();
     foreach ($issues as $id => $issue) {
         $driftMgr = $issue->getDriftMgr();
         $driftMgrColor = $issue->getDriftColor($driftMgr);
         $drift = $issue->getDrift();
         $driftColor = $issue->getDriftColor($drift);
         $user = UserCache::getInstance()->getUser($issue->getHandlerId());
         $issueArray[$id] = array("mantisLink" => Tools::mantisIssueURL($issue->getId(), NULL, TRUE), "bugid" => Tools::issueInfoURL(sprintf("%07d\n", $issue->getId())), "extRef" => $issue->getTcId(), "project" => $issue->getProjectName(), "target" => $issue->getTargetVersion(), "status" => $issue->getCurrentStatusName(), "progress" => round(100 * $issue->getProgress()), "effortEstim" => $issue->getEffortEstim() + $issue->getEffortAdd(), "mgrEffortEstim" => $issue->getMgrEffortEstim(), "elapsed" => $issue->getElapsed(), "driftMgr" => $driftMgr, "driftMgrColor" => $driftMgrColor, "drift" => $drift, "driftColor" => $driftColor, "duration" => $issue->getDuration(), "summary" => $issue->getSummary(), "type" => $issue->getType(), "handlerName" => $user->getName());
     }
     return $issueArray;
 }
Exemplo n.º 14
0
 protected function getUserData()
 {
     $userId = $this->userId;
     $cache = UserCache::getInstance();
     $data = $cache->read($userId);
     if ((ENVIRONMENT & PRODUCTION) > 0 && !$data) {
         list($fp) = $cache->lock($userId);
         $data = $this->_getUserData($userId);
         $cache->write($fp, $data);
     }
     if (!$data) {
         $data = $this->_getUserData($userId);
     }
     return Sabel_ValueObject::fromArray(array("userId" => $userId, "friends" => Follower::getFriends($userId, FRIENDS_ICON_LIMIT + 1), "friendsCount" => $data["friends"], "followersCount" => $data["followers"], "statusesCount" => $data["statuses"], "latestComment" => $data["comment"]));
 }
Exemplo n.º 15
0
 protected function logicsFollowRemove($userId, $targetId, $result)
 {
     if ($result->isFailure() || $result->removeType !== "follow") {
         return;
     }
     $cache = UserCache::getInstance();
     list($fp, $data) = $cache->lock($userId);
     if ($data) {
         $data["friends"]--;
         $cache->write($fp, $data);
     }
     list($fp, $data) = $cache->lock($targetId);
     if ($data) {
         $data["followers"]--;
         $cache->write($fp, $data);
     }
 }
Exemplo n.º 16
0
 /**
  * fiches analyzed dont BI non renseignes
  * fiches analyzed dont RAE non renseignes
  * @return ConsistencyError[]
  */
 public function checkAnalyzed()
 {
     // CoDev FDJ custom, defined in Mantis
     $status_analyzed = Config::getVariableKeyFromValue(Config::id_statusNames, 'analyzed');
     $status_accepted = Config::getVariableKeyFromValue(Config::id_statusNames, 'accepted');
     $status_deferred = Config::getVariableKeyFromValue(Config::id_statusNames, 'deferred');
     $FDJ_teamid = Config::getInstance()->getValue(Config::id_ClientTeamid);
     $cerrList = array();
     // select all issues which current status is 'analyzed'
     $query = "SELECT * " . "FROM `mantis_bug_table` " . "WHERE status in ({$status_analyzed}, {$status_accepted}, " . Constants::$status_open . ", {$status_deferred}) ";
     if (0 != count($this->projectList)) {
         $formatedProjects = implode(', ', array_keys($this->projectList));
         $query .= "AND project_id IN ({$formatedProjects}) ";
     }
     $query .= "ORDER BY last_updated DESC, bug_id DESC";
     $result = SqlWrapper::getInstance()->sql_query($query);
     if (!$result) {
         echo "<span style='color:red'>ERROR: Query FAILED</span>";
         exit;
     }
     while ($row = SqlWrapper::getInstance()->sql_fetch_object($result)) {
         $issue = IssueCache::getInstance()->getIssue($row->id, $row);
         if (NULL == $issue->getEffortEstim()) {
             $cerr = new ConsistencyError($row->id, $row->handler_id, $row->status, $row->last_updated, T_("BI not specified: BI = Time(Analysis + Dev + Tests)"));
             $cerr->severity = T_("Error");
             $cerrList[] = $cerr;
         }
         if (is_null($issue->getBacklog())) {
             $cerr = new ConsistencyError($row->bug_id, $row->handler_id, $row->status, $row->last_updated, T_("Backlog not specified: Backlog = Time(BI - Analysis)"));
             $cerr->severity = T_("Error");
             $cerrList[] = $cerr;
         }
         if ($status_analyzed == $row->status) {
             $user = UserCache::getInstance()->getUser($row->handler_id);
             if (!$user->isTeamMember($FDJ_teamid)) {
                 $cerr = new ConsistencyError($row->bug_id, $row->handler_id, $row->status, $row->last_updated, T_("Once analysed, a Task must be assigned to 'FDJ' for validation"));
                 $cerr->severity = T_("Error");
                 $cerrList[] = $cerr;
             }
         }
     }
     // check if fields correctly set
     return $cerrList;
 }
Exemplo n.º 17
0
 protected function display()
 {
     if (Tools::isConnectedUser()) {
         // Admins only
         $session_user = UserCache::getInstance()->getUser($_SESSION['userid']);
         if ($session_user->isTeamMember(Config::getInstance()->getValue(Config::id_adminTeamId))) {
             if (isset($_POST['projects']) && !empty($_POST['projects'])) {
                 $selectedProjects = $_POST['projects'];
                 $result = array();
                 foreach ($selectedProjects as $projectid) {
                     $project = ProjectCache::getInstance()->getProject($projectid);
                     $result[$projectid] = $project->getName();
                     Project::prepareProjectToCodev($projectid);
                 }
                 $this->smartyHelper->assign('result', $result);
             }
             $this->smartyHelper->assign('projects', $this->getProjectList());
         }
     }
 }
Exemplo n.º 18
0
Arquivo: blog.php Projeto: fg-ok/codev
 /**
  * @param BlogPost[] $postList
  * @return mixed[]
  */
 private function getBlogPosts(array $postList)
 {
     $blogPosts = array();
     foreach ($postList as $id => $bpost) {
         $srcUser = UserCache::getInstance()->getUser($bpost->src_user_id);
         $item = array();
         // TODO
         $item['category'] = Config::getVariableValueFromKey(Config::id_blogCategories, $bpost->category);
         $item['severity'] = BlogPost::getSeverityName($bpost->severity);
         $item['summary'] = $bpost->summary;
         $item['content'] = $bpost->content;
         $item['date_submitted'] = date('Y-m-d G:i', $bpost->date_submitted);
         $item['from'] = $srcUser->getRealname();
         // find receiver
         if (0 != $bpost->dest_user_id) {
             $destUser = UserCache::getInstance()->getUser($bpost->dest_user_id);
             $item['to'] = $destUser->getRealname();
         } else {
             if (0 != $bpost->dest_team_id) {
                 $team = TeamCache::getInstance()->getTeam($bpost->dest_team_id);
                 $item['to'] = $team->getName();
             } else {
                 if (0 != $bpost->dest_project_id) {
                     $destProj = ProjectCache::getInstance()->getProject($bpost->dest_project_id);
                     $item['to'] = $destProj->getName();
                 } else {
                     $item['to'] = '?';
                 }
             }
         }
         $item['activity'] = 'activities...';
         $item['buttons'] = "<input type='button' value='" . T_('Ack') . "' onclick='javascript: ackPost(" . $bpost->id . ")' />";
         $item['buttons'] .= "<input type='button' value='" . T_('Hide') . "' onclick='javascript: hidePost(" . $bpost->id . ")' />";
         // TODO only if i'm the owner
         $item['buttons'] .= "<input type='button' value='" . T_('Delete') . "' onclick='javascript: deletePost(" . $bpost->id . ")' />";
         $item['isHidden'] = '0';
         $blogPosts[$id] = $item;
     }
     return $blogPosts;
 }
Exemplo n.º 19
0
 /**
  * Get consistency errors
  * @param int $teamid
  * @return mixed[]
  */
 private function getTeamConsistencyErrors($teamid)
 {
     if (self::$logger->isDebugEnabled()) {
         self::$logger->debug("getTeamConsistencyErrors teamid={$teamid}");
     }
     // get team projects
     $issueList = TeamCache::getInstance()->getTeam($teamid)->getTeamIssueList(true, false);
     if (self::$logger->isDebugEnabled()) {
         self::$logger->debug("getTeamConsistencyErrors nbIssues=" . count($issueList));
     }
     #$ccheck = new ConsistencyCheck2($issueList);
     $ccheck = new ConsistencyCheck2($issueList, $teamid);
     $cerrList = $ccheck->check();
     $cerrs = NULL;
     if (count($cerrList) > 0) {
         $i = 0;
         foreach ($cerrList as $cerr) {
             $i += 1;
             if (NULL != $cerr->userId) {
                 $user = UserCache::getInstance()->getUser($cerr->userId);
             } else {
                 $user = NULL;
             }
             if (Issue::exists($cerr->bugId)) {
                 $issue = IssueCache::getInstance()->getIssue($cerr->bugId);
                 $summary = $issue->getSummary();
                 $projName = $issue->getProjectName();
                 $refExt = $issue->getTcId();
             } else {
                 $summary = '';
                 $projName = '';
             }
             $cerrs[$i] = array('userName' => isset($user) ? $user->getName() : '', 'issueURL' => NULL == $cerr->bugId ? '' : Tools::issueInfoURL($cerr->bugId, $summary), 'mantisURL' => NULL == $cerr->bugId ? '' : Tools::mantisIssueURL($cerr->bugId, $summary, true), 'extRef' => NULL == $refExt ? '' : $refExt, 'date' => NULL == $cerr->timestamp ? '' : date("Y-m-d", $cerr->timestamp), 'status' => NULL == $cerr->status ? '' : Constants::$statusNames[$cerr->status], 'severity' => $cerr->getLiteralSeverity(), 'project' => $projName, 'desc' => $cerr->desc, 'summary' => $summary);
         }
     }
     return $cerrs;
 }
Exemplo n.º 20
0
 protected function display()
 {
     if (Tools::isConnectedUser()) {
         $session_user = UserCache::getInstance()->getUser($_SESSION['userid']);
         $mTeamList = $session_user->getDevTeamList();
         $lTeamList = $session_user->getLeadedTeamList();
         $oTeamList = $session_user->getObservedTeamList();
         $managedTeamList = $session_user->getManagedTeamList();
         $teamList = $mTeamList + $lTeamList + $oTeamList + $managedTeamList;
         $defaultTeam = isset($_SESSION['teamid']) ? $_SESSION['teamid'] : 0;
         $teamid = Tools::getSecureGETIntValue('teamid', $defaultTeam);
         $_SESSION['teamid'] = $teamid;
         $this->smartyHelper->assign('teams', SmartyTools::getSmartyArray($teamList, $teamid));
         // if current team is not in allowed list, do not display
         if (array_key_exists($teamid, $teamList)) {
             $team = TeamCache::getInstance()->getTeam($teamid);
             $start_year = date("Y", $team->getDate());
             $start_month = date("m", $team->getDate());
             $start_day = date("d", $team->getDate());
             $statusNames = Config::getInstance()->getValue("statusNames");
             ksort($statusNames);
             $this->smartyHelper->assign('statusNames', $statusNames);
             $periodStatsReport = new PeriodStatsReport($start_year, $start_month, $start_day, $teamid);
             $periodStatsList = $periodStatsReport->computeReport();
             $periods = array();
             foreach ($periodStatsList as $date => $ps) {
                 $status = array();
                 foreach ($statusNames as $s => $sname) {
                     $status[$s] = $ps->getStatusCount($s);
                 }
                 $periods[Tools::formatDate("%B %Y", $date)] = $status;
             }
             $this->smartyHelper->assign('periods', $periods);
         }
     }
 }
Exemplo n.º 21
0
 /**
  * actionView 
  * 
  * @param int $id 
  */
 public function actionView($id)
 {
     $model = $this->loadModel($id);
     // Fill taskIds for checkBoxList
     foreach ($model->tasks as $task) {
         $model->taskIds[] = $task->id;
     }
     if (isset($_POST['UserRole']['taskIds'])) {
         UserRoleHasUserTask::model()->deleteAllByAttributes(array('user_role_id' => $id));
         // Reset cache
         UserCache::model()->updateAll(array('status' => 0));
         if (is_array($_POST['UserRole']['taskIds'])) {
             foreach ($_POST['UserRole']['taskIds'] as $taskId) {
                 $newTask = new UserRoleHasUserTask();
                 $newTask->user_role_id = $id;
                 $newTask->user_task_id = $taskId;
                 $newTask->save(false);
             }
         }
         Yii::app()->user->setFlash('taskSaved', 'aga');
         $this->redirect(array('view', 'id' => $id));
     }
     $this->render('view', compact('model'));
 }
Exemplo n.º 22
0
 protected function updateTeamSelector()
 {
     if (Tools::isConnectedUser()) {
         // use the teamid set in the form, if not defined (first page call) use session teamid
         if (isset($_GET['teamid'])) {
             $this->teamid = Tools::getSecureGETIntValue('teamid');
             $_SESSION['teamid'] = $this->teamid;
         } else {
             $this->teamid = isset($_SESSION['teamid']) ? $_SESSION['teamid'] : 0;
         }
         $this->smartyHelper->assign('teamid', $this->teamid);
         $this->session_userid = $_SESSION['userid'];
         $this->session_user = UserCache::getInstance()->getUser($_SESSION['userid']);
         $this->teamList = $this->session_user->getTeamList();
         if (count($this->teamList) > 0) {
             $this->smartyHelper->assign('teams', SmartyTools::getSmartyArray($this->teamList, $_SESSION['teamid']));
         }
         $this->session_user->setDefaultTeam($this->teamid);
         // used to disable some menu items
         if ($this->session_user->isTeamMember(Config::getInstance()->getValue(Config::id_adminTeamId))) {
             $this->smartyHelper->assign('isAdmin', true);
         }
     }
 }
Exemplo n.º 23
0
 /**
  * @param string $field
  * @param string $value
  * @return string HTML
  * @throws MWException
  */
 function formatValue($field, $value)
 {
     /** @var $row object */
     $row = $this->mCurrentRow;
     $formatted = '';
     switch ($field) {
         case 'log_timestamp':
             // when timestamp is null, this is a old protection row
             if ($value === null) {
                 $formatted = Html::rawElement('span', array('class' => 'mw-protectedpages-unknown'), $this->msg('protectedpages-unknown-timestamp')->escaped());
             } else {
                 $formatted = htmlspecialchars($this->getLanguage()->userTimeAndDate($value, $this->getUser()));
             }
             break;
         case 'pr_page':
             $title = Title::makeTitleSafe($row->page_namespace, $row->page_title);
             if (!$title) {
                 $formatted = Html::element('span', array('class' => 'mw-invalidtitle'), Linker::getInvalidTitleDescription($this->getContext(), $row->page_namespace, $row->page_title));
             } else {
                 $formatted = Linker::link($title);
             }
             if (!is_null($row->page_len)) {
                 $formatted .= $this->getLanguage()->getDirMark() . ' ' . Html::rawElement('span', array('class' => 'mw-protectedpages-length'), Linker::formatRevisionSize($row->page_len));
             }
             break;
         case 'pr_expiry':
             $formatted = htmlspecialchars($this->getLanguage()->formatExpiry($value, true));
             $title = Title::makeTitleSafe($row->page_namespace, $row->page_title);
             if ($this->getUser()->isAllowed('protect') && $title) {
                 $changeProtection = Linker::linkKnown($title, $this->msg('protect_change')->escaped(), array(), array('action' => 'unprotect'));
                 $formatted .= ' ' . Html::rawElement('span', array('class' => 'mw-protectedpages-actions'), $this->msg('parentheses')->rawParams($changeProtection)->escaped());
             }
             break;
         case 'log_user':
             // when timestamp is null, this is a old protection row
             if ($row->log_timestamp === null) {
                 $formatted = Html::rawElement('span', array('class' => 'mw-protectedpages-unknown'), $this->msg('protectedpages-unknown-performer')->escaped());
             } else {
                 $username = UserCache::singleton()->getProp($value, 'name');
                 if (LogEventsList::userCanBitfield($row->log_deleted, LogPage::DELETED_USER, $this->getUser())) {
                     if ($username === false) {
                         $formatted = htmlspecialchars($value);
                     } else {
                         $formatted = Linker::userLink($value, $username) . Linker::userToolLinks($value, $username);
                     }
                 } else {
                     $formatted = $this->msg('rev-deleted-user')->escaped();
                 }
                 if (LogEventsList::isDeleted($row, LogPage::DELETED_USER)) {
                     $formatted = '<span class="history-deleted">' . $formatted . '</span>';
                 }
             }
             break;
         case 'pr_params':
             $params = array();
             // Messages: restriction-level-sysop, restriction-level-autoconfirmed
             $params[] = $this->msg('restriction-level-' . $row->pr_level)->escaped();
             if ($row->pr_cascade) {
                 $params[] = $this->msg('protect-summary-cascade')->escaped();
             }
             $formatted = $this->getLanguage()->commaList($params);
             break;
         case 'log_comment':
             // when timestamp is null, this is an old protection row
             if ($row->log_timestamp === null) {
                 $formatted = Html::rawElement('span', array('class' => 'mw-protectedpages-unknown'), $this->msg('protectedpages-unknown-reason')->escaped());
             } else {
                 if (LogEventsList::userCanBitfield($row->log_deleted, LogPage::DELETED_COMMENT, $this->getUser())) {
                     $formatted = Linker::formatComment($value !== null ? $value : '');
                 } else {
                     $formatted = $this->msg('rev-deleted-comment')->escaped();
                 }
                 if (LogEventsList::isDeleted($row, LogPage::DELETED_COMMENT)) {
                     $formatted = '<span class="history-deleted">' . $formatted . '</span>';
                 }
             }
             break;
         default:
             throw new MWException("Unknown field '{$field}'");
     }
     return $formatted;
 }
Exemplo n.º 24
0
 /**
  * _checkCache 
  *
  * Get agailiable routes from cache (or UserCache model)
  * 
  * @param boolean $forGuest
  *
  * @return array / CActiveRecord
  */
 private function _checkCache($forGuest = false)
 {
     if ($forGuest) {
         $userCache = UserCache::model()->find('is_guest = 1');
     } else {
         $user = User::model()->active()->with('cache')->findByPk((int) Yii::app()->user->id);
         // If no user (let's say he's been banned during session)
         // then return empty array - no allowed routes
         if (!$user) {
             return array();
         }
         $userCache = $user->cache;
     }
     // No cache
     if (!$userCache) {
         $cache = new UserCache();
         if (!$forGuest) {
             $cache->user_id = $user->id;
         }
         return $cache;
     } elseif ($userCache->status == 0) {
         return $userCache;
     } elseif ($userCache->update_time < time() - Yii::app()->getModule('UserAdmin')->cache_time) {
         return $userCache;
     } else {
         return unserialize($userCache->routes);
     }
 }
Exemplo n.º 25
0
 /**
  * Get consistency errors
  * @param Command $cmd
  * @return mixed[]
  */
 private function getConsistencyErrors(Command $cmd)
 {
     $consistencyErrors = array();
     // if null, array_merge fails !
     $cerrList = $cmd->getConsistencyErrors();
     if (count($cerrList) > 0) {
         foreach ($cerrList as $cerr) {
             if (!is_null($cerr->userId)) {
                 $user = UserCache::getInstance()->getUser($cerr->userId);
             } else {
                 $user = NULL;
             }
             if (Issue::exists($cerr->bugId)) {
                 $issue = IssueCache::getInstance()->getIssue($cerr->bugId);
                 $projName = $issue->getProjectName();
                 $summary = $issue->getSummary();
             } else {
                 $projName = '';
                 $summary = '';
             }
             $titleAttr = array(T_('Project') => $projName, T_('Summary') => $summary);
             $consistencyErrors[] = array('issueURL' => Tools::issueInfoURL($cerr->bugId, $titleAttr), 'issueStatus' => Constants::$statusNames[$cerr->status], 'user' => isset($user) ? $user->getName() : '', 'severity' => $cerr->getLiteralSeverity(), 'severityColor' => $cerr->getSeverityColor(), 'desc' => $cerr->desc);
         }
     }
     return $consistencyErrors;
 }
Exemplo n.º 26
0
	function doBatchLookups() {
		$userIds = array();
		$this->mResult->seek( 0 );
		foreach ( $this->mResult as $row ) {
			$userIds[] = $row->img_user;
		}
		# Do a link batch query for names and userpages
		UserCache::singleton()->doQuery( $userIds, array( 'userpage' ), __METHOD__ );
	}
Exemplo n.º 27
0
 /**
  * Get the real name of a user given their user ID
  *
  * @param int $id User ID
  * @return string|bool The corresponding user's real name
  */
 public static function whoIsReal($id)
 {
     return UserCache::singleton()->getProp($id, 'real_name');
 }
Exemplo n.º 28
0
if (Tools::isConnectedUser() && (isset($_GET['action']) || isset($_POST['action']))) {
    if (isset($_GET['action'])) {
        $smartyHelper = new SmartyHelper();
        if ($_GET['action'] == 'getTeamProjects') {
            $withDisabled = '1' == Tools::getSecureGETIntValue('withDisabledProjects', 1) ? true : false;
            $projects = TeamCache::getInstance()->getTeam(Tools::getSecureGETIntValue('teamid'))->getProjects(false, $withDisabled);
            $smartyHelper->assign('projects', SmartyTools::getSmartyArray($projects, 0));
            $smartyHelper->display('form/projectSelector');
        } elseif ($_GET['action'] == 'getTeamAllProjects') {
            $withDisabled = '1' == Tools::getSecureGETIntValue('withDisabledProjects', 1) ? true : false;
            $projects[0] = T_('All projects');
            $projects += $projects = TeamCache::getInstance()->getTeam(Tools::getSecureGETIntValue('teamid'))->getProjects(false, $withDisabled);
            $smartyHelper->assign('projects', SmartyTools::getSmartyArray($projects, 0));
            $smartyHelper->display('form/projectSelector');
        } elseif ($_GET['action'] == 'getProjectIssues') {
            $user = UserCache::getInstance()->getUser($_SESSION['userid']);
            $withDisabled = '1' == Tools::getSecureGETIntValue('withDisabledProjects', 1) ? true : false;
            // --- define the list of tasks the user can display
            // All projects from teams where I'm a Developper or Manager AND Observer
            $allProject[0] = T_('(all)');
            $dTeamList = $user->getDevTeamList();
            $devProjList = count($dTeamList) > 0 ? $user->getProjectList($dTeamList, true, $withDisabled) : array();
            $managedTeamList = $user->getManagedTeamList();
            $managedProjList = count($managedTeamList) > 0 ? $user->getProjectList($managedTeamList, true, $withDisabled) : array();
            $oTeamList = $user->getObservedTeamList();
            $observedProjList = count($oTeamList) > 0 ? $user->getProjectList($oTeamList, true, $withDisabled) : array();
            $projList = $allProject + $devProjList + $managedProjList + $observedProjList;
            // WORKAROUND
            if ($_GET['bugid'] == 'null') {
                $_GET['bugid'] = 0;
            }
Exemplo n.º 29
0
 /**
  *
  * @param IssueSelection $iSel
  * @param type $projectid
  * @param type $odtTemplate
  * @return string filepath complete path to generated ODT file
  */
 private function generateODT(IssueSelection $iSel, $projectid, $odtTemplate)
 {
     self::$logger->debug("genProjectODT(): project {$projectid} template {$odtTemplate}");
     $project = ProjectCache::getInstance()->getProject($projectid);
     $odf = new odf($odtTemplate);
     try {
         $odf->setVars('today', date('Y-m-d'));
     } catch (Exception $e) {
     }
     try {
         $odf->setVars('selectionName', $project->getName());
     } catch (Exception $e) {
     }
     try {
         $session_user = UserCache::getInstance()->getUser($this->session_userid);
         $odf->setVars('sessionUser', $session_user->getRealname());
     } catch (Exception $e) {
     }
     $issueList = $iSel->getIssueList();
     if (self::$logger->isDebugEnabled()) {
         self::$logger->debug("nb issues = " . count($issueList));
     }
     $q_id = 0;
     try {
         $issueSegment = $odf->setSegment('issueSelection');
     } catch (Exception $e) {
         self::$logger->error("generateODT: TAG 'issueSelection'");
         self::$logger->error("generateODT: " + $e->getMessage());
         return "FAILED: error on segment 'issueSelection'.";
     }
     if (self::$logger->isDebugEnabled()) {
         self::$logger->debug('XML=' . $issueSegment->getXml());
     }
     foreach ($issueList as $issue) {
         $q_id += 1;
         if (0 == $issue->getHandlerId()) {
             $userName = T_('unknown');
         } else {
             $user = UserCache::getInstance()->getUser($issue->getHandlerId());
             $userName = utf8_decode($user->getRealname());
             if (empty($userName)) {
                 $userName = "******" . $issue->getHandlerId();
             }
         }
         if (self::$logger->isDebugEnabled()) {
             self::$logger->debug("issue " . $issue->getId() . ": handlerName = " . $userName);
         }
         if (0 == $issue->getReporterId()) {
             $reporterName = T_('unknown');
         } else {
             $reporter = UserCache::getInstance()->getUser($issue->getReporterId());
             $reporterName = utf8_decode($reporter->getRealname());
             if (empty($reporterName)) {
                 $reporterName = "user_" . $issue->getReporterId();
             }
         }
         if (self::$logger->isDebugEnabled()) {
             self::$logger->debug("issue " . $issue->getId() . ": reporterName = " . $reporterName);
         }
         // add issue
         try {
             $issueSegment->setVars('q_id', $q_id);
         } catch (Exception $e) {
         }
         try {
             $issueSegment->setVars('bugId', $issue->getId());
         } catch (Exception $e) {
             $this->logException($e);
         }
         try {
             $issueSegment->setVars('summary', utf8_decode($issue->getSummary()));
         } catch (Exception $e) {
             $this->logException($e);
         }
         try {
             $issueSegment->setVars('dateSubmission', date('d/m/Y', $issue->getDateSubmission()));
         } catch (Exception $e) {
         }
         try {
             $timestamp = $issue->getLatestStatusOccurrence($issue->getBugResolvedStatusThreshold());
             if (is_null($timestamp)) {
                 $issueSegment->setVars('dateResolved', '');
             } else {
                 $issueSegment->setVars('dateResolved', date('d/m/Y', $timestamp));
             }
         } catch (Exception $e) {
         }
         try {
             $timestamp = $issue->getDeadLine();
             $deadline = 0 == $timestamp ? '' : date('d/m/Y', $issue->getDeadLine());
             $issueSegment->setVars('deadline', $deadline);
         } catch (Exception $e) {
             $this->logException($e);
         }
         try {
             $issueSegment->setVars('currentStatus', Constants::$statusNames[$issue->getCurrentStatus()]);
         } catch (Exception $e) {
         }
         try {
             $issueSegment->setVars('handlerId', $userName);
         } catch (Exception $e) {
         }
         try {
             $issueSegment->setVars('reporterId', $reporterName);
         } catch (Exception $e) {
         }
         try {
             $issueSegment->setVars('reporterName', $reporterName);
         } catch (Exception $e) {
         }
         try {
             $issueSegment->setVars('description', utf8_decode($issue->getDescription()));
         } catch (Exception $e) {
         }
         #try { $issueSegment->setVars('description', utf8_decode(Tools::convertToUTF8($issue->getDescription()))); } catch (Exception $e) { };
         try {
             $issueSegment->setVars('category', $issue->getCategoryName());
         } catch (Exception $e) {
         }
         try {
             $issueSegment->setVars('severity', $issue->getSeverityName());
         } catch (Exception $e) {
         }
         try {
             $issueSegment->setVars('status', Constants::$statusNames[$issue->getStatus()]);
         } catch (Exception $e) {
         }
         try {
             $issueSegment->setVars('extId', $issue->getTcId());
         } catch (Exception $e) {
         }
         // add issueNotes
         $issueNotes = $issue->getIssueNoteList();
         $noteId = 0;
         foreach ($issueNotes as $id => $issueNote) {
             $noteId += 1;
             if (self::$logger->isDebugEnabled()) {
                 self::$logger->debug("issue " . $issue->getId() . ": note {$id} = " . $issueNote->getNote());
             }
             $noteReporter = UserCache::getInstance()->getUser($issueNote->getReporterId());
             try {
                 $noteReporterName = utf8_decode($noteReporter->getRealname());
             } catch (Exception $e) {
             }
             try {
                 $issueSegment->bugnotes->noteId($noteId);
             } catch (Exception $e) {
             }
             try {
                 $issueSegment->bugnotes->noteReporter($noteReporterName);
             } catch (Exception $e) {
             }
             try {
                 $issueSegment->bugnotes->noteDateSubmission(date('d/m/Y', $issueNote->getDateSubmitted()));
             } catch (Exception $e) {
             }
             try {
                 $issueSegment->bugnotes->note(utf8_decode($issueNote->getNote()));
             } catch (Exception $e) {
             }
             try {
                 $issueSegment->bugnotes->merge();
             } catch (Exception $e) {
             }
         }
         $issueSegment->merge();
     }
     $odf->mergeSegment($issueSegment);
     // INFO: the following line is MANDATORY and fixes the following error:
     // "wrong .odt file encoding"
     #ob_end_clean();
     #$odf->exportAsAttachedFile();
     // 2nd solution : show link in page
     $odtFilename = basename($odtTemplate, ".odt") . '_' . $project->getName() . '_' . date('Ymd') . '.odt';
     $filepath = Constants::$codevOutputDir . '/reports/' . $odtFilename;
     if (self::$logger->isDebugEnabled()) {
         self::$logger->debug("save odt file " . $filepath);
     }
     $odf->saveToDisk($filepath);
     return $filepath;
 }
Exemplo n.º 30
0
 /**
  * 结算发送合体奖励邮件
  *
  * @access public
  * @param 无
  * @return JsonView 响应json
  */
 public function sendFitMail($user_id, $friend_id)
 {
     $user_name = UserCache::getByKey($user_id, "s_name");
     if (!$friend_id) {
         $userInfo = MailModel::getUserInfo($user_id);
         $user_name = $userInfo['s_name'];
     }
     $type = Constants::FIT_REWARD_TYPE;
     $coin = Constants::FIT_REWARD_NUM;
     $str = "你的好友" . $user_name . "邀你助战,你获得人生果" . $coin;
     $res = MailModel::insert(array('n_send_id' => $user_id, 'n_receive_id' => $friend_id, 's_message' => $str, 'n_item_type' => $type, 'n_item_num' => $coin, 'n_type' => 1, 't_update_time' => date("Y-m-d H:i:s"), 't_create_time' => date("Y-m-d H:i:s")));
 }