public function log($message, $priority = self::INFO) { if ($message instanceof \Exception) { $message = $message->getMessage(); $context = []; } elseif (is_string($message)) { $context = []; } else { $context = $message; unset($context[0]); unset($context[1]); if (isset($message[1])) { $message = preg_replace('#\\s*\\r?\\n\\s*#', ' ', trim($message[1])); } } switch ($priority) { case self::DEBUG: return $this->monolog->addDebug($message, $context); case self::CRITICAL: return $this->monolog->addCritical($message, $context); case self::ERROR: return $this->monolog->addError($message, $context); case self::EXCEPTION: return $this->monolog->addEmergency($message, $context); case self::WARNING: return $this->monolog->addWarning($message, $context); case 'access': return $this->monolog->addNotice($message, $context); case 'emergency': return $this->monolog->addEmergency($message, $context); default: return $this->monolog->addInfo($message, $context); } }
/** * @param string $token Access token from the calling client * * @return string|false The result from the cURL call against the oauth API. * * @codeCoverageIgnore This function is not tested because we can't test * curl_* calls in PHPUnit. */ protected function _call($token) { $ch = curl_init(); $url = $this->_apiUrl . $token; $this->_logger->addDebug('calling GET: ' . $url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json')); $result = curl_exec($ch); $responseCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlErrno = curl_errno($ch); $curlError = curl_error($ch); // remove token from url for log output $url = substr($url, 0, stripos($url, 'token') + 6); if (0 !== $curlErrno) { $this->_logger->addError('curl error (' . $curlErrno . '): ' . $curlError . ' url: ' . $url); } if ($responseCode >= 500) { $this->_logger->addError('curl call error: ' . $responseCode . ' url: ' . $url); } elseif ($responseCode >= 300) { $this->_logger->addWarning('curl call warning: ' . $responseCode . ' url: ' . $url); } $this->_logger->addDebug('result: (' . $responseCode . ') ' . var_export($result, true)); curl_close($ch); return $result; }
protected function writeEntry($level, $message, $indent, $category = "", $additionalData = []) { $message = str_pad($category, 16, " ", STR_PAD_RIGHT) . "\t" . str_repeat(" ", $indent) . $message; switch ($level) { case Log::BULK_DATA_LEVEL: $this->logger->addDebug($message, $additionalData); break; case Log::DEBUG_LEVEL: $this->logger->addDebug($message, $additionalData); break; case Log::ERROR_LEVEL: $this->logger->addError($message, $additionalData); break; case Log::PERFORMANCE_LEVEL: $this->logger->addNotice($message, $additionalData); break; case Log::WARNING_LEVEL: $this->logger->addWarning($message, $additionalData); break; case Log::REPOSITORY_LEVEL: $this->logger->addNotice($message, $additionalData); break; default: $this->logger->addNotice($message, $additionalData); } }
public function exceptionHandler(\Exception $exception) { #Send the error to the log file // these are our templates $traceline = "#%s %s(%s): %s(%s)" . PHP_EOL; $msg = "\n\n PHP Fatal error: Uncaught exception '%s' with message '%s' in %s:%s\nStack trace:\n%s\n Thrown in %s on line %s \n\n"; // alter your trace as you please, here $trace = $exception->getTrace(); foreach ($trace as $key => $stackPoint) { // I'm converting arguments to their type // (prevents passwords from ever getting logged as anything other than 'string') $trace[$key]['args'] = \array_map('gettype', $trace[$key]['args']); } // build your tracelines $result = array(); $key = 0; foreach ($trace as $key => $stackPoint) { $result[] = \sprintf($traceline, $key, $stackPoint['file'], $stackPoint['line'], $stackPoint['function'], \implode(', ', $stackPoint['args'])); $key = $key; } // trace always ends with {main} $result[] = '#' . ++$key . ' {main}'; // write tracelines into main template $msg = \sprintf($msg, \get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine(), \implode("\n", $result), $exception->getFile(), $exception->getLine()); #write to log $this->log->addError($msg); # log to console $this->output->writeln('<error>' . $msg . '</error>'); }
/** * Uses the Monolog file Logger to write a log message in a file. * * @param string $message Message that needs to be output * @param bool $error If the log message is considered an error, for logging purposes */ public function write($message, $error = false) { if (!$error) { $this->logger->addWarning($message); return; } $this->logger->addError($message); }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable|null $next * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { if ($next) { $this->logger->addError('Bar', ['next' => true]); $response = $next($request, $response); } return $response; }
/** * * @param \Exception $objEx */ public function saveToDisk(\Exception $objEx) { try { $this->logger->addError(Carbon::now()->toDateTimeString() . ' : ' . $objEx->getTraceAsString()); } catch (\Exception $e) { $this->push($e); } $this->push($objEx); }
public function run() { $configFile = tempnam(sys_get_temp_dir(), 'satis-admin'); file_put_contents($configFile, $this->manager->getJson()); $process = ProcessBuilder::create(['php', $this->binDir . '/satis', 'build', $configFile, $this->outputDir])->getProcess(); $this->logger->addInfo('Building config...', ['command-line' => $process->getCommandLine()]); if (0 === $process->run()) { $this->logger->addInfo('Config built.'); } else { $this->logger->addError('Config not build', ['stdout' => $process->getOutput(), 'stderr' => $process->getErrorOutput()]); } }
/** * @param String $url * @param array $parameters * @param array $headers * @return mixed */ public function post(string $url, $parameters = array(), $headers = array()) { $headers = array_merge($headers, ["Connection: keep-alive", "Keep-Alive: timeout=10, max=1000", "Content-Type: application/x-www-form-urlencoded"]); try { $curl = curl_init(); curl_setopt_array($curl, [CURLOPT_USERAGENT => "Sovereign Discord Bot", CURLOPT_TIMEOUT => 8, CURLOPT_FORBID_REUSE => false, CURLOPT_RETURNTRANSFER => true, CURLOPT_FAILONERROR => true, CURLOPT_URL => $url, CURLOPT_POST => true, CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => http_build_query($parameters)]); $result = curl_exec($curl); return $result; } catch (\Exception $e) { $this->log->addError("There was an error using cURL: ", [$e->getMessage()]); } }
public function run() { $configFile = tempnam($this->cacheDir . '/satis', 'satis-admin'); file_put_contents($configFile, $this->manager->getJson()); $process = ProcessBuilder::create(['php', $this->binDir . '/satis', 'build', $configFile, $this->outputDir])->setTimeout(null)->addEnvironmentVariables(['HOME' => $this->cacheDir])->getProcess(); $this->logger->addInfo('Building config...', ['command-line' => $process->getCommandLine()]); if (0 === $process->run()) { unlink($configFile); $this->logger->addInfo('Config built.'); } else { $this->logger->addError('Config not build', ['stdout' => $process->getOutput(), 'stderr' => $process->getErrorOutput()]); } }
/** * @param $configFile */ public function loadFile($configFile) { if (!file_exists(realpath($configFile))) { $this->logger->addError('Config file ' . realpath($configFile) . ' not found.'); return; } try { $this->config = array_change_key_case(include $configFile, \CASE_LOWER); $this->logger->addDebug('Config file loaded: ' . realpath($configFile)); } catch (\Exception $e) { $this->logger->addError('Failed loading config file (' . realpath($configFile) . '): ' . $e->getMessage()); } }
public function run(Message $message, Discord $discord, WebSocket $webSocket, Logger $log, &$audioStreams, Channel $channel, cURL $curl) { $exp = explode(" ", $message->content); unset($exp[0]); $youtubeLink = implode(" ", $exp); // URL Checker $parts = parse_url($youtubeLink); if (!stristr($parts["host"], "youtube.com")) { return $message->reply("Error, you can only use youtube links!"); } // Generate song md5 $md5 = md5($youtubeLink); // Now get the mp3 from the cache $songFile = __DIR__ . "/../../../../../cache/songs/{$md5}.mp3"; $dl = new YoutubeDl(["extract-audio" => true, "audio-format" => "mp3", "audio-quality" => 0, "output" => $songFile]); $title = ""; try { $video = $dl->download($youtubeLink); $title = $video->getTitle(); $log->addNotice("Downloading {$title} from YouTube"); } catch (NotFoundException $e) { $log->addError("Error: the song was not found: {$e->getMessage()}"); $message->reply("Error: the song was not found: {$e->getMessage()}"); } catch (PrivateVideoException $e) { $log->addError("Error: song has been made private: {$e->getMessage()}"); $message->reply("Error: song has been made private: {$e->getMessage()}"); } catch (CopyrightException $e) { $log->addError("Error: song is under copyright: {$e->getMessage()}"); $message->reply("Error: song is under copyright: {$e->getMessage()}"); } catch (\Exception $e) { $log->addError("Error: {$e->getMessage()}"); $message->reply("Error: {$e->getMessage()}"); } $webSocket->joinVoiceChannel($channel)->then(function (VoiceClient $vc) use($message, $discord, $webSocket, $log, &$audioStreams, $channel, $curl, $songFile, $title) { $guildID = $message->getChannelAttribute()->guild_id; if (file_exists($songFile)) { // Add this audio stream to the array of audio streams $audioStreams[$guildID] = $vc; $vc->setFrameSize(40)->then(function () use($vc, &$audioStreams, $guildID, $songFile, $log, $message, $title, $channel) { $vc->setBitrate(128000); $message->reply("Now playing **{$title}** in {$channel->name}"); $vc->playFile($songFile, 2)->done(function () use($vc, &$audioStreams, $guildID) { unset($audioStreams[$guildID]); $vc->close(); }); }); } }); }
/** * format - prune the registry based on xml config * * @param string XMLpath * @param Registry registry * * @return array */ public static function format(YAMLConfiguration $params, HTTPRequest $request, HTTPResponse &$response, Logger $logger) { $attributes = $request->getAttributes(); $output = array(); if (count($params) < 1) { if (self::PARANOID_MODE) { $logger->addError('XML is missing CherryPicker configs for ' . $uri); throw new XMLNodeNotConfiguredException('need to customize error for YAML configs for ' . $uri); } //not paranoid? ok - dump the whole registry to the user foreach ($attributes as $key => $value) { $output[self::trimNamespacing($key)] = $attributes[$key]; } return $output; } $configs = array_filter($params->getConfigs()); foreach ($configs as $key => $outputSet) { // pr($outputSet); // exit; foreach ($outputSet as $className => $columns) { if (is_array($outputSet)) { self::formatArray($className, $columns, $output, $attributes, $logger); } } } $response = new HTTPResponse($output); }
/** * Called when this object is called as a function * * @param Context $context * @param OptionsFactory $optionsFactory * @throws \Exception if haltOnError setting is true */ public function __invoke(Context $context, OptionsFactory $optionsFactory) { $getopt = $context->getopt(array_keys(self::$options)); // Get directory list $dirListFactory = new DirectoryListFactory(); $dirListFactory->loadFromCommandline($getopt->get(), 2); $dirListFactory->loadFromStdin(new StdinReader(3)); $dirList = $dirListFactory->getList(); $this->logger->addDebug('Found directories', [count($dirList)]); // Load base options $baseOptions = $optionsFactory->newInstance(); $baseOptions->validateAllRequired(); if ($baseOptions->preview) { $this->logger->addNotice('PREVIEW MODE'); } foreach ($dirList as $dir) { try { $this->logger->addNotice('In directory', [$dir]); $this->processDirectory($dir, $baseOptions, $optionsFactory); } catch (\Exception $e) { if ($baseOptions->haltOnError) { throw $e; } elseif ($baseOptions->verbosity == 2) { $this->logger->addError($e, []); } else { $this->logger->addError($e->getMessage(), []); } } } }
private function sendRequest($url, $method, $request) { try { if (strtoupper($method) == 'GET') { $this->logger->debug("Sending GET request to {$url}, query=" . json_encode($request)); $reply = $this->httpClient->get($url, ['query' => $request]); } else { $this->logger->debug("Sending {$method} request to {$url}, body=" . json_encode($request)); $reply = $this->httpClient->send($this->httpClient->createRequest($method, $url, ['body' => json_encode($request)])); } } catch (RequestException $e) { //Stash error: it can't send more then 1mb of json data. So just skip suck pull requests or files $this->logger->debug("Request finished with error: " . $e->getMessage()); if ($e->getMessage() == 'cURL error 56: Problem (3) in the Chunked-Encoded data') { throw new Exception\StashJsonFailure($e->getMessage(), $e->getRequest(), $e->getResponse(), $e); } else { throw $e; } } $this->logger->debug("Request finished"); $json = (string) $reply->getBody(); //an: пустой ответ - значит все хорошо if (empty($json)) { return true; } $data = json_decode($json, true); if ($data === null && $data != 'null') { $this->logger->addError("Invalid json received", ['url' => $url, 'method' => $method, 'request' => $request, 'reply' => $json]); throw new \Exception('invalid_json_received'); } return $data; }
/** * Inserts a new user into the database with the values in $postdata. * Returns true if the user was successfully inserted, false otherwise. * * @param array $postdata The array containing the data of the user to be added. * * @return boolean True if the user was successfully added, false otherwise. */ public function addNewUser(array $postdata) { $password_options = ['cost' => 10]; $commit = true; $verification = null; try { $this->db->beginTransaction(); $stmt = $this->db->prepare("INSERT INTO user_profile(`username`, `password`,`email`,`first_name`,\r\n `last_name`,`date_of_birth`,`created`,`last_active`)\r\n VALUES (:username, :password, :email, :first_name, :last_name, :date_of_birth,\r\n :created, :last_active)"); $stmt->execute(array(':username' => $postdata['username'], ':password' => password_hash($postdata['password'], PASSWORD_BCRYPT, $password_options), ':email' => $postdata['email'], ':first_name' => $postdata['first_name'], ':last_name' => $postdata['last_name'], ':date_of_birth' => $postdata['date_of_birth'], ':created' => date('Y-m-d H:i:s'), ':last_active' => date('Y-m-d H:i:s'))); if ($stmt->rowCount() <= 0) { $commit = false; } $verification = $this->generateVerificationKey(); $stmt = $this->db->prepare("INSERT INTO user_registration(`user_id`, `verification`)\r\n VALUES ((SELECT `id`\r\n FROM user_profile\r\n WHERE username = :username),\r\n :verification)"); $stmt->execute(array(':username' => $postdata['username'], ':verification' => $verification)); if ($stmt->rowCount() <= 0) { $commit = false; } if ($commit) { $this->db->commit(); } else { $this->db->rollBack(); } } catch (PDOException $exception) { $this->logger->addError($exception); $commit = false; $this->db->rollBack(); } return $verification ?: null; }
/** * Отправляет сообщение в лог * * @param string $message сообщение * @param int $level уровень * * @return void */ public function log($message, $level = AbstractLogger::NOTICE) { if ($level < $this->severity) { return; } switch ($level) { case AbstractLogger::EMERGENCY: $this->impl->addEmergency($message); break; case AbstractLogger::ALERT: $this->impl->addAlert($message); break; case AbstractLogger::CRITICAL: $this->impl->addCritical($message); break; case AbstractLogger::ERROR: $this->impl->addError($message); break; case AbstractLogger::WARNING: $this->impl->addWarning($message); break; case AbstractLogger::NOTICE: $this->impl->addNotice($message); break; case AbstractLogger::INFO: $this->impl->addInfo($message); break; case AbstractLogger::DEBUG: $this->impl->addDebug($message); break; } }
/** * @param String $query * @param array $parameters * @return int|null|string */ public function execute(string $query, $parameters = array()) { try { $this->pdo->beginTransaction(); $stmt = $this->pdo->prepare($query); $stmt->execute($parameters); if ($stmt->errorCode() != 0) { $this->pdo->rollBack(); return 0; } $returnID = $this->pdo->lastInsertId(); $this->pdo->commit(); $stmt->closeCursor(); return $returnID; } catch (\Exception $e) { $this->log->addError("There was an error during a query: ", [$e->getMessage()]); try { $this->pdo = $this->connect(); } catch (\Exception $e2) { $this->log->addCritical("Couldn't reconnect to the database: " . $e->getMessage()); die(1); } } return null; }
/** * Log a message * * @param string $message * @param int $level * @param array $context * @return void */ public function log($message, $level = Logger::INFO, array $context = []) { if (!$this->logger) { return; } if (null === $level) { $level = Logger::INFO; } switch ($level) { case Logger::DEBUG: $this->logger->addDebug($message, $context); break; case Logger::INFO: $this->logger->addInfo($message, $context); break; case Logger::NOTICE: $this->logger->addNotice($message, $context); break; case Logger::WARNING: $this->logger->addWarning($message, $context); break; case Logger::ERROR: $this->logger->addError($message, $context); break; case Logger::CRITICAL: $this->logger->addCritical($message, $context); break; case Logger::EMERGENCY: $this->logger->addEmergency($message, $context); break; default: break; } }
/** * Error Handler... */ function systemErrorHandler($errno, $errstr, $errfile, $errline, $errcontext = null) { $log = new Logger('movim'); $log->pushHandler(new SyslogHandler('movim')); $log->addError($errstr); return false; }
/** * @param string $number * @param string $content * * @return boolean */ public function sendSms($number, $content) { if ($number === null) { return false; } try { $this->client->account->messages->sendMessage($this->sendingPhoneNumber, $this->sanitizeNumber($number), $content); return true; } catch (\Services_Twilio_RestException $e) { $this->logger->addError($e->getMessage(), ['exception' => $e]); return false; } catch (NumberParseException $e) { $this->logger->addError($e->getMessage(), ['exception' => $e]); return false; } }
public function getLegacyRoute($givenRoute) { try { $result = false; foreach ($this->routesCollection as $route) { if (!$result && (isset($route['legacy']) && $route['legacy'] == $givenRoute)) { $result = true; $controller = $route['controller']; $class = explode('::', $controller)[0]; $method = explode('::', $controller)[1]; if (!class_exists($class)) { throw new \Exception('Legacy The route class doesn\'t exist!'); } else { if (!method_exists($class, $method)) { throw new \Exception('Legacy The route class\'s method doesn\'t exist!'); } } $this->logger->addInfo("Legacy Route controller method found: {$class} -> {$method}"); $result = array('pattern' => $route['pattern'], 'class' => $class, 'method' => $method); } } if (!$result) { return null; } else { return $result; } } catch (\Exception $e) { $this->logger->addError('Error handling route: ' . $e->getMessage()); throw new \Exception($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
public function runRequest($request) { $c = $this->loadController($request); $sess = \Sessionx::start(); $sess->refreshCookie(); if (is_callable(array($c, 'load'))) { $c->name = $request; $c->load(); $c->checkSession(); $c->dispatch(); // If the controller ask to display a different page if ($request != $c->name) { $new_name = $c->name; $c = $this->loadController($new_name); $c->name = $new_name; $c->load(); $c->dispatch(); } // We display the page ! $c->display(); } else { $log = new Logger('movim'); $log->pushHandler(new SyslogHandler('movim')); $log->addError(t("Could not call the load method on the current controller")); } }
/** * @param array $data */ public function log(array $data) { $loggedMessage = new LoggedMessage(); $loggedMessage->setMessageFields($data['message']); $loggedMessage->setResult($data['result']); $loggedMessage->setFailedRecipients($data['failed_recipients']); $em = $this->doctrine->getManager(); // application should not crash when logging fails try { $em->persist($loggedMessage); $em->flush($loggedMessage); } catch (\Exception $e) { $message = 'Logging sent message with TweedeGolf\\SwiftmailerLoggerBundle\\Logger\\EntityLogger failed: ' . $e->getMessage(); $this->logger->addError($message); } }
/** * Raise an error using logger (monolog) * * @param string $message The message to log * @param array $parameters (optional) Additional parameters */ public function raiseError($message, $parameters = array()) { if ($this->logger instanceof \Monolog\Logger) { return $this->logger->addError($message, $parameters); } else { return false; } }
public function index() { $this->load->view('welcome_message'); $log = new Logger('test001'); $log->pushHandler(new StreamHandler('/tmp/my.log', Logger::WARNING)); $log->addWarning('Foo'); $log->addError('Bar'); }
/** * @param GenerateSchemaEventArgs $args */ public function postGenerateSchema(GenerateSchemaEventArgs $args) { $schema = $args->getSchema(); try { if (!$schema->hasTable(MAUTIC_TABLE_PREFIX . 'lead_fields')) { return; } $objects = ['lead' => 'leads', 'company' => 'companies']; foreach ($objects as $object => $tableName) { $table = $schema->getTable(MAUTIC_TABLE_PREFIX . $tableName); //get a list of fields $fields = $args->getEntityManager()->getConnection()->createQueryBuilder()->select('f.alias, f.is_unique_identifer as is_unique, f.type, f.object')->from(MAUTIC_TABLE_PREFIX . 'lead_fields', 'f')->where("f.object = '{$object}'")->orderBy('f.field_order', 'ASC')->execute()->fetchAll(); // Compile which ones are unique identifiers // Email will always be included first $uniqueFields = 'lead' === $object ? ['email' => 'email'] : ['companyemail' => 'companyemail']; foreach ($fields as $f) { if ($f['is_unique'] && $f['alias'] != 'email') { $uniqueFields[$f['alias']] = $f['alias']; } $columnDef = FieldModel::getSchemaDefinition($f['alias'], $f['type'], !empty($f['is_unique'])); $table->addColumn($columnDef['name'], $columnDef['type'], $columnDef['options']); if ('text' != $columnDef['type']) { $table->addIndex([$columnDef['name']], MAUTIC_TABLE_PREFIX . $f['alias'] . '_search'); } } // Only allow indexes for string types $columns = $table->getColumns(); /** @var \Doctrine\DBAL\Schema\Column $column */ foreach ($columns as $column) { $type = $column->getType(); $name = $column->getName(); if (!$type instanceof StringType) { unset($uniqueFields[$name]); } elseif (isset($uniqueFields[$name])) { $uniqueFields[$name] = $uniqueFields[$name]; } } if (count($uniqueFields) > 1) { // Only use three to prevent max key length errors $uniqueFields = array_slice($uniqueFields, 0, 3); $table->addIndex($uniqueFields, MAUTIC_TABLE_PREFIX . 'unique_identifier_search'); } switch ($object) { case 'lead': $table->addIndex(['attribution', 'attribution_date'], MAUTIC_TABLE_PREFIX . 'contact_attribution'); break; case 'company': $table->addIndex(['companyname', 'companyemail'], MAUTIC_TABLE_PREFIX . 'company_filter'); $table->addIndex(['companyname', 'companycity', 'companycountry', 'companystate'], MAUTIC_TABLE_PREFIX . 'company_match'); break; } } } catch (\Exception $e) { //table doesn't exist or something bad happened so oh well $this->logger->addError('SCHEMA ERROR: ' . $e->getMessage()); } }
public function log() { // create a log channel $log = new Logger('name'); $log->pushHandler(new StreamHandler(BASE_PATH . '/storage/log/demo.log', Logger::WARNING)); // add records to the log $log->addWarning('Foo'); $log->addError('Bar'); }
public function indexAction() { // create a log channel $log = new Logger('name'); $log->pushHandler(new StreamHandler(LOG_PATH, Logger::WARNING)); // add records to the log $log->addWarning('Foo', array('username' => 'Seldaek')); $log->addError('Bar'); $log->pushProcessor(function ($record) { $record['extra']['dummy'] = 'Hello world!'; return $record; }); exit; $em = $this->getEntityManager(); // $user = new \Application\Entity\AssUser(); // $objectManager->persist($user); // // $objectManager->flush(); $user = $em->find("Application\\Entity\\AssUser", 2); $myFirstComment = new \Application\Entity\AssComment(); $user->setFirstComment($myFirstComment); $em->persist($myFirstComment); $em->flush(); // $user = new \Application\Entity\User(); // $user->setName('engineer'); // $objectManager->persist($user); // $objectManager->flush(); // $productIds = array(1,2,3); // $reporter = $objectManager->find("Application\Entity\User", 2); // $engineer = $objectManager->find("Application\Entity\User", 3); // if (!$reporter || !$engineer) { // echo "No reporter and/or engineer found for the input.\n"; // exit(1); // } // $bug = new \Application\Entity\Bug(); // $bug->setDescription("Something does not work!"); // $bug->setCreated(new \DateTime("now")); // $bug->setStatus("OPEN"); // foreach ($productIds as $productId) { // $product = $objectManager->find("Application\Entity\Product", $productId); // $bug->assignToProduct($product); // } // $bug->setReporter($reporter); // $bug->setEngineer($engineer); // $objectManager->persist($bug); // $objectManager->flush(); // echo "Your new Bug Id: ".$bug->getId()."\n"; // $product = new \Application\Entity\Product(); // $product->setName('test'); // $objectManager->persist($product); // $objectManager->flush(); // var_dump($product); // Debug::dump($product); // $objectManager->clear(); // $objectManager->close(); return new ViewModel(); }
function process_page($app, $action, &$var) { global $config; // the default date format is "Y-m-d H:i:s" $dateFormat = "Y-m-d H:i:s"; // the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n" $output = "[%datetime%]: %message%\n"; // finally, create a formatter $formatter = new LineFormatter($output, $dateFormat); // create the login log $stream = new StreamHandler($config['logfile'], Logger::INFO); $stream->setFormatter($formatter); $logger = new Logger('login'); $logger->pushHandler($stream); // get headers $headers = getallheaders(); if (isset($headers['X-Real-Ip'])) { $ip = $headers['X-Real-Ip']; } else { $ip = $_SERVER['REMOTE_ADDR']; } if ($action == 'login') { $user = User::list_by_email($var['email']); if (!$user == null) { if ($user->verify_password($var['password'])) { if ($user->is_admin()) { $_SESSION['user_id'] = $user->get_id(); $logger->addInfo("IP: " . $ip . " Login success: " . $user->get_email()); $app->reload(); } else { $app->err->add($app->txt->tr('txt_login_no_access')); $logger->addError("IP: " . $ip . " Login failed: " . $user->get_email() . " Reason: " . $app->txt->tr('txt_login_no_access')); } } else { $app->err->add($app->txt->tr('txt_login_wrong_password')); $logger->addError("IP: " . $ip . " Login failed: " . $user->get_email() . " Reason: " . $app->txt->tr('txt_login_wrong_password')); } } else { $app->err->add($app->txt->tr('txt_login_email_not_found')); $logger->addError("IP: " . $ip . " Login failed: " . $var['email'] . " Reason: " . $app->txt->tr('txt_login_email_not_found')); } } }