Example #1
0
 /**
  * Bootstrap a server from command line options
  *
  * @param \Aerys\Logger $logger
  * @param \Aerys\Console $console
  * @return \Aerys\Server
  */
 public function boot(Logger $logger, Console $console) : Server
 {
     $configFile = $this->selectConfigFile((string) $console->getArg("config"));
     $logger->info("Using config file found at {$configFile}");
     if (!(include $configFile)) {
         throw new \DomainException("Config file inclusion failure: {$configFile}");
     } elseif (!defined("AERYS_OPTIONS")) {
         $options = [];
     } elseif (is_array(AERYS_OPTIONS)) {
         $options = AERYS_OPTIONS;
     } else {
         throw new \DomainException("Invalid AERYS_OPTIONS constant: array expected, got " . gettype(AERYS_OPTIONS));
     }
     if ($console->isArgDefined("debug")) {
         $options["debug"] = true;
     }
     $options = $this->generateOptionsObjFromArray($options);
     $vhosts = new VhostContainer();
     $ticker = new Ticker($logger);
     $server = new Server($options, $vhosts, $logger, $ticker);
     $bootLoader = function (Bootable $bootable) use($server, $logger) {
         return $bootable->boot($server, $logger);
     };
     $hosts = \call_user_func($this->hostAggregator) ?: [new Host()];
     foreach ($hosts as $host) {
         $vhost = $this->buildVhost($host, $bootLoader);
         $vhosts->use($vhost);
     }
     return $server;
 }
Example #2
0
 /**
  * Request the page from IMDb
  * @param $url
  * @return string Page html. Empty string on failure
  * @throws Exception\Http
  */
 protected function requestPage($url)
 {
     $this->logger->info("[Page] Requesting [{$url}]");
     $req = $this->buildRequest($url);
     if (!$req->sendRequest()) {
         $this->logger->error("[Page] Failed to connect to server when requesting url [{$url}]");
         if ($this->config->throwHttpExceptions) {
             throw new Exception\Http("Failed to connect to server when requesting url [{$url}]");
         } else {
             return '';
         }
     }
     if (200 == $req->getStatus()) {
         return $req->getResponseBody();
     } elseif ($redirectUrl = $req->getRedirect()) {
         $this->logger->debug("[Page] Following redirect from [{$url}] to [{$redirectUrl}]");
         return $this->requestPage($redirectUrl);
     } else {
         $this->logger->error("[Page] Failed to retrieve url [{url}]. Response headers:{headers}", array('url' => $url, 'headers' => $req->getLastResponseHeaders()));
         if ($this->config->throwHttpExceptions) {
             throw new Exception\Http("Failed to retrieve url [{$url}]. Status code [{$req->getStatus()}]");
         } else {
             return '';
         }
     }
 }
Example #3
0
 /**
  * Mark the last started query as stopped. This can be used for timing of queries.
  *
  * @return void
  */
 public function stopQuery()
 {
     $result = microtime() - $this->startTime;
     if ($this->logger->isDebugEnabled()) {
         $this->logger->debug("query done for {$result}");
     }
 }
