Example #1
0
 /**
  * @param string|\Exception $msg
  * @param array $context
  * @throws \RuntimeException
  */
 public static function info($msg, array $context = array())
 {
     if (empty(static::$instance)) {
         throw new \RuntimeException('Logger instance not added to proxy yet');
     }
     static::$instance->info($msg, $context);
 }
Example #2
0
 /**
  * log if verbose mode active
  *
  * @param OutputInterface $output The output
  * @param string $message The message
  */
 protected function log(OutputInterface $output, $message)
 {
     if (null === $this->logger) {
         $this->logger = new CommandLogger($output);
     }
     $this->logger->info($message);
 }
 private function importDumpFile(Project $project, $xml_svn, $extraction_path)
 {
     $attrs = $xml_svn->attributes();
     if (!isset($attrs['dump-file'])) {
         return true;
     }
     $rootpath_arg = escapeshellarg($project->getSVNRootPath());
     $dumpfile_arg = escapeshellarg("{$extraction_path}/{$attrs["dump-file"]}");
     $commandline = "svnadmin load {$rootpath_arg} <{$dumpfile_arg} 2>&1";
     $this->logger->info($commandline);
     try {
         $cmd = new System_Command();
         $command_output = $cmd->exec($commandline);
         foreach ($command_output as $line) {
             $this->logger->debug("svnadmin: {$line}");
         }
         $this->logger->debug("svnadmin returned with status 0");
     } catch (System_Command_CommandException $e) {
         foreach ($e->output as $line) {
             $this->logger->error("svnadmin: {$line}");
         }
         $this->logger->error("svnadmin returned with status {$e->return_value}");
         throw new SVNXMLImporterException("failed to svnadmin load {$dumpfile_arg} in {$rootpath_arg}:" . " exited with status {$e->return_value}");
     }
 }
Example #4
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 #5
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;
 }
Example #6
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);
 }
 public function cleanUpGitoliteAdminWorkingCopy()
 {
     if ($this->dao->isGitGcEnabled()) {
         $this->logger->info('Running git gc on gitolite admin working copy.');
         $this->execGitGcAsAppAdm();
     } else {
         $this->logger->warn('Cannot run git gc on gitolite admin working copy. ' . 'Please run as root: /usr/share/codendi/src/utils/php-launcher.sh ' . '/usr/share/codendi/plugins/git/bin/gl-admin-housekeeping.php');
     }
 }
 private function importLanguage(Project $project, $language)
 {
     $this->logger->info("Set language to {$language} for {$project->getUnixName()}");
     try {
         $this->language_manager->saveLanguageOption($project, $language);
     } catch (Mediawiki_UnsupportedLanguageException $e) {
         $this->logger->warn("Could not set up the language for {$project->getUnixName()} mediawiki, {$language} is not sopported.");
     }
 }
 public function exportArtifact($tracker_id, array $artifact_row)
 {
     $artifact_id = (int) $artifact_row['artifact_id'];
     $this->logger->info("Export artifact: " . $artifact_id);
     $artifact_node = $this->node_helper->createElement('artifact');
     $artifact_node->setAttribute('id', $artifact_row['artifact_id']);
     $this->addAllChangesets($artifact_node, $tracker_id, $artifact_id, $artifact_row);
     $this->attachment_exporter->addFilesToArtifact($artifact_node, $tracker_id, $artifact_id);
     return $artifact_node;
 }
 public function export(Project $project, array $options, PFUser $user, ZipArchive $archive)
 {
     $this->logger->info("Start exporting project " . $project->getPublicName());
     $xml_element = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>
                                          <project />');
     $this->exportProjectUgroups($project, $xml_element);
     $this->exportPlugins($project, $xml_element, $options, $user, $archive);
     $this->logger->info("Finish exporting project " . $project->getPublicName());
     return $this->convertToXml($xml_element);
 }
