public static function add($serviceName, $object, $code = self::CODE_FAILED, $message = null, User $authUser = null, $data = null, PropelPDO $con = null) { if ($object === null) { $entityName = 'null'; $index = 0; } elseif (is_object($object)) { $entityName = get_class($object); $idMethod = array($object, 'getId'); $index = is_callable($idMethod) ? call_user_func($idMethod) : null; } elseif (is_array($object) and isset($object[0], $object[1])) { list($entityName, $index) = $object; } else { $entityName = 'data'; $index = json_encode($object); } if ($authUser === null) { $userName = '******'; } else { try { $userName = $authUser->getFQN($con); } catch (Exception $doubleException) { $userName = '******' . $authUser->getId() . ']'; } } try { $log = new SystemLog(); $log->setUser($authUser)->setService($serviceName)->setEntity($entityName)->setIndex($index)->setCode($code)->setMessage($message)->setData($data)->save($con); } catch (Exception $e) { error_log(__METHOD__ . ': Could not log: ' . $entityName . ' #' . $index . ', code ' . $code . ', message: ' . $message . ', user "' . $userName . '", data: ' . json_encode($data) . ', exception ' . $e->__toString()); } }
/** * 'onFlush' event handling. * This method will be called when the 'flush' method of RLog is called * like: <pre>Rays::logger()->flush();</pre> * @param $event event object */ public function onFlush($event) { $logs = $event->getParams(); if (!empty($logs)) { foreach ($logs as $log) { $sysLog = new SystemLog(array('host' => Rays::app()->request()->getUserHostAddress(), 'path' => Rays::uri(), 'title' => $this->getHeaderTitle(), 'uri' => Rays::referrerUri(), 'timestamp' => date('Y-m-d H:i:s'))); $sysLog->userId = Rays::isLogin() ? Rays::user()->id : 0; $sysLog->message = $log['message']; $level = null; switch ($log['level']) { case RLog::LEVEL_ERROR: $level = 2; break; case RLog::LEVEL_INFO: $level = 0; break; case RLog::LEVEL_WARNING: $level = 1; break; } if ($level === null) { continue; } $sysLog->severity = $level; $sysLog->type = $log['type']; $sysLog->save(); unset($sysLog); } } }
public function exec() { foreach ($this->jobs() as $name => $file) { $pid = shell_exec(self::PHP_CMD . " {$file} >> " . LOG_DIR . "/job_exec.log 2>&1 &"); SystemLog::local_log('job_manager', "{$name} started, PID:" . str_replace('[1]', '', $pid)); } }
public static function getInstance($logFolderPath = null) { if (!is_object(self::$_instance)) { self::$_instance = new SystemLog($logFolderPath); } return self::$_instance; }
/** * Render the view and return the result. * * @return string */ public function render() { // Start buffering ob_start(); // Extract all variables into the local scope $__vars = $this->getView()->getVariables(); extract($__vars, EXTR_REFS); unset($__vars); // Include PHP source template if ($this->getView()->getSource() === null) { // No external source template has been defined, so check the rawSource //if($this->rawSource!==NULL) { // echo $this->rawSource; //} } else { if (is_file($this->getView()->getSource()) && (include $this->getView()->getSource())) { // Successfully included } else { SystemLog::add("View template source is missing: {$this->getView()->getSource()}", SystemLog::WARNING); } } // Read the output buffer $buffer = ob_get_clean(); // Remove any UTF-8 BOM (Byte Order Mark) from the beginning of the buffer // This is required, at least, on child templates because otherwise the // BOM is displayed as a visible character in the output. $buffer = preg_replace("/^/", "", $buffer); // Result return $buffer; }
/** * View system logs */ public function actionLogs() { $curPage = $this->getPage("page"); $pageSize = $this->getPageSize("pagesize", 10); $count = SystemLog::find()->count(); $logs = SystemLog::find()->order_desc("id")->join('user')->range(($curPage - 1) * $pageSize, $pageSize); $pager = new RPager('page', $count, $pageSize, RHtml::siteUrl('admin/logs'), $curPage); $this->setHeaderTitle("System logs"); $this->render('logs', ['logs' => $logs, 'pager' => $pager->showPager(), 'count' => $count], false); }
public function repos($params) { $view = new View(); if (!Core::hasAdminAccess()) { return Core::getLoginView($view); } $view->setSource(Config::get('ext.acl.dir.views') . '/repos.tpl'); if (isset($_GET['id'])) { $view->setSource(Config::get('ext.acl.dir.views') . '/repos.edit.tpl'); $repo = Model::create('AclRepo'); if ($_GET['id'] > 0) { $repo->id = (int) $_GET['id']; if (!$repo->getModelManager()->load($repo)) { SystemLog::add(array('Failed to load repository #%s', $repo->id), SystemLog::WARNING); $view->setSource(NULL); return $view; } } // Save if (isset($_POST['name'])) { $repo->name = $_POST['name']; if ($repo->getModelManager()->save($repo)) { SystemLog::add('Data saved!', SystemLog::INFO); } else { SystemLog::add('Failed to save data.', SystemLog::WARNING); } } else { if (isset($_GET['remove']) && $repo->isInDatabase()) { if ($repo->getModelManager()->delete($repo)) { SystemLog::add('Data removed!', SystemLog::INFO); $repo = Model::create('AclRepo'); } else { SystemLog::add('Failed to remove data.', SystemLog::WARNING); } } } // View $view->repo = $repo; return $view; } // View $view->repos = ModelManager::select('AclRepo'); return $view; }
public function uninstall() { // Get DB connection try { $DB = Database::getConnection(); } catch (Exception $e) { SystemLog::add('This extension requires a database. (' . $e->getMessage() . ')', SystemLog::WARNING); return FALSE; } // Table definitions $tables = array('acl_repo', 'acl_role', 'acl_resource', 'acl_role_member', 'acl_type', 'acl_entry'); // Create tables try { $DB->beginTransaction(); foreach ($tables as $table) { if (!ModelManager::sqlQuery('DROP TABLE IF EXISTS ' . $table)) { throw new PDOException("Invalid SQL"); } } $DB->commit(); return TRUE; } catch (PDOException $e) { SystemLog::add($e->getMessage(), SystemLog::WARNING); try { $DB->rollBack(); } catch (PDOException $e) { SystemLog::add($e->getMessage(), SystemLog::WARNING); } } // Catch-all result return FALSE; }
/** * Exclude object from result * * @param SystemLog $systemLog Object to remove from the list of results * * @return SystemLogQuery The current query, for fluid interface */ public function prune($systemLog = null) { if ($systemLog) { $this->addUsingAlias(SystemLogPeer::ID, $systemLog->getId(), Criteria::NOT_EQUAL); } return $this; }
public static function getRelation($modelSource, $modelTarget = null, $relationRef = null) { // Pass back ALL relationships if ($modelTarget === null) { $relations = []; $relationMap = isset(self::$relationships[$modelSource]) ? self::$relationships[$modelSource] : []; foreach ($relationMap as $k => $rel) { foreach ($rel as $r) { $relations[] = $r; } reset(self::$relationships[$modelSource][$k]); } return $relations; } // First, check if we've got a direct relationship (works for 1:1, 1:M and M:1) if (isset(self::$relationships[$modelSource][$modelTarget])) { if ($relationRef === null) { $rel = count(self::$relationships[$modelSource][$modelTarget]) > 1 ? self::$relationships[$modelSource][$modelTarget] : current(self::$relationships[$modelSource][$modelTarget]); return $rel; } else { if (isset(self::$relationships[$modelSource][$modelTarget][$relationRef])) { return self::$relationships[$modelSource][$modelTarget][$relationRef]; } else { if ($modelSource != $modelTarget) { SystemLog::add("No relationship with reference '{$relationRef}' has been defined for {$modelSource}:{$modelTarget}", SystemLog::CORE); return new ModelRelation(['modelSource' => $modelSource, 'modelTarget' => $modelTarget, 'cardinality' => ModelRelation::NONE]); } } } } // Try to construct a M:M relationship /*if(isset(self::$relationships[$modelSource])) { $relationRef = $relationRef===NULL ? self::REF_DEFAULT : $relationRef; foreach(self::$relationships[$modelSource] as $linkModel=>$relation) { if(isset(self::$relationships[$linkModel][$modelTarget][$relationRef])) { return self::$relationships[$modelSource][$modelTarget][$relationRef] = new ModelRelation(array( 'modelSource'=>$modelSource, 'modelTarget'=>$modelTarget, 'cardinality'=>ModelRelation::MANY_TO_MANY, 'modelLink'=>$linkModel, 'reference'=>$relationRef )); } } }*/ // If all else fails, return a ModelRelation with NONE cardinality SystemLog::add("No relationship has been defined for {$modelSource}:{$modelTarget}", SystemLog::CORE); return new ModelRelation(['modelSource' => $modelSource, 'modelTarget' => $modelTarget, 'cardinality' => ModelRelation::NONE]); }
/** * Adds an object to the instance pool. * * Propel keeps cached copies of objects in an instance pool when they are retrieved * from the database. In some cases -- especially when you override doSelect*() * methods in your stub classes -- you may need to explicitly add objects * to the cache in order to ensure that the same objects are always returned by doSelect*() * and retrieveByPK*() calls. * * @param SystemLog $obj A SystemLog object. * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). */ public static function addInstanceToPool($obj, $key = null) { if (Propel::isInstancePoolingEnabled()) { if ($key === null) { $key = (string) $obj->getId(); } // if key === null SystemLogPeer::$instances[$key] = $obj; } }
private function write_log($user_id, $exception) { $file = $exception->getFile(); $file = str_replace('\\', '\\\\', $file); $trace_as_string = $exception->getTraceAsString(); $trace_as_string = str_replace('\\', '\\\\', $trace_as_string); $trace_as_string = str_replace('\'', '\\"', $trace_as_string); $system_log = new SystemLog(null); $system_log->create($user_id, 2, 1, $exception->getMessage(), $exception->getCode(), $file, $exception->getLine(), null); $system_log->set_stack_trace($trace_as_string); }
/** * Returns the View stored in the specified slot, or an empty Buan\View if the * slot does not exist. * * @param string ID of the slot you want to retrieve * @return \View */ public function getSlot($slotId) { if (isset($this->slots[$slotId])) { return $this->slots[$slotId]; } else { SystemLog::add("There is no View object in slot \"{$slotId}\"", SystemLog::WARNING); return new View(); } }
/** * 获取系统日志实例 * @return SystemLog */ public static function getSystemLog () { if (!self::$SYS_LOG){ include_once SUISHI_PHP_PATH . '/Log/SystemLog.class.php'; $obj = new SystemLog(); $obj->setLogFormat(SystemLog::FORMAT_JSON); $obj->setLogpath(SuiShiPHPConfig::getSysLogDir()); self::$SYS_LOG = $obj; } return self::$SYS_LOG; }
/** * @see SecurityInterface::ip_error_count() * @return integer */ public static function ip_error_count() { $ip = $_SERVER['REMOTE_ADDR']; $lead_time = date("Y-m-d H:i:s", time() - (int) Registry::get_value("base_max_ip_lead_time")); return SystemLog::count_ip_failed_logins_with_begin($ip, $lead_time); }
/** * Sets this Model's PK value. * Persistent Models cannot have their primary key changed. * * This method will be automatically executed (via __set()) if the * primary-key field is altered directly. For example, if the PK is "id", then * the following are equivalent: * $this->id = 5; * $this->setPrimaryKeyValue(5); * * For a composite PK, there are two methods of setting the values for each * field involved in the key: * $this->setPrimaryKeyValue(array(field1=>value, field2=>value));, or * $this->setPrimaryKeyValue(field1, value); * $this->setPrimaryKeyValue(field2, value); * * @param string|mixed See description above * @param mixed Value of specified composite key field * @return bool */ public function setPrimaryKeyValue($arg1, $arg2 = null) { // Check that $this Model is not persistent. if ($this->isInDatabase()) { // TODO: What about the hasChanged flag? it was set to true by __set(), but we might need it false here. // Maybe move this method's code to __set and have a special case "... if($fieldName=="id") { ... } ..." SystemLog::add("Attempting to reset primary-key on a persistent Model", SystemLog::WARNING); return false; } else { if (!$this->hasCompositePrimaryKey()) { $this->dbData[$this->getPrimaryKey()] = $arg1; } else { if (is_array($arg1)) { // TODO: Should we ensure that all array keys in $arg1 are actually primary key fields? foreach ($arg1 as $k => $v) { $this->dbData[$k] = $v; } } else { if ($arg2 !== null) { $this->dbData[$arg1] = $arg2; } else { // TODO: THROW exception? would be better } } } } // Flag as changed $this->hasChanged(true); return true; }
/** * save cron job log * @param string $string */ public function log($string) { SystemLog::local_log('CronJob_' . get_class($this), $string); }
/** * @throws SystemLogIDMissingException */ public static function ip_info() { if ($_GET['id']) { $ip = $_GET['id']; $successful_logins = SystemLog::count_ip_successful_logins($ip); $failed_logins = SystemLog::count_ip_failed_logins($ip); $template = new HTMLTemplate("base/admin/system_log/ip_info.html"); $template->set_var("ip", $ip); if ($successful_logins) { $template->set_var("successful_logins", $successful_logins); } else { $template->set_var("successful_logins", 0); } if ($failed_logins) { $template->set_var("failed_logins", $failed_logins); } else { $template->set_var("failed_logins", 0); } $user_array = SystemLog::list_ip_users($ip); $user_content_array = array(); $counter = 0; if (is_array($user_array) and count($user_array) >= 1) { foreach ($user_array as $key => $value) { $user = new User($value); $user_content_array[$counter]['username'] = $user->get_username(); $user_content_array[$counter]['fullname'] = $user->get_full_name(false); $counter++; } $template->set_var("no_user", false); } else { $template->set_var("no_user", true); } $template->set_var("user", $user_content_array); $template->output(); } else { throw new SystemLogIDMissingException(); } }
/** * @see UserInterface::delete() * @return bool */ public function delete() { global $transaction; if ($this->user) { if ($this->check_delete_dependencies() == true) { $transaction_id = $transaction->begin(); // Sessions if (Session::delete_user_sessions($this->user_id) == false) { if ($transaction_id != null) { $transaction->rollback($transaction_id); } return false; } // Profile and Settings $user_profile = new UserProfile_Access($this->user_id); if ($user_profile->delete() == false) { if ($transaction_id != null) { $transaction->rollback($transaction_id); } return false; } $user_profile_setting = new UserProfileSetting_Access($this->user_id); if ($user_profile_setting->delete() == false) { if ($transaction_id != null) { $transaction->rollback($transaction_id); } return false; } $user_admin_setting = new UserAdminSetting_Access($this->user_id); if ($user_admin_setting->delete() == false) { if ($transaction_id != null) { $transaction->rollback($transaction_id); } return false; } // Groups if (GroupHasUser_Access::delete_by_user_id($this->user_id) == false) { if ($transaction_id != null) { $transaction->rollback($transaction_id); } return false; } // System-Logs if (SystemLog::set_user_id_on_null($this->user_id) == false) { if ($transaction_id != null) { $transaction->rollback($transaction_id); } return false; } $user_delete_event = new UserDeleteEvent($this->user_id); $event_handler = new EventHandler($user_delete_event); if ($event_handler->get_success() == false) { if ($transaction_id != null) { $transaction->rollback($transaction_id); } return false; } if ($this->user->delete() == false) { if ($transaction_id != null) { $transaction->rollback($transaction_id); } return false; } $user_post_delete_event = new UserPostDeleteEvent($this->user_id); $event_handler = new EventHandler($user_post_delete_event); if ($event_handler->get_success() == false) { if ($transaction_id != null) { $transaction->rollback($transaction_id); } return false; } else { if ($transaction_id != null) { $transaction->commit($transaction_id); } return true; } } else { return false; } } else { return false; } }
/** * @param SystemLog $systemLog The systemLog object to add. */ protected function doAddSystemLog($systemLog) { $this->collSystemLogs[] = $systemLog; $systemLog->setUser($this); }
/** * This method simply includes the given configuration files, which prepare the * application environment, and sets a few of it's own configuration variables. * * The first script, $configFile, should only perform the following tasks: * - Define settings via Config::set() * - Optionally define database connections and model relationships * * The second scripts, $bootstrap, is then free to do anything it wants. * * For a full list of required and optional config variable, see the bundled * "application/app/config.php" * * @param string $configFile Absolute path to the configuration file * @param string $bootstrap Absolute path to the bootstrap script * @return void */ public static function configure($configFile, $bootstrap = null) { // Include configuration file if (include $configFile) { // Check for existence of some required settings and set defaults or halt $app = Config::get('app'); if (!isset($app['docRoot'])) { SystemLog::add("You have not defined your application's document root in {$configFile}.", SystemLog::FATAL); Core::halt(); } if (!isset($app['command']['urlPrefix'])) { $app['command']['urlPrefix'] = ''; } if (!isset($app['command']['parameter']) || $app['command']['parameter'] === '') { $app['command']['parameter'] = 'do'; } if (!isset($app['command']['default'])) { $app['command']['default'] = ''; } if (!isset($app['dir']['ignored'])) { $app['dir']['ignored'] = ['.', '..', '.svn', 'cvs']; } if (!isset($app['domain'])) { $app['domain'] = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost'; } if (!isset($app['password'])) { $app['password'] = rand(1000000, 9999999); } if (!isset($app['urlRoot'])) { $app['urlRoot'] = ''; } else { if ($app['urlRoot'] !== '') { $app['urlRoot'] = preg_replace("/^\\/*/", "/", preg_replace("/\\/+\$/", "", $app['urlRoot'])); } } // Reassign filtered settings to Config Config::set('app', $app); // Ensure that any encoded forward slashes in the command URL remain // encoded if (isset($_SERVER['QUERY_STRING']) && preg_match("/" . $app['command']['parameter'] . "=([^&]*\\%2F[^&]*)/i", $_SERVER['QUERY_STRING'], $m) > 0) { $_REQUEST[$app['command']['parameter']] = $_GET[$app['command']['parameter']] = $m[1]; } // Store the requested command $cp = Config::get('app.command.parameter'); if (isset($_REQUEST[$cp])) { Config::set('app.command.requested', isset($_REQUEST[$cp]) ? $_REQUEST[$cp] : ''); } else { if (isset($_SERVER['REQUEST_URI']) && preg_match("/^" . preg_quote($app['urlRoot'], '/') . "\\/index\\.php\\/(.+)\$/i", $_SERVER['REQUEST_URI'], $m)) { Config::set('app.command.requested', $m[1]); } else { Config::set('app.command.requested', ''); } } } else { // Log and halt SystemLog::add("Cannot find an application configuration file (looking for {$configFile})", SystemLog::FATAL); Core::halt(); } // Store the given application configuration file in the global Config so it // may be retrieved by other processes if needs be. Config::set('app.configFile', $configFile); // Include bootstrap script if ($bootstrap !== null && (include $bootstrap)) { // Success } }
public static final function getExtensionByName($extName) { // Vars $extClassName = Inflector::extensionName_extensionClass($extName); static $extensions = []; if (isset($extensions[$extName])) { return $extensions[$extName]; } // Find the extension // Extensions in "app" will override the same extension in "core". $extFolders = ['app' => Config::get('app.dir.extensions'), 'core' => Config::get('core.dir.extensions')]; foreach ($extFolders as $namespace => $extFolder) { if ($extFolder == '' || !file_exists("{$extFolder}/{$extName}") || in_array($extName, Config::get('app.dir.ignored'))) { continue; } if (!is_file("{$extFolder}/{$extName}/{$extClassName}.php")) { SystemLog::add('Extension "' . $extName . '" is missing a class definition.', SystemLog::WARNING); } else { if (!isset($extensions[$extName])) { $extFilePath = sprintf('%s/%s/%s.php', $extFolder, $extName, $extClassName); include_once $extFilePath; $ext = new $extClassName($extName, $namespace); $extensions[$extName] = $ext; } } } // Result return isset($extensions[$extName]) ? $extensions[$extName] : null; }
/** * Filter the query by a related SystemLog object * * @param SystemLog|PropelObjectCollection $systemLog the related object to use as filter * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return UserQuery The current query, for fluid interface * @throws PropelException - if the provided filter is invalid. */ public function filterBySystemLog($systemLog, $comparison = null) { if ($systemLog instanceof SystemLog) { return $this->addUsingAlias(UserPeer::ID, $systemLog->getUserId(), $comparison); } elseif ($systemLog instanceof PropelObjectCollection) { return $this->useSystemLogQuery()->filterByPrimaryKeys($systemLog->getPrimaryKeys())->endUse(); } else { throw new PropelException('filterBySystemLog() only accepts arguments of type SystemLog or PropelCollection'); } }
/** * @see AuthInterface::forgot_password() * @param string $username * @param string $name * @return bool */ public function forgot_password($username, $mail) { if ($username and $mail) { $system_log = new SystemLog(null); if (User::exist_username($username)) { $user_id = User::get_user_id_by_username($username); $user = new User($user_id); if ($user->check_mail(strtolower($mail))) { if ($user->get_boolean_user_entry("user_inactive") == false) { $new_password = User::generate_password(); $mail = new Mail(); $mail->set_recipient($user_id); $mail->set_subject("Your New Open-LIMS Password"); $mail->set_text("Your new password: "******"must_change_password", true); // Password sended successfully $system_log->create($user_id, 1, 1, "Password Send", "Forgot Password", "auth.php", null, null); return true; } else { // Error via sending throw new AuthForgotPasswordSendFailedException("", 0); } } else { // Inactive User $system_log->create($user_id, 1, 1, "Inactive User", "Forgot Password", "auth.php", null, null); throw new AuthUserNotFoundException("", 0); } } else { // Wrong E-Mail $system_log->create($user_id, 1, 0, "Wrong E-Mail", "Forgot Password", "auth.php", null, null); throw new AuthUserNotFoundException("", 0); } } else { // User Not Found $system_log->create(null, 1, 0, "User \"" . $username . "\" Not Found", "Forgot Password", "auth.php", null, null); throw new AuthUserNotFoundException("", 0); } } else { throw new AuthUserNotFoundException("", 0); } }