Example #4
0
 public function stream(Git_HTTP_Command $command)
 {
     $cwd = '/tmp';
     $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"));
     if (ForgeConfig::get('sys_logger_level') == Logger::DEBUG) {
         $descriptorspec[2] = array('file', ForgeConfig::get('codendi_log') . '/git_http_error_log', 'a');
     }
     $pipes = array();
     $this->logger->debug('Command: ' . $command->getCommand());
     $this->logger->debug('Environment: ' . print_r($command->getEnvironment(), true));
     $process = proc_open($command->getCommand(), $descriptorspec, $pipes, $cwd, $command->getEnvironment());
     if (is_resource($process)) {
         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
             fwrite($pipes[0], file_get_contents('php://input'));
         }
         fclose($pipes[0]);
         $first = true;
         while ($result = stream_get_contents($pipes[1], self::CHUNK_LENGTH)) {
             if ($first) {
                 list($headers, $body) = http_split_header_body($result);
                 foreach (explode("\r\n", $headers) as $header) {
                     header($header);
                 }
                 file_put_contents('php://output', $body);
             } else {
                 file_put_contents('php://output', $result);
             }
             $first = false;
         }
         fclose($pipes[1]);
         $return_value = proc_close($process);
     }
 }
 public static function GetItemsForCategoryForAPI($category, $page, $itemsPerPage, $user)
 {
     $properties = new ReadeyProperties();
     $logFile = $properties->getLogFile();
     $logLevel = $properties->getLogLevel();
     $logger = new Logger($logLevel, $logFile);
     $limit = intval($itemsPerPage);
     $index = $page > 0 ? ($page - 1) * $itemsPerPage : 0;
     $itemArray = array();
     $startTime = microtime(true);
     $sql = "\n\t\t\tSELECT\n\t\t\t\tDISTINCT\n\t\t\t\tSQL_CALC_FOUND_ROWS\n\t\t\t\tri.uuid,\n\t\t\t\trf.title AS feedTitle,\n\t\t\t\tri.title,\n\t\t\t\tri.date,\n\t\t\t\trl.rssItemUuid AS alreadyRead,\n\t\t\t\tri.permalink,\n\t\t\t\tri.content\n\t\t\tFROM\n\t\t\t\trssItems ri\n\t\t\t\tJOIN rssFeeds rf ON rf.uuid = ri.feed\n\t\t\t\tJOIN rssCategories rc ON rc.uuid = rf.category\n\t\t\t\tLEFT JOIN readLogs rl ON rl.rssItemUuid = ri.uuid AND rl.user = '{$user}'\n\t\t\t\tJOIN category_feed cf ON cf.feed = ri.feed\n\t\t\tWHERE\n\t\t\t\tcf.category = '{$category}'\n\t\t\tORDER BY\n\t\t\t\tdate DESC\n\t\t\tLIMIT " . $index . "," . $limit . "\n\t\t";
     $result = mysql_query($sql);
     $queryTime = microtime(true) - $startTime;
     $resultCount = mysql_query("SELECT FOUND_ROWS()");
     $resultCountRows = mysql_fetch_array($resultCount);
     $itemArray[] = $resultCountRows[0];
     $itemArray[] = $queryTime;
     $logger->info('Query Exec Time: ' . $queryTime);
     while ($row = mysql_fetch_assoc($result)) {
         $row['date'] = date('D, n/j, g:i a', $row['date']);
         $row['wordCount'] = str_word_count($row['content']);
         $row['alreadyRead'] = $row['alreadyRead'] === NULL ? false : true;
         $itemArray[] = $row;
     }
     return $itemArray;
 }
Example #6
0
 public function check()
 {
     $username = $_POST['username'];
     $password = $_POST['password'];
     $conn = Db::getConnection();
     $sql = "SELECT username, password, admin\n\t\t\t\tFROM users\n\t\t\t\tWHERE username = '{$username}'";
     $q = $conn->prepare($sql);
     $q->execute();
     $users = $q->fetch(\PDO::FETCH_ASSOC);
     //var_dump($users);die('  proba');
     $logger = new Logger();
     $error = $logger->checkCredentials($password, $users);
     //$isAdmin = $logger->checkAdmin($password,$users);
     //var_dump($error);die('   ajde vise!!!');
     if ($error) {
         //echo '<pre>'; var_dump($error);die(); echo '</pre>';
         $html = new Html($this->controllerName);
         $html->error = $error;
         //echo '<pre>'; var_dump($html->error);die(); echo '</pre>';
         $html->render('index');
     } else {
         $user = new User($users['username'], $users['admin']);
         $user->login();
         //var_dump($user);die('   jebem li ga');
         header('Location: /');
     }
 }
 /**
  * Extract Field data from XML input
  *
  * @param Tracker_FormElement_Field $field
  * @param SimpleXMLElement $field_change
  *
  * @return mixed
  */
 public function getFieldData(Tracker_FormElement_Field $field, SimpleXMLElement $field_change)
 {
     $values = $field_change->value;
     $files_infos = array();
     if ($this->isFieldChangeEmpty($values)) {
         $this->logger->warn('Skipped attachment field ' . $field->getLabel() . ': field value is empty.');
         return $files_infos;
     }
     foreach ($values as $value) {
         try {
             $attributes = $value->attributes();
             $file_id = (string) $attributes['ref'];
             $file = $this->files_importer->getFileXML($file_id);
             if (!$this->files_importer->fileIsAlreadyImported($file_id)) {
                 $files_infos[] = $this->getFileInfoForAttachment($file);
                 $this->files_importer->markAsImported($file_id);
             }
         } catch (Tracker_Artifact_XMLImport_Exception_FileNotFoundException $exception) {
             $this->logger->warn('Skipped attachment field ' . $field->getLabel() . ': ' . $exception->getMessage());
         }
     }
     if ($this->itCannotImportAnyFiles($values, $files_infos)) {
         throw new Tracker_Artifact_XMLImport_Exception_NoValidAttachementsException();
     }
     return $files_infos;
 }