Example #11
0
 /**
  * Отправляет СМС на указанный номер
  * 
  * @param string $phoneNumber
  * @param string $message
  * @param int $GROUP  14 - tele-plus
  * 
  * @throws \InvalidArgumentException телефонный номер пустой
  */
 public function send($phoneNumber, $message, $GROUP = self::GROUP_TELEPLUS)
 {
     //Не проверяет телефон на мобильный он или городской, потому что возможно на короткий городской тоже отправляет СМС
     $this->_logger->info("{$phoneNumber}, {$message}, {$GROUP}");
     if (!$this->getClearPhoneNumber($phoneNumber)) {
         throw new \InvalidArgumentException("Пустой телефонный номер");
     }
     if (!$message) {
         throw new \InvalidArgumentException("Пустое СМС сообщение");
     }
     $connection = Core::getConnection();
     $connection->exec("INSERT INTO TMCOMDEVS_TASKS(KIND, STATUS, SMSMESSAGE, PHONE, ORDID, CREW_GROUP_ID) VALUES (1, 0, {$connection->quote($message)}, '{$this->getClearPhoneNumber($phoneNumber)}', Null, {$GROUP})");
 }
Example #12
0
 public function process($raw_mail)
 {
     $incoming_message = $this->parser->parse($raw_mail);
     $user = $incoming_message->getRecipient()->getUser();
     $artifact = $incoming_message->getRecipient()->getArtifact();
     $this->logger->debug("Receiving new follow-up comment from " . $user->getUserName());
     if (!$artifact->userCanUpdate($user)) {
         $this->logger->info("User " . $user->getUnixName() . " has no right to update the artifact #" . $artifact->getId());
         return;
     }
     $body = $this->citation_stripper->stripText($incoming_message->getBody());
     $artifact->createNewChangeset(array(), $body, $user, true, Tracker_Artifact_Changeset_Comment::TEXT_COMMENT);
 }
 private function executeSystemEvent(SystemEvent $sysevent)
 {
     $this->logger->info("Processing event #" . $sysevent->getId() . " " . $sysevent->getType() . "(" . $sysevent->getParameters() . ")");
     try {
         $sysevent->process();
     } catch (Exception $exception) {
         $sysevent->logException($exception);
     }
     $this->dao->close($sysevent);
     $sysevent->notify();
     $this->logger->info("Processing event #" . $sysevent->getId() . ": done.", Backend::LOG_INFO);
     // Output errors???
 }
Example #14
0
 /**
  * @param string $statement
  * @return mixed
  */
 public function query($statement)
 {
     # Execute
     $start = microtime(true);
     $result = call_user_func_array('parent::query', func_get_args());
     $time = microtime(true) - $start;
     # Explain
     $explain = new Explain($this, $statement);
     # Log
     if (!preg_match('/^\\s*(EXPLAIN)\\s+/i', $statement)) {
         $this->logger->info('query', array('queryString' => $statement, 'parameters' => array(), 'time' => $time, 'explain' => $explain->getResult(), 'backtrace' => debug_backtrace()));
     }
     # Return
     return $result;
 }
Example #15
0
 /**
  * @param array $parameters
  */
 public function execute($parameters = array())
 {
     # Execute
     $start = microtime(true);
     $result = $this->sth->execute($parameters);
     $time = microtime(true) - $start;
     # Explain
     $explain = new Explain($this->pdo, $this->sth->queryString, $parameters);
     # Log
     if (!preg_match('/^\\s*(EXPLAIN)\\s+/i', $this->sth->queryString)) {
         $this->logger->info('prepare', array('queryString' => $this->sth->queryString, 'parameters' => $parameters, 'time' => $time, 'explain' => $explain->getResult(), 'backtrace' => debug_backtrace()));
     }
     # Return
     return $result;
 }
 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 #17
