/** * The basic node * @static * @param string $nodeName * @param string $nodeLabel * @param bool $isLeaf * @param array $metaData * @param bool $close * @param bool $print * @return void|string */ public static function renderNode($nodeName, $nodeLabel, $isLeaf, $metaData = array(), $close = true, $print = true) { $string = "<tree"; $metaData["filename"] = $nodeName; if (AJXP_Utils::detectXSS($nodeName)) { $metaData["filename"] = "/XSS Detected - Please contact your admin"; } if (!isset($metaData["text"])) { if (AJXP_Utils::detectXSS($nodeLabel)) { $nodeLabel = "XSS Detected - Please contact your admin"; } $metaData["text"] = $nodeLabel; } else { if (AJXP_Utils::detectXSS($metaData["text"])) { $metaData["text"] = "XSS Detected - Please contact your admin"; } } $metaData["is_file"] = $isLeaf ? "true" : "false"; $metaData["ajxp_im_time"] = time(); foreach ($metaData as $key => $value) { if (AJXP_Utils::detectXSS($value)) { $value = "XSS Detected!"; } $value = AJXP_Utils::xmlEntities($value, true); $string .= " {$key}=\"{$value}\""; } if ($close) { $string .= "/>"; } else { $string .= ">"; } return AJXP_XMLWriter::write($string, $print); }
/** * Write text to the log file. * * If write is not allowed because the file is not yet open, the message is buffered until * file becomes available. * * @param String $level Log severity: one of LOG_LEVEL_* (DEBUG,INFO,NOTICE,WARNING,ERROR) * @param String $ip The client ip * @param String $user The user login * @param String $source The source of the message * @param String $prefix The prefix of the message * @param String $message The message to log * @throws Exception * @return void */ public function write2($level, $ip, $user, $source, $prefix, $message, $nodePathes = array()) { if (AJXP_Utils::detectXSS($message)) { $message = "XSS Detected in message!"; } $textMessage = date("m-d-y") . " " . date("H:i:s") . "\t"; $textMessage .= "{$ip}\t" . strtoupper((string) $level) . "\t{$user}\t{$source}\t{$prefix}\t{$message}\n"; if ($this->fileHandle !== false) { if (count($this->stack)) { $this->stackFlush(); } if (fwrite($this->fileHandle, $textMessage) === false) { throw new Exception("There was an error writing to log file ({$this->logFileName})"); } } else { $this->stack[] = $textMessage; } }
public function switchAction($action, $httpVars, $fileVars) { parent::accessPreprocess($action, $httpVars, $fileVars); $xmlBuffer = ""; foreach ($httpVars as $getName => $getValue) { ${$getName} = AJXP_Utils::securePath($getValue); } $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); if (isset($dir) && $action != "upload") { $safeDir = $dir; $dir = SystemTextEncoding::fromUTF8($dir); } // FILTER DIR PAGINATION ANCHOR if (isset($dir) && strstr($dir, "%23") !== false) { $parts = explode("%23", $dir); $dir = $parts[0]; $page = $parts[1]; } if (isset($dest)) { $dest = SystemTextEncoding::fromUTF8($dest); } $mess = ConfService::getMessages(); // Sanitize all httpVars entries foreach ($httpVars as $k => &$value) { $value = AJXP_Utils::sanitize($value, AJXP_SANITIZE_FILENAME); } switch ($action) { //------------------------------------ // ONLINE EDIT //------------------------------------ case "edit_record": $isNew = false; if (isset($record_is_new) && $record_is_new == "true") { $isNew = true; } $tableName = $_POST["table_name"]; $pkName = $_POST["pk_name"]; $query = ""; $arrValues = array(); foreach ($_POST as $key => $value) { if (substr($key, 0, strlen("ajxp_mysql_")) == "ajxp_mysql_") { $newKey = substr($key, strlen("ajxp_mysql_")); $arrValues[$newKey] = $value; } } if ($isNew) { $string = ""; $index = 0; foreach ($arrValues as $k => $v) { // CHECK IF AUTO KEY!!! $string .= "'" . addslashes(SystemTextEncoding::fromUTF8($v)) . "'"; if ($index < count($arrValues) - 1) { $string .= ","; } $index++; } $query = "INSERT INTO {$tableName} VALUES ({$string})"; } else { $string = ""; $index = 0; foreach ($arrValues as $k => $v) { if ($k == $pkName) { $pkValue = $v; } else { $string .= $k . "='" . addslashes(SystemTextEncoding::fromUTF8($v)) . "'"; if ($index < count($arrValues) - 1) { $string .= ","; } } $index++; } $query = "UPDATE {$tableName} SET {$string} WHERE {$pkName}='{$pkValue}'"; } $link = $this->createDbLink(); $res = $this->execQuery($query); $this->closeDbLink($link); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; } break; //------------------------------------ // CHANGE COLUMNS OR CREATE TABLE //------------------------------------ //------------------------------------ // CHANGE COLUMNS OR CREATE TABLE //------------------------------------ case "edit_table": $link = $this->createDbLink(); if (isset($httpVars["current_table"])) { if (isset($httpVars["delete_column"])) { $query = "ALTER TABLE " . $httpVars["current_table"] . " DROP COLUMN " . $httpVars["delete_column"]; $res = $this->execQuery($query); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; } $this->closeDbLink($link); break; } if (isset($httpVars["add_column"])) { $defString = $this->makeColumnDef($httpVars, "add_field_"); $query = "ALTER TABLE " . $httpVars["current_table"] . " ADD COLUMN ({$defString})"; if (isset($httpVars["add_field_pk"]) && $httpVars["add_field_pk"] == "1") { $query .= ", ADD PRIMARY KEY (" . $httpVars["add_field_name"] . ")"; } if (isset($httpVars["add_field_index"]) && $httpVars["add_field_index"] == "1") { $query .= ", ADD INDEX (" . $httpVars["add_field_name"] . ")"; } if (isset($httpVars["add_field_uniq"]) && $httpVars["add_field_uniq"] == "1") { $query .= ", ADD UNIQUE (" . $httpVars["add_field_name"] . ")"; } $res = $this->execQuery($query); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; } $this->closeDbLink($link); break; } } $fields = array("origname", "name", "default", "null", "size", "type", "flags", "pk", "index", "uniq"); $rows = array(); foreach ($httpVars as $k => $val) { $split = explode("_", $k); if (count($split) == 3 && $split[0] == "field" && is_numeric($split[2]) && in_array($split[1], $fields)) { if (!isset($rows[intval($split[2])])) { $rows[intval($split[2])] = array(); } $rows[intval($split[2])][$split[1]] = $val; } else { if (count($split) == 2 && $split[0] == "field" && in_array($split[1], $fields)) { if (!isset($rows[0])) { $rows[0] = array(); } $rows[0][$split[1]] = $val; } } } if (isset($current_table)) { $qMessage = ''; foreach ($rows as $row) { $sizeString = $row["size"] != "" ? "(" . $row["size"] . ")" : ""; $defString = $row["default"] != "" ? " DEFAULT " . $row["default"] . "" : ""; $query = "ALTER TABLE {$current_table} CHANGE " . $row["origname"] . " " . $row["name"] . " " . $row["type"] . $sizeString . $defString . " " . $row["null"]; $res = $this->execQuery(trim($query)); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; $this->closeDbLink($link); break; } else { $qMessage .= $query; $reload_file_list = true; } } $logMessage = $qMessage; } else { if (isset($new_table)) { $fieldsDef = array(); $pks = array(); $indexes = array(); $uniqs = array(); foreach ($rows as $index => $row) { $fieldsDef[] = $this->makeColumnDef($row); // Analyse keys if ($row["pk"] == "1") { $pks[] = $row["name"]; } if ($row["index"] == "1") { $indexes[] = $row["name"]; } if ($row["uniq"] == "1") { $uniqs[] = $row["name"]; } } $fieldsDef = implode(",", $fieldsDef); if (count($pks)) { $fieldsDef .= ",PRIMARY KEY (" . implode(",", $pks) . ")"; } if (count($indexes)) { $fieldsDef .= ",INDEX (" . implode(",", $indexes) . ")"; } if (count($uniqs)) { $fieldsDef .= ",UNIQUE (" . implode(",", $uniqs) . ")"; } $query = "CREATE TABLE {$new_table} ({$fieldsDef})"; $res = $this->execQuery(trim($query)); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; $reload_current_node = true; } } } $this->closeDbLink($link); break; //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ case "delete_table": case "delete_record": $dir = basename($dir); $link = $this->createDbLink(); if (trim($dir) == "") { // ROOT NODE => DROP TABLES $tables = $selection->getFiles(); $query = "DROP TABLE"; foreach ($tables as $index => $tableName) { $tables[$index] = basename($tableName); } $query .= " " . implode(",", $tables); $res = $this->execQuery($query); $reload_current_node = true; } else { // TABLE NODE => DELETE RECORDS $tableName = $dir; $pks = $selection->getFiles(); foreach ($pks as $key => $pkString) { $parts = explode(".", $pkString); array_pop($parts); // remove .pk extension array_shift($parts); // remove record prefix foreach ($parts as $index => $pkPart) { $parts[$index] = str_replace("__", "='", $pkPart) . "'"; } $pks[$key] = "(" . implode(" AND ", $parts) . ")"; } $query = "DELETE FROM {$tableName} WHERE " . implode(" OR ", $pks); $res = $this->execQuery($query); } //AJXP_Exception::errorToXml($res); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; } $this->closeDbLink($link); break; //------------------------------------ // RENOMMER / RENAME //------------------------------------ //------------------------------------ // RENOMMER / RENAME //------------------------------------ case "set_query": $query = $httpVars["query"]; $_SESSION["LAST_SQL_QUERY"] = $query; print "<tree store=\"true\"></tree>"; break; //------------------------------------ // XML LISTING //------------------------------------ //------------------------------------ // XML LISTING //------------------------------------ case "ls": if (!isset($dir) || $dir == "/") { $dir = ""; } $searchMode = $fileListMode = $completeMode = false; if (isset($mode)) { if ($mode == "search") { $searchMode = true; } else { if ($mode == "file_list") { $fileListMode = true; } else { if ($mode == "complete") { $completeMode = true; } } } } $link = $this->createDbLink(); //AJXP_Exception::errorToXml($link); if ($dir == "") { AJXP_XMLWriter::header(); $tables = $this->listTables(); AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="list" switchGridMode="filelist"><column messageString="Table Name" attributeName="ajxp_label" sortType="String"/><column messageString="Byte Size" attributeName="bytesize" sortType="NumberKo"/><column messageString="Count" attributeName="count" sortType="Number"/></columns>'); $icon = $mode == "file_list" ? "sql_images/mimes/ICON_SIZE/table_empty.png" : "sql_images/mimes/ICON_SIZE/table_empty_tree.png"; foreach ($tables as $tableName) { if (AJXP_Utils::detectXSS($tableName)) { $tableName = "XSS Detected!"; $size = 'N/A'; $count = 'N/A'; } else { $size = $this->getSize($tableName); $count = $this->getCount($tableName); } print "<tree is_file=\"0\" text=\"{$tableName}\" filename=\"/{$tableName}\" bytesize=\"{$size}\" count=\"{$count}\" icon=\"{$icon}\" ajxp_mime=\"table\" />"; } print "<tree is_file=\"0\" text=\"Search Results\" ajxp_node=\"true\" filename=\"/ajxpmysqldriver_searchresults\" bytesize=\"-\" count=\"-\" icon=\"search.png\"/>"; AJXP_XMLWriter::close(); } else { $tableName = basename($dir); if (isset($page)) { $currentPage = $page; } else { $currentPage = 1; } $query = "SELECT * FROM {$tableName}"; $searchQuery = false; if ($tableName == "ajxpmysqldriver_searchresults") { if (isset($_SESSION["LAST_SQL_QUERY"])) { $query = $_SESSION["LAST_SQL_QUERY"]; $matches = array(); if (preg_match("/SELECT [\\S, ]* FROM (\\S*).*/i", $query, $matches) !== false) { $tableName = $matches[1]; $searchQuery = true; } else { break; } } else { break; } } if (isset($order_column)) { $query .= " ORDER BY {$order_column} " . strtoupper($order_direction); if (!isset($_SESSION["AJXP_ORDER_DATA"])) { $_SESSION["AJXP_ORDER_DATA"] = array(); } $_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName] = array("column" => $order_column, "dir" => $order_direction); } else { if (isset($_SESSION["AJXP_ORDER_DATA"])) { if (isset($_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName])) { $order_column = $_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName]["column"]; $order_direction = $_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName]["dir"]; $query .= " ORDER BY {$order_column} " . strtoupper($order_direction); } } } try { $result = $this->showRecords($query, $tableName, $currentPage); } catch (AJXP_Exception $ex) { unset($_SESSION["LAST_SQL_QUERY"]); throw $ex; } AJXP_XMLWriter::header(); $blobCols = array(); $columnsString = '<columns switchDisplayMode="list" switchGridMode="grid">'; foreach ($result["COLUMNS"] as $col) { $columnsString .= "<column messageString=\"" . $col["NAME"] . "\" attributeName=\"" . $col["NAME"] . "\" field_name=\"" . $col["NAME"] . "\" field_type=\"" . $col["TYPE"] . "\" field_size=\"" . $col["LENGTH"] . "\" field_flags=\"" . $this->cleanFlagString($col["FLAGS"]) . "\" field_pk=\"" . (preg_match("/primary/", $col["FLAGS"]) ? "1" : "0") . "\" field_null=\"" . (preg_match("/not_null/", $col["FLAGS"]) ? "NOT_NULL" : "NULL") . "\" sortType=\"" . $this->sqlTypeToSortType($col["TYPE"]) . "\" field_default=\"" . $col["DEFAULT"] . "\"/>"; if (stristr($col["TYPE"], "blob") !== false && ($col["FLAGS"] != "" && stristr($col["FLAGS"], "binary"))) { $blobCols[] = $col["NAME"]; } } $columnsString .= '</columns>'; AJXP_XMLWriter::sendFilesListComponentConfig($columnsString); //print '<pagination total="'.$result["TOTAL_PAGES"].'" current="'.$currentPage.'" remote_order="true" currentOrderCol="'.$order_column.'" currentOrderDir="'.$order_direction.'"/>'; if ($result["TOTAL_PAGES"] > 1) { AJXP_XMLWriter::renderPaginationData($count, $currentPage, $result["TOTAL_PAGES"]); } foreach ($result["ROWS"] as $arbitIndex => $row) { print '<tree '; $pkString = ""; foreach ($row as $key => $value) { if (in_array($key, $blobCols)) { $sizeStr = " - NULL"; if (strlen($value)) { $sizeStr = " - " . AJXP_Utils::roundSize(strlen($value)); } print "{$key}=\"BLOB{$sizeStr}\" "; } else { $value = str_replace("\"", "", $value); if (AJXP_Utils::detectXSS($value)) { $value = "Possible XSS Detected - Cannot display value!"; } $value = AJXP_Utils::xmlEntities($value); print $key . '="' . SystemTextEncoding::toUTF8($value) . '" '; if ($result["HAS_PK"] > 0) { if (in_array($key, $result["PK_FIELDS"])) { $pkString .= $key . "__" . $value . "."; } } } } if ($result["HAS_PK"] > 0) { print 'filename="record.' . $pkString . 'pk" '; print 'is_file="1" ajxp_mime="pk"/>'; } else { print 'filename="record_' . $arbitIndex . '.no_pk" '; print 'is_file="1" ajxp_mime="row"/>'; } } AJXP_XMLWriter::close(); } $this->closeDbLink($link); exit(1); break; } if (isset($logMessage) || isset($errorMessage)) { if (AJXP_Utils::detectXSS($logMessage) || AJXP_Utils::detectXSS($errorMessage)) { $xmlBuffer = AJXP_XMLWriter::sendMessage(null, "XSS Detected!", false); } $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if (isset($requireAuth)) { $xmlBuffer .= AJXP_XMLWriter::requireAuth(false); } if (isset($reload_current_node) && $reload_current_node == "true" || isset($reload_file_list)) { $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", "", false); } return $xmlBuffer; }
/** * Write an entry to the log. * * @param String $level Log severity: one of LOG_LEVEL_* (DEBUG,INFO,NOTICE,WARNING,ERROR) * @param String $ip The client ip * @param String $user The user login * @param String $source The source of the message * @param String $prefix The prefix of the message * @param String $message The message to log * @param array $nodesPathes */ public function write2($level, $ip, $user, $source, $prefix, $message, $nodesPathes = array()) { if ($prefix == "Log In" && $message == "context=API") { // Limit the number of logs $test = dibi::query('SELECT [logdate] FROM [ajxp_log] WHERE [user]=%s AND [message]=%s AND [params]=%s ORDER BY [logdate] DESC %lmt %ofs', $user, $prefix, $message, 1, 0); $lastInsert = $test->fetchSingle(); $now = new DateTime('NOW'); if (is_a($lastInsert, "DibiDateTime")) { $lastTimestamp = $lastInsert->getTimestamp(); } else { $lastTimestamp = strtotime($lastInsert); } if ($lastInsert !== false && $now->getTimestamp() - $lastTimestamp < 60 * 60) { // IGNORING, LIMIT API LOGINS TO ONE PER HOUR, OR IT WILL FILL THE LOGS return; } } $files = array(array("dirname" => "", "basename" => "")); if (AJXP_Utils::detectXSS($message)) { $message = "XSS Detected in Message!"; } else { if (count($nodesPathes)) { $files = array(); foreach ($nodesPathes as $path) { $parts = pathinfo($path); $files[] = array("dirname" => $parts["dirname"], "basename" => $parts["basename"]); } } } foreach ($files as $fileDef) { $log_row = array('logdate' => new DateTime('NOW'), 'remote_ip' => $this->inet_ptod($ip), 'severity' => strtoupper((string) $level), 'user' => $user, 'source' => $source, 'message' => $prefix, 'params' => $message, 'repository_id' => ConfService::getInstance()->getContextRepositoryId(), 'device' => $_SERVER['HTTP_USER_AGENT'], 'dirname' => $fileDef["dirname"], 'basename' => $fileDef["basename"]); //we already handle exception for write2 in core.log dibi::query('INSERT INTO [ajxp_log]', $log_row); } }
/** * Write an entry to the log. * * @param String $level Log severity: one of LOG_LEVEL_* (DEBUG,INFO,NOTICE,WARNING,ERROR) * @param String $ip The client ip * @param String $user The user login * @param String $source The source of the message * @param String $prefix The prefix of the message * @param String $message The message to log * */ public function write2($level, $ip, $user, $source, $prefix, $message) { if ($prefix == "Log In" && ($message = "context=API")) { // Limit the number of logs $test = dibi::query('SELECT [logdate] FROM [ajxp_log] WHERE [user]=%s AND [message]=%s AND [params]=%s ORDER BY [logdate] DESC %lmt %ofs', $user, $prefix, $message, 1, 0); $lastInsert = $test->fetchSingle(); $now = new DateTime('NOW'); if (is_a($lastInsert, "DibiDateTime")) { $lastTimestamp = $lastInsert->getTimestamp(); } else { $lastTimestamp = strtotime($lastInsert); } if ($lastInsert !== false && $now->getTimestamp() - $lastTimestamp < 60 * 60) { // IGNORING, LIMIT API LOGINS TO ONE PER HOUR, OR IT WILL FILL THE LOGS return; } } if (AJXP_Utils::detectXSS($message)) { $message = "XSS Detected in Message!"; } $log_row = array('logdate' => new DateTime('NOW'), 'remote_ip' => $this->inet_ptod($ip), 'severity' => strtoupper((string) $level), 'user' => $user, 'source' => $source, 'message' => $prefix, 'params' => $message); //we already handle exception for write2 in core.log dibi::query('INSERT INTO [ajxp_log]', $log_row); }