Example #8
0
 /**
  * Sends a notice about deprecated use of a function, view, etc.
  *
  * @param string $msg             Message to log
  * @param string $dep_version     Human-readable *release* version: 1.7, 1.8, ...
  * @param int    $backtrace_level How many levels back to display the backtrace.
  *                                Useful if calling from functions that are called
  *                                from other places (like elgg_view()). Set to -1
  *                                for a full backtrace.
  * @return bool
  */
 function sendNotice($msg, $dep_version, $backtrace_level = 1)
 {
     $msg = "Deprecated in {$dep_version}: {$msg} Called from ";
     // Get a file and line number for the log. Skip over the function that
     // sent this notice and see who called the deprecated function itself.
     $stack = array();
     $backtrace = debug_backtrace();
     // never show this call.
     array_shift($backtrace);
     $i = count($backtrace);
     foreach ($backtrace as $trace) {
         if (empty($trace['file'])) {
             // file/line not set for Closures
             $stack[] = "[#{$i}] unknown";
         } else {
             $stack[] = "[#{$i}] {$trace['file']}:{$trace['line']}";
         }
         $i--;
         if ($backtrace_level > 0) {
             if ($backtrace_level <= 1) {
                 break;
             }
             $backtrace_level--;
         }
     }
     $msg .= implode("<br /> -> ", $stack);
     $this->logger->warn($msg);
     return true;
 }
