/**
  * Factory method to create command instances.
  * New commands should be added to commands_definition.json
  *
  * @param array $post
  *        	Reference to $_POST
  * @param \RedmineCommand\Configuration $config
  *        	Configuration instance with parameters.
  * @return \RedmineCommand\AbstractCommand Returns an instance of an AbstractCommand subclass.
  */
 public static function create($post, $config)
 {
     $cmd = new CmdUnknown($post, $config);
     $log = new Logger($config->log_dir, $config->log_level);
     $log->debug("CommandFactory: post received (json encoded): " . json_encode($post));
     // checking if commands definitions have been loaded
     if (self::$classes == null || self::$help_data == null) {
         $result = self::reloadDefinitions();
         if ($result) {
             $log->debug("CommandFactory: commands_definition.json loaded");
         } else {
             $log->error("CommandFactory: Error loading commands_definition.json, check json format or file permissions.");
         }
     }
     // TODO move strings parameter 'text' to global definition
     if (isset($post['text']) && self::$classes != null) {
         $log->debug("CommandFactory: text received: " . $post['text']);
         // parsing inputs by space
         $input = preg_split("/[\\s]+/", $post['text']);
         // the first word represents the command
         if (in_array($input[0], array_keys(self::$classes))) {
             $class = self::$classes[$input[0]];
             array_shift($input);
             $cmd = new $class($post, $config, $input);
         }
     }
     return $cmd;
 }
Exemple #2
0
 /**
  * Class constructor. Feeds in output destination from env vars
  *
  * @param [array]  $options           Options for operation of logger
  *        [array] config Configuration options from Runner
  * @param [string] $logDirectory      File path to the logging directory
  * @param [string] $logLevelThreshold The LogLevel Threshold
  * @return [Logger] $this
  */
 public function __construct(array $options = array(), $logDirectory = 'php://stderr', $logLevelThreshold = LogLevel::INFO)
 {
     $config = $options['config'];
     unset($options['config']);
     $options['dateFormat'] = 'Y-m-d H:i:s';
     if ($config['debug']) {
         $logLevelThreshold = LogLevel::DEBUG;
     }
     if (!isset($options['logFormat'])) {
         if ($config['json'] != null) {
             $options['logFormat'] = 'json';
         }
         if ($config['bash'] != null) {
             $options['logFormat'] = 'bash';
         }
     }
     if (isset($_SERVER['TERMINUS_LOG_DIR'])) {
         $logDirectory = $_SERVER['TERMINUS_LOG_DIR'];
     } elseif ($config['silent']) {
         $logDirectory = ini_get('error_log');
         if ($logDirectory == '') {
             die('You must either set error_log in your php.ini, or define ' . ' TERMINUS_LOG_DIR to use silent mode.' . PHP_EOL);
         }
     }
     parent::__construct($logDirectory, $logLevelThreshold, $options);
 }
 /**
  * @param array $params
  * @return string
  */
 public function cancel(array $params)
 {
     $status = $this->transaction->cancel(array_merge($params, $this->getMerchantCredentials()));
     if ($this->loggingIsEnabled()) {
         $this->log->info("Cancelled the transaction with ID: {$params['transactionId']}. Status: {$status}");
     }
     return $status;
 }
 /**
  * Post the SlackResult json representation to the Slack Incoming WebHook.
  */
 public function post()
 {
     $json = $this->result->toJson();
     $this->log->debug("AbstractCommand (" . get_class($this) . "): response json: {$json}");
     $result = Util::post($this->config->slack_webhook_url, $json);
     if (!$result) {
         $log->error("AbstractCommand: Error sending json: {$json} to slack hook: " . $this->config->slack_webhook_url);
     }
     return $result;
 }
 /**
  * Locates (using slack api) the channel name of a given channel id.
  *
  * @param \RedmineCommand\Configuration $config        	
  * @param string $channelId
  *        	slack channel id to be found.
  * @return string
  */
 public static function getChannelName($config, $channelId)
 {
     // TODO move constants to global configuration file
     $log = new Logger($config->log_dir, $config->log_level);
     $channel = '';
     $api_channels_info_url = $config->api_channels_info_url;
     $api_groups_list_url = $config->api_groups_list_url;
     $slack_api_token = $config->slack_api_token;
     // Querying channels info service first
     $payload = array("token" => $slack_api_token, "channel" => $channelId);
     $log->debug("Util: going to invoke channels.info: {$api_channels_info_url} with payload: " . http_build_query($payload));
     $result = self::post($api_channels_info_url, http_build_query($payload), 'multipart/form-data');
     if (!$result) {
         $log->error("Util: Error sending: " . http_build_query($payload) . " to channels info service: {$api_channels_info_url}");
     }
     $result = json_decode($result, true);
     if ($result["ok"]) {
         // Channel found!
         $channel = $result["channel"]["name"];
         $log->debug("Util: channel found!: " . $channel);
     } else {
         // Querying groups list service
         $log->debug("Util: going to invoke groups.list: {$api_groups_list_url} with payload: " . http_build_query($payload));
         $payload = array("token" => $slack_api_token);
         $result = self::post($api_groups_list_url, http_build_query($payload), 'multipart/form-data');
         if (!$result) {
             $log->error("Util: Error sending: " . http_build_query($payload) . " to groups list service: {$api_channels_info_url}");
         }
         $result = json_decode($result, true);
         if ($result["ok"]) {
             // look for group
             foreach ($result["groups"] as $group) {
                 if (strcmp($group["id"], $channelId) == 0) {
                     $channel = $group["name"];
                     $log->debug("Util: group found!: " . $channel);
                     break;
                 }
             }
         }
     }
     return "#" . $channel;
 }
