private static function getLogger()
 {
     if (self::$logger == null) {
         $ctx = AgaviContext::getInstance();
         self::$logger = $ctx->getLoggerManager();
     }
     return self::$logger;
 }
 public function postConnect(Doctrine_Event $event)
 {
     $invoker = $event->getInvoker();
     if (!$invoker instanceof Doctrine_Connection) {
         AppKitLogger::warn("Couldn't call ConnectionListenerHook, no connection found");
         return;
     }
     if ($this->initConnectionSql !== null) {
         AppKitLogger::verbose("Executing connection init command for connection %s : %s", $invoker->getName(), $this->initConnectionSql);
     }
     $invoker->setDateFormat($this->dateFormat);
     $invoker->execute($this->initConnectionSql);
 }
 public function dispatchCommands()
 {
     $dispatcher = $this->getContext()->getModel("Commands.CommandDispatcher", "Api");
     $this->context->getLoggerManager()->log(print_r($this->selection, 1));
     $this->selection = AppKitArrayUtil::uniqueMultidimensional($this->selection);
     $this->context->getLoggerManager()->log(print_r($this->selection, 1));
     AppKitLogger::debug("Trying to send commands, targets: %s , data: %s ", json_encode($this->selection), json_encode($this->data));
     foreach ($this->selection as $target) {
         $console = $this->getConsoleInstance($target['instance']);
         $dispatcher->setConsoleContext($console);
         AppKitLogger::debug("Submitting command %s to %s", $this->command, json_encode($target));
         $dispatcher->submitCommand($this->command, array_merge($target, $this->data));
         AppKitLogger::debug("Finished submitting command");
     }
 }
 public function merge(array &$result)
 {
     if (!$this->createView) {
         $this->createMergeView();
     }
     $mergeResult = $this->createView->getResult();
     AppKitLogger::verbose("Got mergeResult \\w %i results %s", count($mergeResult), $mergeResult);
     switch ($this->type) {
         case 'left':
             $this->mergeLeft($result, $mergeResult);
             return $result;
         case 'right':
             return $this->mergeRight($mergeResult, $result);
             break;
     }
 }
 public function connect()
 {
     if ($this->connected) {
         return true;
     }
     AppKitLogger::verbose("Connecting to ssh instance %s:%s", $this->host, $this->port);
     $success = false;
     $this->resource = new Net_SSH2($this->host, $this->port);
     switch ($this->authType) {
         case 'none':
             AppKitLogger::verbose("No-auth login with %s", $this->username);
             $success = $this->resource->login($this->username);
             break;
         case 'password':
             AppKitLogger::verbose("Password login with %s", $this->username);
             $success = $this->resource->login($this->username, $this->password);
             break;
         case 'key':
             AppKitLogger::verbose("Pub-Key login with ssh key at %s", $this->privKeyLocation);
             if (!is_readable($this->privKeyLocation)) {
                 throw new ApiAuthorisationFailedException("SSH private key not found/readable at the specified location");
             }
             $key = new Crypt_RSA();
             if ($this->password) {
                 $key->setPassword($this->password);
             }
             $key->loadKey(file_get_contents($this->privKeyLocation));
             $success = $this->resource->login($this->username, $key);
             break;
         default:
             throw new ApiInvalidAuthTypeException("Unknown authtype " . $this->authType);
     }
     AppKitLogger::verbose("Login success: %s", $success);
     if (!$success || !is_object($this->resource)) {
         throw new ApiAuthorisationFailedException("SSH auth for user " . $this->username . " failed (using authtype " . $this->authType . ') :' . print_r($this->resource->getErrors(), true));
     }
     $this->connected = true;
 }
 public function submitCommand($cmd_name, array $params, $commandClass = array("Console.ConsoleCommand", "Api"))
 {
     try {
         $user = $this->getContext()->getUser()->getNsmUser();
         $onlySimple = $user->hasTarget('IcingaCommandRestrictions');
         $command = $this->getCommand($cmd_name);
         $string = $this->buildCommandString($command, $params) . "\n";
         if ($onlySimple && !$command["isSimple"]) {
             throw new Exception("Could not send command. Your user isn't allowed to send this command.");
         }
         $this->context->getLoggerManager()->log(sprintf('(%s) %s', $user->user_name, $string), AppKitLogger::COMMAND);
         AppKitLogger::debug("Sending icinga-command %s", $string);
         $cmd = $this->getContext()->getModel($commandClass[0], $commandClass[1], array("command" => "printf", "arguments" => array($string)));
         $cmd->stdoutFile("icinga_pipe");
         $this->consoleContext->exec($cmd);
         if ($cmd->getReturnCode() != '0') {
             throw new Exception("Could not send command. Check if your webserver's user has correct permissions for writing to the command pipe.");
         }
     } catch (Exception $e) {
         $this->context->getLoggerManager()->log("Sending command failed " . $e->getMessage());
         throw $e;
     }
 }