Example #9
0
 /**
  * @param $message
  */
 public function log($message)
 {
     $this->doLog($message);
     if ($this->next !== null) {
         $this->next->doLog($message);
     }
 }
 /**
  * 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);
 }
Example #11
0
 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);
 }
Example #12
0
 public function dealError($type, $errorItem)
 {
     $path = BeanFinder::get('configs')->dicomErrorLog;
     $logger = new Logger('dicomerror', $path);
     $logger->addError('dicomparse error: ' . $type, array($this->file, $errorItem));
     throw new DicomParseException('dicomparse error');
 }
Example #13
0
function flickrthumbnails_crawl()
{
    global $THINKTANK_CFG;
    global $db;
    global $conn;
    if (isset($THINKTANK_CFG['flickr_api_key']) && $THINKTANK_CFG['flickr_api_key'] != '') {
        $logger = new Logger($THINKTANK_CFG['log_location']);
        $fa = new FlickrAPIAccessor($THINKTANK_CFG['flickr_api_key'], $logger);
        $ldao = new LinkDAO($db, $logger);
        $flickrlinkstoexpand = $ldao->getLinksToExpandByURL('http://flic.kr/');
        if (count($flickrlinkstoexpand > 0)) {
            $logger->logStatus(count($flickrlinkstoexpand) . " Flickr links to expand", "Flickr Plugin");
        } else {
            $logger->logStatus("No Flickr links to expand", "Flickr Plugin");
        }
        foreach ($flickrlinkstoexpand as $fl) {
            $eurl = $fa->getFlickrPhotoSource($fl);
            if ($eurl["expanded_url"] != '') {
                $ldao->saveExpandedUrl($fl, $eurl["expanded_url"], '', 1);
            } elseif ($eurl["error"] != '') {
                $ldao->saveExpansionError($fl, $eurl["error"]);
            }
        }
        $logger->close();
        # Close logging
    }
}
Example #14
0
 public function initialize()
 {
     // check if user is logged in
     $authentication = Authentication::getInstance();
     $request = Request::getInstance();
     if ($authentication->isLogin() && !$authentication->isRole(SystemUser::ROLE_BACKEND)) {
         $this->log->info("Failed access for " . $authentication->getUserName() . " (not enough privileges for admin section) from " . $request->getValue('REMOTE_ADDR', Request::SERVER));
         throw new Exception('Access denied');
     }
     // check if admin section is restricted by ip-addresses
     $ip_allow = $this->director->getConfig()->admin_section_ip_allow;
     if ($ip_allow) {
         $ips = explode(",", $ip_allow);
         if (!in_array($request->getValue('REMOTE_ADDR', Request::SERVER), $ips)) {
             $this->log->info("Failed access for " . $authentication->getUserName() . " (ip not in list for admin access) from " . $request->getValue('REMOTE_ADDR', Request::SERVER));
             throw new Exception('Access denied');
         }
     }
     // create tree object
     $treefile = Director::getConfigPath() . $this->director->getConfig()->admin_menu;
     $useLogin = $this->director->getConfig()->dsn;
     $this->tree = new AdminTree($treefile, $useLogin);
     $this->tree->setPrefix($this->urlPrefix);
     // check if path is set. is not, get the startpage path
     $path = $request->getPath();
     $currentId = $this->tree->isSiteRoot() ? $this->tree->getStartNodeId() : $this->tree->getIdFromPath($path);
     // current id does not exist. try to search login pages
     if (!$currentId && $this->tree->pathExists($path)) {
         $this->tree->setCurrentIdExists($this->tree->getIdFromPath($path, Tree::TREE_ORIGINAL));
     }
     $this->tree->setCurrentId($currentId);
 }
Example #15
0
 /**
  * Run jobs
  *
  * Run all jobs provided by the job provider.
  *
  * Jobs are run parallel in the background. The number of jobs executed in 
  * parallel can be specified as the second parameter.
  *
  * Returns once all jobs have been executed.
  * 
  * @param JobProvider $jobs 
  * @param int $parallel 
  * @return void
  */
 public function run(JobProvider $jobs, $parallel = 4)
 {
     $this->logger->startExecutor($this, $jobs);
     $forks = array();
     $jobNr = 0;
     while ($jobs->hasJobs() || count($forks)) {
         while (count($forks) < $parallel && ($job = $jobs->getNextJob())) {
             $this->logger->progressJob(++$jobNr);
             if (($forks[] = pcntl_fork()) === 0) {
                 // We are the newly forked child, just execute the job
                 call_user_func($job);
                 exit(0);
             }
         }
         do {
             // Check if the registered jobs are still alive
             if ($pid = pcntl_wait($status)) {
                 // Job has finished
                 $jobId = array_search($pid, $forks);
                 unset($forks[$jobId]);
             }
         } while (count($forks) >= $parallel);
     }
     $this->logger->finishedExecutor();
 }
 public function getProcessForQueue($request_queue)
 {
     $owner = SystemEvent::OWNER_APP;
     $custom_queues = array();
     $this->event_manager->processEvent(Event::SYSTEM_EVENT_GET_CUSTOM_QUEUES, array('queues' => &$custom_queues));
     if (isset($custom_queues[$request_queue])) {
         $this->logger = $custom_queues[$request_queue]->getLogger();
         $this->logger->debug('Processing ' . $request_queue . ' queue.');
         $process = new SystemEventProcessCustomQueue($request_queue);
         $owner = $custom_queues[$request_queue]->getOwner();
     } else {
         switch ($request_queue) {
             case SystemEvent::OWNER_APP:
                 $this->logger->debug('Processing default queue as app user.');
                 $process = new SystemEventProcessApplicationOwnerDefaultQueue();
                 break;
             case SystemEvent::DEFAULT_QUEUE:
                 $this->logger->debug('Processing default queue as root user.');
                 $owner = SystemEvent::OWNER_ROOT;
                 $process = new SystemEventProcessRootDefaultQueue();
                 break;
             default:
                 $this->logger->debug('Ignoring ' . $request_queue . ' queue.');
                 exit(0);
         }
     }
     if ($owner === SystemEvent::OWNER_APP) {
         return new SystemEventProcessor_ApplicationOwner($process, $this->system_event_manager, new SystemEventDao(), $this->logger);
     }
     return new SystemEventProcessor_Root($process, $this->system_event_manager, new SystemEventDao(), $this->logger, Backend::instance('Aliases'), Backend::instance('CVS'), Backend::instance('SVN'), Backend::instance('System'), new SiteCache($this->logger));
 }