0
 /**
  * Filterの処理を実行します。
  *
  */
 public function execute()
 {
     $clsname = get_class($this);
     // 現在のアクション名を取得
     $actionName = $this->actionChain->getCurActionName();
     // 実行対象かどうかのチェック
     $isTarget = $this->isTarget($actionName);
     if (!$isTarget) {
         $this->log->info("{$clsname} は実行対象外のためスキップします。");
     }
     // prefilterを実行
     if ($isTarget) {
         $this->log->debug("{$clsname}のprefilterを実行します。");
         $this->prefilter();
         $this->log->debug("{$clsname}のprefilterを実行しました。");
     }
     // filterChain
     $this->filterChain->execute();
     // postfilterを実行
     if ($isTarget) {
         $this->log->debug("{$clsname}のpostfilterを実行します。");
         $this->postfilter();
         $this->log->debug("{$clsname}のpostfilterを実行しました。");
     }
     return;
 }
 /**
  * Remove database
  */
 public static function removeStructure()
 {
     $class = static::getClassName();
     Logger::info('Removing ' . $class . ' database structure');
     Database::removeTable(static::getDBTable());
     Logger::info('Done for ' . $class);
 }
Example #19
0
 public function checkPermission($object, IPermission $perm, LoginContext $context = null)
 {
     try {
         if ($object === null) {
             throw new EyeNullPointerException('$object cannot be null.');
         }
         if ($perm === null) {
             throw new EyeNullPointerException('$perm cannot be null.');
         }
         if ($context === null) {
             $currentProcess = ProcManager::getInstance()->getCurrentProcess();
             if ($currentProcess === null) {
                 self::$Logger->warn('Cannot check permission on object of class ' . get_class($object) . ': No current process.');
                 throw new EyeAccessControlException('Access denied: No current process.');
             }
             $context = $currentProcess->getLoginContext();
             if ($context === null) {
                 //self::$Logger->warn('Cannot check permission on object of class ' . get_class($object) . ': No LoginContext found in current process.');
                 //throw new EyeAccessControlException('Access denied: No LoginContext found in current process.');
                 self::$Logger->info('Initializing blank login context for permission check on object of class ' . get_class($object) . '.');
                 $context = new LoginContext('eyeos-login', new Subject());
             }
         }
         $checker = new SecurityChecker();
         $checker->doCheck($object, $perm, $context);
     } catch (Exception $e) {
         self::$Logger->error('Cannot perform permission check: ' . $e->getMessage());
         if (self::$Logger->isDebugEnabled()) {
             self::$Logger->debug(ExceptionStackUtil::getStackTrace($e, false));
         }
         throw $e;
     }
 }
 /**
  *
  *
  * This start method swallows ALL exceptions, logs them
  * (default in the file: logger.output.html), and returns a GENERIC_FAILURE_MSG response with status code
  * 500.
  */
 public function start($test_post_data = NULL)
 {
     try {
         if ($test_post_data === NULL) {
             $requestPayload = RemoteServiceServlet::readPayloadAsUtf8();
         } else {
             $requestPayload = $test_post_data;
         }
         // Let subclasses see the serialized request.
         //
         $this->onBeforeRequestDeserialized($requestPayload);
         // Invoke the core dispatching logic, which returns the serialized
         // result.
         //
         $this->logger->info($requestPayload);
         $responsePayload = $this->processCall($requestPayload);
         $this->logger->info($responsePayload);
         // Let subclasses see the serialized response.
         //
         $this->onAfterResponseSerialized($responsePayload);
         // Write the response.
         //
         if ($test_post_data === NULL) {
             $this->writeResponse($responsePayload);
         } else {
             return $responsePayload;
         }
     } catch (Exception $ex) {
         $this->doUnexpectedFailure($ex);
     }
 }
