notice() public méthode

This method allows to have an easy ZF compatibility.
public notice ( string $message, array $context = [] ) : boolean
$message string The log message
$context array The log context
Résultat boolean Whether the record has been processed
Exemple #1
0
 public function inspect()
 {
     $inspectionDto = new InspectionDto();
     $inspectionMessage = '';
     if ($this->createdTasksBeforeHandling !== $this->correctlyExecuted + count($this->executedWithError)) {
         $this->allTasksComplete = false;
         $inspectionMessage .= "Not all tasks complete: " . " created (before handling): " . $this->createdTasksBeforeHandling . " correctlyExecuted: " . serialize($this->getCorrectlyExecuted()) . " executedWithError: " . serialize($this->getExecutedWithError()) . $this->loggerPostfix;
     }
     $this->logger->notice("CreatedTasks before handling: " . serialize($this->createdTasksBeforeHandling));
     $this->logger->notice("CreatedTasks after handling: " . serialize($this->createdTasksNumber));
     $this->logger->notice("CorrectlyExecuted: " . serialize($this->getCorrectlyExecuted()));
     $this->logger->notice("Executed with error: " . serialize($this->executedWithError));
     if (!empty($this->executedWithError)) {
         switch ($this->attentionMethod) {
             case InspectorConstants::LOG:
                 $this->makeAttentionLog($inspectionMessage);
                 break;
             case InspectorConstants::MAIL:
                 $this->sendAttentionMail($inspectionMessage);
                 break;
             default:
                 $this->makeAttentionLog($inspectionMessage);
                 //$this->sendAttentionMail($inspectionMessage);
         }
     }
     $inspectionDto->setInspectionMessage($inspectionMessage);
     return $inspectionDto;
 }
Exemple #2
0
 private function workOn(CommittedJob $job, HandlerInterface $jobHandler)
 {
     try {
         $this->logger->notice("Starting work on {$job->getId()}");
         $logProvider = new LogProvider($this->logger, $jobHandler);
         $this->jobExecutor->execute($job, $logProvider);
         $this->metro->succeed($job->getId());
         $this->logger->notice("Finished work on {$job->getId()}");
     } catch (\Exception $e) {
         $this->logException($e, $job->getId());
         $this->metro->fail($job->getId());
     }
 }
Exemple #3
0
 public function notice($message, array $args = [], array $context = [])
 {
     if (count($args)) {
         $message = vsprintf($message, $args);
     }
     return parent::notice($message, $context);
 }
 protected function stopDaemon()
 {
     $pid = $this->getRunningPid();
     if (!$pid) {
         $this->logger->notice("Cannot stop the daemon as it is not started");
         return "notstarted";
     }
     $this->logger->info("Trying to terminate the daemon", array('pid' => $pid));
     $this->processControl->kill($pid);
     for ($i = 0; ($pid = $this->getRunningPid()) && $i < 5; $i++) {
         sleep(1);
     }
     if ($pid) {
         $this->logger->warning("The daemon is resiting, trying to kill it", array('pid' => $pid));
         $this->processControl->kill($pid, true);
         for ($i = 0; ($pid = $this->getRunningPid()) && $i < 5; $i++) {
             sleep(1);
         }
     }
     if (!$pid) {
         $this->logger->notice("Daemon stopped");
         return "stopped";
     }
     $this->logger->error("Could not stop the daemon");
 }