Exemple #6
0
 public function assertLastLineNotEquals(Logger $logr)
 {
     $this->assertNotEquals($logr->getLastLogLine(), $this->getLastLine($logr->getLogFilePath()));
 }
Exemple #7
0
function getGroupMeDirectMessages()
{
    global $config;
    $url = "https://v2.groupme.com/chats?token=" . $config->token . "&page=1&per_page=" . DM_COUNT;
    $hndl = curl_init();
    curl_setopt($hndl, CURLOPT_URL, $url);
    curl_setopt($hndl, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($hndl, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($hndl);
    curl_close($hndl);
    return json_decode($result);
}
$data = getGroupMeDirectMessages();
// Use a GroupMe API client for documented API calls
$gm = new GroupMePHP\groupme($config->token);
$logger = new Logger("logs", LogLevel::DEBUG, array("extension" => "log", "logFormat" => "[listen - {date}] [{level}] {message}"));
//$logger->setLogLevelThreshold($config->log);
if ($data->meta->code != 200) {
    // Ignore some codes
    if ($data->meta->code == 408) {
        // Timeout
        // Do nothing
    } else {
        $logger->debug(sprintf("An error occured getting chat list (%s)", print_r($data, true)));
    }
    die;
}
foreach ($data->response->chats as $chat) {
    if ($chat->last_message->sender_id == $chat->other_user->id) {
        // Parse commands like a normal bot
        $bot = new PMBot($config->token);
Exemple #8
0
 /**
  * custom class constructor
  *
  * @param string $logDirectory      path to log directory
  * @param string $logLevelThreshold the log level
  *
  * @return void
  */
 public function altConstructor($logDirectory, $logLevelThreshold = LogLevel::DEBUG)
 {
     parent::__construct($logDirectory, $logLevelThreshold);
 }
Exemple #9
0
 /**
  * Main Runner
  */
 public function run()
 {
     try {
         $console = new Console();
         $render = null;
         $destinationProcessedCount = 0;
         $destinationProcessedSuccessCount = 0;
         $taxonomyFilePath = $console->inputDir . DS . BatchProcessor::app()->config->get('taxonomy_file');
         $destinationsFilePath = $console->inputDir . DS . BatchProcessor::app()->config->get('destinations_file');
         if (!file_exists($console->outputDir)) {
             $console->close("`{$console->outputDir}` output directory does not exists.", Console::ERROR_OUT);
         }
         if (!is_writable($console->outputDir)) {
             $console->close("Specified output directory is not writable.", Console::ERROR_OUT);
         }
         $this->logger = new Logger($console->outputDir . DS . 'log');
         $console->write(date('F j, Y, H:i:s') . " :: Starting file processing...");
         $this->logger->notice('----------------------');
         $this->logger->info('Started file processing');
         $render = new HtmlRender(BatchProcessor::app()->config->get('template_dir_path'), $console->outputDir);
         $destinationHandler = new DestinationHandler($destinationsFilePath);
         $taxonomyHandler = new TaxonomyHandler($taxonomyFilePath);
         while ($destination = $destinationHandler->fetch()) {
             if (!$taxonomyHandler->hasNode($destination)) {
                 $this->logger->alert('Destination with atlas id ' . $destination->id . ' node details not found in taxonomy.');
             }
             $fileName = self::makeFileName($destination->id, $destination->title);
             $dataWritten = file_put_contents($console->outputDir . DS . $fileName, $render->render(['destination' => $destination, 'taxonomyHandler' => $taxonomyHandler]));
             $destinationProcessedCount++;
             if ($dataWritten !== false) {
                 $this->logger->info('destination file created - ' . $fileName);
                 $destinationProcessedSuccessCount++;
             } else {
                 $this->logger->error('failed to create destination file - ' . $fileName);
             }
         }
         $console->write(date('F j, Y, H:i:s') . " :: Processing finished.\n");
         $console->write("Memory Usage: " . self::convert(memory_get_usage()));
         $console->write("Total Files Written: {$destinationProcessedSuccessCount}");
         $console->write("Total Failed: " . ($destinationProcessedCount - $destinationProcessedSuccessCount));
         $this->logger->info('Processing finished.');
         $this->logger->info('Memory Usage: ' . self::convert(memory_get_usage()));
         $this->logger->info("Total Files Written: {$destinationProcessedSuccessCount}");
         $this->logger->info('Total Failed: ' . ($destinationProcessedCount - $destinationProcessedSuccessCount));
     } catch (\Exception $ex) {
         $message = $ex->getMessage() . "\n" . $ex->getTraceAsString();
         $this->logger->debug($message);
         $console->close($message, Console::ERROR_OUT);
     }
 }
 /**
  * 错误日志
  * @param string $api 方法名
  * @param string $msg 信息
  */
 protected function errorLogs($api, $msg)
 {
     $this->logger->error($api . ":: " . $msg);
 }
<?php

use Katzgrau\KLogger\Logger;
require_once 'vendor/autoload.php';
$logger = new Logger(__DIR__ . "/logs");
$logger->info("Info example");
$errorInfo = array('code' => 404, 'message' => "Not Found");
$logger->error("Error example", $errorInfo);
 /**
  * The constructor. Sets up the logger service to log to a specific
  * path and file configured in environment.ini
  * @param store $store module\application\service\store
  */
 public function __construct(store $store)
 {
     $env = $store->get('ENV');
     parent::__construct(APPLICATION_ROOT . $env->log->path, LogLevel::DEBUG, ['filename' => $env->application->env . '.log']);
 }