Example #21
0
 /**
  * @covers Phossa\Logger\Logger::getDecorators
  */
 public function testGetDecorators()
 {
     // get default decorator
     $this->object->info('test');
     $da = $this->object->getDecorators();
     $this->assertInstanceOf('Phossa\\Logger\\Decorator\\InterpolateDecorator', $da[0]);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $validJobs = array();
     if ($input->getOption("job")) {
         $validJobs = explode(",", $input->getOption("job"));
     }
     // create manager
     $manager = Schedule\Manager\Factory::getManager("maintenance.pid");
     $manager->setValidJobs($validJobs);
     $manager->setForce((bool) $input->getOption("force"));
     // register scheduled tasks
     $manager->registerJob(new Schedule\Maintenance\Job("scheduledtasks", new Schedule\Task\Executor(), "execute"));
     $manager->registerJob(new Schedule\Maintenance\Job("logmaintenance", new \Pimcore\Log\Maintenance(), "mail"));
     $manager->registerJob(new Schedule\Maintenance\Job("cleanuplogfiles", new \Pimcore\Log\Maintenance(), "cleanupLogFiles"));
     $manager->registerJob(new Schedule\Maintenance\Job("httperrorlog", new \Pimcore\Log\Maintenance(), "httpErrorLogCleanup"));
     $manager->registerJob(new Schedule\Maintenance\Job("usagestatistics", new \Pimcore\Log\Maintenance(), "usageStatistics"));
     $manager->registerJob(new Schedule\Maintenance\Job("checkErrorLogsDb", new \Pimcore\Log\Maintenance(), "checkErrorLogsDb"));
     $manager->registerJob(new Schedule\Maintenance\Job("archiveLogEntries", new \Pimcore\Log\Maintenance(), "archiveLogEntries"));
     $manager->registerJob(new Schedule\Maintenance\Job("sanitycheck", "\\Pimcore\\Model\\Element\\Service", "runSanityCheck"));
     $manager->registerJob(new Schedule\Maintenance\Job("versioncleanup", new \Pimcore\Model\Version(), "maintenanceCleanUp"));
     $manager->registerJob(new Schedule\Maintenance\Job("versioncompress", new \Pimcore\Model\Version(), "maintenanceCompress"));
     $manager->registerJob(new Schedule\Maintenance\Job("redirectcleanup", "\\Pimcore\\Model\\Redirect", "maintenanceCleanUp"));
     $manager->registerJob(new Schedule\Maintenance\Job("cleanupbrokenviews", "\\Pimcore\\Db", "cleanupBrokenViews"));
     $manager->registerJob(new Schedule\Maintenance\Job("downloadmaxminddb", "\\Pimcore\\Update", "updateMaxmindDb"));
     $manager->registerJob(new Schedule\Maintenance\Job("cleanupcache", "\\Pimcore\\Model\\Cache", "maintenance"));
     $manager->registerJob(new Schedule\Maintenance\Job("tmpstorecleanup", "\\Pimcore\\Model\\Tool\\TmpStore", "cleanup"));
     $manager->registerJob(new Schedule\Maintenance\Job("imageoptimize", "\\Pimcore\\Model\\Asset\\Image\\Thumbnail\\Processor", "processOptimizeQueue"));
     \Pimcore::getEventManager()->trigger("system.maintenance", $manager);
     $manager->run();
     \Logger::info("All maintenance-jobs finished!");
 }
 public static function Nuevo($request)
 {
     try {
         self::ProblemaValido($request);
     } catch (InvalidArgumentException $e) {
         Logger::warn("imposible crear nuevo problema:" . $e->getMessage());
         return array("result" => "error", "reason" => $e->getMessage());
     }
     $usuarioActual = c_sesion::usuarioActual();
     if (!SUCCESS($usuarioActual)) {
         Logger::error("no hay permiso para crear nuevo problema");
         return array("result" => "error", "reason" => "No tienes permiso de hacer esto.");
     }
     $sql = "insert into Problema (titulo, problema, tiempoLimite, usuario_redactor) values (?,?,?,?)";
     $inputarray = array($request["titulo"], $request["problema"], $request["tiempoLimite"], $usuarioActual["userID"]);
     global $db;
     $res = $db->Execute($sql, $inputarray);
     if ($res === false) {
         Logger::error("TEDDY:" . $db->ErrorNo() . " " . $db->ErrorMsg());
         return array("result" => "error", "reason" => "Error interno.");
     }
     $id = $db->Insert_ID();
     if (!file_exists(PATH_TO_CASOS)) {
         Logger::error("TEDDY: " . PATH_TO_CASOS . " no existe");
         return array("result" => "error", "reason" => "Error interno.");
     }
     file_put_contents(PATH_TO_CASOS . "/" . $id . ".in", $request["entrada"]);
     file_put_contents(PATH_TO_CASOS . "/" . $id . ".out", $request["salida"]);
     Logger::info("Nuevo problema creado. ProbID: " . $id . " Titulo: " . $request["titulo"]);
     return array("result" => "ok", "probID" => $id);
 }