Exemple #5
0
 /**
  * Ping a journal, check on it's health, etc.
  *
  * @param Journal $journal
  *
  * @return PingResult
  *
  * @throws Exception
  */
 public function ping(Journal $journal)
 {
     $this->logger->notice("Pinging {$journal}");
     $url = $journal->getGatewayUrl();
     $client = $this->getClient();
     try {
         $response = $client->get($url, array('allow_redirects' => false, 'headers' => array('User-Agent' => 'PkpPlnBot 1.0; http://pkp.sfu.ca', 'Accept' => 'application/xml,text/xml,*/*;q=0.1')));
         $pingResponse = new PingResult($response);
         if ($pingResponse->getHttpStatus() === 200) {
             $journal->setContacted(new DateTime());
             $journal->setTitle($pingResponse->getJournalTitle('(unknown title)'));
             $journal->setOjsVersion($pingResponse->getOjsRelease());
             $journal->setTermsAccepted($pingResponse->areTermsAccepted() === 'yes');
         } else {
             $journal->setStatus('ping-error');
         }
         $this->em->flush($journal);
         return $pingResponse;
     } catch (RequestException $e) {
         $journal->setStatus('ping-error');
         $this->em->flush($journal);
         if ($e->hasResponse()) {
             return new PingResult($e->getResponse());
         }
         throw $e;
     } catch (XmlParseException $e) {
         $journal->setStatus('ping-error');
         $this->em->flush($journal);
         return new PingResult($e->getResponse());
     } catch (Exception $e) {
         $journal->setStatus('ping-error');
         $this->em->flush($journal);
         throw $e;
     }
 }
 /**
  * Handles incoming webhook requests.
  */
 public function index()
 {
     // set up logging to email
     $this->log = Log::getMonolog();
     if ($to = config('auto-deploy.notify')) {
         $domain = parse_url(config('app.url'), PHP_URL_HOST);
         $msg = \Swift_Message::newInstance('Project Deployed')->setFrom(["do_not_reply@{$domain}" => "Laravel Auto-Deploy[{$domain}]"])->setTo($to)->setBody('', 'text/html');
         $handler = new SwiftMailerHandler(Mail::getSwiftMailer(), $msg, Logger::NOTICE);
         $handler->setFormatter(new HtmlFormatter());
         $this->log->pushHandler($handler);
     }
     // check to see if we should execute this event
     if (in_array($this->origin->event(), array_keys(config("auto-deploy.{$this->origin->name}")))) {
         // get the parameters for the event we're handling
         $configKey = "auto-deploy.{$this->origin->name}.{$this->origin->event()}";
         $this->webroot = config("{$configKey}.webroot");
         $this->installDir = dirname($this->webroot) . '/' . date('Y-m-d') . '_' . $this->commitId;
         $steps = config("{$configKey}.steps");
         // execute the configured steps
         $this->result = ['Commit_ID' => $this->commitId, 'Timestamp' => date('r'), 'output' => ''];
         $whitelist = ['backupDatabase', 'pull', 'copyEnv', 'composer', 'npm', 'migrate', 'seed', 'deploy'];
         foreach ($steps as $step) {
             if (in_array($step, $whitelist) && !$this->{$step}()) {
                 $this->log->error('Deploy failed.', $this->result);
                 return;
             }
         }
         $this->log->notice('Deploy succeeded!', $this->result);
     } else {
         $this->log->error('Deploy failed.', ['Reason' => 'This event was not configured.']);
     }
 }
Exemple #7
0
 /**
  * Get the staging directory for processed deposits.
  *
  * @param Journal $journal
  *
  * @return string
  */
 public final function getStagingDir(Journal $journal)
 {
     $path = $this->absolutePath('staged', $journal);
     if (!$this->fs->exists($path)) {
         $this->logger->notice("Creating directory {$path}");
         $this->fs->mkdir($path);
     }
     return $path;
 }
 /**
  * Process one deposit. Fetch the data and write it to the file system.
  * Updates the deposit status, and may remove the processing files if 
  * LOCKSSOatic reports agreement.
  *
  * @param Deposit $deposit
  *
  * @return type
  */
 protected function processDeposit(Deposit $deposit, $force = false)
 {
     if ($deposit->getPlnState() === 'agreement') {
         $this->logger->notice($deposit->getDepositUuid());
         $this->delFileTree($this->filePaths->getHarvestFile($deposit), $force);
         $this->delFileTree($this->filePaths->getProcessingBagPath($deposit), $force);
         // $this->delFileTree($this->filePaths->getStagingBagPath($deposit), $force);
     }
 }