Example #17
0
 /**
  * Get parsed payments
  *
  * @return \ArrayObject Payments array
  */
 public function getPayments()
 {
     if ($this->_payments->count() == 0) {
         $this->_logger->info("No payments found, did you invoke Parser::parse() before this call?");
     }
     return $this->_payments;
 }
    public function addRemitFromPhone($request, $response)
    {/*{{{*/
        $bankPhoneNo = $request->bankPhoneNo;
        $phoneNo = $request->phoneNo;
        //if($phoneNo != 13439853264 || $phoneNo != 13501126300)
        //{
        //    echo "错误的手机号";
        //    exit;
        //}
        $remitTime = $request->remitTime/1000;
        $remitTime = xdatetime::valueOfTime($remitTime);
        $message = mb_convert_encoding($request->message, "gbk", "utf-8");
        //$message = $request->message;

        $device = $request->device;
        $logger = new Logger('sms_remit', BeanFinder::get('configs')->remitLogPath, Logger::getLevelName(Logger::INFO));
        $logger->addInfo('device:'.$device.' bankPhoneNo:'.$bankPhoneNo.' phoneNo:'.$phoneNo.' message:'.$message);

        $recorder = DAL::get()->find_by_name('user', 'jm130');
        $res = AccountClient::getInstance()->createRemitAuto($recorder, $bankPhoneNo, $phoneNo, $remitTime, $message);

        if ($res['errorcode'] != 0 && false == empty($message)) 
        {
            $msg = $device." errorcode:".$res['errorcode']." message:".$message;
            //给whd & yyp & wk
            SMSClient::getInstance()->sendSMS(array(18612032258, 13691343423, 13720084864), $msg);
        }

        $res = json_encode($res);
        echo $res;
        return parent::DIRECT_OUTPUT;
    }/*}}}*/
Example #19
0
 /**
  * Main action. Will use the action mapper to get a controller that can
  * handle the given Action, and then the viewresolver to get a View that
  * can render the returned ModelAndView from the controller.
  *
  * @param Action  $action Action to dispatch.
  *
  * @throws MvcException
  * @return void
  */
 public function dispatch(DispatchInfo $dispatchInfo)
 {
     $controller = $dispatchInfo->handler;
     $actionHandler = $dispatchInfo->method;
     $action = $dispatchInfo->action;
     if (!method_exists($controller, $actionHandler)) {
         throw new MvcException('No valid action handler found: ' . $actionHandler);
     }
     $interceptors = $dispatchInfo->interceptors;
     $filtersPassed = true;
     $result = false;
     foreach ($interceptors as $interceptor) {
         $this->_logger->debug("Running pre filter: " . get_class($interceptor));
         $result = $interceptor->preHandle($action, $controller);
         if ($result === false) {
             $filtersPassed = false;
             $this->_logger->debug("Filter returned false, stopping dispatch");
             break;
         } else {
             if ($result instanceof ModelAndView) {
                 return $result;
             }
         }
     }
     if ($filtersPassed) {
         $result = $this->invokeAction($controller, $actionHandler, $action->getArguments());
         foreach ($interceptors as $interceptor) {
             $this->_logger->debug("Running post filter: " . get_class($interceptor));
             $interceptor->postHandle($action, $controller);
         }
     }
     return $result;
 }