Example #24
0
 /**
  * 指定されたconfigで変換を実行します。
  *
  * @param mixed $obj
  * @param array $config
  */
 public function execute(&$obj, &$config)
 {
     foreach ($config as $fieldName => $fieldConfig) {
         foreach ($fieldConfig as $converterName => $attr) {
             // Converterインスタンスを作成
             $converter = $this->container->getPrototype("Teeple_Converter_" . ucfirst($converterName));
             if (!is_object($converter)) {
                 throw new Teeple_Exception("Converterのインスタンスを作成できません。({$converterName})");
             }
             // 属性をセット
             foreach ($attr as $key => $value) {
                 $converter->{$key} = $value;
             }
             // Converterを実行
             if ($fieldName == self::FIELD_ALL) {
                 $keys = Teeple_Util::getPropertyNames($obj);
             } else {
                 $keys = array($fieldName);
             }
             foreach ($keys as $key) {
                 if (!$converter->convert($obj, $key)) {
                     $this->log->info("{$converterName}は{$key}に対して実行されませんでした。");
                 }
             }
         }
     }
     return;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $status = ["success" => true];
     $config = $input->getArgument("config");
     if ($config) {
         $job = json_decode($config, true);
         if (is_array($job)) {
             if (isset($job["dry-run"])) {
                 // do not do anything here
                 \Logger::info("skipped update job because it is in dry-run mode", $job);
             } elseif ($job["type"] == "files") {
                 Update::installData($job["revision"]);
             } elseif ($job["type"] == "clearcache") {
                 \Pimcore\Cache::clearAll();
             } elseif ($job["type"] == "preupdate") {
                 $status = Update::executeScript($job["revision"], "preupdate");
             } elseif ($job["type"] == "postupdate") {
                 $status = Update::executeScript($job["revision"], "postupdate");
             } elseif ($job["type"] == "cleanup") {
                 Update::cleanup();
             }
         }
     }
     $this->output->write(json_encode($status));
 }
Example #26
0
 /**
  * Creates an instance of the component which is being loaded.
  *
  * @param $namespace
  * @param $class
  * @param $params
  * @param $method_name
  * @param $data
  * @return object
  */
 private function _createInstance($namespace, $class, $params, $method_name, $data)
 {
     $ns_class = $namespace . $class;
     //create a reflection class so that we can pass parameters to the constructor
     $ref_class = new \ReflectionClass($ns_class);
     if (is_array($params) && sizeof($params) > 0) {
         $instance = $ref_class->newInstanceArgs($params);
     } else {
         $instance = new $ns_class();
     }
     $this->logger->info("{$namespace} object created for {$class} class");
     //call the method along with parameters, if they exist !
     if (method_exists($instance, $method_name)) {
         if (is_callable(array($instance, $method_name))) {
             $last_hook = $this->loading[count($this->loading) - 1];
             $this->loaderHooks($instance, "pre_{$last_hook}", $class, $method_name, $data);
             call_user_func_array(array($instance, $method_name), $data);
             $this->loaderHooks($instance, "post_{$last_hook}", $class, $method_name, $data);
         } else {
             die("You do not have access to this link :-)");
         }
     }
     $this->clearCurrentLoader();
     return $instance;
 }
Example #27
0
 public function getList()
 {
     Logger::debug('main', 'UserGroupDBDynamic::internal::getList');
     if (is_null(self::table)) {
         Logger::error('main', 'UserGroupDBDynamic::internal::getList table is null');
         return NULL;
     }
     $sql2 = SQL::getInstance();
     $res = $sql2->DoQuery('SELECT @1, @2, @3, @4, @5 FROM #6', 'id', 'name', 'description', 'published', 'validation_type', self::table);
     if ($res !== false) {
         $result = array();
         $rows = $sql2->FetchAllResults($res);
         foreach ($rows as $row) {
             $rules = UserGroup_Rules::getByUserGroupId('dynamic_' . $row['id']);
             $ug = new UsersGroup_dynamic($row['id'], $row['name'], $row['description'], (bool) $row['published'], $rules, $row['validation_type']);
             if ($this->isOK($ug)) {
                 $result[$ug->id] = $ug;
             } else {
                 Logger::info('main', 'UserGroupDBDynamic::internal::getList group \'' . $row['id'] . '\' not ok');
             }
         }
         return $result;
     } else {
         Logger::error('main', 'UserGroupDBDynamic::internal::getList failed (sql query failed)');
         // not the right argument
         return NULL;
     }
 }