Exemple #9
0
 /**
  *
  */
 public function testPushErrors()
 {
     $redis = \Mockery::mock('Predis\\Client')->shouldReceive('publish')->times(8)->with('log', \Mockery::any())->mock();
     $monolog = new Logger('test');
     $monolog->pushHandler(new PublishHandler(new RedisPublisher($redis)));
     $monolog->debug('the message was: {message}', ['DEBUG!']);
     $monolog->info('the message was: {message}', ['INFO!']);
     $monolog->notice('the message was: {message}', ['NOTICE!']);
     $monolog->warning('the message was: {message}', ['WARNING!']);
     $monolog->error('the message was: {message}', ['ERROR!']);
     $monolog->critical('the message was: {message}', ['CRITICAL!']);
     $monolog->alert('the message was: {message}', ['ALERT!']);
     $monolog->emergency('the message was: {message}', ['EMERGENCY!']);
 }
 /**
  * Run job in singlethread mode
  *
  * @param   string  Job unique identifier
  *
  * @return  array   {[pid],[name],[success],[start],[end],[result],[id]}
  */
 private function runMultithread($jobUid)
 {
     $job = $this->jobs[$jobUid];
     // get job start timestamp
     $start_timestamp = microtime(true);
     $this->logger->notice("Starting job " . $job['name'] . "(" . $job['id'] . ")");
     $name = $job['name'];
     $id = $job['id'];
     $parameters = $job['parameters'];
     $task = $job['task'];
     $task_class = $job['class'];
     $this->ipc_array[$jobUid] = array();
     // create a comm socket
     $socket = socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $this->ipc_array[$jobUid]);
     if ($socket === false) {
         $this->logger->error("No IPC communication, aborting", array("JOBUID" => $jobUid, "ERROR" => socket_strerror(socket_last_error()), "ERRID" => null));
         array_push($this->completed_processes, array(null, $name, false, $start_timestamp, microtime(true), 'No IPC communication, exiting - ' . socket_strerror(socket_last_error()), $id, null));
         return array("pid" => null, "name" => $name, "uid" => $jobUid, "timestamp" => $start_timestamp, "id" => $id);
     }
     list($reader, $writer) = $this->ipc_array[$jobUid];
     $pid = pcntl_fork();
     if ($pid == -1) {
         $this->logger->error("Could not fok job, aborting");
         array_push($this->completed_processes, array(null, $name, false, $start_timestamp, microtime(true), 'Could not fok job', $id, null));
     } elseif ($pid) {
         //PARENT will take actions on processes later
         self::adjustNiceness($pid, $this->logger);
     } else {
         socket_close($reader);
         $thetask = new $task_class($parameters, $this->logger, null, $name, $start_timestamp, true, $id);
         try {
             $result = $thetask->start();
             $return = serialize(array("success" => $result["success"], "result" => $result["result"], "timestamp" => $result["timestamp"], "worklogid" => $result["worklogid"]));
             $exit = 0;
         } catch (TaskException $te) {
             $return = serialize(array("success" => false, "result" => $te->getMessage(), "timestamp" => $te->getEndTimestamp(), "worklogid" => $te->getWorklogId()));
             $exit = 1;
         } catch (Exception $e) {
             $return = serialize(array("success" => false, "result" => $e->getMessage(), "timestamp" => microtime(true), "worklogid" => null));
             $exit = 1;
         }
         if (socket_write($writer, $return, strlen($return)) === false) {
             $this->logger->error("socket_write() failed ", array("ERROR" => socket_strerror(socket_last_error($writer))));
         }
         socket_close($writer);
         exit($exit);
     }
     return array("pid" => $pid == -1 ? null : $pid, "name" => $name, "uid" => $jobUid, "id" => $id, "timestamp" => $start_timestamp);
 }
 /**
  * Fetch one deposit from LOCKSSOMatic.
  *
  * @param Deposit $deposit
  * @param string  $href
  */
 public function fetch(Deposit $deposit, $href)
 {
     $client = $this->getHttpClient();
     $filepath = $this->filePaths->getRestoreDir($deposit->getJournal()) . '/' . basename($href);
     $this->logger->notice("Saving {$deposit->getJournal()->getTitle()} vol. {$deposit->getVolume()} no. {$deposit->getIssue()} to {$filepath}");
     try {
         $client->get($href, array('allow_redirects' => false, 'decode_content' => false, 'save_to' => $filepath));
         $hash = strtoupper(hash_file($deposit->getPackageChecksumType(), $filepath));
         if ($hash !== $deposit->getPackageChecksumValue()) {
             $this->logger->warning("Package checksum failed. Expected {$deposit->getPackageChecksumValue()} but got {$hash}");
         }
     } catch (Exception $ex) {
         $this->logger->error($ex->getMessage());
     }
 }