Example #20
0
 public function testWriteln()
 {
     $logger = $this->getMockBuilder('Psr\\Log\\LoggerInterface')->setMethods(array('emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'info', 'debug', 'log'))->getMock();
     $logger->expects($this->once())->method('info')->with($this->identicalTo('foobar' . PHP_EOL));
     $output = new Logger($logger);
     $output->writeln('foobar');
 }
Example #21
0
 /**
  *
  * Behaviour extracted from official email hook prep_for_email() function
  *
  * @param GitRepository $repository
  * @param PFUser $user
  * @param type $oldrev
  * @param type $newrev
  * @param type $refname
  * @return Git_Hook_PushDetails
  */
 public function getPushDetails(GitRepository $repository, PFUser $user, $oldrev, $newrev, $refname)
 {
     $change_type = Git_Hook_PushDetails::ACTION_ERROR;
     $revision_list = array();
     $rev_type = '';
     try {
         if ($oldrev == self::FAKE_EMPTY_COMMIT) {
             $revision_list = $this->exec_repo->revListSinceStart($refname, $newrev);
             $change_type = Git_Hook_PushDetails::ACTION_CREATE;
         } elseif ($newrev == self::FAKE_EMPTY_COMMIT) {
             $change_type = Git_Hook_PushDetails::ACTION_DELETE;
         } else {
             $revision_list = $this->exec_repo->revList($oldrev, $newrev);
             $change_type = Git_Hook_PushDetails::ACTION_UPDATE;
         }
         if ($change_type == Git_Hook_PushDetails::ACTION_DELETE) {
             $rev_type = $this->exec_repo->getObjectType($oldrev);
         } else {
             $rev_type = $this->exec_repo->getObjectType($newrev);
         }
     } catch (Git_Command_Exception $exception) {
         $this->logger->error(__CLASS__ . " {$repository->getFullName()} {$refname} {$oldrev} {$newrev} " . $exception->getMessage());
     }
     return new Git_Hook_PushDetails($repository, $user, $refname, $change_type, $rev_type, $revision_list);
 }
Example #22
0
 /**
  * Sends a notice about deprecated use of a function, view, etc.
  *
  * @param string $msg             Message to log
  * @param string $dep_version     Human-readable *release* version: 1.7, 1.8, ...
  * @param int    $backtrace_level How many levels back to display the backtrace.
  *                                Useful if calling from functions that are called
  *                                from other places (like elgg_view()). Set to -1
  *                                for a full backtrace.
  * @return bool
  */
 function sendNotice($msg, $dep_version, $backtrace_level = 1)
 {
     if (!$dep_version) {
         return false;
     }
     $elgg_version = elgg_get_version(true);
     $elgg_version_arr = explode('.', $elgg_version);
     $elgg_major_version = (int) $elgg_version_arr[0];
     $elgg_minor_version = (int) $elgg_version_arr[1];
     $dep_version_arr = explode('.', (string) $dep_version);
     $dep_major_version = (int) $dep_version_arr[0];
     $dep_minor_version = (int) $dep_version_arr[1];
     $msg = "Deprecated in {$dep_major_version}.{$dep_minor_version}: {$msg} Called from ";
     // Get a file and line number for the log. Skip over the function that
     // sent this notice and see who called the deprecated function itself.
     $stack = array();
     $backtrace = debug_backtrace();
     // never show this call.
     array_shift($backtrace);
     $i = count($backtrace);
     foreach ($backtrace as $trace) {
         $stack[] = "[#{$i}] {$trace['file']}:{$trace['line']}";
         $i--;
         if ($backtrace_level > 0) {
             if ($backtrace_level <= 1) {
                 break;
             }
             $backtrace_level--;
         }
     }
     $msg .= implode("<br /> -> ", $stack);
     $this->logger->warn($msg);
     return true;
 }
 /**
  * Framework entry point
  *
  * @return void.
  */
 public function dispatch()
 {
     include_once 'action/controller/http/HTTPResponse.php';
     include_once 'action/controller/http/HTTPRequest.php';
     $request = new HTTPRequest();
     $response = new HTTPResponse();
     try {
         $configurator = $this->manager->getConfigurator();
         Registry::put($configurator, '__configurator');
         Registry::put($logger = new Logger($configurator), '__logger');
         $ap = $configurator->getApplicationPath();
         // application path
         $an = $configurator->getApplicationName();
         // application name
         $logger->debug('[Medick] >> version: ' . Medick::getVersion() . ' ready for ' . $an);
         $logger->debug('[Medick] >> Application path ' . $ap);
         $routes_path = $ap . DIRECTORY_SEPARATOR . 'conf' . DIRECTORY_SEPARATOR . $an . '.routes.php';
         include_once $routes_path;
         // load routes
         $logger->debug('[Medick] >> Config File: ' . str_replace($ap, '${' . $an . '}', $configurator->getConfigFile()));
         $logger->debug('[Medick] >> Routes loaded from: ' . str_replace($ap, '${' . $an . '}', $routes_path));
         ActionControllerRouting::recognize($request)->process($request, $response)->dump();
     } catch (Exception $ex) {
         ActionController::process_with_exception($request, $response, $ex)->dump();
         $logger->warn($ex->getMessage());
     }
 }
 private function logError(GitRepository $repository, $sysevent_prefix, $log_prefix, Exception $e)
 {
     $this->dao->setGerritMigrationError($repository->getId());
     $this->error($sysevent_prefix . $e->getMessage());
     $this->logger->error($log_prefix . $this->verbalizeParameters(null), $e);
     $this->sendErrorNotification($repository);
 }
 /**
  * Create an ILogger implementation instance.
  *
  * @param array $options the options for create logger
  * current supported options list as below:
  * storage : the storage handler for log( file, DB , etc.). the default
  *           storage is file.
  * log_level : the log level. one of the const LOG_OFF,LOG_DEBUG,LOG_INFO,LOG_ERROR.
  *           The default log level is LOG_ERROR
  * @return ILogger
  */
 public static function getLogger($options = null)
 {
     if (isset($options['storage'])) {
         $storage = strtolower(preg_replace('/[^A-Z0-9_\\.-]/i', '', $options['storage']));
     } else {
         $app_config = get_app_config();
         $storage = $app_config->getGlobalConfig('log_storage');
         if ($storage === false) {
             $storage = 'file';
         }
     }
     if (isset($options['log_level'])) {
         // set the log level
         $log_level = intval($options['log_level']);
     } else {
         // default log level is log error message
         $log_level = ELEX_LOG_ERROR;
     }
     $storageClass = 'Log' . ucfirst($storage) . 'Storage';
     if (!class_exists($storageClass, false)) {
         $path = FRAMEWORK . '/log/storage/' . $storageClass . '.class.php';
         if (file_exists($path)) {
             require_once $path;
         } else {
             // user the file storage
             $storageClass = 'LogFileStorage';
             require_once FRAMEWORK . '/log/storage/LogFileStorage' . '.class.php';
         }
     }
     $storageInstance = new $storageClass($options);
     $instance = new Logger($storageInstance);
     $instance->setLogLevel($log_level);
     return $instance;
 }
Example #26
0
function facebook_crawl()
{
    //TODO Crawl Facebook posts and comments and insert them into the database
    global $THINKTANK_CFG;
    global $db;
    global $conn;
    $logger = new Logger($THINKTANK_CFG['log_location']);
    $id = new InstanceDAO($db, $logger);
    $oid = new OwnerInstanceDAO($db, $logger);
    $instances = $id->getAllActiveInstancesStalestFirstByNetwork('facebook');
    foreach ($instances as $i) {
        $logger->setUsername($i->network_username);
        $tokens = $oid->getOAuthTokens($i->id);
        $session_key = $tokens['oauth_access_token'];
        $fb = new Facebook($THINKTANK_CFG['facebook_api_key'], $THINKTANK_CFG['facebook_api_secret']);
        $cfg = new Config($i->network_username, $i->network_user_id);
        $id->updateLastRun($i->id);
        $crawler = new FacebookCrawler($i, $logger, $fb, $db);
        $crawler->fetchInstanceUserInfo($i->network_user_id, $session_key);
        $crawler->fetchUserPostsAndReplies($i->network_user_id, $session_key);
        $id->save($crawler->instance, $crawler->owner_object->post_count, $logger, $fb);
    }
    $logger->close();
    # Close logging
}
Example #27
0
 /**
  * For a given post, extract URLs and store them, including image_src if that's from a known source like Twitpic,
  * Twitgoo, Yfrog, Instagr.am.
  * @param str $post_text
  * @param int $post_id
  * @param str $network
  * @param Logger $logger
  * @param arr $urls Array of URLs, optionally set, defaults to null
  */
 public static function processPostURLs($post_text, $post_id, $network, $logger, $urls = null)
 {
     if (!$urls) {
         $urls = Post::extractURLs($post_text);
     }
     if ($urls) {
         $link_dao = DAOFactory::getDAO('LinkDAO');
         $post_dao = DAOFactory::getDAO('PostDAO');
         $post = $post_dao->getPost($post_id, $network);
         if (isset($post->id)) {
             foreach ($urls as $url) {
                 $logger->logInfo("Processing URL {$url}", __METHOD__ . ',' . __LINE__);
                 $image_src = self::getImageSource($url);
                 //if we have an image_src, the URL is a known image source not in need of expansion
                 $expanded_url = $image_src !== '' ? $url : '';
                 $link_array = array('url' => $url, 'expanded_url' => $expanded_url, "image_src" => $image_src, 'post_key' => $post->id);
                 $link = new Link($link_array);
                 try {
                     $link_dao->insert($link);
                     $logger->logSuccess("Inserted " . $url . " " . ($image_src == '' ? '' : "(thumbnail " . $image_src . ") ") . "into links table", __METHOD__ . ',' . __LINE__);
                 } catch (DuplicateLinkException $e) {
                     $logger->logInfo($url . " " . ($image_src == '' ? '' : "(thumbnail " . $image_src . ") ") . " already exists in links table", __METHOD__ . ',' . __LINE__);
                 } catch (DataExceedsColumnWidthException $e) {
                     $logger->logInfo($url . " " . ($image_src == '' ? '' : "(thumbnail " . $image_src . ") ") . " data exceeds table column width", __METHOD__ . ',' . __LINE__);
                 }
             }
         }
     }
 }
Example #28
0
 /**
  * Test that the storage number can be set and retrieved.
  */
 public function testSetGetStorageAsInteger()
 {
     $randNumber = rand(9999, 99999);
     $logger = new Logger();
     $logger->set('testNumber', $randNumber);
     $this->assertSame($randNumber, $logger->get('testNumber'));
 }
 public function tearDown()
 {
     $this->builders = null;
     parent::tearDown();
     $this->logger->close();
     $this->DAO = null;
 }
 public function login()
 {
     vendor("Logger.Logger", LIB_PATH . '../Extend/Vendor');
     $logger = new Logger();
     $logger->trace('The stacktrace is ');
     $domain = $_SERVER['SERVER_NAME'];
     if (preg_match("/^([A-Za-z0-9]+)\\.weixin\\.[A-Za-z0-9]+\\.com\$/i", $domain, $matches)) {
         //是oem客户
         $oem_name = $matches[1];
         if (!empty($oem_name)) {
             $login_pic = session('oem_logo');
             if (empty($login_pic)) {
                 $sql = "select ac.cfg_data, u.role from  tp_user as u LEFT JOIN tp_oem_cfg as ac on u.id = ac.agent_id where u.domain_prefix = '{$oem_name}'; ";
                 $Model = new Model();
                 $user = $Model->query($sql);
                 if ($user != false) {
                     $this->agent_cfg = $this->getAgentCfg($user[0]['cfg_data']);
                     $login_pic = $this->agent_cfg['company_logo'];
                     if (!empty($login_pic)) {
                         session('oem_logo', $login_pic);
                     }
                 }
             }
         }
         $this->assign('is_oem', 1);
     } else {
         //不是oem用户
         $login_pic = '/images/login_logo.png';
     }
     $this->assign('login_pic', $login_pic);
     $this->display();
 }