/** * Sets up the niftyException object * * @param string $message * @param mixed $code * @param Exception $previous */ public function __construct($message, $code = 0, Exception $previous = null) { $this->priorException = $previous; parent::__construct($message, $code); $this->logger = new logger(); $this->logger->log($this); }
/** * Logs with an arbitrary level. * * @param mixed $level * @param mixed $message * @param mixed[] $context * @return null */ public function log($level, $message, array $context = array()) { if (!array_key_exists($level, $this->levels)) { $level = $this->defaultLevel; } $level = \LoggerLevel::toLevel($this->levels[$level], $this->defaultLevel); $message = $this->formatter->format($level, $message, $context); $this->logger->log($level, $message); }
/** * Function to test the storage of logs in mail. */ public function testCreation() { $this->markTestSkipped('Mailing log results currently cannot be tested automatically.'); $myLogger = new Logger(__DIR__ . "/../../../libs/logs/media/default_mail_config.php"); //create a handler to store the logs. Provide that logger with a configuration file. $myLogger->log("This is the first message", "WARNING", "LOW"); //store this log. $myLogger->log("This is the second message"); //store this log. //You should see two mails in your mailbox. }
/** * Function to test the storage of logs in SYSLOG. */ public function testCreation() { $myLogger = new Logger(__DIR__ . "/../../../libs/logs/media/default_syslog_config.php"); //create a handler to store the logs. Provide that logger with a configuration file. $myLogger->log("This is the first message", "WARNING", "LOW"); //store this log. $myLogger->log("This is the second message"); //store this log. //You can see the results in the console. //You can also check using this command in your shell: //grep -R "This is the first message" /var/log //You should see entries containing message "This is the first message" }
/** * Function to test the storage of logs in file. */ public function testCreation() { $myLogger = new Logger(__DIR__ . "/testFileConfig.php"); //create a handler to store the logs. Provide that logger with a configuration file. $myLogger->log("This is the first message", "WARNING", "LOW"); //store this log. $myLogger->log("This is the second message"); //store this log. if (file_exists("myfile.php")) { $this->assertTrue(TRUE); } else { $this->assertTrue(FALSE); } }
/** * Logs a message. * * @param $sMessage @type string The message. */ public function log($sMessage) { $level = 'info'; $message = $sMessage; $matches = []; preg_match('/^(\\w+):\\s*(.*)$/', $sMessage, $matches); if (count($matches) == 3) { $act = strtolower($matches[1]); $message = $matches[2]; if ($act != 'status') { $level = $act; } } $this->monolog->log($level, $message); }
/** * Logs message or exception to file (if not disabled) and sends email notification (if enabled). * @param string|Exception * @param int one of constant Debugger::INFO, WARNING, ERROR (sends email), CRITICAL (sends email) * @return string logged error filename */ public static function log($message, $priority = self::INFO) { if (self::$logDirectory === FALSE) { return; } elseif (!self::$logDirectory) { throw new InvalidStateException('Logging directory is not specified in Debugger::$logDirectory.'); } if ($message instanceof Exception) { $exception = $message; $message = ($message instanceof FatalErrorException ? 'Fatal error: ' . $exception->getMessage() : get_class($exception) . ": " . $exception->getMessage()) . " in " . $exception->getFile() . ":" . $exception->getLine(); $hash = md5($exception . (method_exists($exception, 'getPrevious') ? $exception->getPrevious() : (isset($exception->previous) ? $exception->previous : ''))); $exceptionFilename = "exception-" . @date('Y-m-d-H-i-s') . "-{$hash}.html"; foreach (new DirectoryIterator(self::$logDirectory) as $entry) { if (strpos($entry, $hash)) { $exceptionFilename = $entry; $saved = TRUE; break; } } } self::$logger->log(array(@date('[Y-m-d H-i-s]'), trim($message), self::$source ? ' @ ' . self::$source : NULL, !empty($exceptionFilename) ? ' @@ ' . $exceptionFilename : NULL), $priority); if (!empty($exceptionFilename)) { $exceptionFilename = self::$logDirectory . '/' . $exceptionFilename; if (empty($saved) && ($logHandle = @fopen($exceptionFilename, 'w'))) { ob_start(); // double buffer prevents sending HTTP headers in some PHP ob_start(create_function('$buffer', 'extract(NCFix::$vars[' . NCFix::uses(array('logHandle' => $logHandle)) . '], EXTR_REFS); fwrite($logHandle, $buffer); '), 4096); self::$blueScreen->render($exception); ob_end_flush(); ob_end_clean(); fclose($logHandle); } return strtr($exceptionFilename, '\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR); } }
public function parse_cookie($cookie) { // Parse the given cookie if (!preg_match("/^uid:(\\d+):([a-z0-9]+):([a-z0-9]+)\$/", $cookie, $m)) { Logger::log("Invalid login cookie received: {$cookie}", LOGGER_WARNING); // Invalid cookie - ignore it return FALSE; } list(, $this->user_id, $this->series, $this->token) = $m; $this->user_id = (int) $this->user_id; // Flush old cookies Dal::query("DELETE FROM login_cookies WHERE expires < NOW()"); // Locate our cookie $r = Dal::query_one("SELECT token FROM login_cookies WHERE user_id=? AND series=?", array($this->user_id, $this->series)); if (!$r) { // Totally invalid - we don't even know of the series. Probably timed out. return FALSE; } list($token) = $r; if ($token != $this->token) { // Possible attack detected - invalidate all sessions for this user Dal::query("DELETE FROM login_cookies WHERE user_id=?", array($this->user_id)); Logger::log("Invalidated all sessions for user {$this->user_id} as a valid series ID but invalid token was presented -- someone has possibly had their login cookie stolen!", LOGGER_WARNING); return FALSE; } // Success -- assign a new token $this->token = $this->make_token(); Dal::query("UPDATE login_cookies SET token=?, expires=DATE_ADD(NOW(), INTERVAL " . LoginCookie::$cookie_lifetime . " SECOND) WHERE user_id=? AND series=?", array($this->token, $this->user_id, $this->series)); return $this->user_id; }
private function convertdata($data) { $this->data = null; if (is_null($data)) { return; } else { $this->copyValueToKey($data); // first copys in all the data that has one to one relation foreach ($this->propertyTable as $key => &$obj) { //then copy the logical properties over $value = null; $datafieldname = $this->getDatafieldname($key); if (is_null($datafieldname) == false) { $value = $data->{$datafieldname}; } if ($obj->logicdefined == true) { if ($key == 'boek') { $book = new boek(null); $booktoget = intval($data->boekid); $book->retrieveByID($booktoget); $this->data->{$key} = $book; // $this->valtodata($key,false); } else { $msg = 'objectfield \'' . $key . '\' should be logicdefined while no definition in objectDef ' . '<br/>'; Logger::log($msg); die; } } } unset($obj); } }
function UpdateManager($continue) { if ($continue == "false") { Logger::log(__FUNCTION__, "Skipping update check. Change SMARTSOCKET_AUTOUPDATE to true on Config.xml"); return false; } else { Logger::log(__FUNCTION__, "Checking for updates..."); if ($latest = @(int) file_get_contents("http://smartsocket.googlecode.com/svn/trunk/DIST/BUILD")) { //# Compare build number if (SMARTSOCKET_BUILD < $latest) { Logger::log(__FUNCTION__, "Update found..."); if ($file = @file_get_contents("http://smartsocket.googlecode.com/svn/trunk/DIST/libsmartsocket.dll", FILE_BINARY)) { Logger::log(__FUNCTION__, "Update retrieved..."); $update = fopen("libsmartsocket.dll", "wb"); fwrite($update, $file); fclose($update); Logger::log(__FUNCTION__, "Update applied."); Logger::log(__FUNCTION__, "To see the changes, check out http://www.smartsocket.net"); Logger::log(__FUNCTION__, "You must now restart SmartSocket.", true); } else { Logger::log(__FUNCTION__, "Could not reach the latest stable build file."); } } elseif (SMARTSOCKET_BUILD > $latest) { Logger::log(__FUNCTION__, "Your build (" . SMARTSOCKET_BUILD . ") is newer than the public release ({$latest})."); } else { Logger::log(__FUNCTION__, "You already have the latest build."); } } else { Logger::log(__FUNCTION__, "Could not reach the latest stable build report."); } } }
public function rebuild($start_date = null, $end_date = null) { if (!$start_date) { $start_date = config_option('last_sharing_table_rebuild'); } if ($start_date instanceof DateTimeValue) { $start_date = $start_date->toMySQL(); } if ($end_date instanceof DateTimeValue) { $end_date = $end_date->toMySQL(); } if ($end_date) { $end_cond = "AND updated_on <= '{$end_date}'"; } try { $object_ids = Objects::instance()->findAll(array('id' => true, "conditions" => "updated_on >= '{$start_date}' {$end_cond}")); $obj_count = 0; DB::beginWork(); foreach ($object_ids as $id) { $obj = Objects::findObject($id); if ($obj instanceof ContentDataObject) { $obj->addToSharingTable(); $obj_count++; } } set_config_option('last_sharing_table_rebuild', DateTimeValueLib::now()->toMySQL()); DB::commit(); } catch (Exception $e) { DB::rollback(); Logger::log("Failed to rebuild sharing table: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString()); } return $obj_count; }
public function saveAction() { try { if ($this->getParam("id")) { $link = Document\Hardlink::getById($this->getParam("id")); $this->setValuesToDocument($link); $link->setModificationDate(time()); $link->setUserModification($this->getUser()->getId()); if ($this->getParam("task") == "unpublish") { $link->setPublished(false); } if ($this->getParam("task") == "publish") { $link->setPublished(true); } // only save when publish or unpublish if ($this->getParam("task") == "publish" && $link->isAllowed("publish") || $this->getParam("task") == "unpublish" && $link->isAllowed("unpublish")) { $link->save(); $this->_helper->json(["success" => true]); } } } catch (\Exception $e) { \Logger::log($e); if (\Pimcore\Tool\Admin::isExtJS6() && $e instanceof Element\ValidationException) { $this->_helper->json(["success" => false, "type" => "ValidationException", "message" => $e->getMessage(), "stack" => $e->getTraceAsString(), "code" => $e->getCode()]); } throw $e; } $this->_helper->json(false); }
public static function logCreation($path, $isDir) { $message = $_SERVER['REMOTE_ADDR'] . " " . GateKeeper::getUserName() . " created "; $message .= $isDir ? "dir" : "file"; $message .= " " . $path; Logger::log($message); }
function http($method = "GET", $url, $argArray = null) { require_once "HTTP/Client.php"; $agent = new HTTP_Client(); if ($method == "POST") { $code = $agent->post($url, $argArray); } else { if ($argArray) { // build query string from $argArray if (strpos("?", $url)) { $query = "&"; } else { $query = "?"; } $url .= $query . http_build_query($argArray); } $code = $agent->get($url); } if (PEAR::isError($code)) { $error = $code->getMessage(); Logger::log(basename(__FILE__) . " {$method} {$url} failed: {$error}"); return false; } else { $responseArray = $agent->currentResponse(); return $responseArray['body']; } }
public static function add_user_play($username, $password, $artist, $album, $title, $length) { // ensure we have the length in milliseconds. $length = Format::fix_length($length); if ($length === -1) { Logger::log("add_play: failed to convert length to milliseconds"); return false; } // unknown artist/album ("") becomes "N/A" if ($artist === "") { $artist = "N/A"; } if ($album === "") { $album = "N/A"; } $db = Database::instance(); $sql = 'SELECT api_add_user_play(?, ?, ?, ?, ?, ?) AS success'; $params = array($username, $password, $artist, $album, $title, $length); try { $rows = $db->select($sql, $params); } catch (Exception $e) { Logger::log("add_user_play: database failure: " . $e->getMessage()); return false; } return count($rows) === 1 && $rows[0]['success'] === true; }
public function procede() { try { if ($this->oRequest->existParam('name')) { if ($this->oRequest->existParam('edit')) { $oRank = new Rank($this->oRequest->getParam('name', 'string'), $this->oRequest->getParam('default', 'boolean'), $this->oRequest->getParam('edit', 'int')); //Delete if ($this->oRequest->existParam('delete') && $this->oRequest->getParam('delete', 'boolean')) { $oRank->delete(); Logger::log('admin', Language::translate('RANKS_ADMIN_RANK_DELLOG') . $this->oRequest->getParam('name', 'string') . ' [' . $this->oCurrentUser->getLogin() . ']'); $this->oView->addAlert(Language::translate('RANKS_ADMIN_RANK_DEL'), 'success'); } else { //Edit $oRank->update(); Logger::log('admin', Language::translate('RANKS_ADMIN_RANK_UPDATELOG') . $this->oRequest->getParam('name', 'string') . ' [' . $this->oCurrentUser->getLogin() . ']'); $this->oView->addAlert(Language::translate('RANKS_ADMIN_RANK_UPDATE'), 'success'); } } else { $oRank = new Rank($this->oRequest->getParam('name', 'string'), $this->oRequest->getParam('default', 'boolean')); $oRank->store(); Logger::log('admin', Language::translate('RANKS_ADMIN_RANK_ADDLOG') . $this->oRequest->getParam('name', 'string') . ' [' . $this->oCurrentUser->getLogin() . ']'); $this->oView->addAlert(Language::translate('RANKS_ADMIN_RANK_ADD'), 'success'); } } } catch (Exception $ex) { $this->oView->addAlert($ex, 'danger'); } finally { $this->createView(); } }
function main_error_handler($errno, $errstr, $errfile, $errline) { $logger_error = new Logger(array("dir" => APP_PATH . "/logs", "file" => date("Y-m-d") . ".txt", 'type' => Logger::TYPE_ERROR)); $string = "[Error] " . "No. " . $errno . ", File: " . $errfile . ", Line: " . $errline . ", String: " . $errstr . ";"; $logger_error->log($string); // throw new \Framework\Core\Exception($string); }
/** * Deduplicate component parts of a record * * Component part deduplication is special. It will only go through * component parts of other records deduplicated with the host record * and stops when it finds a set of component parts that match. * * @param array $hostRecord Mongo record for the host record * * @return integer Number of component parts deduplicated */ protected function dedupComponentParts($hostRecord) { if ($this->verbose) { echo "Deduplicating component parts\n"; } if (!$hostRecord['linking_id']) { $this->log->log('dedupComponentParts', 'Linking ID missing from record ' . $hostRecord['_id'], Logger::ERROR); return 0; } $components1 = $this->getComponentPartsSorted($hostRecord['source_id'], $hostRecord['linking_id']); $component1count = count($components1); // Go through all other records with same dedup id and see if their // component parts match $marked = 0; $otherRecords = $this->db->record->find(['dedup_id' => $hostRecord['dedup_id'], 'deleted' => false])->timeout($this->cursorTimeout); foreach ($otherRecords as $otherRecord) { if ($otherRecord['source_id'] == $hostRecord['source_id']) { continue; } $components2 = $this->getComponentPartsSorted($otherRecord['source_id'], $otherRecord['linking_id']); $component2count = count($components2); if ($component1count != $component2count) { $allMatch = false; } else { $allMatch = true; $idx = -1; foreach ($components1 as $component1) { $component2 = $components2[++$idx]; if ($this->verbose) { echo "Comparing {$component1['_id']} with " . "{$component2['_id']}\n"; } if ($this->verbose) { echo 'Original ' . $component1['_id'] . ":\n" . MetadataUtils::getRecordData($component1, true) . "\n"; } $metadataComponent1 = RecordFactory::createRecord($component1['format'], MetadataUtils::getRecordData($component1, true), $component1['oai_id'], $component1['source_id']); if (!$this->matchRecords($component1, $metadataComponent1, $component2)) { $allMatch = false; break; } } } if ($allMatch) { if ($this->verbose) { echo microtime(true) . " All component parts match between " . "{$hostRecord['_id']} and {$otherRecord['_id']}\n"; } $idx = -1; foreach ($components1 as $component1) { $component2 = $components2[++$idx]; $this->markDuplicates($component1, $component2); ++$marked; } break; } else { if ($this->verbose) { echo microtime(true) . " Not all component parts match between " . "{$hostRecord['_id']} and {$otherRecord['_id']}\n"; } } } return $marked; }
public function connect($host, $username, $password, $database, $_charset) { @(list($dbhost, $port) = explode(":", $host, 2)); if (!isset($port)) { $port = ini_get("mysqli.default_port"); } else { $options = array('min_range' => 1, 'max_range' => 65535); if (filter_var($port, FILTER_VALIDATE_INT, $options) === FALSE) { throw new Exception($this->conf['database'] . ' mysqli illegal port range'); } } if ($this->user_test_db) { $mysqliLink = @mysqli_connect($dbhost, $username, $password, '', $port); } else { $mysqliLink = @mysqli_connect($dbhost, $username, $password, $database, $port); } if ((!$mysqliLink or $mysqliLink->connect_error) and $this->show_error) { Logger::log($database . ' mysql connect error', 'mysql_error'); throw new Exception($this->conf['database'] . ' mysqli connect error ' . $mysqliLink->connect_error); } else { if (!$mysqliLink or $mysqliLink->connect_error) { Logger::log($database . ' mysql connect error', 'mysql_error'); $this->error_info = isset($mysqliLink->connect_error) ? $mysqliLink->connect_error : 'mysql connect error'; return false; } } if ($this->user_test_db) { $this->select_db = mysqli_select_db($mysqliLink, $database); } mysqli_set_charset($mysqliLink, $_charset); return $mysqliLink; }
public function __construct($message, $logError = false) { parent::__construct($message); if ($logError) { Logger::log($this->message); } }
/** * 保存记录日志 * * @author liu21st <*****@*****.**> * @lastmodify 2013-01-17 09:26:25 by mrmsl * * @return void 无返回值 */ public static function save() { if (self::$log) { self::write(); self::$log = array(); } }
public function saveFolder(array $folder) { if ($this->getFolder($folder['path'])) { $op = 'UPDATE'; $where = "where path = '" . $folder['path'] . "'"; } else { $op = 'INSERT INTO'; $where = ''; } $folderToSave = $this->buildFolderToSave($folder); //ZDebug::my_print($folderToSave, 'folderToSave'); $setString = implode(', ', $folderToSave); $sql = $op . " `folders` SET " . $setString . ' ' . $where; //ZDebug::my_echo('sql='.$sql); $res = DB::$dbInstance->query($sql); if ($res) { if ($op == 'UPDATE') { return $res; } else { return DB::$dbInstance->insertId(); } } else { Logger::log($sql); return FALSE; } }
function __autoload($class_name) { //# First, let's check and see if the file is a core server file: if (file_exists("CORE/{$class_name}.php")) { require_once "CORE/{$class_name}.php"; return true; } //# Now, let's check to see if the file is an extension: if (file_exists("DIST/Extensions/{$class_name}/{$class_name}.php")) { require_once "DIST/Extensions/{$class_name}/{$class_name}.php"; return true; } //# Now, we check the Etc dir to see if the file exists there: if (file_exists("CORE/ETC/{$class_name}/{$class_name}.php")) { require_once "CORE/ETC/{$class_name}/{$class_name}.php"; return true; } //# THIS IS FOR THE BUILD VERSION //# Now, let's check to see if the file is an extension: if (file_exists("Extensions/{$class_name}/{$class_name}.php")) { require_once "Extensions/{$class_name}/{$class_name}.php"; return true; } //# Now, we check the Etc dir to see if the file exists there: if (file_exists("Etc/{$class_name}/{$class_name}.php")) { require_once "Etc/{$class_name}/{$class_name}.php"; return true; } Logger::log("__autoload", "The class file for {$class_name} could not be found!\n", true); }
/** * Compress CSS file. * @param string source code * @param string original file name * @return string compressed source */ public function compressCss($content, $origFile) { if ($this->requireCompressMark && !preg_match('#/\\*+!#', $content)) { // must contain /**! return $content; } $this->logger->log("Compressing {$origFile}"); $cmd = escapeshellarg($this->javaBinary) . ' -jar ' . escapeshellarg(dirname(__DIR__) . '/vendor/YUI-Compressor/yuicompressor-2.4.8.jar') . ' --type css'; list($ok, $output) = $this->execute($cmd, $content); if (!$ok) { $this->logger->log("Error while executing {$cmd}"); $this->logger->log($output); return $content; } return $output; }
function load($remote_id_or_userinfo) { Logger::log("Enter: ShadowUser::load"); $remote_id = NULL; $userinfo = NULL; if (is_array($remote_id_or_userinfo)) { $userinfo = $remote_id_or_userinfo; $remote_id = $remote_id_or_userinfo['user_id']; } else { $remote_id = $remote_id_or_userinfo; } $u = parent::quick_search_extended_profile('user_id', $remote_id, $this->namespace); try { parent::load($u->login_name); Logger::log("Exit: ShadowUser::load, success"); } catch (PAException $e) { Logger::log("Exit: ShadowUser::load, fail"); return NULL; } // if we have been passed userinfo // pass it on the check for needed sync if ($userinfo) { $this->sync($userinfo); } // load th display_login_name $this->display_login_name = $this->get_profile_field($this->namespace, 'display_login_name'); return $this->user_id; }
/** * check if the $role has access to $action on $resource * * @param string $role * @param string $resource * @param string $action if set to "*", then check if $actions parameter was assigned to "*" when using allow() method * This indicates the $role has access to all actions on $resource * @param array $config configuration data to be passed to condition methods * @throws Exception if $config is empty or method doesn't exists * @return boolean */ public static function check($role, $resource, $action = "*", array $config = []) { //checks if action was allowed at least once $allowed = false; $action = strtolower($action); foreach (self::$perms as $perm) { if ($perm['role'] === $role && $perm['resource'] === $resource) { if (in_array($action, $perm["actions"], true) || $perm["actions"] === ["*"]) { $allowed = true; foreach ($perm["conditions"] as $condition) { if (!method_exists(__CLASS__, $condition)) { throw new Exception("Permission, Method doesnt exists: " . $condition); } if (self::$condition($config) === false) { Logger::log("Permission", $role . " is not allowed to perform '" . $action . "' action on " . $resource . " because of " . $condition, __FILE__, __LINE__); return false; } } } } } if (!$allowed) { Logger::log("Permission", $role . " is not allowed to perform '" . $action . "' action on " . $resource, __FILE__, __LINE__); } return $allowed; }
/** * Get the specified number of random bytes. * * Attempts to use a cryptographically secure (not predictable) * source of randomness if available. If there is no high-entropy * randomness source available, it will fail. As a last resort, * for non-critical systems, define * <code>Auth_OpenID_RAND_SOURCE</code> as <code>null</code>, and * the code will fall back on a pseudo-random number generator. * * @param int $num_bytes The length of the return value * @return string $bytes random bytes */ function getBytes($num_bytes) { static $f = null; $bytes = ''; if ($f === null) { if (Auth_OpenID_RAND_SOURCE === null) { $f = false; } else { $f = @fopen(Auth_OpenID_RAND_SOURCE, "r"); Logger::log('Security breach: OpenID could not read from ' . Auth_OpenID_RAND_SOURCE . '.'); /* if ($f === false) { $msg = 'Define Auth_OpenID_RAND_SOURCE as null to ' . ' continue with an insecure random number generator.'; trigger_error($msg, E_USER_ERROR); } */ } } if ($f === false) { // pseudorandom used $bytes = ''; for ($i = 0; $i < $num_bytes; $i += 4) { $bytes .= pack('L', mt_rand()); } $bytes = substr($bytes, 0, $num_bytes); } else { $bytes = fread($f, $num_bytes); } return $bytes; }
/** * Загружает файл в S3. */ public static function moveFileToS3($fileName, $mimeType = null, $baseName = null) { self::checkEnv($ctx = Context::last()); $conf = $ctx->config->get('modules/s3'); $s3 = new S3($conf['accesskey'], $conf['secretkey']); if (!($bucketName = trim($ctx->config->get('modules/s3/bucket', 'files'), '/'))) { throw new RuntimeException(t('Модуль s3 не настроен (bucket).')); } if ($folderName = $ctx->config->get('module/s3/folder', 'files')) { $folderName .= '/'; } /* if (!in_array($bucketName, $s3->listBuckets())) throw new RuntimeException(t('Нет такой папки: ' . $bucketName)); */ if ($f = fopen($fileName, 'rb')) { if (null === $baseName) { $baseName = basename($fileName); } if (!($r = S3::inputResource($f, filesize($fileName)))) { throw new RuntimeException(t('Не удалось создать ресурс из файла %filename.', array('%filename' => $fileName))); } if (!($response = S3::putObject($r, $bucketName, $folderName . $baseName, S3::ACL_PUBLIC_READ))) { throw new RuntimeException(t('Не удалось загрузить файл %filename в папку %bucket.', array('%filename' => $fileName, '%bucket' => $bucketName))); } $url = 'http://' . $bucketName . '.s3.amazonaws.com/' . $folderName . $baseName; Logger::log('S3: ' . $url); return $url; } }
/** * Checks if session data exists and valid or not. * * @access public * @static static method * @param string $ip * @param string $userAgent * @return boolean * */ public static function isSessionValid($ip, $userAgent) { $isLoggedIn = self::getIsLoggedIn(); $userId = self::getUserId(); $userRole = self::getUserRole(); //1. check if there is any data in session if (empty($isLoggedIn) || empty($userId) || empty($userRole)) { return false; } /*if(!self::isConcurrentSessionExists()){ self::remove(); return false; }*/ //2. then check ip address and user agent if (!self::validateIPAddress($ip) || !self::validateUserAgent($userAgent)) { Logger::log("SESSION", "current session is invalid", __FILE__, __LINE__); self::remove(); return false; } //3. check if session is expired if (!self::validateSessionExpiry()) { self::remove(); return false; } return true; }
function purge_trash() { Env::useHelper("permissions"); $days = config_option("days_on_trash", 0); $count = 0; if ($days > 0) { $date = DateTimeValueLib::now()->add("d", -$days); $objects = Objects::findAll(array("conditions" => array("`trashed_by_id` > 0 AND `trashed_on` < ?", $date), "limit" => 100)); foreach ($objects as $object) { $concrete_object = Objects::findObject($object->getId()); if (!$concrete_object instanceof ContentDataObject) { continue; } if ($concrete_object instanceof MailContent && $concrete_object->getIsDeleted() > 0) { continue; } try { DB::beginWork(); if ($concrete_object instanceof MailContent) { $concrete_object->delete(false); } else { $concrete_object->delete(); } ApplicationLogs::createLog($concrete_object, ApplicationLogs::ACTION_DELETE); DB::commit(); $count++; } catch (Exception $e) { DB::rollback(); Logger::log("Error delting object in purge_trash: " . $e->getMessage(), Logger::ERROR); } } } return $count; }