Exemple #12
0
 /**
  * Execute une requete curl
  *
  * @param string $url
  * @param string $method
  * @param array  $data
  *
  * @return array
  *
  * @author Benjamin Levoir <*****@*****.**>
  */
 private function sendRequest($url, $method, $data)
 {
     // Initialisation du curl
     $curl = curl_init($url);
     $this->logger->info('API CALL');
     $this->logger->info('API   ' . $url);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
     $json = json_encode($data);
     $this->logger->info('API   ' . $json);
     switch ($method) {
         case 'POST':
             curl_setopt($curl, CURLOPT_POST, true);
             curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
             curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($json)));
             break;
         default:
             break;
     }
     // Nombre d'essai max
     $try = 5;
     do {
         $error = false;
         $curl_response = curl_exec($curl);
         $this->logger->info('API   ' . $curl_response);
         // Erreur sur requete curl
         if ($curl_response === false) {
             $info = curl_getinfo($curl);
             $this->logger->notice('API   ' . $info);
             curl_close($curl);
             break;
         }
         $decoded = json_decode($curl_response);
         if (isset($decoded->status)) {
             if (isset($decoded->status->status_code) && $decoded->status->status_code == '429') {
                 $error = true;
                 sleep(2);
                 $try--;
             } else {
                 // Erreur autre
                 $this->logger->error($curl_response);
                 return null;
             }
         }
     } while ($try && $error);
     curl_close($curl);
     return $decoded;
 }
 /**
  * Get all the queued changes that are for unpublished videos.
  * If the video has become published set the correct time to execute based
  * on the videos' publish time.
  *
  * @return null
  */
 public function checkForPublishedVideos()
 {
     // First get all videos (one result per video) where its excute time has not yet been set
     $pendingVideos = DescriptionChange::whereNotNull('execute_mins_after_publish')->whereNull('executed_at')->groupBy('video_id')->get();
     $pendingVideoCount = count($pendingVideos);
     if ($pendingVideoCount === 1) {
         $this->log->info("1 video needs checking if it's published yet.");
     } else {
         $this->log->info($pendingVideoCount . " videos need checking if they're published yet.");
     }
     foreach ($pendingVideos as $pendingVideo) {
         /** @var DescriptionChange $pendingVideo */
         $user = $pendingVideo->getUser();
         if (!$user) {
             $this->log->error("User {$pendingVideo->user_id} not found in database.");
             continue;
         }
         $this->log->info("Checking if video {$pendingVideo->video_id} (user {$user->name}) is published yet.");
         // We need to login as the user that owns this video in order to query it
         try {
             /** @var \Google_Client $googleClient */
             $googleClient = App::make('Google_Client');
             $googleClient->setAccessToken($user->access_token);
         } catch (Exception $e) {
             $this->log->error("Exception setting Google access token: " . $e->getMessage());
             continue;
         }
         $video = $pendingVideo->getVideo();
         if ($video->isPublished()) {
             $this->log->info("Video {$pendingVideo->video_id} was published at " . date('Y-m-d H:i:s', $video->getPublishedTimestamp()));
             $thisVideoChanges = DescriptionChange::where('video_id', $pendingVideo->video_id)->whereNotNull('execute_mins_after_publish')->whereNull('executed_at')->get();
             foreach ($thisVideoChanges as $thisVideoChange) {
                 $publishedAt = $video->getPublishedTimestamp();
                 $executeAt = $publishedAt + $thisVideoChange->execute_mins_after_publish * 60;
                 $thisVideoChange->execute_at = date('Y-m-d H:i:s', $executeAt);
                 $thisVideoChange->execute_mins_after_publish = null;
                 $thisVideoChange->save();
                 $this->log->info("Set execute time for change {$thisVideoChange->id} to " . $thisVideoChange->execute_at);
             }
         } else {
             $this->log->notice("Video {$pendingVideo->video_id} is not published.");
         }
     }
 }
 /**
  * Normal but significant events.
  *
  * @param string $message
  * @param array $params
  * @param array $context
  * @return null
  */
 public function notice($message, array $params = array(), array $context = array())
 {
     $logMessage = $this->createMessage($message, $params);
     $this->logger->notice($logMessage, $context);
 }