Example #28
0
 /**
  * FilterChainの最後にFilterを追加
  *
  * @param   string  $name   Filterのクラス名
  * @param   string  $alias  Filterのエイリアス名
  * @param   array   $attributes Filterの属性値
  */
 public function add($name, $alias = '', $attributes = NULL)
 {
     // エイリアス名が指定されていない場合はクラス名をセット
     if (empty($alias)) {
         $alias = $name;
     }
     // Filterの実行が既に始まっていたらエラー(実行後の追加はエラー)
     if ($this->_index > -1) {
         throw new Teeple_Exception("既にフィルターが実行されています。");
     }
     // Filterのクラス名が不正だったらエラー
     if (!preg_match("/^[0-9a-zA-Z_]+\$/", $name)) {
         throw new Teeple_Exception("フィルターのクラス名が不正です。({$name})");
     }
     // 既に同名のFilterが追加されていたら何もしない
     if (isset($this->_list[$alias]) && is_object($this->_list[$alias])) {
         $this->log->info("このFilterは既に登録されています({$name}[alias:{$alias}])");
         return;
     }
     // オブジェクトの生成に失敗していたらエラー
     $className = "Teeple_Filter_" . ucfirst($name);
     $filter = $this->container->getComponent($className);
     if (!is_object($filter)) {
         throw new Teeple_Exception("Filterオブジェクトの生成に失敗しました。({$name})");
     }
     if (is_array($attributes)) {
         $filter->setAttributes($attributes);
     }
     $this->_list[$alias] = $filter;
     $this->_position[] = $alias;
     return;
 }
 /**
  * @param user
  * @param pass
  *
  * */
 public static function login($request)
 {
     $request["user"] = isset($request["user"]) ? $request["user"] : null;
     $request["email"] = $request["user"];
     if (isset($request["password"])) {
         $request["pass"] = $request["password"];
     }
     $sql = "select pswd, cuenta, userID, mail from Usuario where BINARY ( userID = ? or mail = ? )";
     $inputarray = array($request["user"], $request["email"]);
     global $db;
     $result = $db->Execute($sql, $inputarray);
     $resultData = $result->GetArray();
     if (sizeof($resultData) == 1) {
         $dbUser = $resultData[0];
         if (crypt($request["pass"], $dbUser["pswd"]) == $dbUser["pswd"]) {
             unset($dbUser["pswd"]);
             unset($dbUser[0]);
             $_SESSION['userID'] = $dbUser['userID'];
             Logger::info("sesion iniciada para " . $dbUser["userID"]);
             return array("result" => "ok", "user" => $dbUser);
         }
     }
     Logger::error("Credenciales invalidas para usuario :" . $request["user"]);
     return array("result" => "error", "reason" => "Credenciales invalidas.");
 }
Example #30
0
/**
 * Checks for new versions of Terminus once per week and saves to cache
 *
 * @param Logger $logger Logger to use to report result of check
 * @return void
 */
function checkForUpdate($logger)
{
    $cache = new FileCache();
    $cache_data = $cache->getData('latest_release', ['decode_array' => true]);
    if (!$cache_data || (int) $cache_data['check_date'] < (int) strtotime('-7 days')) {
        try {
            $current_version = checkCurrentVersion();
            if (version_compare($current_version, TERMINUS_VERSION, '>')) {
                $logger->info('An update to Terminus is available. Please update to {version}.', ['version' => $current_version]);
            }
        } catch (\Exception $e) {
            $logger->info($e->getMessage());
            $logger->info('Cannot retrieve current Terminus version.');
        }
    }
}