Example #7
0
 /**
  * Binds a PHP variable to a corresponding named or question mark placeholder in the 
  * SQL statement that was use to prepare the statement. Unlike Doctrine_Adapter_Statement_Interface->bindValue(),
  * the variable is bound as a reference and will only be evaluated at the time 
  * that Doctrine_Adapter_Statement_Interface->execute() is called.
  *
  * Most parameters are input parameters, that is, parameters that are 
  * used in a read-only fashion to build up the query. Some drivers support the invocation 
  * of stored procedures that return data as output parameters, and some also as input/output
  * parameters that both send in data and are updated to receive it.
  *
  * @param mixed $param          Parameter identifier. For a prepared statement using named placeholders,
  *                              this will be a parameter name of the form :name. For a prepared statement
  *                              using question mark placeholders, this will be the 1-indexed position of the parameter
  *
  * @param mixed $variable       Name of the PHP variable to bind to the SQL statement parameter.
  *
  * @param integer $type         Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return
  *                              an INOUT parameter from a stored procedure, use the bitwise OR operator to set the
  *                              Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter.
  *
  * @param integer $length       Length of the data type. To indicate that a parameter is an OUT parameter
  *                              from a stored procedure, you must explicitly set the length.
  * @param mixed $driverOptions
  * @return boolean              Returns TRUE on success or FALSE on failure.
  */
 public function bindParam($column, &$variable, $type = null, $length = null, $driverOptions = array())
 {
     AppKitLogger::verbose("Binding %s=>%s", $column, $variable);
     if ($driverOptions || $length) {
         throw new Doctrine_Adapter_Exception('Unsupported parameters:$length, $driverOptions');
     }
     if ($length === null) {
         $oci_length = -1;
     }
     $oci_type = SQLT_CHR;
     switch ($type) {
         case Doctrine_Core::PARAM_STR:
             $oci_type = SQLT_CHR;
             break;
     }
     if (is_integer($column)) {
         $variable_name = ":oci_b_var_{$column}";
     } else {
         $variable_name = $column;
     }
     //print "Binding $variable to $variable_name".PHP_EOL;
     $status = @oci_bind_by_name($this->statement, $variable_name, $variable, $oci_length, $oci_type);
     if ($status === false) {
         $this->handleError();
     }
     return $status;
 }
 /**
  * Writes session data to database tables
  * @param string $id
  * @param mixed $data
  */
 public function sessionWrite($id, &$data)
 {
     $max = ini_get('session.gc_maxlifetime');
     $update = false;
     if (!$max) {
         $max = 1440;
     }
     $date = DateTime::createFromFormat('Y-m-d H:i:s', $this->NsmSession->session_modified);
     $m = md5($data);
     if ($date === false || time() - $date->getTimestamp() >= $max) {
         $update = true;
     }
     if (!$update && $this->NsmSession->session_checksum === $m) {
         return;
     }
     AppKitLogger::verbose("Writing new session information (checksum=%s)", $m);
     $this->NsmSession->session_data = $data;
     $this->NsmSession->session_checksum = $m;
     $this->NsmSession->session_modified = date('Y-m-d H:i:s');
     $this->NsmSession->save();
     AppKitLogger::debug("Write session update: %s", $id);
     AppKitLogger::verbose("Writing new session information successful");
 }
 private function parseDependencies()
 {
     if (!isset($this->view["merge"])) {
         return;
     }
     foreach ($this->view["merge"] as $mergeDependency) {
         $merger = $this->getContext()->getModel("Views.Merger." . ucfirst($mergeDependency["strategy"]) . "Merger", "Api");
         $type = "left";
         if (isset($mergeDependency["type"])) {
             $type = $mergeDependency["type"];
         }
         AppKitLogger::verbose("Merge dependency detected: %s -> %s ", $this->view["name"], $mergeDependency["source"]);
         $merger->setup($mergeDependency["source"], $mergeDependency["field"], $type);
         $this->mergeDependencies[] = $merger;
     }
 }
 public static function applyApiSecurityPrincipals(&$search)
 {
     $user = AgaviContext::getInstance()->getUser()->getNsmUser();
     $hostOnly = true;
     foreach ($search->getResultColumns() as $col) {
         if (stripos($col, 'HOST') !== 0) {
             $hostOnly = false;
         }
     }
     $sarr = $user->getTargetValuesArray();
     AppKitLogger::verbose("TargetValuesArray = %s", var_export($sarr, true));
     $models = $user->getTargets(null, true, true);
     $parts = array("host" => array(), "service" => array(), "other" => array());
     foreach ($models as $model) {
         if ($model->target_type != 'icinga') {
             continue;
         }
         $targetname = $model->get('target_name');
         if (!isset($sarr[$targetname])) {
             continue;
         }
         $to = $model->getTargetObject($targetname);
         if (!self::checkIfTargetAffectsSearch($to, $search, $sarr[$targetname])) {
             continue;
         }
         if (count($sarr[$targetname]) > 0) {
             if ($hostOnly && stripos($targetname, 'IcingaService') === 0) {
                 continue;
             }
             $map = $to->getMapArray($sarr[$targetname]);
             AppKitLogger::verbose("MapArray: %s, %s", $targetname, $map);
         } else {
             $map = $to->getCustomMap();
             AppKitLogger::verbose("CustomMap: %s %s", $targetname, $map);
         }
         if (preg_match("#^icingahost#i", $targetname)) {
             $parts["host"][] = $map;
         } else {
             if (preg_match("#^icingaservice#i", $targetname)) {
                 $parts["service"][] = $map;
             } else {
                 $parts["other"][] = $map;
             }
         }
     }
     $query = "";
     # the following logic is built here:
     # ( <hostcredentials> AND <servicecredentials> ) OR <othercredentials>
     # host
     if (count($parts["host"]) > 0) {
         $hostquery = join(' OR ', $parts["host"]);
         $query = $hostquery;
     }
     # service
     if (count($parts["service"]) > 0) {
         if (!$hostOnly) {
             $servicequery = join(' OR ', $parts["service"]);
             if ($query) {
                 $query = "({$query}) AND ({$servicequery})";
             } else {
                 $query = $servicequery;
             }
         }
     }
     # other
     if (count($parts["other"]) > 0) {
         $otherquery = join(' OR ', $parts["other"]);
         if ($query) {
             $query = "( {$query} ) OR {$otherquery}";
         } else {
             $query = $otherquery;
         }
     }
     if ($query) {
         AppKitLogger::verbose("Apply credential WHERE to query: %s", $query);
         $search->setSearchFilterAppendix("( {$query} )", IcingaApiConstants::SEARCH_AND);
         return true;
     } else {
         return false;
     }
 }
 private function readDataSourceDefinition()
 {
     $tpl = $this->getTemplate();
     AppKitLogger::verbose("Reading data definition from template (data : %s)", $tpl->getTemplateData());
     $source = $tpl->getSection("datasource");
     if (!isset($source["target"])) {
         AppKitLogger::fatal("Invalid template: Can't find datasource target!");
         throw new AgaviException("Invalid template, no datasource target given");
     }
     $target = $source["target"];
     return $target;
 }