Exemple #15
0
 protected function logMessage($message, array $context = array(), $severity)
 {
     $adminLevel = $this->helper->getConfigValue('shqlogmenu/shqlogger/admin_level');
     $systemLogLevel = $this->helper->getConfigValue('shqlogmenu/shqlogger/system_level');
     $emailLevel = $this->helper->getConfigValue('shqlogmenu/shqlogger/email_level');
     if ($adminLevel > 0 && $adminLevel >= $severity) {
         $this->logAdmin($message, $context, $severity);
     }
     if ($systemLogLevel > 0 && $systemLogLevel >= $severity) {
         $message = is_string($message) ? $message : var_export($message, true);
         switch ($severity) {
             case self::SEVERITY_NOTICE:
                 parent::debug($message, $context);
                 break;
             case self::SEVERITY_MINOR:
                 parent::notice($message, $context);
                 break;
             case self::SEVERITY_MAJOR:
                 parent::warning($message, $context);
                 break;
             case self::SEVERITY_CRITICAL:
                 parent::critical($message, $context);
                 break;
         }
     }
     if ($emailLevel > 0 && $emailLevel >= $severity) {
         $this->logEmail($message, $context, $severity);
     }
     return true;
 }
 private function cycle()
 {
     // fire extender ready event
     $this->events->fire("extender", "VOID", $this);
     // dispatch signals (if multithread active)
     if ($this->getMultithreadMode()) {
         pcntl_signal_dispatch();
     }
     // if extender is paused (SIGINT), skip to extend
     if ($this->paused) {
         return;
     }
     // fix relative timestamp
     $this->timestamp = microtime(true);
     // fire tasktable event
     $this->tasks = $this->events->fire("extender.tasks", "TASKSTABLE", $this->tasks);
     // get the next planned activity interval
     $plans = Planner::get();
     if (!is_null($plans) and $this->timestamp < $plans) {
         // nothing to do right now, still waiting if in daemon mode
         $this->logger->info("Next planned job: " . date('c', $plans));
         $this->logger->notice("Extender completed\n");
         if ($this->getDaemonMode() === false) {
             $this->shutdown(true);
             self::end(0);
         }
         return;
     }
     // if no plan is retrieved, try to retrieve it from scheduler
     try {
         // get schedules and dispatch schedule event
         list($schedules, $planned) = Scheduler::getSchedules($this->logger, $this->timestamp);
         // write next planned activity interval
         if (!is_null($planned) and $planned != 0) {
             Planner::set($planned);
         }
         $scheduled = new Schedule();
         $scheduled->setSchedules($schedules);
         // expose the current shcedule via events
         $scheduled = $this->events->fire("extender.schedule", "SCHEDULE", $scheduled);
         // if no jobs in queue, exit gracefully
         if ($scheduled->howMany() == 0) {
             $this->logger->info("No jobs to process right now, exiting");
             $this->logger->notice("Extender completed\n");
             if ($this->getDaemonMode() === false) {
                 $this->shutdown(true);
                 self::end(0);
             }
             return;
         }
         // compose jobs
         foreach ($scheduled->getSchedules() as $schedule) {
             if ($this->tasks->isRegistered($schedule['task'])) {
                 $job = new Job();
                 $job->setName($schedule['name'])->setId($schedule['id'])->setParameters(unserialize($schedule['params']))->setTask($schedule['task'])->setClass($this->tasks->getClass($schedule['task']));
                 $this->runner->addJob($job);
             } else {
                 $this->logger->warning("Skipping job due to unknown task", array("ID" => $schedule['id'], "NAME" => $schedule['name'], "TASK" => $schedule['task']));
             }
         }
         // lauch runner
         $result = $this->runner->run();
         // free runner for next cycle
         $this->runner->free();
         // compose results
         $results = new JobsResult($result);
         // update schedules
         Scheduler::updateSchedules($this->logger, $result);
         // increment counters
         foreach ($result as $r) {
             if ($r[2]) {
                 $this->completed_processes++;
             } else {
                 $this->failed_processes++;
             }
         }
     } catch (Exception $e) {
         $this->logger->error($e->getMessage());
         if ($this->getDaemonMode() === false) {
             self::end(1);
         }
     }
     // fire result event
     $this->events->fire("extender.result", "VOID", $results);
     $this->logger->notice("Extender completed\n");
     // show summary (if -s)
     if ($this->summary_mode) {
         self::showSummary($this->timestamp, $result, $this->color);
     }
     Status::dump($this->timestamp_absolute, $this->parent_pid, $this->completed_processes, $this->failed_processes, $this->paused);
     if ($this->getDaemonMode() === false) {
         $this->shutdown(true);
         self::end(0);
     }
 }
<?php

include 'basics.php';
use unreal4u\MonologHandler;
use unreal4u\TgLog;
use Monolog\Logger;
#$monologTgLogger = new MonologHandler(new TelegramLog(BOT_TOKEN), A_USER_CHAT_ID, Logger::DEBUG); // Sends from DEBUG+
$monologTgLogger = new MonologHandler(new TgLog(BOT_TOKEN), A_USER_CHAT_ID, Logger::ERROR);
// Sends ERROR+
//Create logger
$logger = new Logger('TelegramLogger');
$logger->pushHandler($monologTgLogger);
//Now you can use the logger, and further attach additional information
$logger->debug('Nobody gives a dime for debug messages', ['moreInfo' => 'Within here']);
$logger->info('A user has logged in');
$logger->notice('Something unusual has happened!', ['it did indeed']);
$logger->warning('Somebody should attend this', ['some', 'extra' => 'information']);
$logger->error('Something really bad happened');
$logger->critical('A critical message', ['please' => 'Check this out']);
$logger->alert('This is an alert', ['oh no...' => 'This might be urgent']);
$logger->emergency('Run for your lives!', ['this is it' => 'everything has stopped working']);
 /**
  * @inheritdoc
  * @return boolean Whether the record has been processed.
  */
 public function notice($message, array $context = [])
 {
     return $this->_monolog->notice($message, $context);
 }
Exemple #19
0
 public function notice($msg)
 {
     $this->logger->notice($msg);
 }
Exemple #20
0
 /**
  * @param string $message
  * @param array $context
  * @return bool
  */
 public function notice($message, array $context = array())
 {
     return parent::notice($message, $context);
 }
Exemple #21
0
 /**
  * Adds a log record at the INFO level.
  *
  * @param string $message The log message
  * @param array $context The log context
  * @return Boolean Whether the record has been processed
  */
 public function notice($message, array $context = array())
 {
     return $this->_logger->notice($message, $context);
 }