Example #12
0
 /**
  * Sets a pref value
  * @param string $key
  * @param mixed $val
  * @param boolean $overwrite
  * @param boolean $blob
  * @return unknown_type
  * @throws AppKitException
  * @author Marius Hein
  */
 public function setPref($key, $val, $overwrite = true, $blob = false)
 {
     $field = "upref_val";
     if ($blob == true) {
         $field = "upref_longval";
     }
     try {
         $pref = $this->getPrefObject($key, false, true);
         // DO NOT OVERWRITE
         if ($overwrite === false) {
             return false;
         }
         Doctrine_Query::create($this->getContext()->getDatabaseConnection("icinga_web"))->update("NsmUserPreference p")->set($field, "?", $val)->where("p.upref_user_id=? and p.upref_key=?", array($this->user_id, $key))->execute();
         if (is_array($pref)) {
             $pref[$field] = $val;
         }
     } catch (AppKitDoctrineException $e) {
         $pref = new NsmUserPreference();
         $pref->upref_key = $key;
         $pref->{$field} = $val;
         $pref->NsmUser = $this;
         $pref->save();
         AppKitLogger::warn("New: Setting %s => %s", $key, $pref->toArray(false));
     }
     NsmUser::$cachedPreferences = array();
     return true;
 }
 /**
  * (non-PHPdoc)
  * @see Doctrine_Query_Abstract::_execute()
  */
 protected function _execute($params)
 {
     if ($this->filterChain->canExecutePost()) {
         $this->filterChain->postQuery($this);
     }
     AppKitLogger::verbose("EXEC %s ", $params);
     return parent::_execute($params);
 }
 /**
  * Updates the simple role data
  * @param NsmRole $role
  * @param AgaviRequestDataHolder $rd
  * @return boolean
  * @author Marius Hein
  */
 public function updateRoleData(NsmRole &$role, AgaviRequestDataHolder &$rd)
 {
     AppKitDoctrineUtil::updateRecordsetFromArray($role, $rd->getParameters(), self::$editableAttributes);
     // Checking the principal
     if (!$role->NsmPrincipal->principal_id) {
         $role->NsmPrincipal->principal_type = NsmPrincipal::TYPE_ROLE;
     }
     if ($role->role_id === null) {
         // insert a new role
         $role->save();
     } else {
         // update role
         $parts = array();
         $params = array();
         foreach ($role as $property => $value) {
             if ($property == "role_id" || !in_array($property, self::$editableAttributes)) {
                 continue;
             }
             if ($value === null) {
                 $parts[] = "{$property} = NULL";
             } else {
                 $parts[] = "{$property} = ? ";
                 $params[] = $value;
             }
         }
         $params[] = $role->role_id;
         $dql = "UPDATE NsmRole SET " . implode(",", $parts) . " WHERE role_id = ?";
         AppKitLogger::warn("Test: %s - %s", $dql, var_export($params, true));
         $query = new Doctrine_Query();
         $query->setConnection(AppKitDoctrineUtil::getConnection());
         $query->parseDqlQuery($dql);
         $query->execute($params);
     }
     return true;
 }
 public function execRead()
 {
     $request = $this->createRequestDescriptor();
     $this->applyModifiers($request);
     $result = null;
     $this->lastQuery = $request;
     $request->autoResolveAliases();
     if (!$this->isCount) {
         AppKitLogger::verbose("Executing non count query (resultType = %s)", $this->resultType);
         $result = $request->execute(NULL, $this->resultType);
     } else {
         AppKitLogger::verbose("Executing count query");
         $result = $request->count();
     }
     AppKitLogger::verbose("Query: %s, \n Result: %s", $request->getSqlQuery(), $result);
     return $result;
 }
 private function fetchDQLViews(DOMXPath $xpath)
 {
     $dqlRoot = $xpath->query('//ae:configuration/node()');
     foreach ($dqlRoot as $node) {
         if ($node->nodeType != XML_ELEMENT_NODE) {
             continue;
         }
         $this->parseDQLPart($node);
     }
     foreach ($this->views as $name => &$vals) {
         if (!$vals["base"]) {
             continue;
         }
         if (!isset($this->views[$vals["base"]])) {
             AppKitLogger::warn("View %s references to unknown base query %s", $name, $vals["base"]);
             continue;
         }
         $base = $this->views[$vals["base"]];
         $vals = AppKitArrayUtil::replaceRecursive($base, $vals);
     }
 }
 public function isValidFilterElement($jsonEl)
 {
     $required = array("label", "value", "operator", "field");
     $valid = true;
     foreach ($required as $type) {
         $valid = $valid && isset($jsonEl[$type]);
         if (!$valid) {
             AppKitLogger::warn("Missing element: {$type} (%s)", $jsonEl);
         }
     }
     if (!$valid) {
         return false;
     }
     $valid = $valid && isset(self::$OPERATOR_TYPES[$jsonEl["operator"]]);
     if (!$valid) {
         AppKitLogger::warn("invalid element %s ", $jsonEl);
     }
     return $valid;
 }
 /**
  * Executes query and return bulk struct
  * @return array
  */
 private function bulkQuery()
 {
     // We want only one specific type
     if ($this->type && array_key_exists($this->type, $this->mapping)) {
         $mappings = array($this->type);
     } else {
         $mappings = array_keys($this->mapping);
     }
     $data = array();
     $count = array();
     AppKitLogger::verbose("Performing bulk query (mappings = %s)", $mappings);
     foreach ($mappings as $mapping) {
         $md = $this->mapping[$mapping];
         $fields = $md['fields'];
         AppKitLogger::verbose("Performing bulk query (current mapping = %s)", $md);
         $search = $this->api->createSearch()->setSearchTarget($md['target'])->setResultColumns(array_values($md['fields']))->setResultType(IcingaApiConstants::RESULT_ARRAY)->setSearchLimit(0, AgaviConfig::get('modules.cronks.search.maximumResults', 200));
         $search_group = $search->createFilterGroup(IcingaApiConstants::SEARCH_OR);
         foreach ($md['search'] as $search_field) {
             $search_group->addFilter($search->createFilter($search_field, $this->query, IcingaApiConstants::MATCH_LIKE));
         }
         $search->setSearchFilter($search_group);
         // Limiting results for security
         IcingaPrincipalTargetTool::applyApiSecurityPrincipals($search);
         $result = $search->fetch();
         AppKitLogger::verbose("Query: %s ", $search->getSqlQuery());
         $count[$mapping] = $result->getResultCount();
         $data[$mapping] = $this->resultToArray($result, $fields, $mapping);
         AppKitLogger::verbose("Result: %s ", $data[$mapping]);
     }
     $new = $this->sortArray($data, $count);
     $sum = array_sum($count);
     AppKitLogger::verbose("Complete search result: %s ", $data);
     return array('resultCount' => array_sum($count), 'resultRows' => $new, 'resultSuccess' => $sum > 0 ? true : false);
 }