Exemple #22
0
} catch (Exception $e) {
    $logger->alert("Unable to connect to DynamoDB (and validate the table)", ['exception' => $e]);
    exit(1);
}
//------------------------------------
// Create the process handler
#TODO - This will become a config option so custom Handlers can be used.
$handler = new \DynamoQueue\Worker\Handler\Autoloader();
//------------------------------------
// Create the (a) Worker
$worker = new \DynamoQueue\Worker\Worker($queue, $handler, $logger);
//---
declare (ticks=1);
pcntl_signal(SIGTERM, array($worker, 'stop'));
pcntl_signal(SIGINT, array($worker, 'stop'));
pcntl_signal(SIGQUIT, array($worker, 'stop'));
//---
try {
    $logger->notice("Worker started");
    $okay = $worker->run();
} catch (Exception $e) {
    $logger->emergency("An unknown exception has caused the queue to terminate", ['exception' => $e]);
    exit(1);
}
//---
$logger->notice("Worker stopped");
if ($okay) {
    exit(0);
} else {
    exit(1);
}
Exemple #23
0
 /**
  * Executes a call to the QBank API.
  * @internal Uses Curl to communicate.
  * @param string $function The name of the API-function to call.
  * @param array $data The data to be sent to the called API-function. Usually normal PHP-arrays or objects.
  * @param bool $log Whether to log the call. Mainly used for debugging.
  * @param string $pathToFile A path to a file to send. Used when uploading.
  * @throws ConnectionException Thrown if something went wrong with the connection.
  * @throws CommunicationException Thrown if the call returned an exception.
  * @throws APIException Thrown when $pathToFile is on the wrong format.
  * @author Björn Hjortsten
  * @return mixed The result of a successfull call in the form of an object or array where applicable. If buffering is enabled, it will return the ticket name.
  */
 protected function call($function, $data, $log = false, $pathToFile = null)
 {
     if (!empty($this->hash) && strtolower($function) != 'login') {
         $data['hash'] = $this->hash;
     }
     $json = json_encode($data);
     if ($pathToFile != null) {
         $path = realpath($pathToFile);
         if (!is_file($path)) {
             $this->wrapperLog->critical('Error while uploading. The supplied path is not a path to a file!', array('path' => $path));
             throw new APIException('The supplied path "' . $pathToFile . '" is not a path to a file!');
         }
         if (!is_readable($path)) {
             $this->wrapperLog->critical('Error while uploading. The supplied path is not readable!', array('path' => $path));
             throw new APIException('The supplied path "' . $pathToFile . '" is not readable!');
         }
         if (function_exists('curl_file_create')) {
             // PHP 5.5+
             $file = curl_file_create($path);
         } else {
             $file = '@' . $path;
         }
         $data = array('data' => $json, 'file' => $file);
     } else {
         $data = array('data' => $json);
     }
     $url = sprintf('%s/%s/%s', $this->apiAddress, $this->qbankAddress, $function);
     curl_setopt($this->curlHandle, CURLOPT_URL, $url);
     curl_setopt($this->curlHandle, CURLOPT_POST, true);
     curl_setopt($this->curlHandle, CURLOPT_POSTFIELDS, $data);
     curl_setopt($this->curlHandle, CURLOPT_FOLLOWLOCATION, true);
     curl_setopt($this->curlHandle, CURLOPT_FAILONERROR, true);
     curl_setopt($this->curlHandle, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($this->curlHandle, CURLOPT_TIMEOUT, $this->requestTimeout);
     if ($this->useSSL === true) {
         curl_setopt($this->curlHandle, CURLOPT_SSL_VERIFYPEER, false);
     }
     curl_setopt($this->curlHandle, CURLOPT_USERAGENT, 'QBankAPIWrapper ' . BaseAPI::VERSION);
     $resultJSON = curl_exec($this->curlHandle);
     $this->lastCallInfo = curl_getinfo($this->curlHandle);
     if ($resultJSON === false) {
         $error = sprintf('Error while comunicating with QBank: %s', curl_error($this->curlHandle));
         $this->lastCall = $error;
         curl_close($this->curlHandle);
         $this->curlHandle = curl_init();
         $this->callLog->critical($error, array('address' => $this->apiAddress . '/' . $this->qbankAddress . '/' . $function, 'request' => $json));
         throw new ConnectionException($error, curl_errno($this->curlHandle));
     } else {
         $this->lastCall = $resultJSON;
         $result = json_decode($resultJSON);
         if (!isset($result->success) || $result->success === false) {
             if (isset($result->error)) {
                 $this->callLog->critical('Error response from the API. ' . $result->error->message, array('code' => $result->error->code, 'type' => $result->error->type, 'address' => $this->apiAddress . '/' . $this->qbankAddress . '/' . $function, 'request' => $json, 'response' => $resultJSON));
                 throw new CommunicationException($result->error->message, $result->error->code, $result->error->type);
             } else {
                 $this->callLog->critical('Non-successful call to QBank API and no specified error.', array('address' => $this->apiAddress . '/' . $this->qbankAddress . '/' . $function, 'request' => $json, 'response' => $resultJSON));
                 throw new CommunicationException('Unknown error! Non-successful call to QBank API and no specified error. Please note the time and report this to support@kaigantbk.se', 99, 'UnknownError');
             }
         }
         if ($log === true) {
             $this->callLog->notice('API call.', array('address' => $this->apiAddress . '/' . $this->qbankAddress . '/' . $function, 'request' => $json, 'response' => $resultJSON));
         } else {
             $this->callLog->debug('API call.', array('address' => $this->apiAddress . '/' . $this->qbankAddress . '/' . $function, 'request' => $json, 'response' => $resultJSON));
         }
         return $result;
     }
 }
Exemple #24
0
 /**
  * Adds a log record at the NOTICE level.
  *
  * @param string $message The log message
  * @param array $context The log context
  * @return Boolean Whether the record has been processed
  * @static 
  */
 public static function notice($message, $context = array())
 {
     return \Monolog\Logger::notice($message, $context);
 }
 /**
  * Normal but significant events.
  *
  * @param string $message
  * @param array  $context
  *
  * @return void
  */
 public function notice($message, array $context = array())
 {
     $this->monolog->notice($message, $context);
 }