From 0698d99146e1a6b7a24ea087c63c29a3c846bd03 Mon Sep 17 00:00:00 2001 From: Travis Rowland Date: Wed, 6 May 2015 21:24:26 -0700 Subject: [PATCH 01/17] Took inventory of services, made a few changes in preparation for Medieval Engineers -- refers to #48 --- app/Config/Schema/sqlUpdates.sql | 1 + app/Config/bootstrap.php | 133 +- app/Config/hecpanelconfig.php.default | 4 +- .../Console/Command/SeServerShell.php | 798 ++++---- .../Component/SEServerComponent.php | 1753 ++++++++--------- 5 files changed, 1408 insertions(+), 1281 deletions(-) create mode 100644 app/Config/Schema/sqlUpdates.sql diff --git a/app/Config/Schema/sqlUpdates.sql b/app/Config/Schema/sqlUpdates.sql new file mode 100644 index 0000000..6d28bdb --- /dev/null +++ b/app/Config/Schema/sqlUpdates.sql @@ -0,0 +1 @@ +ALTER TABLE `instances` ADD `game_id` INT NOT NULL AFTER `host_server_id`; \ No newline at end of file diff --git a/app/Config/bootstrap.php b/app/Config/bootstrap.php index c5c8a48..4fd73aa 100644 --- a/app/Config/bootstrap.php +++ b/app/Config/bootstrap.php @@ -106,8 +106,139 @@ Configure::load('hecpanelconfig'); Configure::write(APP_CONFIG_SCOPE . '.App.apiVersion', 'v1'); +// TODO: Move to config file in Instances plugin +Configure::write(APP_CONFIG_SCOPE . '.Instances.games', array( + '1' => array( + 'name' => 'Space Engineers', + 'folder' => 'SPACE_ENGINEERS', + 'config' => 'SpaceEngineers-Dedicated.cfg', + 'configOptions' => array( + 'SessionSettings' => array( + 'gameModes' => array( + 'Survival' => 'Survival', + 'Creative' => 'Creative' + ), + 'onlineModes' => array( + 'PUBLIC' => 'PUBLIC', + 'PRIVATE' => 'PRIVATE' + ), + 'environmentHostilities' => array( + 'SAFE' => 'SAFE', + 'NORMAL' => 'NORMAL', + 'CATACLYSM' => 'CATACLYSM', + 'CATACLYSM_UNREAL' => 'CATACLYSM_UNREAL' + ), + 'autoHealings' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'enableCopyPastes' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'autoSaves' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'weaponsEnableds' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'showPlayerNamesOnHuds' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'thrusterDamages' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'cargoShipsEnableds' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'enableSpectators' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'removeTrashes' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'respawnShipDeletes' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'resetOwnerships' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'realisticSounds' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'clientCanSaves' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'permanentDeaths' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'pauseGameWhenEmpties' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'ignoreLastSessions' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'destructibleBlocks' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'enableIngameScripts' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'enableOxygens' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'scenarioSubtypes' => array( + 'EasyStart1' => 'EasyStart1', + 'EasyStart2' => 'EasyStart2', + 'Survival' => 'Survival', + 'CrashedRedShip' => 'CrashedRedShip', + 'TwoPlatforms' => 'TwoPlatforms', + 'Asteroids' => 'Asteroids', + 'EmptyWorld' => 'EmptyWorld' + ), + 'inventorySizeMultipliers' => array_combine(range(1, 100, 1), range(1, 100, 1)), // 1-100, increment of 1 + 'assemblerSpeedMultipliers' => array_combine(range(1, 100, 1), range(1, 100, 1)), // 1-100, increment of 1 + 'assemblerEfficiencyMultipliers' => array_combine(range(1, 100, 1), range(1, 100, 1)), // 1-100, increment of 1 + 'refinerySpeedMultipliers' => array_combine(range(1, 100, 1), range(1, 100, 1)), // 1-100, increment of 1 + 'maxPlayers' => array_combine(range(1, 100, 1), range(1, 100, 1)), // 1-100, increment of 1 + 'maxFloatingObjects' => array_combine(range(0, 500, 1), range(0, 500, 1)), // 0-500, increment of 1 + 'worldSizeKms' => array_combine(range(0, 500, 1), range(0, 500, 1)), // 0-500, increment of 1 + 'welderSpeedMultipliers' => array_combine(range(1, 100, 1), range(1, 100, 1)), // 1-100, increment of 1 + 'grinderSpeedMultipliers' => array_combine(range(1, 100, 1), range(1, 100, 1)), // 1-100, increment of 1 + 'hackSpeedMultipliers' => array_combine(range(1, 100, 1), range(1, 100, 1)), // 1-100, increment of 1 + 'autoSaveInMinutes' => array_combine(range(15, 90, 15), range(15, 90, 15)), // 15-90, increment of 15 + 'spawnShipTimeMultipliers' => array_combine(range(0, 20, 1), range(0, 20, 1)), // 0-20, increment of 1 + 'asteroidAmounts' => array_combine(range(0, 10, 1), range(0, 10, 1)), // 0-10, increment of 1 + 'proceduralDensities' => array_combine(range(0, 1, .05), range(0, 1, .05)), // 0-1, increment of .05 + 'viewDistances' => array_combine(range(1000, 30000, 1000), range(1000, 30000, 1000)), // 1000-30000, increment of 1000 + ), + ) + ), + '2' => array( + 'name' => 'Medieval Engineers', + 'folder' => 'MEDIEVAL_ENGINEERS', + 'config' => 'MedievalEngineers-Dedicated.cfg', + ), +)); + Configure::write(APP_CONFIG_SCOPE . '.Instances.serverArchiveDirectory', 'SERVER_ARCHIVES'); -Configure::write(APP_CONFIG_SCOPE . '.Instances.serverScriptsDirectory', 'SERVER_SCRIPTS'); Configure::write(APP_CONFIG_SCOPE . '.Instances.serverBinariesDirectory', 'SERVER_BINARIES'); Configure::write('Bootstrap.formButtonStyle', array( diff --git a/app/Config/hecpanelconfig.php.default b/app/Config/hecpanelconfig.php.default index d38a9a7..15e84bf 100644 --- a/app/Config/hecpanelconfig.php.default +++ b/app/Config/hecpanelconfig.php.default @@ -1,4 +1,5 @@ __out('hi'); - } - - public function initialize() { - // Load Models - $this->Instance = ClassRegistry::init('Instances.Instance'); - $this->Instance->recursive = -1; - $this->InstanceType = ClassRegistry::init('Instances.InstanceType'); - $this->InstanceType->recursive = -1; - $this->InstanceProfile = ClassRegistry::init('Instances.InstanceProfile'); - $this->InstanceProfile->recursive = -1; - $this->Configuration = ClassRegistry::init('Config.Configuration'); - $this->Configuration->recursive = -1; - $this->MemoryLog = ClassRegistry::init('Instances.MemoryLog'); - $this->MemoryLog->recursive = -1; - $this->HostServer = ClassRegistry::init('Instances.HostServer'); - $this->HostServer->recursive = -1; - $this->User = ClassRegistry::init('User'); - $this->User->recursive = -1; - $this->CommandQueue = ClassRegistry::init('Instances.CommandQueue'); - $this->CommandQueue->recursive = -1; - // Determine host server - $this->__determineHostServer(); - // Set config - if (!$this->serverBaseDirectory) { - $this->serverBaseDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverBaseDirectory') . DS . Configure::read(APP_CONFIG_SCOPE . '.App.environment'); - } - if (!$this->serverScriptsDirectory) { - $this->serverScriptsDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverScriptsDirectory'); - } - if (!$this->serverDataDirectory) { - $this->serverDataDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverDataDirectory'); - } - if (!$this->serverBinariesDirectory) { - $this->serverBinariesDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverBinariesDirectory'); - } - if (!$this->sourceBinariesDirectory) { - $this->sourceBinariesDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.sourceBinariesDirectory'); - } - if (!$this->backupDirectory) { - $this->backupDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.backupDirectory'); - } - if (!$this->binariesLastUpdated) { - $this->binariesLastUpdated = Cache::read(APP_CONFIG_SCOPE . '.Instances.binariesLastUpdated', 'month'); - } - if (!$this->serverDataSkeletonDirectory) { - $this->serverDataSkeletonDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverDataSkeletonDirectory'); - } - } - - public function cron() { - //$this->__out('Cron initiated.'); - $queuedCommands = $this->__getQueuedCommands(); - $this->__executeCommands($queuedCommands); - $this->__markCommandsAsExecuted($queuedCommands); - $this->__disableNonRecurringCommands($queuedCommands); - $this->__out('Cron completed.'); - } - - private function __getQueuedCommands() { - $queuedCommands = $this->CommandQueue->find('all', array( - 'conditions' => array( - 'CommandQueue.is_enabled', - 'or' => array( - 'CommandQueue.host_server_id IS NULL', - array( - 'CommandQueue.host_server_id' => $this->hostServer['HostServer']['id'], - 'or' => array( - 'CommandQueue.last_executed IS NULL', - array( - 'CommandQueue.is_once_per_day', - 'TIMESTAMP(CURDATE(), CommandQueue.time) < NOW()', - 'TIMESTAMP(CURDATE(), CommandQueue.time) > CommandQueue.last_executed', - ), - array( - 'CommandQueue.is_once_per_day' => '0', - 'CommandQueue.time', - 'SUBTIME(NOW(), CommandQueue.time) > CommandQueue.last_executed', - ), - array( - 'CommandQueue.is_once_per_day' => '0', - 'CommandQueue.time' => '00:00:00', - ) - ), - ), - ) - ) - ) - ); - //$this->__out($this->CommandQueue->getLastQuery());die; - $this->__out('Get queued commands:', $queuedCommands); - return $queuedCommands; - } - - private function __executeCommands($commands) { - $commandsToExecute = Hash::extract($commands, '{n}.CommandQueue.command'); - $this->__out('Execute commands:', $commandsToExecute); - foreach ($commandsToExecute as $command) { - $this->host($command); - } - return $commandsToExecute; - } - - private function __markCommandsAsExecuted($commands) { - $executedCommandIds = Hash::extract($commands, '{n}.CommandQueue.id'); - $this->__out('Mark commands as executed:', $executedCommandIds); - $this->CommandQueue->updateAll( - array( - 'CommandQueue.last_executed' => "NOW()", - 'CommandQueue.last_executed_host_server_id' => "'" . $this->hostServer['HostServer']['id'] . "'" - ), array( - 'CommandQueue.id' => $executedCommandIds - ) - ); - return $executedCommandIds; - } - - private function __disableNonRecurringCommands($commands) { - $nonRecurringCommandIds = array_keys(array_diff(Hash::combine($commands, '{n}.CommandQueue.id', '{n}.CommandQueue.is_recurring'), array(true))); - $this->__out('Disable non-recurring commands:', $nonRecurringCommandIds); - $this->CommandQueue->updateAll( - array( - 'CommandQueue.is_enabled' => NULL, - ), array( - 'CommandQueue.id' => $nonRecurringCommandIds - ) - ); - return $nonRecurringCommandIds; - } - - private function __determineHostServer() { - // Determine this host - $this->hostServer = $this->HostServer->findByServername(Configure::read(APP_CONFIG_SCOPE . '.App.servername')); - } - - public function checkForUpdates() { - $this->__out('Checking for updates:', 'Started'); - $dedicatedServerExeStats = stat(Configure::read(APP_CONFIG_SCOPE . '.Instances.sourceBinariesDirectory') . DS . 'DedicatedServer64\\SpaceEngineersDedicated.exe'); - // TODO: MD5 Checksum of directory? - $lastUpdated = $dedicatedServerExeStats[9]; - if ($this->binariesLastUpdated != $lastUpdated) { - $this->__out('Update found.'); - $this->binariesLastUpdated = $lastUpdated; - $this->updateAll(); - return; - } - $this->__out('No updates found.'); - } - - public function updateAll() { - Cache::write(APP_CONFIG_SCOPE . '.App.maintenanceMode', true, 'hour'); - // Ensure server list is set - $this->__setServerList(); - // Backup servers - //$this->backupAll(); - // Stop servers - $this->stopAll(); - // Update servers - $this->updateBinaries(); - // Cycle servers - $this->cycleAll(); - Cache::delete(APP_CONFIG_SCOPE . '.App.maintenanceMode', 'hour'); - $this->__out('Update process completed.'); - } - - public function backupAll() { - $this->__out('Backing up servers.'); - // Backup servers - passthru('robocopy "' . $this->serverDataDirectory . '" "' . $this->backupDirectory . '" /MIR'); - $this->__out('Server backup completed.'); - } - - public function updateBinaries() { - $this->__out('Updating server binaries.'); - // Get updated server binaries - passthru('robocopy "' . $this->sourceBinariesDirectory . '" "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '" /MIR'); - // Update last modified date - $this->__saveLastUpdated(); - $this->__out('Server binaries updated.'); - } - - private function __saveLastUpdated() { - // Set binaries last updated - Cache::write(APP_CONFIG_SCOPE . '.Instances.binariesLastUpdated', $this->binariesLastUpdated, 'month'); - } - - public function stopAll() { - $this->__out('Stopping all server instances.'); - // Ensure server list is set - $this->__setServerList(); - // Stop main server, force kill - $this->stop('SpaceEngineersDedicated', true); - // Stop each server force kill - foreach ($this->instances as $server) { - $this->stop($server, true); - } - $this->__out('All server instances stopped.'); - } - - public function stop($instanceId, $forced = false) { - if ($this->processState($instanceId) == 'Stopped') { - return $this->__out($instanceId . ' is already stopped.'); - } - // Stop server gracefully - passthru('taskkill /IM ' . $instanceId . '.exe'); - $this->__out($instanceId . ' was sent a graceful termination signal.'); - if ($forced) { - // Force kill server if still running - passthru('taskkill /IM ' . $instanceId . '.exe /F'); - $this->__out($instanceId . ' was sent a forceful termination signal.'); - } - } - - public function cycleAll() { - $this->__out('Cycling all servers.'); - // Ensure server list is set - $this->__setServerList(); - // Cycle each server - foreach ($this->instances as $server) { - // Update each server exe, stop server to ensure binary can copy properly - $this->cycle($server); - } - $this->__out('All servers cycled.'); - } - - public function cycle($instanceId) { - // Check if instance data exists, if not then exit - if (!$this->__verifyInstanceExistence($instanceId)) { - return $this->__out($instanceId . ' data directory does not exist.'); - } - // Backup the server - $this->backup($instanceId); - // Stop server, force kill - $this->stop($instanceId, true); - // Update the server - $this->update($instanceId); - // Start the server - $this->start($instanceId); - $this->__out($instanceId . ' is cycled.'); - } - - public function startAll() { - $this->__out('Starting all servers.'); - // Ensure server list is set - $this->__setServerList(); - // Start each server - foreach ($this->instances as $server) { - $this->start($server); - } - $this->__out('All servers started.'); - } - - public function start($instanceId) { - if ($this->processState($instanceId) != 'Stopped') { - return $this->__out($instanceId . ' is already started.'); - } - // Check if instance data exists, if not then exit - if (!$this->__verifyInstanceExistence($instanceId)) { - return $this->__out($instanceId . ' data directory does not exist.'); - } - // Execute server binary - passthru('start /d "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . DS . 'DedicatedServer64" ' . $instanceId . '.exe -noconsole -path "' . $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . DS . '"'); - $this->__out($instanceId . ' is starting up.'); - } - - public function restartAll() { - $this->__out('Restarting all servers.'); - // Ensure server list is set - $this->__setServerList(); - // Stop all servers - $this->stopAll(); - // Start all servers - $this->startAll(); - $this->__out('All servers restarted.'); - } - - public function backup($instanceId) { - // Copy current world saves to user backup directory - passthru('robocopy "' . $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\Saves" "' . $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\Backup" /MIR'); - $this->__out($instanceId . ' is backed up.'); - } - - public function update($instanceId) { - // Delete server exe - passthru('DEL "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '\\DedicatedServer64\\' . $instanceId . '.exe"'); - // Copy new server exe - passthru('COPY "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '\\DedicatedServer64\\SpaceEngineersDedicated.exe" "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '\\DedicatedServer64\\' . $instanceId . '.exe"'); - $this->__out($instanceId . ' exe is updated.'); - } - - private function __setServerList() { - if (empty($this->instances)) { - $this->instances = array_keys( - $this->Instance->find('list', array( - 'conditions' => array( - 'Instance.host_server_id' => $this->hostServer['HostServer']['id'] - ) - )) - ); - } - } - - public function processState($instanceId) { - if ($instanceId) { - // find tasks matching - $searchPattern = '~(' . substr($instanceId, 0, 23) . ')~i'; - - // get tasklist - $taskList = array(); - exec("tasklist 2>NUL", $taskList); - - // Search through tasklist - foreach ($taskList AS $taskLine) { - if (preg_match($searchPattern, $taskLine, $out)) { - //echo "=> Detected: " . $out[1] . "\n Sending term signal!\n"; - //exec("taskkill /F /IM " . $out[1] . ".exe 2>NUL"); - $taskLineArray = array_values(array_diff(explode(' ', $taskLine), array(''))); - //$memoryUsage = $taskLineArray[4]; - $this->__out($taskLineArray[4] . $taskLineArray[5]); - return $taskLineArray[4] . $taskLineArray[5]; - } - } - } - $this->__out('Stopped'); - return 'Stopped'; - } - - private function __out() { - // Get function arguments - $args = func_get_args(); - if (Configure::read('debug') > 0) { - debug($args); - } - if (isset($args[1]) && empty($args[1])) { - return; - } - CakeLog::write('se_server_shell', json_encode($args)); - } - - // Pass-through function to handle server actions - private function host($action) { - // Get function arguments - $args = func_get_args(); - // Shift off the first argument because that is the function - array_shift($args); - // Call the desired function - return call_user_func_array(array($this, $action), $args); - } - - private function readServer($instanceId) { - $this->Instance->recursive = 1; - return $this->Instance->findById($instanceId); - } - - private function __verifyInstanceExistence($instanceId) { - $userDirExists = file_exists($this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username']); - $instanceDirExists = file_exists($this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId); - // Check if user dir exists - if (!$userDirExists) { - return false; - } - // Check if instance dir exists - if (!$instanceDirExists) { - return false; - } - return true; - } + // Config variables + public $serverBaseDirectory = null; + public $serverDataDirectory = null; + public $serverBinariesDirectory = null; + public $sourceBinariesDirectory = null; + public $backupDirectory = null; + public $binariesLastUpdated = null; + // Instance model + private $Instance = null; + // Instance Type model + private $InstanceType = null; + // Instance Profile model + private $InstanceProfile = null; + // Configuration model + private $Configuration = null; + // MemoryLog model + private $MemoryLog = null; + // HostServer model + private $HostServer = null; + // User model + private $User = null; + // CommandQueue model + private $CommandQueue = null; + // Instance list + private $instances = array(); + // This host server + private $hostServer = array(); + + public function main() { + // TODO: Put usage here + $this->__out('hi'); + } + + public function initialize() { + // Load Models + $this->Instance = ClassRegistry::init('Instances.Instance'); + $this->Instance->recursive = -1; + $this->InstanceType = ClassRegistry::init('Instances.InstanceType'); + $this->InstanceType->recursive = -1; + $this->InstanceProfile = ClassRegistry::init('Instances.InstanceProfile'); + $this->InstanceProfile->recursive = -1; + $this->Configuration = ClassRegistry::init('Config.Configuration'); + $this->Configuration->recursive = -1; + $this->MemoryLog = ClassRegistry::init('Instances.MemoryLog'); + $this->MemoryLog->recursive = -1; + $this->HostServer = ClassRegistry::init('Instances.HostServer'); + $this->HostServer->recursive = -1; + $this->User = ClassRegistry::init('User'); + $this->User->recursive = -1; + $this->CommandQueue = ClassRegistry::init('Instances.CommandQueue'); + $this->CommandQueue->recursive = -1; + // Determine host server + $this->__determineHostServer(); + // Set config + if (!$this->serverBaseDirectory) { + $this->serverBaseDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverBaseDirectory') . DS . Configure::read(APP_CONFIG_SCOPE . '.App.environment'); + } + if (!$this->serverDataDirectory) { + $this->serverDataDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverDataDirectory'); + } + if (!$this->serverBinariesDirectory) { + $this->serverBinariesDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverBinariesDirectory'); + } + if (!$this->sourceBinariesDirectory) { + $this->sourceBinariesDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.sourceBinariesDirectory'); + } + if (!$this->backupDirectory) { + $this->backupDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.backupDirectory'); + } + if (!$this->binariesLastUpdated) { + $this->binariesLastUpdated = Cache::read(APP_CONFIG_SCOPE . '.Instances.binariesLastUpdated', 'month'); + } + } + + public function cron() { + //$this->__out('Cron initiated.'); + $queuedCommands = $this->__getQueuedCommands(); + $this->__executeCommands($queuedCommands); + $this->__markCommandsAsExecuted($queuedCommands); + $this->__disableNonRecurringCommands($queuedCommands); + $this->__out('Cron completed.'); + } + + private function __getQueuedCommands() { + $queuedCommands = $this->CommandQueue->find('all', array( + 'conditions' => array( + 'CommandQueue.is_enabled', + 'or' => array( + 'CommandQueue.host_server_id IS NULL', + array( + 'CommandQueue.host_server_id' => $this->hostServer['HostServer']['id'], + 'or' => array( + 'CommandQueue.last_executed IS NULL', + array( + 'CommandQueue.is_once_per_day', + 'TIMESTAMP(CURDATE(), CommandQueue.time) < NOW()', + 'TIMESTAMP(CURDATE(), CommandQueue.time) > CommandQueue.last_executed', + ), + array( + 'CommandQueue.is_once_per_day' => '0', + 'CommandQueue.time', + 'SUBTIME(NOW(), CommandQueue.time) > CommandQueue.last_executed', + ), + array( + 'CommandQueue.is_once_per_day' => '0', + 'CommandQueue.time' => '00:00:00', + ) + ), + ), + ) + ) + ) + ); + //$this->__out($this->CommandQueue->getLastQuery());die; + $this->__out('Get queued commands:', $queuedCommands); + return $queuedCommands; + } + + private function __executeCommands($commands) { + $commandsToExecute = Hash::extract($commands, '{n}.CommandQueue.command'); + $this->__out('Execute commands:', $commandsToExecute); + foreach ($commandsToExecute as $command) { + $this->host($command); + } + return $commandsToExecute; + } + + private function __markCommandsAsExecuted($commands) { + $executedCommandIds = Hash::extract($commands, '{n}.CommandQueue.id'); + $this->__out('Mark commands as executed:', $executedCommandIds); + $this->CommandQueue->updateAll( + array( + 'CommandQueue.last_executed' => "NOW()", + 'CommandQueue.last_executed_host_server_id' => "'" . $this->hostServer['HostServer']['id'] . "'" + ), array( + 'CommandQueue.id' => $executedCommandIds + ) + ); + return $executedCommandIds; + } + + private function __disableNonRecurringCommands($commands) { + $nonRecurringCommandIds = array_keys(array_diff(Hash::combine($commands, '{n}.CommandQueue.id', '{n}.CommandQueue.is_recurring'), array(true))); + $this->__out('Disable non-recurring commands:', $nonRecurringCommandIds); + $this->CommandQueue->updateAll( + array( + 'CommandQueue.is_enabled' => NULL, + ), array( + 'CommandQueue.id' => $nonRecurringCommandIds + ) + ); + return $nonRecurringCommandIds; + } + + private function __determineHostServer() { + // Determine this host + $this->hostServer = $this->HostServer->findByServername(Configure::read(APP_CONFIG_SCOPE . '.App.servername')); + } + + // TODO: Medieval Engineers + public function checkForUpdates() { + $this->__out('Checking for updates:', 'Started'); + $dedicatedServerExeStats = stat(Configure::read(APP_CONFIG_SCOPE . '.Instances.sourceBinariesDirectory') . DS . 'DedicatedServer64\\SpaceEngineersDedicated.exe'); + // TODO: MD5 Checksum of directory? + $lastUpdated = $dedicatedServerExeStats[9]; + if ($this->binariesLastUpdated != $lastUpdated) { + $this->__out('Update found.'); + $this->binariesLastUpdated = $lastUpdated; + $this->updateAll(); + return; + } + $this->__out('No updates found.'); + } + + public function updateAll() { + Cache::write(APP_CONFIG_SCOPE . '.App.maintenanceMode', true, 'hour'); + // Ensure server list is set + $this->__setServerList(); + // Backup servers + //$this->backupAll(); + // Stop servers + $this->stopAll(); + // Update servers + $this->updateBinaries(); + // Cycle servers + $this->cycleAll(); + Cache::delete(APP_CONFIG_SCOPE . '.App.maintenanceMode', 'hour'); + $this->__out('Update process completed.'); + } + + //TODO: Implement this in $this->updateAll() + public function backupAll() { + $this->__out('Backing up servers.'); + // Backup servers + passthru('robocopy "' . $this->serverDataDirectory . '" "' . $this->backupDirectory . '" /MIR'); + $this->__out('Server backup completed.'); + } + + // TODO: Medieval Engineers + public function updateBinaries() { + $this->__out('Updating server binaries.'); + // Get updated server binaries + passthru('robocopy "' . $this->sourceBinariesDirectory . '" "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '" /MIR'); + // Update last modified date + $this->__saveLastUpdated(); + $this->__out('Server binaries updated.'); + } + + // TODO: Medieval Engineers + private function __saveLastUpdated() { + // Set binaries last updated + Cache::write(APP_CONFIG_SCOPE . '.Instances.binariesLastUpdated', $this->binariesLastUpdated, 'month'); + } + + public function stopAll() { + $this->__out('Stopping all server instances.'); + // Ensure server list is set + $this->__setServerList(); + // Stop main server, force kill + // TODO: Medieval Engineers + $this->stop('SpaceEngineersDedicated', true); + // Stop each server force kill + foreach ($this->instances as $server) { + $this->stop($server, true); + } + $this->__out('All server instances stopped.'); + } + + public function stop($instanceId, $forced = false) { + if ($this->processState($instanceId) == 'Stopped') { + return $this->__out($instanceId . ' is already stopped.'); + } + // Stop server gracefully + passthru('taskkill /IM ' . $instanceId . '.exe'); + $this->__out($instanceId . ' was sent a graceful termination signal.'); + if ($forced) { + // Force kill server if still running + passthru('taskkill /IM ' . $instanceId . '.exe /F'); + $this->__out($instanceId . ' was sent a forceful termination signal.'); + } + } + + public function cycleAll() { + $this->__out('Cycling all servers.'); + // Ensure server list is set + $this->__setServerList(); + // Cycle each server + foreach ($this->instances as $server) { + // Update each server exe, stop server to ensure binary can copy properly + $this->cycle($server); + } + $this->__out('All servers cycled.'); + } + + public function cycle($instanceId) { + // Check if instance data exists, if not then exit + if (!$this->__verifyInstanceExistence($instanceId)) { + return $this->__out($instanceId . ' data directory does not exist.'); + } + // Backup the server + $this->backup($instanceId); + // Stop server, force kill + $this->stop($instanceId, true); + // Update the server + $this->update($instanceId); + // Start the server + $this->start($instanceId); + $this->__out($instanceId . ' is cycled.'); + } + + public function startAll() { + $this->__out('Starting all servers.'); + // Ensure server list is set + $this->__setServerList(); + // Start each server + foreach ($this->instances as $server) { + $this->start($server); + } + $this->__out('All servers started.'); + } + + public function start($instanceId) { + if ($this->processState($instanceId) != 'Stopped') { + return $this->__out($instanceId . ' is already started.'); + } + // Check if instance data exists, if not then exit + if (!$this->__verifyInstanceExistence($instanceId)) { + return $this->__out($instanceId . ' data directory does not exist.'); + } + // Execute server binary + // TODO: Medieval Engineers + passthru('start /d "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . DS . 'DedicatedServer64" ' . $instanceId . '.exe -noconsole -path "' . $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . DS . '"'); + $this->__out($instanceId . ' is starting up.'); + } + + public function restartAll() { + $this->__out('Restarting all servers.'); + // Ensure server list is set + $this->__setServerList(); + // Stop all servers + $this->stopAll(); + // Start all servers + $this->startAll(); + $this->__out('All servers restarted.'); + } + + public function backup($instanceId) { + // Copy current world saves to user backup directory + passthru('robocopy "' . $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\Saves" "' . $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\Backup" /MIR'); + $this->__out($instanceId . ' is backed up.'); + } + + // TODO: Medieval Engineers + public function update($instanceId) { + // Delete server exe + passthru('DEL "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '\\DedicatedServer64\\' . $instanceId . '.exe"'); + // Copy new server exe + passthru('COPY "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '\\DedicatedServer64\\SpaceEngineersDedicated.exe" "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '\\DedicatedServer64\\' . $instanceId . '.exe"'); + $this->__out($instanceId . ' exe is updated.'); + } + + private function __setServerList() { + if (empty($this->instances)) { + $this->instances = array_keys( + $this->Instance->find('list', array( + 'conditions' => array( + 'Instance.host_server_id' => $this->hostServer['HostServer']['id'] + ) + )) + ); + } + } + + public function processState($instanceId) { + if ($instanceId) { + // find tasks matching + $searchPattern = '~(' . substr($instanceId, 0, 23) . ')~i'; + + // get tasklist + $taskList = array(); + exec("tasklist 2>NUL", $taskList); + + // Search through tasklist + foreach ($taskList AS $taskLine) { + if (preg_match($searchPattern, $taskLine, $out)) { + //echo "=> Detected: " . $out[1] . "\n Sending term signal!\n"; + //exec("taskkill /F /IM " . $out[1] . ".exe 2>NUL"); + $taskLineArray = array_values(array_diff(explode(' ', $taskLine), array(''))); + //$memoryUsage = $taskLineArray[4]; + $this->__out($taskLineArray[4] . $taskLineArray[5]); + return $taskLineArray[4] . $taskLineArray[5]; + } + } + } + $this->__out('Stopped'); + return 'Stopped'; + } + + private function __out() { + // Get function arguments + $args = func_get_args(); + if (Configure::read('debug') > 0) { + debug($args); + } + if (isset($args[1]) && empty($args[1])) { + return; + } + CakeLog::write('se_server_shell', json_encode($args)); + } + + // Pass-through function to handle server actions + private function host($action) { + // Get function arguments + $args = func_get_args(); + // Shift off the first argument because that is the function + array_shift($args); + // Call the desired function + return call_user_func_array(array($this, $action), $args); + } + + private function readServer($instanceId) { + $this->Instance->recursive = 1; + return $this->Instance->findById($instanceId); + } + + private function __verifyInstanceExistence($instanceId) { + $userDirExists = file_exists($this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username']); + $instanceDirExists = file_exists($this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId); + // Check if user dir exists + if (!$userDirExists) { + return false; + } + // Check if instance dir exists + if (!$instanceDirExists) { + return false; + } + return true; + } } diff --git a/app/Plugin/Instances/Controller/Component/SEServerComponent.php b/app/Plugin/Instances/Controller/Component/SEServerComponent.php index 837aa50..3216e76 100644 --- a/app/Plugin/Instances/Controller/Component/SEServerComponent.php +++ b/app/Plugin/Instances/Controller/Component/SEServerComponent.php @@ -1,4 +1,5 @@ array( - 'gameModes' => array( - 'Survival' => 'Survival', - 'Creative' => 'Creative' - ), - 'onlineModes' => array( - 'PUBLIC' => 'PUBLIC', - 'PRIVATE' => 'PRIVATE' - ), - 'environmentHostilities' => array( - 'SAFE' => 'SAFE', - 'NORMAL' => 'NORMAL', - 'CATACLYSM' => 'CATACLYSM', - 'CATACLYSM_UNREAL' => 'CATACLYSM_UNREAL' - ), - 'autoHealings' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'enableCopyPastes' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'autoSaves' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'weaponsEnableds' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'showPlayerNamesOnHuds' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'thrusterDamages' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'cargoShipsEnableds' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'enableSpectators' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'removeTrashes' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'respawnShipDeletes' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'resetOwnerships' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'realisticSounds' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'clientCanSaves' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'permanentDeaths' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'pauseGameWhenEmpties' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'ignoreLastSessions' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'destructibleBlocks' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'enableIngameScripts' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'enableOxygens' => array( - 'true' => 'true', - 'false' => 'false' - ), - 'scenarioSubtypes' => array( - 'EasyStart1' => 'EasyStart1', - 'EasyStart2' => 'EasyStart2', - 'Survival' => 'Survival', - 'CrashedRedShip' => 'CrashedRedShip', - 'TwoPlatforms' => 'TwoPlatforms', - 'Asteroids' => 'Asteroids', - 'EmptyWorld' => 'EmptyWorld' - ), - ), - ); - // Command options for form - public $remoteCommands = array( - 'commands' => array( - 'backupAll' => '[backupAll] Backup all server instances', - 'checkForUpdates' => '[checkForUpdates] Check for Space Engineers updates', - 'cycleAll' => '[cycleAll] Cycle all server instances', - 'restartAll' => '[restartAll] Restart all server instances', - 'startAll' => '[startAll] Start all server instances', - 'stopAll' => '[stopAll] Stop all server instances', - 'updateAll' => '[updateAll] Update all server instances', - 'updateBinaries' => '[updateBinaries] Update all server instance binaries', - ) - ); - // Http socket - private $Http = null; - protected $apiPathMap = array( - 'start' => 'instances/instances/start', - 'stop' => 'instances/instances/stop', - 'cycle' => 'instances/instances/cycle', - 'processState' => 'instances/instances/check', - 'reroll' => 'instances/instances/reroll', - 'spawn' => 'instances/instances/spawn', - 'processState' => 'instances/instances/check', - 'getLogs' => 'instances/instances/instance_log', - ); - - public function initialize(Controller $controller) { - // Load Models - $this->Instance = ClassRegistry::init('Instances.Instance'); - $this->InstanceType = ClassRegistry::init('Instances.InstanceType'); - $this->InstanceProfile = ClassRegistry::init('Instances.InstanceProfile'); - $this->Configuration = ClassRegistry::init('Config.Configuration'); - $this->MemoryLog = ClassRegistry::init('Instances.MemoryLog'); - $this->HostServer = ClassRegistry::init('Instances.HostServer'); - $this->User = ClassRegistry::init('User'); - // Determine host servers - $this->__determineHostServers(); - // Set config - if (!$this->serverBaseDirectory) { - $this->serverBaseDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverBaseDirectory') . DS . Configure::read(APP_CONFIG_SCOPE . '.App.environment'); - } - if (!$this->serverScriptsDirectory) { - $this->serverScriptsDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverScriptsDirectory'); - } - if (!$this->serverDataDirectory) { - $this->serverDataDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverDataDirectory'); - } - if (!$this->serverBinariesDirectory) { - $this->serverBinariesDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverBinariesDirectory'); - } - if (!$this->sourceBinariesDirectory) { - $this->sourceBinariesDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.sourceBinariesDirectory'); - } - if (!$this->backupDirectory) { - $this->backupDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.backupDirectory'); - } - if (!$this->binariesLastUpdated) { - $this->binariesLastUpdated = Configure::read(APP_CONFIG_SCOPE . '.Instances.binariesLastUpdated'); - } - if (!$this->serverDataSkeletonDirectory) { - $this->serverDataSkeletonDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverDataSkeletonDirectory'); - } - if (!$this->firstOpenPort) { - $this->firstOpenPort = Configure::read(APP_CONFIG_SCOPE . '.Instances.firstOpenPort'); - } - if (!$this->lastOpenPort) { - $this->lastOpenPort = Configure::read(APP_CONFIG_SCOPE . '.Instances.lastOpenPort'); - } - if (!$this->hostServerInstanceLimit) { - $this->hostServerInstanceLimit = Configure::read(APP_CONFIG_SCOPE . '.Instances.hostServerInstanceLimit'); - } - if (!$this->apiVersion) { - $this->apiVersion = Configure::read(APP_CONFIG_SCOPE . '.App.apiVersion'); - } - if (!$this->apiKey) { - $this->apiKey = Configure::read(APP_CONFIG_SCOPE . '.App.apiKey'); - } - if (!$this->apiSecret) { - $this->apiSecret = Configure::read(APP_CONFIG_SCOPE . '.App.apiSecret'); - } - // Create Http Socket oject - $this->Http = new HttpSocket(); - } - - public function getConfigOptions($key) { - $options = array(); - if (!empty($this->configOptions[$key])) { - $options = $this->configOptions[$key]; - $zeroToOne = array_combine(range(0, 1, .05), range(0, 1, .05)); - $zeroToTen = array_combine(range(0, 10, 1), range(0, 10, 1)); - $zeroToTwenty = array_combine(range(0, 20, 1), range(0, 20, 1)); - //$oneToFifty = array_combine(range(1, 50, 1), range(1, 50, 1)); - $fifteenToNinety = array_combine(range(15, 90, 15), range(15, 90, 15)); - $oneToOneHundred = array_combine(range(1, 100, 1), range(1, 100, 1)); - $oneThousandToThirtyThousand = array_combine(range(1000, 30000, 1000), range(1000, 30000, 1000)); - $zeroToFiveHundred = array_combine(range(0, 500, 1), range(0, 500, 1)); - $options['inventorySizeMultipliers'] = $oneToOneHundred; - $options['assemblerSpeedMultipliers'] = $oneToOneHundred; - $options['assemblerEfficiencyMultipliers'] = $oneToOneHundred; - $options['refinerySpeedMultipliers'] = $oneToOneHundred; - $options['maxPlayers'] = $oneToOneHundred; - $options['maxFloatingObjects'] = $zeroToFiveHundred; - $options['worldSizeKms'] = $zeroToFiveHundred; - $options['welderSpeedMultipliers'] = $oneToOneHundred; - $options['grinderSpeedMultipliers'] = $oneToOneHundred; - $options['hackSpeedMultipliers'] = $oneToOneHundred; - $options['autoSaveInMinutes'] = $fifteenToNinety; - $options['spawnShipTimeMultipliers'] = $zeroToTwenty; - $options['asteroidAmounts'] = $zeroToTen; - $options['proceduralDensities'] = $zeroToOne; - $options['viewDistances'] = $oneThousandToThirtyThousand; - } - return $options; - } - - public function getRemoteCommands() { - return $this->remoteCommands; - } - - public function pollAllMemoryUsage() { - // Ensure server list is set - $this->__setServerList(); - // Cycle each server - foreach ($this->instances as $instanceId) { - // Update each server's memory usage in the database - // TODO: Single SQL update - $status = $this->processState($instanceId); - if ($status !== 'Stopped') { - $this->MemoryLog->create(); - $memoryUsage = str_replace(array('K', ','), '', $status); - $memoryLog[$this->MemoryLog->alias] = array( - 'instance_id' => $instanceId, - 'memory' => $memoryUsage - ); - $this->MemoryLog->save($memoryLog); - } - } - } - - // TODO: This may be deprecated (merged into cycle) in the future in favor of cycle - private function start($instanceId) { - if ($this->processState($instanceId) != 'Stopped') { - return $instanceId . ' is already started'; - } - // Check if instance data exists, if not then cycle - if (!$this->__verifyInstanceExistence($instanceId, false, false, false)) { - return $this->cycle($instanceId); - } - // Update Session XML - $this->__refreshConfig($instanceId); - // Execute server binary - exec('start /d "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . DS . 'DedicatedServer64" ' . $instanceId . '.exe -noconsole -path "' . $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . DS . '"'); - return $instanceId . ' is starting up'; - } - - private function stop($instanceId, $forced = false) { - if ($this->processState($instanceId) == 'Stopped') { - return $instanceId . ' is already stopped'; - } - // Stop server gracefully - exec('taskkill /IM ' . $instanceId . '.exe'); - if ($forced) { - // Force kill server if still running - exec('taskkill /IM ' . $instanceId . '.exe /F'); - } - return $instanceId . ' was sent a termination signal.'; - } - - private function cycle($instanceId) { - // Check if instance data exists - $this->__verifyInstanceExistence($instanceId, true, false); - // Backup the server - $this->backup($instanceId); - // Stop server, force kill - $this->stop($instanceId, true); - // Update the server - $this->update($instanceId); - // Start the server - $this->start($instanceId); - return $instanceId . ' is starting up.'; - } - - private function reroll($instanceId) { - // Backup the server - $this->backup($instanceId); - // Stop server, force kill - $this->stop($instanceId, true); - // Remove world save - $this->__removePath($this->getConfigPath($instanceId, 'active_world')); - // Start the server - $this->cycle($instanceId); - return $instanceId . ' now has a whole new world.'; - } - - private function backup($instanceId) { - // Copy current world saves to user backup directory - // TODO: Change this path, make it configurable - exec('robocopy "' . $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\Saves" "' . $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\Backup" /MIR'); - return $instanceId . ' is backed up.'; - } - - private function update($instanceId) { - // Delete server exe - exec('DEL "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '\\DedicatedServer64\\' . $instanceId . '.exe"'); - // Copy new server exe - exec('COPY "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '\\DedicatedServer64\\SpaceEngineersDedicated.exe" "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '\\DedicatedServer64\\' . $instanceId . '.exe"'); - return $instanceId . ' is updated.'; - } - - private function processState($instanceId) { - if ($instanceId) { - // find tasks matching - $searchPattern = '~(' . substr($instanceId, 0, 23) . ')~i'; - - // get tasklist - $taskList = array(); - exec("tasklist 2>NUL", $taskList); - - // Search through tasklist - foreach ($taskList AS $taskLine) { - if (preg_match($searchPattern, $taskLine, $out)) { - //echo "=> Detected: " . $out[1] . "\n Sending term signal!\n"; - //exec("taskkill /F /IM " . $out[1] . ".exe 2>NUL"); - $taskLineArray = array_values(array_diff(explode(' ', $taskLine), array(''))); - //$memoryUsage = $taskLineArray[4]; - return $taskLineArray[4] . $taskLineArray[5]; - } - } - } - return 'Stopped'; - } - - private function getConfigPath($instanceId, $configType = 'server') { - // TODO: Use this everywhere, find where it is not being used - switch ($configType) { - case 'server': - $configPath = $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\SpaceEngineers-Dedicated.cfg'; - break; - case 'active_world': - $configPath = $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\Saves\\Active'; - break; - case 'session': - $configPath = $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\Saves\\Active\\Sandbox.sbc'; - break; - } - return $configPath; - } - - // Remove path recursively - private function __removePath($path) { - if (is_dir($path) === true) { - $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST); - foreach ($files as $file) { - if (in_array($file->getBasename(), array('.', '..')) !== true) { - if ($file->isDir() === true) { - rmdir($file->getPathName()); - } else if (($file->isFile() === true) || ($file->isLink() === true)) { - unlink($file->getPathname()); - } - } - } - return rmdir($path); - } else if ((is_file($path) === true) || (is_link($path) === true)) { - return unlink($path); - } - return false; - } - - private function __refreshConfig($instanceId) { - $configPath = $this->getConfigPath($instanceId); - // Delete current settings - unlink($configPath); - // Copy skeleton SpaceEngineers-Dedicated.cfg to instance - $source = $this->serverDataSkeletonDirectory . DS . 'SpaceEngineers-Dedicated.cfg'; - copy($source, $configPath); - // Retrieve instance data - $instanceData = $this->readServer($instanceId); - // Refresh mods list - $this->__refreshMods($instanceId, $instanceData['Instance']['mods']); - // Merge config from instance_type, instance_profile and instance - $instance = $this->__stripValues($instanceData['Instance'], array('id', 'created', 'updated', 'user_id', 'instance_profile_id', 'instance_type_id')); - $instanceType = $this->__stripValues($instanceData['InstanceType'], array('id', 'name', 'created', 'updated')); - $instanceProfile = $this->__stripValues($instanceData['InstanceProfile'], array('id', 'name', 'user_id', 'created', 'updated')); - $configProfile = array_merge( - $instanceType, $instanceProfile, $instance - ); - $configProfile['world_name'] = 'Active'; - $configProfile['load_world'] = $this->getConfigPath($instanceId, 'active_world'); - // Parse server admins field - $configProfile['server_admins'] = $this->__parseServerAdmins($configProfile['server_admins']); - // Inject config into SpaceEngineers-Dedicated.cfg - $this->__injectConfig($instanceId, $configProfile); - // Delete session settings from world save - $this->__deleteSandboxSettings($instanceId); - // Set session settings into world save - $this->__setSandboxSettings($instanceId); - } - - // This function strips values from an array and fixes the data to be compatible with the configuration template - private function __stripValues($data, $keys) { - foreach ($keys as $key) { - unset($data[$key]); - } - return $this->__fixKeys($data); - } - - private function __parseServerAdmins($serverAdmins) { - if (!empty($serverAdmins)) { - $explodedAdmins = explode("\r\n", $serverAdmins); - // - // 76561198031956608 - // - $parsedAdmins = "\r\n"; - foreach ($explodedAdmins as $admin) { - $parsedAdmins .= "\t" . $admin . "\r\n"; - } - $parsedAdmins .= " "; - return $parsedAdmins; - } - return ''; - } - - // This function fixes keys to be compatible with configuration template - // TODO: refactor to take an array to tell which keys to fix to what - private function __fixKeys($data) { - if (isset($data['name'])) { - $data['server_name'] = $data['name']; - unset($data['name']); - } - if (isset($data['port'])) { - $data['server_port'] = $data['port']; - unset($data['port']); - } - return $data; - } - - private function __deleteSandboxSettings($instanceId) { - $sandboxSbcPath = $this->getConfigPath($instanceId, 'session'); - try { - $sandboxSbc = $this->loadXml($sandboxSbcPath); - } catch (Exception $e) { - return true; - } - unset($sandboxSbc->Settings); - unset($sandboxSbc->SessionSettings); - return $sandboxSbc->asXml($sandboxSbcPath); - } - - // TODO: This is terribly dirty - ICKY! - private function __setSandboxSettings($instanceId) { - $dedicatedServerCfgPath = $this->getConfigPath($instanceId, 'server'); - $sandboxSbcPath = $this->getConfigPath($instanceId, 'session'); - try { - $dedicatedServerCfg = $this->loadXml($dedicatedServerCfgPath); - } catch (Exception $e) { - return true; - } - try { - $sandboxSbc = $this->loadXml($sandboxSbcPath); - } catch (Exception $e) { - return true; - } - $this->__sxml_append($sandboxSbc, $dedicatedServerCfg->SessionSettings); - $sandboxSbc->asXml($sandboxSbcPath); - return $this->__renameSandboxSettings($instanceId); - } - - // TODO: This is terribly dirty - ICKY! - private function __renameSandboxSettings($instanceId) { - $sandboxSbcPath = $this->getConfigPath($instanceId, 'session'); - try { - $sandboxSbc = file_get_contents($sandboxSbcPath); - } catch (Exception $e) { - return true; - } - $sandboxSbc = str_replace('', ' ', $sandboxSbc); - $sandboxSbc = str_replace('', "\r\n", $sandboxSbc); - return file_put_contents($sandboxSbcPath, $sandboxSbc); - } - - private function __sxml_append(SimpleXMLElement $to, SimpleXMLElement $from) { - $toDom = dom_import_simplexml($to); - $fromDom = dom_import_simplexml($from); - $toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true)); - } - - private function __refreshMods($instanceId, $mods) { - $sandboxSbcPath = $this->getConfigPath($instanceId, 'session'); - try { - $sandboxSbc = $this->loadXml($this->getConfigPath($instanceId, 'session')); - } catch (Exception $e) { - return true; - } - unset($sandboxSbc->Mods); - $moddedSandboxSbc = $this->__parseMods($sandboxSbc, $mods); - return $this->__saveFormattedXml($moddedSandboxSbc, $sandboxSbcPath); - } - - private function __parseMods($sandboxSbc, $modList) { - $modsXml = $sandboxSbc->addChild('Mods'); - if (!empty($modList)) { - $explodedMods = explode("\r\n", $modList); - foreach ($explodedMods as $mod) { - $modItem = $modsXml->addChild('ModItem'); - $modItem->addChild('Name', $mod . '.sbm'); - $modItem->addChild('PublishedFileId', $mod); - } - } - return $sandboxSbc; - } - - private function __saveFormattedXml($xml, $path) { - unlink($path); - $dom = new DOMDocument('1.0'); - // TODO: Why are these 2 things coming through to the XML? - $dom->preserveWhiteSpace = false; - $dom->formatOutput = true; - $dom->loadXML($xml->asXML()); - $formattedXml = $dom->saveXML(); - return file_put_contents($path, $formattedXml); - } - - private function __determineHostServers() { - // Set host server name list - $this->hostServerNameList = $this->HostServer->find('list'); - // Determine this host - @$this->hostServer = $this->HostServer->findByServername(Configure::read(APP_CONFIG_SCOPE . '.App.servername')); - if (empty($this->hostServer['HostServer']['hostname']) || !in_array($this->hostServer['HostServer']['hostname'], $this->hostServerNameList)) { - $this->hostServer = array( - 'HostServer' => array( - 'id' => null, - 'hostname' => 'localhost' - ) - ); - //throw new NotFoundException(__('Invalid source host.')); - } - } - - private function __verifyInstanceExistence($instanceId, $spawn = true, $cycle = true, $create = true) { - $instanceCreated = false; - $userDirExists = file_exists($this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username']); - $instanceDirExists = file_exists($this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId); - // Check if user dir exists - if ($create && !$userDirExists) { - // create user dir - $userDirExists = mkdir($this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username']); - } - // Check if instance dir exists - if ($create && !$instanceDirExists) { - // create user dir - $instanceCreated = $instanceDirExists = mkdir($this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId); - } - if ($spawn && $instanceCreated) { - return $this->spawn($instanceId, $cycle); - } - return $instanceDirExists; - } - - public function createInstance($instance = array()) { - // Set user id to current user if unspecified - if (empty($instance['Instance']['user_id'])) { - $instance['Instance']['user_id'] = AuthComponent::user('id'); - } - // Set host server - if (empty($instance['Instance']['host_server_id'])) { - // Host server based on least usage - $availableHostServers = $this->HostServer->find('list', array( - 'conditions' => array( - 'or' => array( - 'HostServer.instance_count <' => $this->hostServerInstanceLimit, - 'HostServer.instance_count < HostServer.instance_limit' - ) - ), - 'order' => array( - 'HostServer.instance_count ASC' - ) - )); - if (empty($availableHostServers)) { - throw new NotFoundException(__('No available host servers')); - } - // Get first key - reset($availableHostServers); - $instance['Instance']['host_server_id'] = key($availableHostServers); - } - $this->Instance->create(); - if ($this->Instance->save($instance)) { - $instanceId = $this->Instance->id; - return $this->server('spawn', $instanceId); - } - return false; - } - - private function spawn($instanceId, $cycle = true) { - $this->Instance->id = $instanceId; - if (!$this->Instance->exists()) { - return 'Instance not found'; - } - $this->__verifyInstanceExistence($instanceId, false, false, true); - $instance = $this->readServer($instanceId); - // TODO: Error checking - // Set port - $instance['Instance']['port'] = $this->__getOpenPort(); - $source = $this->serverDataSkeletonDirectory; - $destination = $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId; - $this->__copyDir($source, $destination); - $configurations = array_merge($this->InstanceType->findById($instance['Instance']['instance_type_id'])['InstanceType'], array( - 'server_port' => $instance['Instance']['port'], - 'server_name' => $instance['Instance']['name'], - 'world_name' => 'Active', - 'group_id' => 0, - 'load_world' => $destination . DS . 'Saves' . DS . 'Active' - )); - $this->__injectConfig($instanceId, $configurations); - $instanceProfile['InstanceProfile'] = array_merge($configurations, array( - 'name' => $instance['Instance']['name'], - 'user_id' => $instance['Instance']['user_id'] - )); - $this->InstanceProfile->create($instanceProfile, true, array_keys($this->Instance->schema())); - if ($this->InstanceProfile->save()) { - $instance['Instance']['instance_profile_id'] = $this->InstanceProfile->id; - if ($this->Instance->save($instance)) { - $this->__sendInstanceCreationMail($instanceId); - if ($cycle) { - return $this->server('cycle', $instanceId, true, false); - } - return 'Instance spawned successfully.'; - } - } - return 'Instance creation failed'; - } - - private function __getOpenPort() { - $this->Instance->displayField = 'port'; - $usedPorts = $this->Instance->find('list', array('conditions' => array('Instance.host_server_id' => $this->hostServer['HostServer']['id']))); - // Blacklist port 27036 - $usedPorts[] = 27036; - $nextAvailablePort = @array_shift(array_diff(range($this->firstOpenPort, $this->lastOpenPort), $usedPorts)); - $this->Instance->displayField = 'name'; - return $nextAvailablePort; - } - - public function findOpenPort($hostServerId) { - $this->hostServer['HostServer']['id'] = $hostServerId; - return $this->__getOpenPort(); - } - - // Use robocopy? - // Recursively copies directory - // TODO: error checking / return false on fail - private function __copyDir($src, $dst) { - $dir = opendir($src); - @mkdir($dst); - while (false !== ( $file = readdir($dir))) { - if (( $file != '.' ) && ( $file != '..' )) { - if (is_dir($src . '/' . $file)) { - $this->__copyDir($src . '/' . $file, $dst . '/' . $file); - } else { - copy($src . '/' . $file, $dst . '/' . $file); - } - } - } - closedir($dir); - } - - /* - * This function injects the values into the dedicated server config file and replaces the keys - */ - - private function __injectConfig($instanceId, $configurations) { - $configValues = $this->__buildConfigKeys($configurations); - $configPath = $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . DS . 'SpaceEngineers-Dedicated.cfg'; - $config = str_replace(array_keys($configValues), $configValues, file_get_contents($configPath)); - return file_put_contents($configPath, $config); - } - - /* - * I have no fucking clue what kind of sorcery I performed here - */ - - private function __buildConfigKeys($config) { - $wrappedKeys = array_map( - function ($el) { - return "{{$el}}"; - }, array_keys($config) - ); - return array_combine($wrappedKeys, array_values($config)); - } - - private function __sendInstanceCreationMail($instanceId) { - $instance = $this->readServer($instanceId); - if (!isset($instance['Instance']['user_id'])) { - return; - } - $user = $this->readUser($instance['Instance']['user_id']); - $email = new CakeEmail('mandrill'); - $email->to($user['User']['email']); - $email->subject(Configure::read(APP_CONFIG_SCOPE . '.Email.newInstanceSubject')); - $email->template('new-instance'); - $email->viewVars($instance['Instance']); - $email->viewVars(array('username' => $user['User']['username'])); - $email->addHeaders(array( - 'tags' => array(Configure::read(APP_CONFIG_SCOPE . '.App.environment') . '-new-instance-email'), - )); - $email->send(); - } - - private function readServer($instanceId) { - return $this->Instance->findById($instanceId); - } - - private function readUser($userId) { - return $this->User->findById($userId); - } - - private function getLogs($instanceId) { - $logPath = $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId; - - // Find all log files - $logFiles = glob($logPath . DS . "*.log"); - - //File path of final result - $mergedLogs = $logPath . DS . "mergedLogs.txt"; - - $out = fopen($mergedLogs, "w"); - //Then cycle through the files reading and writing. - - foreach ($logFiles as $file) { - $in = fopen($file, "r"); - while ($line = fgets($in)) { - //print $file; - fwrite($out, $line); - } - fclose($in); - } - - //Then clean up - fclose($out); - - return file_get_contents($mergedLogs); - } - - // Pass-through function to handle server actions - public function server($action) { - if (Cache::read(APP_CONFIG_SCOPE . '.App.maintenanceMode', 'hour')) { - return 'Under maintenance.'; - } - // Get function arguments - $args = func_get_args(); - // Shift off the first argument because that is the function - array_shift($args); - // Convert server UUID to server name - //$instanceName = $this->uuidToName($args[0]); - $instanceId = $args[0]; - // Return false if not the owner - if (!$this->checkOwnership($instanceId)) { - return false; - } - // Set first argument to server name - //$args[0] = $instanceId; - // Execute remote API call if needed - $remoteApiResult = $this->__remoteApiCall($action, $instanceId); - if ($remoteApiResult) { - return $remoteApiResult; - } - // Call the desired function - return call_user_func_array(array($this, $action), $args); - } - - // TODO: Is this used anymore? - public function uuidToName($serverUuid) { - // Check for valid UUID - if (preg_match('/^\{?[a-f\d]{8}-(?:[a-f\d]{4}-){3}[a-f\d]{12}\}?$/i', $serverUuid)) { - // Retrieve server from database - $server = $this->Instance->findById($serverUuid); - // Set servername to variable - $instanceName = $server['Instance']['name']; - // Return servername - return $instanceName; - } - return false; - } - - public function checkOwnership($instanceId) { - // Admin/support own all servers - if (AuthComponent::user('role_id') <= 2) { - return true; - } - // Check ownership if not admin/support - if (AuthComponent::user('role_id') && AuthComponent::user('role_id') > 2) { - // Todo: retrieve just the user_id field - $server = $this->readServer($instanceId); - if ($server['Instance']['user_id'] == AuthComponent::user('id')) { - return true; - } - } - return false; - } - - private function __setServerList() { - if (empty($this->instances)) { - $this->instances = $this->Instance->find('list', array( - 'conditions' => array( - 'Instance.host_server_id' => $this->hostServer['HostServer']['id'] - ) - )); - } - } - - public function loadXml($xmlFilePath, $convertToArray = false) { - $xmlContents = Xml::build($xmlFilePath); - if ($convertToArray) { - $xmlContents = Xml::toArray($xmlContents); - } - return $xmlContents; - } - - private function __remoteApiCall($method, $instanceId) { - $instanceHostServerName = false; - // Are we simulating a remote API call? - if ($this->simulateRemoteApiCall) { - $instanceHostServerName = $this->hostServer['HostServer']['hostname']; - } else { - $instanceHostServerName = $this->hostServerNameList[$this->Instance->findById($instanceId)['Instance']['host_server_id']]; - // Determine remote host (if exists) - if (!in_array($instanceHostServerName, $this->hostServerNameList)) { - throw new NotFoundException(__('Invalid remote host.')); - } - if ($this->hostServer['HostServer']['hostname'] == $instanceHostServerName) { - return false; - } - } - // Execute remote call if required or simulated - if (in_array($method, array_keys($this->apiPathMap)) && $instanceHostServerName) { - $remoteApiPath = $this->apiPathMap[$method]; - $result = json_decode($this->Http->get('http://' . $instanceHostServerName . '/api_' . $this->apiVersion . '/' . $this->apiKey . '/' . $remoteApiPath . '/' . $instanceId)); - return $result->Message; - } - return false; - } + // Config variables + public $serverBaseDirectory = null; + public $serverDataDirectory = null; + public $serverBinariesDirectory = null; + public $serverDataSkeletonDirectory = null; + public $firstOpenPort = null; + public $lastOpenPort = null; + public $hostServerInstanceLimit = null; + public $apiVersion = null; + public $apiKey = null; + // TODO: Implement apiSecret (hash request with secret) + public $apiSecret = null; + // Simulate remote API call + public $simulateRemoteApiCall = false; + // Instance model + private $Instance = null; + // Instance Type model + private $InstanceType = null; + // Instance Profile model + private $InstanceProfile = null; + // Configuration model + private $Configuration = null; + // MemoryLog model + private $MemoryLog = null; + // HostServer model + private $HostServer = null; + // User model + private $User = null; + // Instance list + private $instances = array(); + // Host server name list + private $hostServerNameList = false; + // This host server + private $hostServer = array(); + // Configuration options for form + // TODO: Medieval Engineers + public $configOptions = array( + 'SessionSettings' => array( + 'gameModes' => array( + 'Survival' => 'Survival', + 'Creative' => 'Creative' + ), + 'onlineModes' => array( + 'PUBLIC' => 'PUBLIC', + 'PRIVATE' => 'PRIVATE' + ), + 'environmentHostilities' => array( + 'SAFE' => 'SAFE', + 'NORMAL' => 'NORMAL', + 'CATACLYSM' => 'CATACLYSM', + 'CATACLYSM_UNREAL' => 'CATACLYSM_UNREAL' + ), + 'autoHealings' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'enableCopyPastes' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'autoSaves' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'weaponsEnableds' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'showPlayerNamesOnHuds' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'thrusterDamages' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'cargoShipsEnableds' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'enableSpectators' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'removeTrashes' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'respawnShipDeletes' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'resetOwnerships' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'realisticSounds' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'clientCanSaves' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'permanentDeaths' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'pauseGameWhenEmpties' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'ignoreLastSessions' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'destructibleBlocks' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'enableIngameScripts' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'enableOxygens' => array( + 'true' => 'true', + 'false' => 'false' + ), + 'scenarioSubtypes' => array( + 'EasyStart1' => 'EasyStart1', + 'EasyStart2' => 'EasyStart2', + 'Survival' => 'Survival', + 'CrashedRedShip' => 'CrashedRedShip', + 'TwoPlatforms' => 'TwoPlatforms', + 'Asteroids' => 'Asteroids', + 'EmptyWorld' => 'EmptyWorld' + ), + ), + ); + // Command options for form + public $remoteCommands = array( + 'commands' => array( + 'backupAll' => '[backupAll] Backup all server instances', + 'checkForUpdates' => '[checkForUpdates] Check for Space Engineers updates', + 'cycleAll' => '[cycleAll] Cycle all server instances', + 'restartAll' => '[restartAll] Restart all server instances', + 'startAll' => '[startAll] Start all server instances', + 'stopAll' => '[stopAll] Stop all server instances', + 'updateAll' => '[updateAll] Update all server instances', + 'updateBinaries' => '[updateBinaries] Update all server instance binaries', + ) + ); + // Http socket + private $Http = null; + protected $apiPathMap = array( + 'start' => 'instances/instances/start', + 'stop' => 'instances/instances/stop', + 'cycle' => 'instances/instances/cycle', + 'processState' => 'instances/instances/check', + 'reroll' => 'instances/instances/reroll', + 'spawn' => 'instances/instances/spawn', + 'getLogs' => 'instances/instances/instance_log', + ); + + public function initialize(Controller $controller) { + // Load Models + $this->Instance = ClassRegistry::init('Instances.Instance'); + $this->InstanceType = ClassRegistry::init('Instances.InstanceType'); + $this->InstanceProfile = ClassRegistry::init('Instances.InstanceProfile'); + $this->Configuration = ClassRegistry::init('Config.Configuration'); + $this->MemoryLog = ClassRegistry::init('Instances.MemoryLog'); + $this->HostServer = ClassRegistry::init('Instances.HostServer'); + $this->User = ClassRegistry::init('User'); + // Determine host servers + $this->__determineHostServers(); + // Set config + if (!$this->serverBaseDirectory) { + $this->serverBaseDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverBaseDirectory') . DS . Configure::read(APP_CONFIG_SCOPE . '.App.environment'); + } + if (!$this->serverDataDirectory) { + $this->serverDataDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverDataDirectory'); + } + if (!$this->serverBinariesDirectory) { + $this->serverBinariesDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverBinariesDirectory'); + } + if (!$this->serverDataSkeletonDirectory) { + $this->serverDataSkeletonDirectory = Configure::read(APP_CONFIG_SCOPE . '.Instances.serverDataSkeletonDirectory'); + } + if (!$this->firstOpenPort) { + $this->firstOpenPort = Configure::read(APP_CONFIG_SCOPE . '.Instances.firstOpenPort'); + } + if (!$this->lastOpenPort) { + $this->lastOpenPort = Configure::read(APP_CONFIG_SCOPE . '.Instances.lastOpenPort'); + } + if (!$this->hostServerInstanceLimit) { + $this->hostServerInstanceLimit = Configure::read(APP_CONFIG_SCOPE . '.Instances.hostServerInstanceLimit'); + } + if (!$this->apiVersion) { + $this->apiVersion = Configure::read(APP_CONFIG_SCOPE . '.App.apiVersion'); + } + if (!$this->apiKey) { + $this->apiKey = Configure::read(APP_CONFIG_SCOPE . '.App.apiKey'); + } + if (!$this->apiSecret) { + $this->apiSecret = Configure::read(APP_CONFIG_SCOPE . '.App.apiSecret'); + } + // Create Http Socket oject + $this->Http = new HttpSocket(); + } + + public function getConfigOptions($key) { + $options = array(); + // TODO: Medieval Engineers + if (!empty($this->configOptions[$key])) { + $options = $this->configOptions[$key]; + $zeroToOne = array_combine(range(0, 1, .05), range(0, 1, .05)); + $zeroToTen = array_combine(range(0, 10, 1), range(0, 10, 1)); + $zeroToTwenty = array_combine(range(0, 20, 1), range(0, 20, 1)); + //$oneToFifty = array_combine(range(1, 50, 1), range(1, 50, 1)); + $fifteenToNinety = array_combine(range(15, 90, 15), range(15, 90, 15)); + $oneToOneHundred = array_combine(range(1, 100, 1), range(1, 100, 1)); + $oneThousandToThirtyThousand = array_combine(range(1000, 30000, 1000), range(1000, 30000, 1000)); + $zeroToFiveHundred = array_combine(range(0, 500, 1), range(0, 500, 1)); + $options['inventorySizeMultipliers'] = $oneToOneHundred; + $options['assemblerSpeedMultipliers'] = $oneToOneHundred; + $options['assemblerEfficiencyMultipliers'] = $oneToOneHundred; + $options['refinerySpeedMultipliers'] = $oneToOneHundred; + $options['maxPlayers'] = $oneToOneHundred; + $options['maxFloatingObjects'] = $zeroToFiveHundred; + $options['worldSizeKms'] = $zeroToFiveHundred; + $options['welderSpeedMultipliers'] = $oneToOneHundred; + $options['grinderSpeedMultipliers'] = $oneToOneHundred; + $options['hackSpeedMultipliers'] = $oneToOneHundred; + $options['autoSaveInMinutes'] = $fifteenToNinety; + $options['spawnShipTimeMultipliers'] = $zeroToTwenty; + $options['asteroidAmounts'] = $zeroToTen; + $options['proceduralDensities'] = $zeroToOne; + $options['viewDistances'] = $oneThousandToThirtyThousand; + } + return $options; + } + + public function getRemoteCommands() { + return $this->remoteCommands; + } + + // This function not utilized yet + public function pollAllMemoryUsage() { + // Ensure server list is set + $this->__setServerList(); + // Cycle each server + foreach ($this->instances as $instanceId) { + // Update each server's memory usage in the database + // TODO: Single SQL update + $status = $this->processState($instanceId); + if ($status !== 'Stopped') { + $this->MemoryLog->create(); + $memoryUsage = str_replace(array('K', ','), '', $status); + $memoryLog[$this->MemoryLog->alias] = array( + 'instance_id' => $instanceId, + 'memory' => $memoryUsage + ); + $this->MemoryLog->save($memoryLog); + } + } + } + + // TODO: This may be deprecated (merged into cycle) in the future in favor of cycle + // TODO: Medieval Engineers + private function start($instanceId) { + if ($this->processState($instanceId) != 'Stopped') { + return $instanceId . ' is already started'; + } + // Check if instance data exists, if not then cycle + if (!$this->__verifyInstanceExistence($instanceId, false, false, false)) { + return $this->cycle($instanceId); + } + // Update Session XML + $this->__refreshConfig($instanceId); + // Execute server binary + exec('start /d "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . DS . 'DedicatedServer64" ' . $instanceId . '.exe -noconsole -path "' . $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . DS . '"'); + return $instanceId . ' is starting up'; + } + + private function stop($instanceId, $forced = false) { + if ($this->processState($instanceId) == 'Stopped') { + return $instanceId . ' is already stopped'; + } + // Stop server gracefully + exec('taskkill /IM ' . $instanceId . '.exe'); + if ($forced) { + // Force kill server if still running + exec('taskkill /IM ' . $instanceId . '.exe /F'); + } + return $instanceId . ' was sent a termination signal.'; + } + + private function cycle($instanceId) { + // Check if instance data exists + $this->__verifyInstanceExistence($instanceId, true, false); + // Backup the server + $this->backup($instanceId); + // Stop server, force kill + $this->stop($instanceId, true); + // Update the server + $this->update($instanceId); + // Start the server + $this->start($instanceId); + return $instanceId . ' is starting up.'; + } + + private function reroll($instanceId) { + // Backup the server + $this->backup($instanceId); + // Stop server, force kill + $this->stop($instanceId, true); + // Remove world save + $this->__removePath($this->getConfigPath($instanceId, 'active_world')); + // Start the server + $this->cycle($instanceId); + return $instanceId . ' now has a whole new world.'; + } + + private function backup($instanceId) { + // Copy current world saves to user backup directory + // TODO: Change this path, make it configurable + exec('robocopy "' . $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\Saves" "' . $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\Backup" /MIR'); + return $instanceId . ' is backed up.'; + } + + // TODO: Medieval Engineers + private function update($instanceId) { + // Delete server exe + exec('DEL "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '\\DedicatedServer64\\' . $instanceId . '.exe"'); + // Copy new server exe + exec('COPY "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '\\DedicatedServer64\\SpaceEngineersDedicated.exe" "' . $this->serverBaseDirectory . DS . $this->serverBinariesDirectory . '\\DedicatedServer64\\' . $instanceId . '.exe"'); + return $instanceId . ' is updated.'; + } + + private function processState($instanceId) { + if ($instanceId) { + // find tasks matching + $searchPattern = '~(' . substr($instanceId, 0, 23) . ')~i'; + + // get tasklist + $taskList = array(); + exec("tasklist 2>NUL", $taskList); + + // Search through tasklist + foreach ($taskList AS $taskLine) { + if (preg_match($searchPattern, $taskLine, $out)) { + //echo "=> Detected: " . $out[1] . "\n Sending term signal!\n"; + //exec("taskkill /F /IM " . $out[1] . ".exe 2>NUL"); + $taskLineArray = array_values(array_diff(explode(' ', $taskLine), array(''))); + //$memoryUsage = $taskLineArray[4]; + return $taskLineArray[4] . $taskLineArray[5]; + } + } + } + return 'Stopped'; + } + + private function getConfigPath($instanceId, $configType = 'server') { + // TODO: Use this everywhere, find where it is not being used + switch ($configType) { + case 'server': + $configPath = $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\SpaceEngineers-Dedicated.cfg'; + break; + case 'active_world': + $configPath = $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\Saves\\Active'; + break; + case 'session': + $configPath = $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . '\\Saves\\Active\\Sandbox.sbc'; + break; + } + return $configPath; + } + + // Remove path recursively + private function __removePath($path) { + if (is_dir($path) === true) { + $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST); + foreach ($files as $file) { + if (in_array($file->getBasename(), array('.', '..')) !== true) { + if ($file->isDir() === true) { + rmdir($file->getPathName()); + } else if (($file->isFile() === true) || ($file->isLink() === true)) { + unlink($file->getPathname()); + } + } + } + return rmdir($path); + } else if ((is_file($path) === true) || (is_link($path) === true)) { + return unlink($path); + } + return false; + } + + private function __refreshConfig($instanceId) { + $configPath = $this->getConfigPath($instanceId); + // Delete current settings + unlink($configPath); + // Copy skeleton SpaceEngineers-Dedicated.cfg to instance + // TODO: Medieval Engineers + $source = $this->serverDataSkeletonDirectory . DS . 'SpaceEngineers-Dedicated.cfg'; + copy($source, $configPath); + // Retrieve instance data + $instanceData = $this->readServer($instanceId); + // Refresh mods list + $this->__refreshMods($instanceId, $instanceData['Instance']['mods']); + // Merge config from instance_type, instance_profile and instance + $instance = $this->__stripValues($instanceData['Instance'], array('id', 'created', 'updated', 'user_id', 'instance_profile_id', 'instance_type_id')); + $instanceType = $this->__stripValues($instanceData['InstanceType'], array('id', 'name', 'created', 'updated')); + $instanceProfile = $this->__stripValues($instanceData['InstanceProfile'], array('id', 'name', 'user_id', 'created', 'updated')); + $configProfile = array_merge( + $instanceType, $instanceProfile, $instance + ); + $configProfile['world_name'] = 'Active'; + $configProfile['load_world'] = $this->getConfigPath($instanceId, 'active_world'); + // Parse server admins field + $configProfile['server_admins'] = $this->__parseServerAdmins($configProfile['server_admins']); + // Inject config into SpaceEngineers-Dedicated.cfg + $this->__injectConfig($instanceId, $configProfile); + // Delete session settings from world save + $this->__deleteSandboxSettings($instanceId); + // Set session settings into world save + $this->__setSandboxSettings($instanceId); + } + + // This function strips values from an array and fixes the data to be compatible with the configuration template + private function __stripValues($data, $keys) { + foreach ($keys as $key) { + unset($data[$key]); + } + return $this->__fixKeys($data); + } + + private function __parseServerAdmins($serverAdmins) { + if (!empty($serverAdmins)) { + $explodedAdmins = explode("\r\n", $serverAdmins); + // + // 76561198031956608 + // + $parsedAdmins = "\r\n"; + foreach ($explodedAdmins as $admin) { + $parsedAdmins .= "\t" . $admin . "\r\n"; + } + $parsedAdmins .= " "; + return $parsedAdmins; + } + return ''; + } + + // This function fixes keys to be compatible with configuration template + // TODO: refactor to take an array to tell which keys to fix to what + private function __fixKeys($data) { + if (isset($data['name'])) { + $data['server_name'] = $data['name']; + unset($data['name']); + } + if (isset($data['port'])) { + $data['server_port'] = $data['port']; + unset($data['port']); + } + return $data; + } + + private function __deleteSandboxSettings($instanceId) { + $sandboxSbcPath = $this->getConfigPath($instanceId, 'session'); + try { + $sandboxSbc = $this->loadXml($sandboxSbcPath); + } catch (Exception $e) { + return true; + } + unset($sandboxSbc->Settings); + unset($sandboxSbc->SessionSettings); + return $sandboxSbc->asXml($sandboxSbcPath); + } + + // TODO: This is terribly dirty - ICKY! + private function __setSandboxSettings($instanceId) { + $dedicatedServerCfgPath = $this->getConfigPath($instanceId, 'server'); + $sandboxSbcPath = $this->getConfigPath($instanceId, 'session'); + try { + $dedicatedServerCfg = $this->loadXml($dedicatedServerCfgPath); + } catch (Exception $e) { + return true; + } + try { + $sandboxSbc = $this->loadXml($sandboxSbcPath); + } catch (Exception $e) { + return true; + } + $this->__sxml_append($sandboxSbc, $dedicatedServerCfg->SessionSettings); + $sandboxSbc->asXml($sandboxSbcPath); + return $this->__renameSandboxSettings($instanceId); + } + + // TODO: This is terribly dirty - ICKY! + private function __renameSandboxSettings($instanceId) { + $sandboxSbcPath = $this->getConfigPath($instanceId, 'session'); + try { + $sandboxSbc = file_get_contents($sandboxSbcPath); + } catch (Exception $e) { + return true; + } + $sandboxSbc = str_replace('', ' ', $sandboxSbc); + $sandboxSbc = str_replace('', "\r\n", $sandboxSbc); + return file_put_contents($sandboxSbcPath, $sandboxSbc); + } + + private function __sxml_append(SimpleXMLElement $to, SimpleXMLElement $from) { + $toDom = dom_import_simplexml($to); + $fromDom = dom_import_simplexml($from); + $toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true)); + } + + private function __refreshMods($instanceId, $mods) { + $sandboxSbcPath = $this->getConfigPath($instanceId, 'session'); + try { + $sandboxSbc = $this->loadXml($this->getConfigPath($instanceId, 'session')); + } catch (Exception $e) { + return true; + } + unset($sandboxSbc->Mods); + $moddedSandboxSbc = $this->__parseMods($sandboxSbc, $mods); + return $this->__saveFormattedXml($moddedSandboxSbc, $sandboxSbcPath); + } + + private function __parseMods($sandboxSbc, $modList) { + $modsXml = $sandboxSbc->addChild('Mods'); + if (!empty($modList)) { + $explodedMods = explode("\r\n", $modList); + foreach ($explodedMods as $mod) { + $modItem = $modsXml->addChild('ModItem'); + $modItem->addChild('Name', $mod . '.sbm'); + $modItem->addChild('PublishedFileId', $mod); + } + } + return $sandboxSbc; + } + + private function __saveFormattedXml($xml, $path) { + unlink($path); + $dom = new DOMDocument('1.0'); + // TODO: Why are these 2 things coming through to the XML? + $dom->preserveWhiteSpace = false; + $dom->formatOutput = true; + $dom->loadXML($xml->asXML()); + $formattedXml = $dom->saveXML(); + return file_put_contents($path, $formattedXml); + } + + private function __determineHostServers() { + // Set host server name list + $this->hostServerNameList = $this->HostServer->find('list'); + // Determine this host + @$this->hostServer = $this->HostServer->findByServername(Configure::read(APP_CONFIG_SCOPE . '.App.servername')); + if (empty($this->hostServer['HostServer']['hostname']) || !in_array($this->hostServer['HostServer']['hostname'], $this->hostServerNameList)) { + $this->hostServer = array( + 'HostServer' => array( + 'id' => null, + 'hostname' => 'localhost' + ) + ); + //throw new NotFoundException(__('Invalid source host.')); + } + } + + private function __verifyInstanceExistence($instanceId, $spawn = true, $cycle = true, $create = true) { + $instanceCreated = false; + $userDirExists = file_exists($this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username']); + $instanceDirExists = file_exists($this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId); + // Check if user dir exists + if ($create && !$userDirExists) { + // create user dir + $userDirExists = mkdir($this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username']); + } + // Check if instance dir exists + if ($create && !$instanceDirExists) { + // create user dir + $instanceCreated = $instanceDirExists = mkdir($this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId); + } + if ($spawn && $instanceCreated) { + return $this->spawn($instanceId, $cycle); + } + return $instanceDirExists; + } + + public function createInstance($instance = array()) { + // Set user id to current user if unspecified + if (empty($instance['Instance']['user_id'])) { + $instance['Instance']['user_id'] = AuthComponent::user('id'); + } + // Set host server + if (empty($instance['Instance']['host_server_id'])) { + // Host server based on least usage + $availableHostServers = $this->HostServer->find('list', array( + 'conditions' => array( + 'or' => array( + 'HostServer.instance_count <' => $this->hostServerInstanceLimit, + 'HostServer.instance_count < HostServer.instance_limit' + ) + ), + 'order' => array( + 'HostServer.instance_count ASC' + ) + )); + if (empty($availableHostServers)) { + throw new NotFoundException(__('No available host servers')); + } + // Get first key + reset($availableHostServers); + $instance['Instance']['host_server_id'] = key($availableHostServers); + } + $this->Instance->create(); + if ($this->Instance->save($instance)) { + $instanceId = $this->Instance->id; + return $this->server('spawn', $instanceId); + } + return false; + } + + private function spawn($instanceId, $cycle = true) { + $this->Instance->id = $instanceId; + if (!$this->Instance->exists()) { + return 'Instance not found'; + } + $this->__verifyInstanceExistence($instanceId, false, false, true); + $instance = $this->readServer($instanceId); + // TODO: Error checking + // Set port + $instance['Instance']['port'] = $this->__getOpenPort(); + // TODO: Medieval Engineers + // TODO: Make function to get Skel dir + $source = $this->serverDataSkeletonDirectory; + $destination = $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId; + $this->__copyDir($source, $destination); + $configurations = array_merge($this->InstanceType->findById($instance['Instance']['instance_type_id'])['InstanceType'], array( + 'server_port' => $instance['Instance']['port'], + 'server_name' => $instance['Instance']['name'], + 'world_name' => 'Active', + 'group_id' => 0, + 'load_world' => $destination . DS . 'Saves' . DS . 'Active' + )); + $this->__injectConfig($instanceId, $configurations); + $instanceProfile['InstanceProfile'] = array_merge($configurations, array( + 'name' => $instance['Instance']['name'], + 'user_id' => $instance['Instance']['user_id'] + )); + $this->InstanceProfile->create($instanceProfile, true, array_keys($this->Instance->schema())); + if ($this->InstanceProfile->save()) { + $instance['Instance']['instance_profile_id'] = $this->InstanceProfile->id; + if ($this->Instance->save($instance)) { + $this->__sendInstanceCreationMail($instanceId); + if ($cycle) { + return $this->server('cycle', $instanceId, true, false); + } + return 'Instance spawned successfully.'; + } + } + return 'Instance creation failed'; + } + + private function __getOpenPort() { + $this->Instance->displayField = 'port'; + $usedPorts = $this->Instance->find('list', array('conditions' => array('Instance.host_server_id' => $this->hostServer['HostServer']['id']))); + // Blacklist port 27036 + $usedPorts[] = 27036; + $nextAvailablePort = @array_shift(array_diff(range($this->firstOpenPort, $this->lastOpenPort), $usedPorts)); + $this->Instance->displayField = 'name'; + return $nextAvailablePort; + } + + public function findOpenPort($hostServerId) { + $this->hostServer['HostServer']['id'] = $hostServerId; + return $this->__getOpenPort(); + } + + // TODO: Use robocopy? + // Recursively copies directory + // TODO: error checking / return false on fail + private function __copyDir($src, $dst) { + $dir = opendir($src); + @mkdir($dst); + while (false !== ( $file = readdir($dir))) { + if (( $file != '.' ) && ( $file != '..' )) { + if (is_dir($src . '/' . $file)) { + $this->__copyDir($src . '/' . $file, $dst . '/' . $file); + } else { + copy($src . '/' . $file, $dst . '/' . $file); + } + } + } + closedir($dir); + } + + /* + * This function injects the values into the dedicated server config file and replaces the keys + */ + + private function __injectConfig($instanceId, $configurations) { + $configValues = $this->__buildConfigKeys($configurations); + $configPath = $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId . DS . 'SpaceEngineers-Dedicated.cfg'; + $config = str_replace(array_keys($configValues), $configValues, file_get_contents($configPath)); + return file_put_contents($configPath, $config); + } + + /* + * I have no fucking clue what kind of sorcery I performed here + */ + + private function __buildConfigKeys($config) { + $wrappedKeys = array_map( + function ($el) { + return "{{$el}}"; + }, array_keys($config) + ); + return array_combine($wrappedKeys, array_values($config)); + } + + private function __sendInstanceCreationMail($instanceId) { + $instance = $this->readServer($instanceId); + if (!isset($instance['Instance']['user_id'])) { + return; + } + $user = $this->readUser($instance['Instance']['user_id']); + $email = new CakeEmail('mandrill'); + $email->to($user['User']['email']); + $email->subject(Configure::read(APP_CONFIG_SCOPE . '.Email.newInstanceSubject')); + $email->template('new-instance'); + $email->viewVars($instance['Instance']); + $email->viewVars(array('username' => $user['User']['username'])); + $email->addHeaders(array( + 'tags' => array(Configure::read(APP_CONFIG_SCOPE . '.App.environment') . '-new-instance-email'), + )); + $email->send(); + } + + private function readServer($instanceId) { + return $this->Instance->findById($instanceId); + } + + private function readUser($userId) { + return $this->User->findById($userId); + } + + private function getLogs($instanceId) { + $logPath = $this->serverDataDirectory . DS . $this->readServer($instanceId)['User']['username'] . DS . $instanceId; + + // Find all log files + $logFiles = glob($logPath . DS . "*.log"); + + //File path of final result + $mergedLogs = $logPath . DS . "mergedLogs.txt"; + + $out = fopen($mergedLogs, "w"); + //Then cycle through the files reading and writing. + + foreach ($logFiles as $file) { + $in = fopen($file, "r"); + while ($line = fgets($in)) { + //print $file; + fwrite($out, $line); + } + fclose($in); + } + + //Then clean up + fclose($out); + + return file_get_contents($mergedLogs); + } + + // Pass-through function to handle server actions + public function server($action) { + if (Cache::read(APP_CONFIG_SCOPE . '.App.maintenanceMode', 'hour')) { + return 'Under maintenance.'; + } + // Get function arguments + $args = func_get_args(); + // Shift off the first argument because that is the function + array_shift($args); + // Convert server UUID to server name + //$instanceName = $this->uuidToName($args[0]); + $instanceId = $args[0]; + // Return false if not the owner + if (!$this->checkOwnership($instanceId)) { + return false; + } + // Set first argument to server name + //$args[0] = $instanceId; + // Execute remote API call if needed + $remoteApiResult = $this->__remoteApiCall($action, $instanceId); + if ($remoteApiResult) { + return $remoteApiResult; + } + // Call the desired function + return call_user_func_array(array($this, $action), $args); + } + + // TODO: Is this used anymore? + public function uuidToName($serverUuid) { + // Check for valid UUID + if (preg_match('/^\{?[a-f\d]{8}-(?:[a-f\d]{4}-){3}[a-f\d]{12}\}?$/i', $serverUuid)) { + // Retrieve server from database + $server = $this->Instance->findById($serverUuid); + // Set servername to variable + $instanceName = $server['Instance']['name']; + // Return servername + return $instanceName; + } + return false; + } + + public function checkOwnership($instanceId) { + // Admin/support own all servers + if (AuthComponent::user('role_id') <= 2) { + return true; + } + // Check ownership if not admin/support + if (AuthComponent::user('role_id') && AuthComponent::user('role_id') > 2) { + // Todo: retrieve just the user_id field + $server = $this->readServer($instanceId); + if ($server['Instance']['user_id'] == AuthComponent::user('id')) { + return true; + } + } + return false; + } + + private function __setServerList() { + if (empty($this->instances)) { + $this->instances = $this->Instance->find('list', array( + 'conditions' => array( + 'Instance.host_server_id' => $this->hostServer['HostServer']['id'] + ) + )); + } + } + + public function loadXml($xmlFilePath, $convertToArray = false) { + $xmlContents = Xml::build($xmlFilePath); + if ($convertToArray) { + $xmlContents = Xml::toArray($xmlContents); + } + return $xmlContents; + } + + private function __remoteApiCall($method, $instanceId) { + $instanceHostServerName = false; + // Are we simulating a remote API call? + if ($this->simulateRemoteApiCall) { + $instanceHostServerName = $this->hostServer['HostServer']['hostname']; + } else { + $instanceHostServerName = $this->hostServerNameList[$this->Instance->findById($instanceId)['Instance']['host_server_id']]; + // Determine remote host (if exists) + if (!in_array($instanceHostServerName, $this->hostServerNameList)) { + throw new NotFoundException(__('Invalid remote host.')); + } + if ($this->hostServer['HostServer']['hostname'] == $instanceHostServerName) { + return false; + } + } + // Execute remote call if required or simulated + if (in_array($method, array_keys($this->apiPathMap)) && $instanceHostServerName) { + $remoteApiPath = $this->apiPathMap[$method]; + $result = json_decode($this->Http->get('http://' . $instanceHostServerName . '/api_' . $this->apiVersion . '/' . $this->apiKey . '/' . $remoteApiPath . '/' . $instanceId)); + return $result->Message; + } + return false; + } } From d73ec9b2e3d721ad14cf2b4929faf82a11f696d5 Mon Sep 17 00:00:00 2001 From: Travis Rowland Date: Wed, 6 May 2015 23:42:50 -0700 Subject: [PATCH 02/17] Many updates -- fixes #60 #59 #58 #57 #56 #55 #50 #48 #49 #46 #2 #3 --- app/Config/bootstrap.php | 13 +- app/Controller/AppController.php | 3 +- app/Model/User.php | 17 +- app/Plugin/DebugKit/.gitignore | 16 + .../Console/Command/BenchmarkShell.php | 159 +++ .../Console/Command/WhitespaceShell.php | 93 ++ .../Controller/Component/ToolbarComponent.php | 504 ++++++++++ .../Controller/DebugKitAppController.php | 25 + .../Controller/ToolbarAccessController.php | 121 +++ app/Plugin/DebugKit/LICENSE.txt | 28 + app/Plugin/DebugKit/Lib/DebugKitDebugger.php | 227 +++++ app/Plugin/DebugKit/Lib/DebugMemory.php | 98 ++ app/Plugin/DebugKit/Lib/DebugPanel.php | 84 ++ app/Plugin/DebugKit/Lib/DebugTimer.php | 201 ++++ app/Plugin/DebugKit/Lib/FireCake.php | 538 ++++++++++ .../DebugKit/Lib/Log/Engine/DebugKitLog.php | 50 + .../DebugKit/Lib/Panel/EnvironmentPanel.php | 81 ++ .../DebugKit/Lib/Panel/HistoryPanel.php | 83 ++ .../DebugKit/Lib/Panel/IncludePanel.php | 160 +++ app/Plugin/DebugKit/Lib/Panel/LogPanel.php | 51 + .../DebugKit/Lib/Panel/RequestPanel.php | 41 + .../DebugKit/Lib/Panel/SessionPanel.php | 32 + app/Plugin/DebugKit/Lib/Panel/SqlLogPanel.php | 64 ++ app/Plugin/DebugKit/Lib/Panel/TimerPanel.php | 36 + .../DebugKit/Lib/Panel/VariablesPanel.php | 31 + app/Plugin/DebugKit/Locale/debug_kit.pot | 138 +++ .../Locale/eng/LC_MESSAGES/debug_kit.po | 135 +++ .../Locale/fra/LC_MESSAGES/debug_kit.po | 135 +++ .../Locale/lim/LC_MESSAGES/debug_kit.po | 136 +++ .../Locale/nld/LC_MESSAGES/debug_kit.po | 141 +++ .../Locale/spa/LC_MESSAGES/debug_kit.po | 135 +++ .../DebugKit/Model/Behavior/TimedBehavior.php | 102 ++ .../DebugKit/Model/DebugKitAppModel.php | 24 + app/Plugin/DebugKit/Model/ToolbarAccess.php | 56 ++ app/Plugin/DebugKit/README.md | 299 ++++++ .../DebugKit/Test/Case/AllDebugKitTest.php | 40 + .../Test/Case/AllDebugKitViewTest.php | 40 + .../Test/Case/AllDebugKitWithoutViewTest.php | 40 + .../DebugKit/Test/Case/AllTestsTest.php | 40 + .../Component/ToolbarComponentTest.php | 524 ++++++++++ .../Test/Case/DebugkitGroupTestCase.php | 79 ++ .../Test/Case/Lib/DebugKitDebuggerTest.php | 76 ++ .../Test/Case/Lib/DebugMemoryTest.php | 65 ++ .../DebugKit/Test/Case/Lib/DebugTimerTest.php | 169 ++++ .../DebugKit/Test/Case/Lib/FireCakeTest.php | 345 +++++++ .../Test/Case/Lib/Panel/LogPanelTest.php | 63 ++ .../Test/Case/Lib/Panel/SqlLogPanelTest.php | 59 ++ .../Case/Model/Behavior/TimedBehaviorTest.php | 89 ++ .../Test/Case/Model/ToolbarAccessTest.php | 69 ++ .../DebugKit/Test/Case/TestFireCake.php | 65 ++ .../View/Helper/FirePhpToolbarHelperTest.php | 152 +++ .../View/Helper/HtmlToolbarHelperTest.php | 452 +++++++++ .../Case/View/Helper/ToolbarHelperTest.php | 179 ++++ .../Controller/DebugKitTestController.php | 63 ++ .../Test/test_app/Lib/Panel/TestPanel.php | 37 + .../Lib/Panel/PluginTestPanel.php | 26 + .../DebugKitTest/request_action_render.ctp | 18 + app/Plugin/DebugKit/VERSION.txt | 1 + .../DebugKit/View/Elements/debug_toolbar.ctp | 59 ++ .../View/Elements/environment_panel.ctp | 84 ++ .../DebugKit/View/Elements/history_panel.ctp | 32 + .../DebugKit/View/Elements/include_panel.ctp | 34 + .../DebugKit/View/Elements/log_panel.ctp | 41 + .../DebugKit/View/Elements/request_panel.ctp | 50 + .../DebugKit/View/Elements/session_panel.ctp | 20 + .../DebugKit/View/Elements/sql_log_panel.ctp | 80 ++ .../DebugKit/View/Elements/timer_panel.ctp | 110 ++ .../View/Elements/variables_panel.ctp | 23 + .../DebugKit/View/Helper/DebugTimerHelper.php | 90 ++ .../View/Helper/FirePhpToolbarHelper.php | 106 ++ .../View/Helper/HtmlToolbarHelper.php | 238 +++++ .../View/Helper/SimpleGraphHelper.php | 88 ++ .../DebugKit/View/Helper/TidyHelper.php | 171 ++++ .../DebugKit/View/Helper/ToolbarHelper.php | 226 +++++ .../View/ToolbarAccess/history_state.ctp | 30 + .../View/ToolbarAccess/sql_explain.ctp | 11 + app/Plugin/DebugKit/composer.json | 35 + .../DebugKit/webroot/css/debug_toolbar.css | 387 ++++++++ app/Plugin/DebugKit/webroot/img/cake.icon.png | Bin 0 -> 943 bytes app/Plugin/DebugKit/webroot/js/jquery.js | 4 + .../DebugKit/webroot/js/js_debug_toolbar.js | 936 ++++++++++++++++++ .../Component/SEServerComponent.php | 153 +-- .../Controller/InstancesController.php | 6 +- .../Instances/View/Instances/admin_add.ctp | 1 + .../Instances/View/Instances/admin_edit.ctp | 1 + app/webroot/debug_kit/img/cake.icon.png | Bin 0 -> 943 bytes 86 files changed, 9697 insertions(+), 67 deletions(-) create mode 100644 app/Plugin/DebugKit/.gitignore create mode 100644 app/Plugin/DebugKit/Console/Command/BenchmarkShell.php create mode 100644 app/Plugin/DebugKit/Console/Command/WhitespaceShell.php create mode 100644 app/Plugin/DebugKit/Controller/Component/ToolbarComponent.php create mode 100644 app/Plugin/DebugKit/Controller/DebugKitAppController.php create mode 100644 app/Plugin/DebugKit/Controller/ToolbarAccessController.php create mode 100644 app/Plugin/DebugKit/LICENSE.txt create mode 100644 app/Plugin/DebugKit/Lib/DebugKitDebugger.php create mode 100644 app/Plugin/DebugKit/Lib/DebugMemory.php create mode 100644 app/Plugin/DebugKit/Lib/DebugPanel.php create mode 100644 app/Plugin/DebugKit/Lib/DebugTimer.php create mode 100644 app/Plugin/DebugKit/Lib/FireCake.php create mode 100644 app/Plugin/DebugKit/Lib/Log/Engine/DebugKitLog.php create mode 100644 app/Plugin/DebugKit/Lib/Panel/EnvironmentPanel.php create mode 100644 app/Plugin/DebugKit/Lib/Panel/HistoryPanel.php create mode 100644 app/Plugin/DebugKit/Lib/Panel/IncludePanel.php create mode 100644 app/Plugin/DebugKit/Lib/Panel/LogPanel.php create mode 100644 app/Plugin/DebugKit/Lib/Panel/RequestPanel.php create mode 100644 app/Plugin/DebugKit/Lib/Panel/SessionPanel.php create mode 100644 app/Plugin/DebugKit/Lib/Panel/SqlLogPanel.php create mode 100644 app/Plugin/DebugKit/Lib/Panel/TimerPanel.php create mode 100644 app/Plugin/DebugKit/Lib/Panel/VariablesPanel.php create mode 100644 app/Plugin/DebugKit/Locale/debug_kit.pot create mode 100644 app/Plugin/DebugKit/Locale/eng/LC_MESSAGES/debug_kit.po create mode 100644 app/Plugin/DebugKit/Locale/fra/LC_MESSAGES/debug_kit.po create mode 100644 app/Plugin/DebugKit/Locale/lim/LC_MESSAGES/debug_kit.po create mode 100644 app/Plugin/DebugKit/Locale/nld/LC_MESSAGES/debug_kit.po create mode 100644 app/Plugin/DebugKit/Locale/spa/LC_MESSAGES/debug_kit.po create mode 100644 app/Plugin/DebugKit/Model/Behavior/TimedBehavior.php create mode 100644 app/Plugin/DebugKit/Model/DebugKitAppModel.php create mode 100644 app/Plugin/DebugKit/Model/ToolbarAccess.php create mode 100644 app/Plugin/DebugKit/README.md create mode 100644 app/Plugin/DebugKit/Test/Case/AllDebugKitTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/AllDebugKitViewTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/AllDebugKitWithoutViewTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/AllTestsTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/Controller/Component/ToolbarComponentTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/DebugkitGroupTestCase.php create mode 100644 app/Plugin/DebugKit/Test/Case/Lib/DebugKitDebuggerTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/Lib/DebugMemoryTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/Lib/DebugTimerTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/Lib/FireCakeTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/Lib/Panel/LogPanelTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/Lib/Panel/SqlLogPanelTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/Model/Behavior/TimedBehaviorTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/Model/ToolbarAccessTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/TestFireCake.php create mode 100644 app/Plugin/DebugKit/Test/Case/View/Helper/FirePhpToolbarHelperTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/View/Helper/HtmlToolbarHelperTest.php create mode 100644 app/Plugin/DebugKit/Test/Case/View/Helper/ToolbarHelperTest.php create mode 100644 app/Plugin/DebugKit/Test/test_app/Controller/DebugKitTestController.php create mode 100644 app/Plugin/DebugKit/Test/test_app/Lib/Panel/TestPanel.php create mode 100644 app/Plugin/DebugKit/Test/test_app/Plugin/DebugkitTestPlugin/Lib/Panel/PluginTestPanel.php create mode 100644 app/Plugin/DebugKit/Test/test_app/View/DebugKitTest/request_action_render.ctp create mode 100644 app/Plugin/DebugKit/VERSION.txt create mode 100644 app/Plugin/DebugKit/View/Elements/debug_toolbar.ctp create mode 100644 app/Plugin/DebugKit/View/Elements/environment_panel.ctp create mode 100644 app/Plugin/DebugKit/View/Elements/history_panel.ctp create mode 100644 app/Plugin/DebugKit/View/Elements/include_panel.ctp create mode 100644 app/Plugin/DebugKit/View/Elements/log_panel.ctp create mode 100644 app/Plugin/DebugKit/View/Elements/request_panel.ctp create mode 100644 app/Plugin/DebugKit/View/Elements/session_panel.ctp create mode 100644 app/Plugin/DebugKit/View/Elements/sql_log_panel.ctp create mode 100644 app/Plugin/DebugKit/View/Elements/timer_panel.ctp create mode 100644 app/Plugin/DebugKit/View/Elements/variables_panel.ctp create mode 100644 app/Plugin/DebugKit/View/Helper/DebugTimerHelper.php create mode 100644 app/Plugin/DebugKit/View/Helper/FirePhpToolbarHelper.php create mode 100644 app/Plugin/DebugKit/View/Helper/HtmlToolbarHelper.php create mode 100644 app/Plugin/DebugKit/View/Helper/SimpleGraphHelper.php create mode 100644 app/Plugin/DebugKit/View/Helper/TidyHelper.php create mode 100644 app/Plugin/DebugKit/View/Helper/ToolbarHelper.php create mode 100644 app/Plugin/DebugKit/View/ToolbarAccess/history_state.ctp create mode 100644 app/Plugin/DebugKit/View/ToolbarAccess/sql_explain.ctp create mode 100644 app/Plugin/DebugKit/composer.json create mode 100644 app/Plugin/DebugKit/webroot/css/debug_toolbar.css create mode 100644 app/Plugin/DebugKit/webroot/img/cake.icon.png create mode 100644 app/Plugin/DebugKit/webroot/js/jquery.js create mode 100644 app/Plugin/DebugKit/webroot/js/js_debug_toolbar.js create mode 100644 app/webroot/debug_kit/img/cake.icon.png diff --git a/app/Config/bootstrap.php b/app/Config/bootstrap.php index 4fd73aa..7a13f84 100644 --- a/app/Config/bootstrap.php +++ b/app/Config/bootstrap.php @@ -108,10 +108,12 @@ Configure::write(APP_CONFIG_SCOPE . '.App.apiVersion', 'v1'); // TODO: Move to config file in Instances plugin Configure::write(APP_CONFIG_SCOPE . '.Instances.games', array( - '1' => array( + array( 'name' => 'Space Engineers', 'folder' => 'SPACE_ENGINEERS', 'config' => 'SpaceEngineers-Dedicated.cfg', + 'dedicatedBinary' => 'SpaceEngineersDedicated.exe', + 'sourceBinariesDirectory' => 'C:' . DS . 'Program Files (x86)' . DS . 'Steam' . DS . 'SteamApps' . DS . 'common' . DS . 'SpaceEngineers', 'configOptions' => array( 'SessionSettings' => array( 'gameModes' => array( @@ -231,15 +233,18 @@ ), ) ), - '2' => array( + array( 'name' => 'Medieval Engineers', 'folder' => 'MEDIEVAL_ENGINEERS', 'config' => 'MedievalEngineers-Dedicated.cfg', + 'dedicatedBinary' => 'MedievalEngineersDedicated.exe', + 'sourceBinariesDirectory' => 'C:' . DS . 'Program Files (x86)' . DS . 'Steam' . DS . 'SteamApps' . DS . 'common' . DS . 'MedievalEngineers', ), )); - -Configure::write(APP_CONFIG_SCOPE . '.Instances.serverArchiveDirectory', 'SERVER_ARCHIVES'); + +//Configure::write(APP_CONFIG_SCOPE . '.Instances.serverArchiveDirectory', 'SERVER_ARCHIVES'); Configure::write(APP_CONFIG_SCOPE . '.Instances.serverBinariesDirectory', 'SERVER_BINARIES'); +Configure::write(APP_CONFIG_SCOPE . '.Instances.serverDataSkeletonDirectory', 'SERVER_SKELETON'); Configure::write('Bootstrap.formButtonStyle', array( 'div' => 'col col-md-9 col-md-offset-3', diff --git a/app/Controller/AppController.php b/app/Controller/AppController.php index 29dee72..c414e44 100644 --- a/app/Controller/AppController.php +++ b/app/Controller/AppController.php @@ -55,6 +55,7 @@ class AppController extends Controller { 'authorize' => 'Controller' ), 'RequestHandler', + 'DebugKit.Toolbar', ); public $helpers = array( 'Html' => array('className' => 'BoostCake.BoostCakeHtml'), @@ -69,7 +70,7 @@ class AppController extends Controller { ), ), 'Paginator' => array('className' => 'BoostCake.BoostCakePaginator'), - 'Time' + 'Time', ); // Alert diff --git a/app/Model/User.php b/app/Model/User.php index 8683f24..4a18aac 100644 --- a/app/Model/User.php +++ b/app/Model/User.php @@ -263,7 +263,7 @@ public function resetAccount($user = array()) { private function __sendResetMail() { $user = $this->read(); - $email = new CakeEmail('mandrill'); + $email = new CakeEmail('default'); $email->to($user['User']['email']); $email->subject(Configure::read(APP_CONFIG_SCOPE . '.Email.resetAccountSubject')); $email->template('reset-account'); @@ -271,7 +271,12 @@ private function __sendResetMail() { $email->addHeaders(array( 'tags' => array(Configure::read(APP_CONFIG_SCOPE . '.App.environment') . '-reset-account-email'), )); - return $email->send()[0]['status']; + if (Configure::read(APP_CONFIG_SCOPE . '.App.emailEnabled')) { + return $email->send()[0]['status']; + } else { + debug('E-mail suppressed because e-mail is disabled.'); + return true; + } } public function afterSave($created, $options = array()) { @@ -288,7 +293,7 @@ private function __sendWelcomeMail() { if (!isset($this->data['User']['email'])) { return; } - $email = new CakeEmail('mandrill'); + $email = new CakeEmail('default'); $email->to($this->data['User']['email']); $email->subject(Configure::read(APP_CONFIG_SCOPE . '.Email.newAccountSubject')); $email->template('new-account'); @@ -297,7 +302,11 @@ private function __sendWelcomeMail() { $email->addHeaders(array( 'tags' => array(Configure::read(APP_CONFIG_SCOPE . '.App.environment') . '-new-account-email'), )); - $email->send(); + if (Configure::read(APP_CONFIG_SCOPE . '.App.emailEnabled')) { + $email->send(); + } else { + debug('E-mail suppressed because e-mail is disabled.'); + } } public function acceptEula() { diff --git a/app/Plugin/DebugKit/.gitignore b/app/Plugin/DebugKit/.gitignore new file mode 100644 index 0000000..0edf96e --- /dev/null +++ b/app/Plugin/DebugKit/.gitignore @@ -0,0 +1,16 @@ +*.diff +*.err +*.orig +*.rej +*.swo +*.swp +*.vi +*~ +.DS_Store +.cache +.project +.settings +.svn +errors.err +tags +/nbproject/ \ No newline at end of file diff --git a/app/Plugin/DebugKit/Console/Command/BenchmarkShell.php b/app/Plugin/DebugKit/Console/Command/BenchmarkShell.php new file mode 100644 index 0000000..cb0e593 --- /dev/null +++ b/app/Plugin/DebugKit/Console/Command/BenchmarkShell.php @@ -0,0 +1,159 @@ +args[0]; + $defaults = array('t' => 100, 'n' => 10); + $options = array_merge($defaults, $this->params); + $times = array(); + + $this->out(String::insert(__d('debug_kit', '-> Testing :url'), compact('url'))); + $this->out(""); + for ($i = 0; $i < $options['n']; $i++) { + if (floor($options['t'] - array_sum($times)) <= 0 || $options['n'] <= 1) { + break; + } + + $start = microtime(true); + file_get_contents($url); + $stop = microtime(true); + + $times[] = $stop - $start; + } + $this->_results($times); + } + +/** + * Prints calculated results + * + * @param array $times Array of time values + * @return void + */ + protected function _results($times) { + $duration = array_sum($times); + $requests = count($times); + + $this->out(String::insert(__d('debug_kit', 'Total Requests made: :requests'), compact('requests'))); + $this->out(String::insert(__d('debug_kit', 'Total Time elapsed: :duration (seconds)'), compact('duration'))); + + $this->out(""); + + $this->out(String::insert(__d('debug_kit', 'Requests/Second: :rps req/sec'), array( + 'rps' => round($requests / $duration, 3) + ))); + + $this->out(String::insert(__d('debug_kit', 'Average request time: :average-time seconds'), array( + 'average-time' => round($duration / $requests, 3) + ))); + + $this->out(String::insert(__d('debug_kit', 'Standard deviation of average request time: :std-dev'), array( + 'std-dev' => round($this->_deviation($times, true), 3) + ))); + + $this->out(String::insert(__d('debug_kit', 'Longest/shortest request: :longest sec/:shortest sec'), array( + 'longest' => round(max($times), 3), + 'shortest' => round(min($times), 3) + ))); + + $this->out(""); + } + +/** + * One-pass, numerically stable calculation of population variance. + * + * Donald E. Knuth (1998). + * The Art of Computer Programming, volume 2: Seminumerical Algorithms, 3rd edn., + * p. 232. Boston: Addison-Wesley. + * + * @param array $times Array of values + * @param boolean $sample If true, calculates an unbiased estimate of the population + * variance from a finite sample. + * @return float Variance + */ + protected function _variance($times, $sample = true) { + $n = $mean = $M2 = 0; + + foreach ($times as $time) { + $n += 1; + $delta = $time - $mean; + $mean = $mean + $delta / $n; + $M2 = $M2 + $delta * ($time - $mean); + } + + if ($sample) { + $n -= 1; + } + + return $M2 / $n; + } + +/** + * Calculate the standard deviation. + * + * @param array $times Array of values + * @param boolean $sample + * @return float Standard deviation + */ + protected function _deviation($times, $sample = true) { + return sqrt($this->_variance($times, $sample)); + } + + public function getOptionParser() { + $parser = parent::getOptionParser(); + $parser->description(__d('debug_kit', + 'Allows you to obtain some rough benchmarking statistics' . + 'about a fully qualified URL.' + )) + ->addArgument('url', array( + 'help' => __d('debug_kit', 'The URL to request.'), + 'required' => true + )) + ->addOption('n', array( + 'default' => 10, + 'help' => __d('debug_kit', 'Number of iterations to perform.') + )) + ->addOption('t', array( + 'default' => 100, + 'help' => __d('debug_kit', 'Maximum total time for all iterations, in seconds.' . + 'If a single iteration takes more than the timeout, only one request will be made' + ) + )) + ->epilog(__d('debug_kit', + 'Example Use: `cake benchmark --n 10 --t 100 http://localhost/testsite`. ' . + 'Note: this benchmark does not include browser render times.' + )); + return $parser; + } +} + diff --git a/app/Plugin/DebugKit/Console/Command/WhitespaceShell.php b/app/Plugin/DebugKit/Console/Command/WhitespaceShell.php new file mode 100644 index 0000000..775a9c5 --- /dev/null +++ b/app/Plugin/DebugKit/Console/Command/WhitespaceShell.php @@ -0,0 +1,93 @@ +params['path']) && strpos($this->params['path'], '/') === 0) { + $path = $this->params['path']; + } elseif (!empty($this->params['path'])) { + $path .= $this->params['path']; + } + $folder = new Folder($path); + + $r = $folder->findRecursive('.*\.php'); + $this->out("Checking *.php in " . $path); + foreach ($r as $file) { + $c = file_get_contents($file); + if (preg_match('/^[\n\r|\n\r|\n|\r|\s]+\<\?php/', $c)) { + $this->out('!!!contains leading whitespaces: ' . $this->shortPath($file)); + } + if (preg_match('/\?\>[\n\r|\n\r|\n|\r|\s]+$/', $c)) { + $this->out('!!!contains trailing whitespaces: ' . $this->shortPath($file)); + } + } + } + +/** + * Much like main() except files are modified. Be sure to have + * backups or use version control. + * + * @return void + */ + public function trim() { + $path = APP; + if (!empty($this->params['path']) && strpos($this->params['path'], '/') === 0) { + $path = $this->params['path']; + } elseif (!empty($this->params['path'])) { + $path .= $this->params['path']; + } + $folder = new Folder($path); + + $r = $folder->findRecursive('.*\.php'); + $this->out("Checking *.php in " . $path); + foreach ($r as $file) { + $c = file_get_contents($file); + if (preg_match('/^[\n\r|\n\r|\n|\r|\s]+\<\?php/', $c) || preg_match('/\?\>[\n\r|\n\r|\n|\r|\s]+$/', $c)) { + $this->out('trimming' . $this->shortPath($file)); + $c = preg_replace('/^[\n\r|\n\r|\n|\r|\s]+\<\?php/', '[\n\r|\n\r|\n|\r|\s]+$/', '?>', $c); + file_put_contents($file, $c); + } + } + } + +/** + * get the option parser + * + * @return ConsoleOptionParser + */ + public function getOptionParser() { + $parser = parent::getOptionParser(); + return $parser->addOption('path', array( + 'short' => 'p', + 'help' => __d('cake_console', 'Absolute path or relative to APP.') + )); + } +} diff --git a/app/Plugin/DebugKit/Controller/Component/ToolbarComponent.php b/app/Plugin/DebugKit/Controller/Component/ToolbarComponent.php new file mode 100644 index 0000000..fbb3272 --- /dev/null +++ b/app/Plugin/DebugKit/Controller/Component/ToolbarComponent.php @@ -0,0 +1,504 @@ + false, + 'autoRun' => true + ); + +/** + * Controller instance reference + * + * @var object + */ + public $controller; + +/** + * Components used by DebugToolbar + * + * @var array + */ + public $components = array('RequestHandler', 'Session'); + +/** + * The default panels the toolbar uses. + * which panels are used can be configured when attaching the component + * + * @var array + */ + protected $_defaultPanels = array( + 'DebugKit.History', + 'DebugKit.Session', + 'DebugKit.Request', + 'DebugKit.SqlLog', + 'DebugKit.Timer', + 'DebugKit.Log', + 'DebugKit.Variables', + 'DebugKit.Environment', + 'DebugKit.Include' + ); + +/** + * Loaded panel objects. + * + * @var array + */ + public $panels = array(); + +/** + * javascript files component will be using + * + * @var array + */ + public $javascript = array( + 'libs' => 'DebugKit./js/js_debug_toolbar' + ); + +/** + * CSS files component will be using + * + * @var array + */ + public $css = array('DebugKit./css/debug_toolbar.css'); + +/** + * CacheKey used for the cache file. + * + * @var string + */ + public $cacheKey = 'toolbar_cache'; + +/** + * Duration of the debug kit history cache + * + * @var string + */ + public $cacheDuration = '+4 hours'; + +/** + * Status whether component is enable or disable + * + * @var boolean + */ + public $enabled = true; + +/** + * Constructor + * + * If debug is off the component will be disabled and not do any further time tracking + * or load the toolbar helper. + * + * @param ComponentCollection $collection + * @param array $settings + * @return \ToolbarComponent + */ + public function __construct(ComponentCollection $collection, $settings = array()) { + $settings = array_merge((array)Configure::read('DebugKit'), $settings); + $panels = $this->_defaultPanels; + if (isset($settings['panels'])) { + $panels = $this->_makePanelList($settings['panels']); + unset($settings['panels']); + } + $this->controller = $collection->getController(); + + parent::__construct($collection, array_merge($this->settings, (array)$settings)); + + if ( + !Configure::read('debug') && + empty($this->settings['forceEnable']) + ) { + $this->enabled = false; + return false; + } + if ( + $this->settings['autoRun'] === false && + !isset($this->controller->request->query['debug']) + ) { + $this->enabled = false; + return false; + } + + $this->controller->getEventManager()->attach($this); + + DebugMemory::record(__d('debug_kit', 'Component initialization')); + + $this->cacheKey .= $this->Session->read('Config.userAgent'); + if ( + in_array('DebugKit.History', $panels) || + (isset($settings['history']) && $settings['history'] !== false) + ) { + $this->_createCacheConfig(); + } + + $this->_loadPanels($panels, $settings); + return false; + } + +/** + * Register all the timing handlers for core events. + * + * @return array + */ + public function implementedEvents() { + $before = function ($name) { + return function () use ($name) { + DebugTimer::start($name, $name); + }; + }; + $after = function ($name) { + return function () use ($name) { + DebugTimer::stop($name); + }; + }; + + return array( + 'Controller.initialize' => array( + array('priority' => 0, 'callable' => $before('Event: Controller.initialize')), + array('priority' => 999, 'callable' => $after('Event: Controller.initialize')) + ), + 'Controller.startup' => array( + array('priority' => 0, 'callable' => $before('Event: Controller.startup')), + array('priority' => 999, 'callable' => $after('Event: Controller.startup')) + ), + 'Controller.beforeRender' => array( + array('priority' => 0, 'callable' => $before('Event: Controller.beforeRender')), + array('priority' => 999, 'callable' => $after('Event: Controller.beforeRender')) + ), + 'Controller.shutdown' => array( + array('priority' => 0, 'callable' => $before('Event: Controller.shutdown')), + array('priority' => 999, 'callable' => $after('Event: Controller.shutdown')) + ), + 'View.beforeRender' => array( + array('priority' => 0, 'callable' => $before('Event: View.beforeRender')), + array('priority' => 999, 'callable' => $after('Event: View.beforeRender')) + ), + 'View.afterRender' => array( + array('priority' => 0, 'callable' => $before('Event: View.afterRender')), + array('priority' => 999, 'callable' => $after('Event: View.afterRender')) + ), + 'View.beforeLayout' => array( + array('priority' => 0, 'callable' => $before('Event: View.beforeLayout')), + array('priority' => 999, 'callable' => $after('Event: View.beforeLayout')) + ), + 'View.afterLayout' => array( + array('priority' => 0, 'callable' => $before('Event: View.afterLayout')), + array('priority' => 999, 'callable' => $after('Event: View.afterLayout')) + ), + ); + } + +/** + * Initialize callback. + * If automatically disabled, tell component collection about the state. + * + * @param Controller $controller + * @return boolean + */ + public function initialize(Controller $controller) { + if (!$this->enabled) { + $this->_Collection->disable('Toolbar'); + } + } + +/** + * Go through user panels and remove default panels as indicated. + * + * @param array $userPanels The list of panels ther user has added removed. + * @return array Array of panels to use. + */ + protected function _makePanelList($userPanels) { + $panels = $this->_defaultPanels; + foreach ($userPanels as $key => $value) { + if (is_numeric($key)) { + $panels[] = $value; + } + if (is_string($key) && $value === false) { + $index = array_search($key, $panels); + if ($index !== false) { + unset($panels[$index]); + } + // Compatibility for when panels were not + // required to have a plugin prefix. + $alternate = 'DebugKit.' . ucfirst($key); + $index = array_search($alternate, $panels); + if ($index !== false) { + unset($panels[$index]); + } + } + } + return $panels; + } + +/** + * Component Startup + * + * @param Controller $controller + * @return boolean + */ + public function startup(Controller $controller) { + $panels = array_keys($this->panels); + foreach ($panels as $panelName) { + $this->panels[$panelName]->startup($controller); + } + DebugTimer::start( + 'controllerAction', + __d('debug_kit', 'Controller action') + ); + DebugMemory::record( + __d('debug_kit', 'Controller action start') + ); + } + +/** + * beforeRedirect callback + * + * @param Controller $controller + * @param $url + * @param null $status + * @param boolean $exit + * @return void + */ + public function beforeRedirect(Controller $controller, $url, $status = null, $exit = true) { + if (!class_exists('DebugTimer')) { + return null; + } + DebugTimer::stop('controllerAction'); + DebugTimer::start( + 'processToolbar', + __d('debug_kit', 'Processing toolbar state') + ); + $vars = $this->_gatherVars($controller); + $this->_saveState($controller, $vars); + DebugTimer::stop('processToolbar'); + } + +/** + * beforeRender callback + * + * Calls beforeRender on all the panels and set the aggregate to the controller. + * + * @param Controller $controller + * @return void + */ + public function beforeRender(Controller $controller) { + if (!class_exists('DebugTimer')) { + return null; + } + DebugTimer::stop('controllerAction'); + + DebugTimer::start( + 'processToolbar', + __d('debug_kit', 'Processing toolbar data') + ); + $vars = $this->_gatherVars($controller); + $this->_saveState($controller, $vars); + + $this->javascript = array_unique(array_merge($this->javascript, $vars['javascript'])); + $this->css = array_unique(array_merge($this->css, $vars['css'])); + unset($vars['javascript'], $vars['css']); + + $controller->set(array( + 'debugToolbarPanels' => $vars, + 'debugToolbarJavascript' => $this->javascript, + 'debugToolbarCss' => $this->css + )); + + $isHtml = ( + !isset($controller->request->params['ext']) || + $controller->request->params['ext'] === 'html' + ); + + if (!$controller->request->is('ajax') && $isHtml) { + $format = 'Html'; + } else { + $format = 'FirePhp'; + } + + $controller->helpers[] = 'DebugKit.DebugTimer'; + $controller->helpers['DebugKit.Toolbar'] = array( + 'output' => sprintf('DebugKit.%sToolbar', $format), + 'cacheKey' => $this->cacheKey, + 'cacheConfig' => 'debug_kit', + 'forceEnable' => $this->settings['forceEnable'], + ); + + DebugTimer::stop('processToolbar'); + DebugMemory::record(__d('debug_kit', 'Controller render start')); + } + +/** + * Load a toolbar state from cache + * + * @param integer $key + * @return array + */ + public function loadState($key) { + $history = Cache::read($this->cacheKey, 'debug_kit'); + if (isset($history[$key])) { + return $history[$key]; + } + return array(); + } + +/** + * Create the cache config for the history + * + * @return void + */ + protected function _createCacheConfig() { + if (Configure::read('Cache.disable') === true || Cache::config('debug_kit')) { + return; + } + $cache = array( + 'duration' => $this->cacheDuration, + 'engine' => 'File', + 'path' => CACHE + ); + if (isset($this->settings['cache'])) { + $cache = array_merge($cache, $this->settings['cache']); + } + Cache::config('debug_kit', $cache); + } + +/** + * collects the panel contents + * + * @param Controller $controller + * @return array Array of all panel beforeRender() + */ + protected function _gatherVars(Controller $controller) { + $vars = array('javascript' => array(), 'css' => array()); + $panels = array_keys($this->panels); + + foreach ($panels as $panelName) { + $panel = $this->panels[$panelName]; + $panelName = Inflector::underscore($panelName); + $vars[$panelName]['content'] = $panel->beforeRender($controller); + $elementName = Inflector::underscore($panelName) . '_panel'; + if (isset($panel->elementName)) { + $elementName = $panel->elementName; + } + $vars[$panelName]['elementName'] = $elementName; + $vars[$panelName]['plugin'] = $panel->plugin; + $vars[$panelName]['title'] = $panel->title; + $vars[$panelName]['disableTimer'] = true; + + if (!empty($panel->javascript)) { + $vars['javascript'] = array_merge($vars['javascript'], (array)$panel->javascript); + } + if (!empty($panel->css)) { + $vars['css'] = array_merge($vars['css'], (array)$panel->css); + } + } + return $vars; + } + +/** + * Load Panels used in the debug toolbar + * + * @param $panels + * @param $settings + * @return void + */ + protected function _loadPanels($panels, $settings) { + foreach ($panels as $panel) { + $className = ucfirst($panel) . 'Panel'; + list($plugin, $className) = pluginSplit($className, true); + + App::uses($className, $plugin . 'Panel'); + if (!class_exists($className)) { + trigger_error(__d('debug_kit', 'Could not load DebugToolbar panel %s', $panel), E_USER_WARNING); + continue; + } + $panelObj = new $className($settings); + if ($panelObj instanceof DebugPanel) { + list(, $panel) = pluginSplit($panel); + $this->panels[Inflector::underscore($panel)] = $panelObj; + } + } + } + +/** + * Save the current state of the toolbar varibles to the cache file. + * + * @param \Controller|object $controller Controller instance + * @param array $vars Vars to save. + * @return void + */ + protected function _saveState(Controller $controller, $vars) { + $config = Cache::config('debug_kit'); + if (empty($config) || !isset($this->panels['history'])) { + return; + } + $history = Cache::read($this->cacheKey, 'debug_kit'); + if (empty($history)) { + $history = array(); + } + if (count($history) == $this->panels['history']->history) { + array_pop($history); + } + + if (isset($vars['variables']['content'])) { + // Remove unserializable native objects. + array_walk_recursive($vars['variables']['content'], function (&$item) { + if ( + $item instanceof Closure || + $item instanceof PDO || + $item instanceof SimpleXmlElement + ) { + $item = 'Unserializable object - ' . get_class($item); + } elseif ($item instanceof Exception) { + $item = sprintf( + 'Unserializable object - %s. Error: %s in %s, line %s', + get_class($item), + $item, + $item->getMessage(), + $item->getFile(), + $item->getLine() + ); + } + return $item; + }); + } + unset($vars['history']); + array_unshift($history, $vars); + Cache::write($this->cacheKey, $history, 'debug_kit'); + } + +} diff --git a/app/Plugin/DebugKit/Controller/DebugKitAppController.php b/app/Plugin/DebugKit/Controller/DebugKitAppController.php new file mode 100644 index 0000000..473b6e3 --- /dev/null +++ b/app/Plugin/DebugKit/Controller/DebugKitAppController.php @@ -0,0 +1,25 @@ + array('output' => 'DebugKit.HtmlToolbar'), + 'Js', 'Number', 'DebugKit.SimpleGraph' + ); + +/** + * Components + * + * @var array + */ + public $components = array('RequestHandler', 'DebugKit.Toolbar'); + +/** + * Uses + * + * @var array + */ + public $uses = array('DebugKit.ToolbarAccess'); + +/** + * beforeFilter callback + * + * @return void + */ + public function beforeFilter() { + parent::beforeFilter(); + if (isset($this->Toolbar)) { + $this->Components->disable('Toolbar'); + } + $this->helpers['DebugKit.Toolbar']['cacheKey'] = $this->Toolbar->cacheKey; + $this->helpers['DebugKit.Toolbar']['cacheConfig'] = 'debug_kit'; + + if (isset($this->Auth) && method_exists($this->Auth, 'mapActions')) { + $this->Auth->mapActions(array( + 'read' => array('history_state', 'sql_explain') + )); + } + } + +/** + * Get a stored history state from the toolbar cache. + * + * @param null $key + * @return void + */ + public function history_state($key = null) { + if (Configure::read('debug') == 0) { + return $this->redirect($this->referer()); + } + $oldState = $this->Toolbar->loadState($key); + $this->set('toolbarState', $oldState); + $this->set('debugKitInHistoryMode', true); + $this->viewClass = null; + $this->layout = null; + } + +/** + * Run SQL explain/profiling on queries. Checks the hash + the hashed queries, + * if there is mismatch a 404 will be rendered. If debug == 0 a 404 will also be + * rendered. No explain will be run if a 404 is made. + * + * @throws BadRequestException + * @return void + */ + public function sql_explain() { + if ( + !$this->request->is('post') || + empty($this->request->data['log']['sql']) || + empty($this->request->data['log']['ds']) || + empty($this->request->data['log']['hash']) || + Configure::read('debug') == 0 + ) { + throw new BadRequestException('Invalid parameters'); + } + $hash = Security::hash($this->request->data['log']['sql'] . $this->request->data['log']['ds'], 'sha1', true); + if ($hash !== $this->request->data['log']['hash']) { + throw new BadRequestException('Invalid parameters'); + } + $result = $this->ToolbarAccess->explainQuery($this->request->data['log']['ds'], $this->request->data['log']['sql']); + $this->set(compact('result')); + } + +} diff --git a/app/Plugin/DebugKit/LICENSE.txt b/app/Plugin/DebugKit/LICENSE.txt new file mode 100644 index 0000000..d031766 --- /dev/null +++ b/app/Plugin/DebugKit/LICENSE.txt @@ -0,0 +1,28 @@ +The MIT License + +CakePHP(tm) : The Rapid Development PHP Framework (http://cakephp.org) +Copyright (c) 2005-2015, Cake Software Foundation, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +Cake Software Foundation, Inc. +1785 E. Sahara Avenue, +Suite 490-204 +Las Vegas, Nevada 89104, +United States of America. diff --git a/app/Plugin/DebugKit/Lib/DebugKitDebugger.php b/app/Plugin/DebugKit/Lib/DebugKitDebugger.php new file mode 100644 index 0000000..14080fa --- /dev/null +++ b/app/Plugin/DebugKit/Lib/DebugKitDebugger.php @@ -0,0 +1,227 @@ + 0) { + return; + } + $timers = array_values($timers); + $end = end($timers); + echo ''; + echo ''; + echo ''; + $i = 0; + foreach ($timers as $timer) { + $indent = 0; + for ($j = 0; $j < $i; $j++) { + if (($timers[$j]['end']) > ($timer['start']) && ($timers[$j]['end']) > ($timer['end'])) { + $indent++; + } + } + $indent = str_repeat(' » ', $indent); + + extract($timer); + $start = round($start * 1000, 0); + $end = round($end * 1000, 0); + $time = round($time * 1000, 0); + echo ""; + $i++; + } + echo '
Debug timer info
MessageStart Time (ms)End Time (ms)Duration (ms)
{$indent}$message$start$end$time
'; + } + +/** + * Start an benchmarking timer. + * + * @param string $name The name of the timer to start. + * @param string $message A message for your timer + * @return boolean true + * @deprecated use DebugTimer::start() + */ + public static function startTimer($name = null, $message = null) { + return DebugTimer::start($name, $message); + } + +/** + * Stop a benchmarking timer. + * + * $name should be the same as the $name used in startTimer(). + * + * @param string $name The name of the timer to end. + * @return boolean true if timer was ended, false if timer was not started. + * @deprecated use DebugTimer::stop() + */ + public static function stopTimer($name = null) { + return DebugTimer::stop($name); + } + +/** + * Get all timers that have been started and stopped. + * Calculates elapsed time for each timer. If clear is true, will delete existing timers + * + * @param boolean $clear false + * @return array + * @deprecated use DebugTimer::getAll() + */ + public static function getTimers($clear = false) { + return DebugTimer::getAll($clear); + } + +/** + * Clear all existing timers + * + * @return boolean true + * @deprecated use DebugTimer::clear() + */ + public static function clearTimers() { + return DebugTimer::clear(); + } + +/** + * Get the difference in time between the timer start and timer end. + * + * @param $name string the name of the timer you want elapsed time for. + * @param $precision int the number of decimal places to return, defaults to 5. + * @return float number of seconds elapsed for timer name, 0 on missing key + * @deprecated use DebugTimer::elapsedTime() + */ + public static function elapsedTime($name = 'default', $precision = 5) { + return DebugTimer::elapsedTime($name, $precision); + } + +/** + * Get the total execution time until this point + * + * @return float elapsed time in seconds since script start. + * @deprecated use DebugTimer::requestTime() + */ + public static function requestTime() { + return DebugTimer::requestTime(); + } + +/** + * get the time the current request started. + * + * @return float time of request start + * @deprecated use DebugTimer::requestStartTime() + */ + public static function requestStartTime() { + return DebugTimer::requestStartTime(); + } + +/** + * get current memory usage + * + * @return integer number of bytes ram currently in use. 0 if memory_get_usage() is not available. + * @deprecated Use DebugMemory::getCurrent() instead. + */ + public static function getMemoryUse() { + return DebugMemory::getCurrent(); + } + +/** + * Get peak memory use + * + * @return integer peak memory use (in bytes). Returns 0 if memory_get_peak_usage() is not available + * @deprecated Use DebugMemory::getPeak() instead. + */ + public static function getPeakMemoryUse() { + return DebugMemory::getPeak(); + } + +/** + * Stores a memory point in the internal tracker. + * Takes a optional message name which can be used to identify the memory point. + * If no message is supplied a debug_backtrace will be done to identifty the memory point. + * If you don't have memory_get_xx methods this will not work. + * + * @param string $message Message to identify this memory point. + * @return boolean + * @deprecated Use DebugMemory::getAll() instead. + */ + public static function setMemoryPoint($message = null) { + return DebugMemory::record($message); + } + +/** + * Get all the stored memory points + * + * @param boolean $clear Whether you want to clear the memory points as well. Defaults to false. + * @return array Array of memory marks stored so far. + * @deprecated Use DebugMemory::getAll() instead. + */ + public static function getMemoryPoints($clear = false) { + return DebugMemory::getAll($clear); + } + +/** + * Clear out any existing memory points + * + * @return void + * @deprecated Use DebugMemory::clear() instead. + */ + public static function clearMemoryPoints() { + DebugMemory::clear(); + } + +/** + * Create a FirePHP error message + * + * @param array $data Data of the error + * @param array $links Links for the error + * @return void + */ + public static function fireError($data, $links) { + $name = $data['error'] . ' - ' . $data['description']; + $message = "{$data['error']} {$data['code']} {$data['description']} on line: {$data['line']} in file: {$data['file']}"; + FireCake::group($name); + FireCake::error($message, $name); + if (isset($data['context'])) { + FireCake::log($data['context'], 'Context'); + } + if (isset($data['trace'])) { + FireCake::log(preg_split('/[\r\n]+/', $data['trace']), 'Trace'); + } + FireCake::groupEnd(); + } + +} + +DebugKitDebugger::getInstance('DebugKitDebugger'); +Debugger::addFormat('fb', array('callback' => 'DebugKitDebugger::fireError')); diff --git a/app/Plugin/DebugKit/Lib/DebugMemory.php b/app/Plugin/DebugKit/Lib/DebugMemory.php new file mode 100644 index 0000000..cb3e985 --- /dev/null +++ b/app/Plugin/DebugKit/Lib/DebugMemory.php @@ -0,0 +1,98 @@ + 1) { + $message .= ' #' . $i; + } + + self::$_timers[$name] = array( + 'start' => $start, + 'message' => $message, + 'named' => $named + ); + return true; + } + +/** + * Stop a benchmarking timer. + * + * $name should be the same as the $name used in startTimer(). + * + * @param string $name The name of the timer to end. + * @return boolean true if timer was ended, false if timer was not started. + */ + public static function stop($name = null) { + $end = microtime(true); + if (!$name) { + $names = array_reverse(array_keys(self::$_timers)); + foreach ($names as $name) { + if (!empty(self::$_timers[$name]['end'])) { + continue; + } + if (empty(self::$_timers[$name]['named'])) { + break; + } + } + } else { + $i = 1; + $_name = $name; + while (isset(self::$_timers[$name])) { + if (empty(self::$_timers[$name]['end'])) { + break; + } + $i++; + $name = $_name . ' #' . $i; + } + } + if (!isset(self::$_timers[$name])) { + return false; + } + self::$_timers[$name]['end'] = $end; + return true; + } + +/** + * Get all timers that have been started and stopped. + * Calculates elapsed time for each timer. If clear is true, will delete existing timers + * + * @param boolean $clear false + * @return array + */ + public static function getAll($clear = false) { + $start = self::requestStartTime(); + $now = microtime(true); + + $times = array(); + if (!empty(self::$_timers)) { + $firstTimer = reset(self::$_timers); + $_end = $firstTimer['start']; + } else { + $_end = $now; + } + $times['Core Processing (Derived from $_SERVER["REQUEST_TIME"])'] = array( + 'message' => __d('debug_kit', 'Core Processing (Derived from $_SERVER["REQUEST_TIME"])'), + 'start' => 0, + 'end' => $_end - $start, + 'time' => round($_end - $start, 6), + 'named' => null + ); + foreach (self::$_timers as $name => $timer) { + if (!isset($timer['end'])) { + $timer['end'] = $now; + } + $times[$name] = array_merge($timer, array( + 'start' => $timer['start'] - $start, + 'end' => $timer['end'] - $start, + 'time' => self::elapsedTime($name) + )); + } + if ($clear) { + self::$_timers = array(); + } + return $times; + } + +/** + * Clear all existing timers + * + * @return boolean true + */ + public static function clear() { + self::$_timers = array(); + return true; + } + +/** + * Get the difference in time between the timer start and timer end. + * + * @param $name string the name of the timer you want elapsed time for. + * @param $precision int the number of decimal places to return, defaults to 5. + * @return float number of seconds elapsed for timer name, 0 on missing key + */ + public static function elapsedTime($name = 'default', $precision = 5) { + if (!isset(self::$_timers[$name]['start']) || !isset(self::$_timers[$name]['end'])) { + return 0; + } + return round(self::$_timers[$name]['end'] - self::$_timers[$name]['start'], $precision); + } + +/** + * Get the total execution time until this point + * + * @return float elapsed time in seconds since script start. + */ + public static function requestTime() { + $start = self::requestStartTime(); + $now = microtime(true); + return ($now - $start); + } + +/** + * get the time the current request started. + * + * @return float time of request start + */ + public static function requestStartTime() { + if (defined('TIME_START')) { + $startTime = TIME_START; + } elseif (isset($GLOBALS['TIME_START'])) { + $startTime = $GLOBALS['TIME_START']; + } else { + $startTime = env('REQUEST_TIME'); + } + return $startTime; + } + +} diff --git a/app/Plugin/DebugKit/Lib/FireCake.php b/app/Plugin/DebugKit/Lib/FireCake.php new file mode 100644 index 0000000..912f5a6 --- /dev/null +++ b/app/Plugin/DebugKit/Lib/FireCake.php @@ -0,0 +1,538 @@ + 10, + 'maxArrayDepth' => 20, + 'useNativeJsonEncode' => true, + 'includeLineNumbers' => true, + ); + +/** + * Message Levels for messages sent via FirePHP + * + * @var array + */ + protected $_levels = array( + 'log' => 'LOG', + 'info' => 'INFO', + 'warn' => 'WARN', + 'error' => 'ERROR', + 'dump' => 'DUMP', + 'trace' => 'TRACE', + 'exception' => 'EXCEPTION', + 'table' => 'TABLE', + 'groupStart' => 'GROUP_START', + 'groupEnd' => 'GROUP_END', + ); + +/** + * Version number for X-Wf-1-Plugin-1 HTML header + * + * @var string + */ + protected $_version = '0.2.1'; + +/** + * internal messageIndex counter + * + * @var integer + */ + protected $_messageIndex = 1; + +/** + * stack of objects encoded by stringEncode() + * + * @var array + */ + protected $_encodedObjects = array(); + +/** + * methodIndex to include in tracebacks when using includeLineNumbers + * + * @var array + */ + protected $_methodIndex = array('info', 'log', 'warn', 'error', 'table', 'trace'); + +/** + * FireCake output status + * + * @var boolean + */ + protected $_enabled = true; + +/** + * get Instance of the singleton + * + * @param string $class Class instance to store in the singleton. Used with subclasses and Tests. + * @return FireCake + */ + public static function getInstance($class = null) { + static $instance = array(); + if (!empty($class)) { + if (!$instance || strtolower($class) !== strtolower(get_class($instance[0]))) { + $instance[0] = new $class(); + $instance[0]->setOptions(); + } + } + if (!isset($instance[0]) || !$instance[0]) { + $instance[0] = new FireCake(); + $instance[0]->setOptions(); + } + return $instance[0]; + } + +/** + * setOptions + * + * @param array $options Array of options to set. + * @return void + */ + public static function setOptions($options = array()) { + $_this = FireCake::getInstance(); + if (empty($_this->options)) { + $_this->options = array_merge($_this->_defaultOptions, $options); + } else { + $_this->options = array_merge($_this->options, $options); + } + } + +/** + * Return boolean based on presence of FirePHP extension + * + * @return boolean + */ + public static function detectClientExtension() { + $ua = FireCake::getUserAgent(); + if (preg_match('/\sFirePHP\/([\.|\d]*)\s?/si', $ua, $match) && version_compare($match[1], '0.0.6', '>=')) { + return true; + } + if (env('HTTP_X_FIREPHP_VERSION') && version_compare(env('HTTP_X_FIREPHP_VERSION'), '0.6', '>=')) { + return true; + } + return false; + } + +/** + * Get the Current UserAgent + * + * @return string UserAgent string of active client connection + */ + public static function getUserAgent() { + return env('HTTP_USER_AGENT'); + } + +/** + * Disable FireCake output + * All subsequent output calls will not be run. + * + * @return void + */ + public static function disable() { + $_this = FireCake::getInstance(); + $_this->_enabled = false; + } + +/** + * Enable FireCake output + * + * @return void + */ + public static function enable() { + $_this = FireCake::getInstance(); + $_this->_enabled = true; + } + +/** + * Convenience wrapper for LOG messages + * + * @param string $message Message to log + * @param string $label Label for message (optional) + * @return void + */ + public static function log($message, $label = null) { + FireCake::fb($message, $label, 'log'); + } + +/** + * Convenience wrapper for WARN messages + * + * @param string $message Message to log + * @param string $label Label for message (optional) + * @return void + */ + public static function warn($message, $label = null) { + FireCake::fb($message, $label, 'warn'); + } + +/** + * Convenience wrapper for INFO messages + * + * @param string $message Message to log + * @param string $label Label for message (optional) + * @return void + */ + public static function info($message, $label = null) { + FireCake::fb($message, $label, 'info'); + } + +/** + * Convenience wrapper for ERROR messages + * + * @param string $message Message to log + * @param string $label Label for message (optional) + * @return void + */ + public static function error($message, $label = null) { + FireCake::fb($message, $label, 'error'); + } + +/** + * Convenience wrapper for TABLE messages + * + * @param string $label Label for message (optional) + * @param string $message Message to log + * @return void + */ + public static function table($label, $message) { + FireCake::fb($message, $label, 'table'); + } + +/** + * Convenience wrapper for DUMP messages + * + * @param string $label Unique label for message + * @param string $message Message to log + * @return void + */ + public static function dump($label, $message) { + FireCake::fb($message, $label, 'dump'); + } + +/** + * Convenience wrapper for TRACE messages + * + * @param string $label Label for message (optional) + * @return void + */ + public static function trace($label) { + FireCake::fb($label, 'trace'); + } + +/** + * Convenience wrapper for GROUP messages + * Messages following the group call will be nested in a group block + * + * @param string $label Label for group (optional) + * @return void + */ + public static function group($label) { + FireCake::fb(null, $label, 'groupStart'); + } + +/** + * Convenience wrapper for GROUPEND messages + * Closes a group block + * + * @internal param string $label Label for group (optional) + * @return void + */ + public static function groupEnd() { + FireCake::fb(null, null, 'groupEnd'); + } + +/** + * fb - Send messages with FireCake to FirePHP + * + * Much like FirePHP's fb() this method can be called with various parameter counts + * fb($message) - Just send a message defaults to LOG type + * fb($message, $type) - Send a message with a specific type + * fb($message, $label, $type) - Send a message with a custom label and type. + * + * @param mixed $message Message to output. For other parameters see usage above. + * @return boolean Success + */ + public static function fb($message) { + $_this = FireCake::getInstance(); + + if (headers_sent($filename, $linenum)) { + trigger_error(__d('debug_kit', 'Headers already sent in %s on line %s. Cannot send log data to FirePHP.', $filename, $linenum), E_USER_WARNING); + return false; + } + if (!$_this->_enabled || !$_this->detectClientExtension()) { + return false; + } + + $args = func_get_args(); + $type = $label = null; + switch (count($args)) { + case 1: + $type = $_this->_levels['log']; + break; + case 2: + $type = $args[1]; + break; + case 3: + $type = $args[2]; + $label = $args[1]; + break; + default: + trigger_error(__d('debug_kit', 'Incorrect parameter count for FireCake::fb()'), E_USER_WARNING); + return false; + } + if (isset($_this->_levels[$type])) { + $type = $_this->_levels[$type]; + } else { + $type = $_this->_levels['log']; + } + + $meta = array(); + $skipFinalObjectEncode = false; + if ($type == $_this->_levels['trace']) { + $trace = debug_backtrace(); + if (!$trace) { + return false; + } + $message = FireCake::_parseTrace($trace, $args[0]); + $skipFinalObjectEncode = true; + } + + if ($_this->options['includeLineNumbers']) { + if (!isset($meta['file']) || !isset($meta['line'])) { + $trace = debug_backtrace(); + for ($i = 0, $len = count($trace); $i < $len; $i++) { + $keySet = (isset($trace[$i]['class']) && isset($trace[$i]['function'])); + $selfCall = ($keySet && + strtolower($trace[$i]['class']) === 'firecake' && + in_array($trace[$i]['function'], $_this->_methodIndex) + ); + if ($selfCall) { + $meta['File'] = isset($trace[$i]['file']) ? Debugger::trimPath($trace[$i]['file']) : ''; + $meta['Line'] = isset($trace[$i]['line']) ? $trace[$i]['line'] : ''; + break; + } + } + } + } + + $structureIndex = 1; + if ($type == $_this->_levels['dump']) { + $structureIndex = 2; + $_this->_sendHeader('X-Wf-1-Structure-2', 'http://meta.firephp.org/Wildfire/Structure/FirePHP/Dump/0.1'); + } else { + $_this->_sendHeader('X-Wf-1-Structure-1', 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1'); + } + + $_this->_sendHeader('X-Wf-Protocol-1', 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2'); + $_this->_sendHeader('X-Wf-1-Plugin-1', 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/' . $_this->_version); + if ($type == $_this->_levels['groupStart']) { + $meta['Collapsed'] = 'true'; + } + if ($type == $_this->_levels['dump']) { + $dump = FireCake::jsonEncode($message); + $msg = '{"' . $label . '":' . $dump . '}'; + } else { + $meta['Type'] = $type; + if ($label !== null) { + $meta['Label'] = $label; + } + $msg = '[' . $_this->jsonEncode($meta) . ',' . $_this->jsonEncode($message, $skipFinalObjectEncode) . ']'; + } + + $lines = explode("\n", chunk_split($msg, 5000, "\n")); + + foreach ($lines as $i => $line) { + if (empty($line)) { + continue; + } + $header = 'X-Wf-1-' . $structureIndex . '-1-' . $_this->_messageIndex; + if (count($lines) > 2) { + $first = ($i == 0) ? strlen($msg) : ''; + $end = ($i < count($lines) - 2) ? '\\' : ''; + $message = $first . '|' . $line . '|' . $end; + $_this->_sendHeader($header, $message); + } else { + $_this->_sendHeader($header, strlen($line) . '|' . $line . '|'); + } + $_this->_messageIndex++; + if ($_this->_messageIndex > 99999) { + trigger_error(__d('debug_kit', 'Maximum number (99,999) of messages reached!'), E_USER_WARNING); + } + } + $_this->_sendHeader('X-Wf-1-Index', $_this->_messageIndex - 1); + return true; + } + +/** + * Parse a debug backtrace + * + * @param array $trace Debug backtrace output + * @param $messageName + * @return array + */ + protected static function _parseTrace($trace, $messageName) { + $message = array(); + for ($i = 0, $len = count($trace); $i < $len; $i++) { + $keySet = (isset($trace[$i]['class']) && isset($trace[$i]['function'])); + $selfCall = ($keySet && $trace[$i]['class'] === 'FireCake'); + if (!$selfCall) { + $message = array( + 'Class' => isset($trace[$i]['class']) ? $trace[$i]['class'] : '', + 'Type' => isset($trace[$i]['type']) ? $trace[$i]['type'] : '', + 'Function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : '', + 'Message' => $messageName, + 'File' => isset($trace[$i]['file']) ? Debugger::trimPath($trace[$i]['file']) : '', + 'Line' => isset($trace[$i]['line']) ? $trace[$i]['line'] : '', + 'Args' => isset($trace[$i]['args']) ? FireCake::stringEncode($trace[$i]['args']) : '', + 'Trace' => FireCake::_escapeTrace(array_splice($trace, $i + 1)) + ); + break; + } + } + return $message; + } + +/** + * Fix a trace for use in output + * + * @param mixed $trace Trace to fix + * @return string + */ + protected static function _escapeTrace($trace) { + for ($i = 0, $len = count($trace); $i < $len; $i++) { + if (isset($trace[$i]['file'])) { + $trace[$i]['file'] = Debugger::trimPath($trace[$i]['file']); + } + if (isset($trace[$i]['args'])) { + $trace[$i]['args'] = FireCake::stringEncode($trace[$i]['args']); + } + } + return $trace; + } + +/** + * Encode non string objects to string. + * Filter out recursion, so no errors are raised by json_encode or $javascript->object() + * + * @param mixed $object Object or variable to encode to string. + * @param integer $objectDepth Current Depth in object chains. + * @param integer $arrayDepth Current Depth in array chains. + * @return string|Object + */ + public static function stringEncode($object, $objectDepth = 1, $arrayDepth = 1) { + $_this = FireCake::getInstance(); + $return = array(); + if (is_resource($object)) { + return '** ' . (string)$object . '**'; + } + if (is_object($object)) { + if ($objectDepth == $_this->options['maxObjectDepth']) { + return '** Max Object Depth (' . $_this->options['maxObjectDepth'] . ') **'; + } + foreach ($_this->_encodedObjects as $encoded) { + if ($encoded === $object) { + return '** Recursion (' . get_class($object) . ') **'; + } + } + $_this->_encodedObjects[] = $object; + + $return['__className'] = $class = get_class($object); + $properties = get_object_vars($object); + foreach ($properties as $name => $property) { + $return[$name] = FireCake::stringEncode($property, 1, $objectDepth + 1); + } + array_pop($_this->_encodedObjects); + } + if (is_array($object)) { + if ($arrayDepth == $_this->options['maxArrayDepth']) { + return '** Max Array Depth (' . $_this->options['maxArrayDepth'] . ') **'; + } + foreach ($object as $key => $value) { + $return[$key] = FireCake::stringEncode($value, 1, $arrayDepth + 1); + } + } + if (is_string($object) || is_numeric($object) || is_bool($object) || $object === null) { + return $object; + } + return $return; + } + +/** + * Encode an object into JSON + * + * @param mixed $object Object or array to json encode + * @param boolean $skipEncode + * @internal param bool $doIt + * @static + * @return string + */ + public static function jsonEncode($object, $skipEncode = false) { + $_this = FireCake::getInstance(); + if (!$skipEncode) { + $object = FireCake::stringEncode($object); + } + return json_encode($object); + } + +/** + * Send Headers - write headers. + * + * @param $name + * @param $value + * @return void + */ + protected function _sendHeader($name, $value) { + header($name . ': ' . $value); + } +} diff --git a/app/Plugin/DebugKit/Lib/Log/Engine/DebugKitLog.php b/app/Plugin/DebugKit/Lib/Log/Engine/DebugKitLog.php new file mode 100644 index 0000000..08c30a2 --- /dev/null +++ b/app/Plugin/DebugKit/Lib/Log/Engine/DebugKitLog.php @@ -0,0 +1,50 @@ +logger = $this; + } + +/** + * Captures log messages in memory + * + * @param $type + * @param $message + * @return void + */ + public function write($type, $message) { + if (!isset($this->logs[$type])) { + $this->logs[$type] = array(); + } + $this->logs[$type][] = array(date('Y-m-d H:i:s'), (string)$message); + } +} diff --git a/app/Plugin/DebugKit/Lib/Panel/EnvironmentPanel.php b/app/Plugin/DebugKit/Lib/Panel/EnvironmentPanel.php new file mode 100644 index 0000000..1117a79 --- /dev/null +++ b/app/Plugin/DebugKit/Lib/Panel/EnvironmentPanel.php @@ -0,0 +1,81 @@ + $phpVer), $_SERVER); + unset($return['php']['argv']); + + // CakePHP Data + $return['cake'] = array( + 'APP' => APP, + 'APP_DIR' => APP_DIR, + 'APPLIBS' => APPLIBS, + 'CACHE' => CACHE, + 'CAKE' => CAKE, + 'CAKE_CORE_INCLUDE_PATH' => CAKE_CORE_INCLUDE_PATH, + 'CORE_PATH' => CORE_PATH, + 'CAKE_VERSION' => Configure::version(), + 'CSS' => CSS, + 'CSS_URL' => CSS_URL, + 'DS' => DS, + 'FULL_BASE_URL' => FULL_BASE_URL, + 'IMAGES' => IMAGES, + 'IMAGES_URL' => IMAGES_URL, + 'JS' => JS, + 'JS_URL' => JS_URL, + 'LOGS' => LOGS, + 'ROOT' => ROOT, + 'TESTS' => TESTS, + 'TMP' => TMP, + 'VENDORS' => VENDORS, + 'WEBROOT_DIR' => WEBROOT_DIR, + 'WWW_ROOT' => WWW_ROOT + ); + + $cakeConstants = array_fill_keys( + array( + 'DS', 'ROOT', 'FULL_BASE_URL', 'TIME_START', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'WEEK', 'MONTH', 'YEAR', + 'LOG_ERROR', 'FULL_BASE_URL' + ), '' + ); + $var = get_defined_constants(true); + $return['app'] = array_diff_key($var['user'], $return['cake'], $cakeConstants); + + if (isset($var['hidef'])) { + $return['hidef'] = $var['hidef']; + } + + return $return; + } +} diff --git a/app/Plugin/DebugKit/Lib/Panel/HistoryPanel.php b/app/Plugin/DebugKit/Lib/Panel/HistoryPanel.php new file mode 100644 index 0000000..eb06d56 --- /dev/null +++ b/app/Plugin/DebugKit/Lib/Panel/HistoryPanel.php @@ -0,0 +1,83 @@ +history = $settings['history']; + } + } + +/** + * beforeRender callback function + * + * @param Controller $controller + * @return array contents for panel + */ + public function beforeRender(Controller $controller) { + $cacheKey = $controller->Toolbar->cacheKey; + $toolbarHistory = Cache::read($cacheKey, 'debug_kit'); + $historyStates = array(); + if (is_array($toolbarHistory) && !empty($toolbarHistory)) { + $prefix = array(); + if (!empty($controller->request->params['prefix'])) { + $prefix[$controller->request->params['prefix']] = false; + } + foreach ($toolbarHistory as $i => $state) { + if (!isset($state['request']['content']['url'])) { + continue; + } + $title = $state['request']['content']['url']; + $query = @$state['request']['content']['query']; + if (isset($query['url'])) { + unset($query['url']); + } + if (!empty($query)) { + $title .= '?' . urldecode(http_build_query($query)); + } + $historyStates[] = array( + 'title' => $title, + 'url' => array_merge($prefix, array( + 'plugin' => 'debug_kit', + 'controller' => 'toolbar_access', + 'action' => 'history_state', + $i + 1)) + ); + } + } + if (count($historyStates) >= $this->history) { + array_pop($historyStates); + } + return $historyStates; + } +} diff --git a/app/Plugin/DebugKit/Lib/Panel/IncludePanel.php b/app/Plugin/DebugKit/Lib/Panel/IncludePanel.php new file mode 100644 index 0000000..1b0cb69 --- /dev/null +++ b/app/Plugin/DebugKit/Lib/Panel/IncludePanel.php @@ -0,0 +1,160 @@ + + */ + protected $_pluginPaths = array(); + +/** + * File Types + * + * @var array + */ + protected $_fileTypes = array( + 'Cache', 'Config', 'Configure', 'Console', 'Component', 'Controller', + 'Behavior', 'Datasource', 'Model', 'Plugin', 'Test', 'View', 'Utility', + 'Network', 'Routing', 'I18n', 'Log', 'Error' + ); + +/** + * Get a list of plugins on construct for later use + */ + public function __construct() { + foreach (CakePlugin::loaded() as $plugin) { + $this->_pluginPaths[$plugin] = CakePlugin::path($plugin); + } + + parent::__construct(); + } + +/** + * Get a list of files that were included and split them out into the various parts of the app + * + * @param Controller $controller + * @return array + */ + public function beforeRender(Controller $controller) { + $return = array('core' => array(), 'app' => array(), 'plugins' => array()); + + foreach (get_included_files() as $file) { + $pluginName = $this->_isPluginFile($file); + + if ($pluginName) { + $return['plugins'][$pluginName][$this->_getFileType($file)][] = $this->_niceFileName($file, $pluginName); + } elseif ($this->_isAppFile($file)) { + $return['app'][$this->_getFileType($file)][] = $this->_niceFileName($file, 'app'); + } elseif ($this->_isCoreFile($file)) { + $return['core'][$this->_getFileType($file)][] = $this->_niceFileName($file, 'core'); + } + } + + $return['paths'] = $this->_includePaths(); + + ksort($return['core']); + ksort($return['plugins']); + ksort($return['app']); + return $return; + } + +/** + * Get the possible include paths + * @return array + */ + protected function _includePaths() { + $paths = array_flip(array_merge(explode(PATH_SEPARATOR, get_include_path()), array(CAKE))); + + unset($paths['.']); + return array_flip($paths); + } + +/** + * Check if a path is part of cake core + * @param string $file + * @return boolean + */ + protected function _isCoreFile($file) { + return strstr($file, CAKE); + } + +/** + * Check if a path is from APP but not a plugin + * @param string $file + * @return boolean + */ + protected function _isAppFile($file) { + return strstr($file, APP); + } + +/** + * Check if a path is from a plugin + * @param string $file + * @return boolean + */ + protected function _isPluginFile($file) { + foreach ($this->_pluginPaths as $plugin => $path) { + if (strstr($file, $path)) { + return $plugin; + } + } + + return false; + } + +/** + * Replace the path with APP, CORE or the plugin name + * @param string $file + * @param string + * - app for app files + * - core for core files + * - PluginName for the name of a plugin + * @return boolean + */ + protected function _niceFileName($file, $type) { + switch ($type) { + case 'app': + return str_replace(APP, 'APP/', $file); + + case 'core': + return str_replace(CAKE, 'CORE/', $file); + + default: + return str_replace($this->_pluginPaths[$type], $type . '/', $file); + } + } + +/** + * Get the type of file (model, controller etc) + * @param string $file + * @return string + */ + protected function _getFileType($file) { + foreach ($this->_fileTypes as $type) { + if (stripos($file, '/' . $type . '/') !== false) { + return $type; + } + } + + return 'Other'; + } +} diff --git a/app/Plugin/DebugKit/Lib/Panel/LogPanel.php b/app/Plugin/DebugKit/Lib/Panel/LogPanel.php new file mode 100644 index 0000000..075a468 --- /dev/null +++ b/app/Plugin/DebugKit/Lib/Panel/LogPanel.php @@ -0,0 +1,51 @@ + 'FileLog' + )); + } + CakeLog::config('debug_kit_log_panel', array( + 'engine' => 'DebugKit.DebugKitLog', + 'panel' => $this + )); + } + +/** + * beforeRender Callback + * + * @param Controller $controller + * @return array + */ + public function beforeRender(Controller $controller) { + $logger = $this->logger; + return $logger; + } +} diff --git a/app/Plugin/DebugKit/Lib/Panel/RequestPanel.php b/app/Plugin/DebugKit/Lib/Panel/RequestPanel.php new file mode 100644 index 0000000..8f4cc0a --- /dev/null +++ b/app/Plugin/DebugKit/Lib/Panel/RequestPanel.php @@ -0,0 +1,41 @@ +request->params; + $out['url'] = $controller->request->url; + $out['query'] = $controller->request->query; + $out['data'] = $controller->request->data; + if (isset($controller->Cookie)) { + $out['cookie'] = $controller->Cookie->read(); + } + $out['get'] = $_GET; + $out['currentRoute'] = Router::currentRoute(); + return $out; + } +} diff --git a/app/Plugin/DebugKit/Lib/Panel/SessionPanel.php b/app/Plugin/DebugKit/Lib/Panel/SessionPanel.php new file mode 100644 index 0000000..4c3db37 --- /dev/null +++ b/app/Plugin/DebugKit/Lib/Panel/SessionPanel.php @@ -0,0 +1,32 @@ +Toolbar->Session->read(); + return $sessions; + } +} diff --git a/app/Plugin/DebugKit/Lib/Panel/SqlLogPanel.php b/app/Plugin/DebugKit/Lib/Panel/SqlLogPanel.php new file mode 100644 index 0000000..a02326b --- /dev/null +++ b/app/Plugin/DebugKit/Lib/Panel/SqlLogPanel.php @@ -0,0 +1,64 @@ +config['driver']) && empty($db->config['datasource'])) || + !method_exists($db, 'getLog') + ) { + continue; + } + if (isset($db->config['datasource'])) { + $driver = $db->config['datasource']; + } + $explain = false; + $isExplainable = (preg_match('/(Mysql|Postgres)$/', $driver)); + if ($isExplainable) { + $explain = true; + } + $connections[$configName] = $explain; + } + return array('connections' => $connections, 'threshold' => $this->slowRate); + } +} diff --git a/app/Plugin/DebugKit/Lib/Panel/TimerPanel.php b/app/Plugin/DebugKit/Lib/Panel/TimerPanel.php new file mode 100644 index 0000000..873ff06 --- /dev/null +++ b/app/Plugin/DebugKit/Lib/Panel/TimerPanel.php @@ -0,0 +1,36 @@ +helpers)))) { + $controller->helpers[] = 'Number'; + } + if (!in_array('SimpleGraph', array_keys(HelperCollection::normalizeObjectArray($controller->helpers)))) { + $controller->helpers[] = 'DebugKit.SimpleGraph'; + } + } +} diff --git a/app/Plugin/DebugKit/Lib/Panel/VariablesPanel.php b/app/Plugin/DebugKit/Lib/Panel/VariablesPanel.php new file mode 100644 index 0000000..88fa250 --- /dev/null +++ b/app/Plugin/DebugKit/Lib/Panel/VariablesPanel.php @@ -0,0 +1,31 @@ +viewVars, array('$request->data' => $controller->request->data)); + } +} diff --git a/app/Plugin/DebugKit/Locale/debug_kit.pot b/app/Plugin/DebugKit/Locale/debug_kit.pot new file mode 100644 index 0000000..df4988d --- /dev/null +++ b/app/Plugin/DebugKit/Locale/debug_kit.pot @@ -0,0 +1,138 @@ +# LANGUAGE translation of Debug Kit Application +# Copyright 2008 Andy Dawson +# No version information was available in the source files. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: debug_kit-\n" +"POT-Creation-Date: 2009-05-27 09:47+0200\n" +"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\n" +"Last-Translator: Andy Dawson \n" +"Language-Team:\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Poedit-Basepath: ../../../\n" + +#: controllers/components/toolbar.php:91 +msgid "Component initialization and startup" +msgstr "" + +#: controllers/components/toolbar.php:140 +msgid "Controller Action" +msgstr "" + +#: controllers/components/toolbar.php:167 +msgid "Render Controller Action" +msgstr "" + +#: controllers/components/toolbar.php:231 +msgid "Could not load DebugToolbar panel %s" +msgstr "" + +#: views/elements/debug_toolbar.ctp:25 +msgid "There are no active panels. You must enable a panel to see its output." +msgstr "" + +#: views/elements/history_panel.ctp:21 +msgid "Request History" +msgstr "" + +#: views/elements/history_panel.ctp:23 +msgid "No previous requests logged." +msgstr "" + +#: views/elements/history_panel.ctp:25 +msgid "previous requests available" +msgstr "" + +#: views/elements/history_panel.ctp:27 +msgid "Restore to current request" +msgstr "" + +#: views/elements/log_panel.ctp:21 +msgid "Logs" +msgstr "" + +#: views/elements/log_panel.ctp:28 +msgid "Time" +msgstr "" + +#: views/elements/log_panel.ctp:28 +#: views/elements/timer_panel.ctp:54 +msgid "Message" +msgstr "" + +#: views/elements/log_panel.ctp:37 +msgid "There were no log entries made this request" +msgstr "" + +#: views/elements/request_panel.ctp:21 +msgid "Request" +msgstr "" + +#: views/elements/request_panel.ctp:35 +msgid "Current Route" +msgstr "" + +#: views/elements/session_panel.ctp:21 +msgid "Session" +msgstr "" + +#: views/elements/sql_log_panel.ctp:21 +msgid "Sql Logs" +msgstr "" + +#: views/elements/sql_log_panel.ctp:31 +msgid "toggle (%s) query explains for %s" +msgstr "" + +#: views/elements/sql_log_panel.ctp:39 +msgid "No slow queries!, or your database does not support EXPLAIN" +msgstr "" + +#: views/elements/sql_log_panel.ctp:44 +msgid "No active database connections" +msgstr "" + +#: views/elements/timer_panel.ctp:33 +msgid "Memory" +msgstr "" + +#: views/elements/timer_panel.ctp:35 +msgid "Current Memory Use" +msgstr "" + +#: views/elements/timer_panel.ctp:39 +msgid "Peak Memory Use" +msgstr "" + +#: views/elements/timer_panel.ctp:43 +msgid "Timers" +msgstr "" + +#: views/elements/timer_panel.ctp:45 +msgid "%s (ms)" +msgstr "" + +#: views/elements/timer_panel.ctp:46 +msgid "Total Request Time:" +msgstr "" + +#: views/elements/timer_panel.ctp:54 +msgid "Time in ms" +msgstr "" + +#: views/elements/timer_panel.ctp:54 +msgid "Graph" +msgstr "" + +#: views/elements/variables_panel.ctp:21 +msgid "View Variables" +msgstr "" + +#: views/helpers/simple_graph.php:79 +msgid "Starting %sms into the request, taking %sms" +msgstr "" + diff --git a/app/Plugin/DebugKit/Locale/eng/LC_MESSAGES/debug_kit.po b/app/Plugin/DebugKit/Locale/eng/LC_MESSAGES/debug_kit.po new file mode 100644 index 0000000..9aec832 --- /dev/null +++ b/app/Plugin/DebugKit/Locale/eng/LC_MESSAGES/debug_kit.po @@ -0,0 +1,135 @@ +# LANGUAGE translation of CakePHP Application +# Copyright YEAR NAME +# No version information was available in the source files. +# +#, fuzzy +msgid "" +msgstr "Project-Id-Version: PROJECT VERSION\n" + "POT-Creation-Date: 2009-05-27 09:47+0200\n" + "PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\n" + "Last-Translator: NAME \n" + "Language-Team: LANGUAGE \n" + "MIME-Version: 1.0\n" + "Content-Type: text/plain; charset=UTF-8\n" + "Content-Transfer-Encoding: 8bit\n" + "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" + +#: controllers/components/toolbar.php:91 +msgid "Component initialization and startup" +msgstr "" + +#: controllers/components/toolbar.php:140 +msgid "Controller Action" +msgstr "" + +#: controllers/components/toolbar.php:167 +msgid "Render Controller Action" +msgstr "" + +#: controllers/components/toolbar.php:231 +msgid "Could not load DebugToolbar panel %s" +msgstr "" + +#: views/elements/debug_toolbar.ctp:25 +msgid "There are no active panels. You must enable a panel to see its output." +msgstr "" + +#: views/elements/history_panel.ctp:21 +msgid "Request History" +msgstr "" + +#: views/elements/history_panel.ctp:23 +msgid "No previous requests logged." +msgstr "" + +#: views/elements/history_panel.ctp:25 +msgid "previous requests available" +msgstr "" + +#: views/elements/history_panel.ctp:27 +msgid "Restore to current request" +msgstr "" + +#: views/elements/log_panel.ctp:21 +msgid "Logs" +msgstr "" + +#: views/elements/log_panel.ctp:28 +msgid "Time" +msgstr "" + +#: views/elements/log_panel.ctp:28 views/elements/timer_panel.ctp:54 +msgid "Message" +msgstr "" + +#: views/elements/log_panel.ctp:37 +msgid "There were no log entries made this request" +msgstr "" + +#: views/elements/request_panel.ctp:21 +msgid "Request" +msgstr "" + +#: views/elements/request_panel.ctp:35 +msgid "Current Route" +msgstr "" + +#: views/elements/session_panel.ctp:21 +msgid "Session" +msgstr "" + +#: views/elements/sql_log_panel.ctp:21 +msgid "Sql Logs" +msgstr "" + +#: views/elements/sql_log_panel.ctp:31 +msgid "toggle (%s) query explains for %s" +msgstr "" + +#: views/elements/sql_log_panel.ctp:39 +msgid "No slow queries!, or your database does not support EXPLAIN" +msgstr "" + +#: views/elements/sql_log_panel.ctp:44 +msgid "No active database connections" +msgstr "" + +#: views/elements/timer_panel.ctp:33 +msgid "Memory" +msgstr "" + +#: views/elements/timer_panel.ctp:35 +msgid "Current Memory Use" +msgstr "" + +#: views/elements/timer_panel.ctp:39 +msgid "Peak Memory Use" +msgstr "" + +#: views/elements/timer_panel.ctp:43 +msgid "Timers" +msgstr "" + +#: views/elements/timer_panel.ctp:45 +msgid "%s (ms)" +msgstr "" + +#: views/elements/timer_panel.ctp:46 +msgid "Total Request Time:" +msgstr "" + +#: views/elements/timer_panel.ctp:54 +msgid "Time in ms" +msgstr "" + +#: views/elements/timer_panel.ctp:54 +msgid "Graph" +msgstr "" + +#: views/elements/variables_panel.ctp:21 +msgid "View Variables" +msgstr "" + +#: views/helpers/simple_graph.php:79 +msgid "Starting %sms into the request, taking %sms" +msgstr "" diff --git a/app/Plugin/DebugKit/Locale/fra/LC_MESSAGES/debug_kit.po b/app/Plugin/DebugKit/Locale/fra/LC_MESSAGES/debug_kit.po new file mode 100644 index 0000000..515574d --- /dev/null +++ b/app/Plugin/DebugKit/Locale/fra/LC_MESSAGES/debug_kit.po @@ -0,0 +1,135 @@ +# LANGUAGE translation of CakePHP Application +# Copyright YEAR NAME +# No version information was available in the source files. +# +#, fuzzy +msgid "" +msgstr "Project-Id-Version: PROJECT VERSION\n" + "POT-Creation-Date: 2013-06-04 12:00+0200\n" + "PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\n" + "Last-Translator: cake17 \n" + "Language-Team: \n" + "MIME-Version: 1.0\n" + "Content-Type: text/plain; charset=UTF-8\n" + "Content-Transfer-Encoding: 8bit\n" + "Plural-Forms: nplurals=2; plural=n>1;\n" + +#: controllers/components/toolbar.php:91 +msgid "Component initialization and startup" +msgstr "Initialisation du component et démarrage" + +#: controllers/components/toolbar.php:140 +msgid "Controller Action" +msgstr "Action du Controller" + +#: controllers/components/toolbar.php:167 +msgid "Render Controller Action" +msgstr "Rendu de l'Action du Controller" + +#: controllers/components/toolbar.php:231 +msgid "Could not load DebugToolbar panel %s" +msgstr "Ne peut charger le panel %s de DebugToolbar" + +#: views/elements/debug_toolbar.ctp:25 +msgid "There are no active panels. You must enable a panel to see its output." +msgstr "Il n'y a pas de panels actifs. Vous devez activer le panel pour voir sa sortie." + +#: views/elements/history_panel.ctp:21 +msgid "Request History" +msgstr "Historique des Requêtes" + +#: views/elements/history_panel.ctp:23 +msgid "No previous requests logged." +msgstr "Pas de demandes antérieures enregistrées." + +#: views/elements/history_panel.ctp:25 +msgid "previous requests available" +msgstr "Des requêtes antérieures sont disponibles" + +#: views/elements/history_panel.ctp:27 +msgid "Restore to current request" +msgstr "Restaure la requête actuelle" + +#: views/elements/log_panel.ctp:21 +msgid "Logs" +msgstr "Logs" + +#: views/elements/log_panel.ctp:28 +msgid "Time" +msgstr "Date" + +#: views/elements/log_panel.ctp:28 views/elements/timer_panel.ctp:54 +msgid "Message" +msgstr "Message" + +#: views/elements/log_panel.ctp:37 +msgid "There were no log entries made this request" +msgstr "Il n'y avait pas d'entrées de log faîtes pour cette requête" + +#: views/elements/request_panel.ctp:21 +msgid "Request" +msgstr "Requête" + +#: views/elements/request_panel.ctp:35 +msgid "Current Route" +msgstr "Route actuelle" + +#: views/elements/session_panel.ctp:21 +msgid "Session" +msgstr "Session" + +#: views/elements/sql_log_panel.ctp:21 +msgid "Sql Logs" +msgstr "Logs Sql" + +#: views/elements/sql_log_panel.ctp:31 +msgid "toggle (%s) query explains for %s" +msgstr "bascule (%s) requêtes expliquées pour %s" + +#: views/elements/sql_log_panel.ctp:39 +msgid "No slow queries!, or your database does not support EXPLAIN" +msgstr "Pas de requêtes lentes!, ou votre base de données ne supporte pas EXPLAIN" + +#: views/elements/sql_log_panel.ctp:44 +msgid "No active database connections" +msgstr "Pas de connections actives de la base de données" + +#: views/elements/timer_panel.ctp:33 +msgid "Memory" +msgstr "Mémoire" + +#: views/elements/timer_panel.ctp:35 +msgid "Current Memory Use" +msgstr "Utilisation de la Mémoire Actuelle" + +#: views/elements/timer_panel.ctp:39 +msgid "Peak Memory Use" +msgstr "Utilisation de la Mémoire au niveau maximum" + +#: views/elements/timer_panel.ctp:43 +msgid "Timers" +msgstr "Timers" + +#: views/elements/timer_panel.ctp:45 +msgid "%s (ms)" +msgstr "%s (ms)" + +#: views/elements/timer_panel.ctp:46 +msgid "Total Request Time:" +msgstr "Total du Temps de Requête" + +#: views/elements/timer_panel.ctp:54 +msgid "Time in ms" +msgstr "Temps en ms" + +#: views/elements/timer_panel.ctp:54 +msgid "Graph" +msgstr "Graph" + +#: views/elements/variables_panel.ctp:21 +msgid "View Variables" +msgstr "Variables du View" + +#: views/helpers/simple_graph.php:79 +msgid "Starting %sms into the request, taking %sms" +msgstr "Début en %sms de la requête, et prend %sms" diff --git a/app/Plugin/DebugKit/Locale/lim/LC_MESSAGES/debug_kit.po b/app/Plugin/DebugKit/Locale/lim/LC_MESSAGES/debug_kit.po new file mode 100644 index 0000000..bf3894a --- /dev/null +++ b/app/Plugin/DebugKit/Locale/lim/LC_MESSAGES/debug_kit.po @@ -0,0 +1,136 @@ +# LANGUAGE translation of Debug Kit Application +# Copyright 2008 Andy Dawson +# No version information was available in the source files. +# +msgid "" +msgstr "" +"Project-Id-Version: debug_kit-\n" +"POT-Creation-Date: 2009-05-27 09:47+0200\n" +"PO-Revision-Date: 2009-05-27 09:47+0200\n" +"Last-Translator: Automatically generated\n" +"Language-Team:none\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Poedit-Basepath: ../../../\n" +"Language: lim\n" + +#: controllers/components/toolbar.php:91 +msgid "Component initialization and startup" +msgstr "" + +#: controllers/components/toolbar.php:140 +msgid "Controller Action" +msgstr "" + +#: controllers/components/toolbar.php:167 +msgid "Render Controller Action" +msgstr "" + +#: controllers/components/toolbar.php:231 +msgid "Could not load DebugToolbar panel %s" +msgstr "" + +#: views/elements/debug_toolbar.ctp:25 +msgid "There are no active panels. You must enable a panel to see its output." +msgstr "" + +#: views/elements/history_panel.ctp:21 +msgid "Request History" +msgstr "" + +#: views/elements/history_panel.ctp:23 +msgid "No previous requests logged." +msgstr "" + +#: views/elements/history_panel.ctp:25 +msgid "previous requests available" +msgstr "" + +#: views/elements/history_panel.ctp:27 +msgid "Restore to current request" +msgstr "" + +#: views/elements/log_panel.ctp:21 +msgid "Logs" +msgstr "" + +#: views/elements/log_panel.ctp:28 +msgid "Time" +msgstr "" + +#: views/elements/log_panel.ctp:28 views/elements/timer_panel.ctp:54 +msgid "Message" +msgstr "" + +#: views/elements/log_panel.ctp:37 +msgid "There were no log entries made this request" +msgstr "" + +#: views/elements/request_panel.ctp:21 +msgid "Request" +msgstr "" + +#: views/elements/request_panel.ctp:35 +msgid "Current Route" +msgstr "" + +#: views/elements/session_panel.ctp:21 +msgid "Session" +msgstr "" + +#: views/elements/sql_log_panel.ctp:21 +msgid "Sql Logs" +msgstr "" + +#: views/elements/sql_log_panel.ctp:31 +msgid "toggle (%s) query explains for %s" +msgstr "" + +#: views/elements/sql_log_panel.ctp:39 +msgid "No slow queries!, or your database does not support EXPLAIN" +msgstr "" + +#: views/elements/sql_log_panel.ctp:44 +msgid "No active database connections" +msgstr "" + +#: views/elements/timer_panel.ctp:33 +msgid "Memory" +msgstr "" + +#: views/elements/timer_panel.ctp:35 +msgid "Current Memory Use" +msgstr "" + +#: views/elements/timer_panel.ctp:39 +msgid "Peak Memory Use" +msgstr "" + +#: views/elements/timer_panel.ctp:43 +msgid "Timers" +msgstr "" + +#: views/elements/timer_panel.ctp:45 +msgid "%s (ms)" +msgstr "" + +#: views/elements/timer_panel.ctp:46 +msgid "Total Request Time:" +msgstr "" + +#: views/elements/timer_panel.ctp:54 +msgid "Time in ms" +msgstr "" + +#: views/elements/timer_panel.ctp:54 +msgid "Graph" +msgstr "" + +#: views/elements/variables_panel.ctp:21 +msgid "View Variables" +msgstr "" + +#: views/helpers/simple_graph.php:79 +msgid "Starting %sms into the request, taking %sms" +msgstr "" diff --git a/app/Plugin/DebugKit/Locale/nld/LC_MESSAGES/debug_kit.po b/app/Plugin/DebugKit/Locale/nld/LC_MESSAGES/debug_kit.po new file mode 100644 index 0000000..b6b754f --- /dev/null +++ b/app/Plugin/DebugKit/Locale/nld/LC_MESSAGES/debug_kit.po @@ -0,0 +1,141 @@ +# LANGUAGE translation of Debug Kit Application +# Copyright 2008 Andy Dawson +# No version information was available in the source files. +# +msgid "" +msgstr "" +"Project-Id-Version: debug_kit-\n" +"POT-Creation-Date: 2009-05-27 09:47+0200\n" +"PO-Revision-Date: 2014-07-17 17:04+0200\n" +"Last-Translator: Marlin Cremers \n" +"Language-Team: \n" +"Language: nld\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=n != 1;\n" +"X-Generator: Weblate 1.9\n" +"X-Poedit-Basepath: ../../../\n" + +#: controllers/components/toolbar.php:91 +msgid "Component initialization and startup" +msgstr "Component initializatie en opstarten" + +#: controllers/components/toolbar.php:140 +msgid "Controller Action" +msgstr "Controller Actie" + +#: controllers/components/toolbar.php:167 +msgid "Render Controller Action" +msgstr "Produceer Controller Actie" + +#: controllers/components/toolbar.php:231 +msgid "Could not load DebugToolbar panel %s" +msgstr "Kon DebugToolbar paneel %s niet laden" + +#: views/elements/debug_toolbar.ctp:25 +msgid "There are no active panels. You must enable a panel to see its output." +msgstr "" +"Er zijn geen actieve panelen. Je moet een paneel aanzetten om de uitvoer te " +"zien." + +#: views/elements/history_panel.ctp:21 +msgid "Request History" +msgstr "Aanvraag Geschiedenis" + +#: views/elements/history_panel.ctp:23 +msgid "No previous requests logged." +msgstr "Geen vorige aanvragen gelogged." + +#: views/elements/history_panel.ctp:25 +msgid "previous requests available" +msgstr "vorige aanvraag beschikbaar" + +#: views/elements/history_panel.ctp:27 +msgid "Restore to current request" +msgstr "Herstel naar actuele aanvraag" + +#: views/elements/log_panel.ctp:21 +msgid "Logs" +msgstr "Logs" + +#: views/elements/log_panel.ctp:28 +msgid "Time" +msgstr "Tijd" + +#: views/elements/log_panel.ctp:28 +#: views/elements/timer_panel.ctp:54 +msgid "Message" +msgstr "Bericht" + +#: views/elements/log_panel.ctp:37 +msgid "There were no log entries made this request" +msgstr "Er zijn geen log vermeldingen gemaakt in deze aanvraag" + +#: views/elements/request_panel.ctp:21 +msgid "Request" +msgstr "Aanvraag" + +#: views/elements/request_panel.ctp:35 +msgid "Current Route" +msgstr "Huide Route" + +#: views/elements/session_panel.ctp:21 +msgid "Session" +msgstr "Sessie" + +#: views/elements/sql_log_panel.ctp:21 +msgid "Sql Logs" +msgstr "Sql Logs" + +#: views/elements/sql_log_panel.ctp:31 +msgid "toggle (%s) query explains for %s" +msgstr "schakel (%s) aanvraag uitleg voor %s" + +#: views/elements/sql_log_panel.ctp:39 +msgid "No slow queries!, or your database does not support EXPLAIN" +msgstr "Geen langzame vragen!, of je database ondersteund geen EXPLAIN" + +#: views/elements/sql_log_panel.ctp:44 +msgid "No active database connections" +msgstr "Geen actieve database verbindingen" + +#: views/elements/timer_panel.ctp:33 +msgid "Memory" +msgstr "Geheugen" + +#: views/elements/timer_panel.ctp:35 +msgid "Current Memory Use" +msgstr "Actueel Geheugen Gebruik" + +#: views/elements/timer_panel.ctp:39 +msgid "Peak Memory Use" +msgstr "Hoogste Geheugen Gebruik" + +#: views/elements/timer_panel.ctp:43 +msgid "Timers" +msgstr "Timers" + +#: views/elements/timer_panel.ctp:45 +msgid "%s (ms)" +msgstr "%s (ms)" + +#: views/elements/timer_panel.ctp:46 +msgid "Total Request Time:" +msgstr "Totale Aanvraag Tijd:" + +#: views/elements/timer_panel.ctp:54 +msgid "Time in ms" +msgstr "Tijd in ms" + +#: views/elements/timer_panel.ctp:54 +msgid "Graph" +msgstr "Diagram" + +#: views/elements/variables_panel.ctp:21 +msgid "View Variables" +msgstr "View Variabelen" + +#: views/helpers/simple_graph.php:79 +msgid "Starting %sms into the request, taking %sms" +msgstr "Starten %sms in de aanvraag, neemt %sms" diff --git a/app/Plugin/DebugKit/Locale/spa/LC_MESSAGES/debug_kit.po b/app/Plugin/DebugKit/Locale/spa/LC_MESSAGES/debug_kit.po new file mode 100644 index 0000000..0833a49 --- /dev/null +++ b/app/Plugin/DebugKit/Locale/spa/LC_MESSAGES/debug_kit.po @@ -0,0 +1,135 @@ +# LANGUAGE translation of CakePHP Application +# Copyright YEAR NAME +# No version information was available in the source files. +# +#, fuzzy +msgid "" +msgstr "Project-Id-Version: PROJECT VERSION\n" + "POT-Creation-Date: 2009-05-27 09:47+0200\n" + "PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\n" + "Last-Translator: NAME \n" + "Language-Team: LANGUAGE \n" + "MIME-Version: 1.0\n" + "Content-Type: text/plain; charset=UTF-8\n" + "Content-Transfer-Encoding: 8bit\n" + "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" + +#: controllers/components/toolbar.php:91 +msgid "Component initialization and startup" +msgstr "" + +#: controllers/components/toolbar.php:140 +msgid "Controller Action" +msgstr "" + +#: controllers/components/toolbar.php:167 +msgid "Render Controller Action" +msgstr "" + +#: controllers/components/toolbar.php:231 +msgid "Could not load DebugToolbar panel %s" +msgstr "" + +#: views/elements/debug_toolbar.ctp:25 +msgid "There are no active panels. You must enable a panel to see its output." +msgstr "" + +#: views/elements/history_panel.ctp:21 +msgid "Request History" +msgstr "" + +#: views/elements/history_panel.ctp:23 +msgid "No previous requests logged." +msgstr "" + +#: views/elements/history_panel.ctp:25 +msgid "previous requests available" +msgstr "" + +#: views/elements/history_panel.ctp:27 +msgid "Restore to current request" +msgstr "" + +#: views/elements/log_panel.ctp:21 +msgid "Logs" +msgstr "" + +#: views/elements/log_panel.ctp:28 +msgid "Time" +msgstr "" + +#: views/elements/log_panel.ctp:28 views/elements/timer_panel.ctp:54 +msgid "Message" +msgstr "" + +#: views/elements/log_panel.ctp:37 +msgid "There were no log entries made this request" +msgstr "" + +#: views/elements/request_panel.ctp:21 +msgid "Request" +msgstr "" + +#: views/elements/request_panel.ctp:35 +msgid "Current Route" +msgstr "" + +#: views/elements/session_panel.ctp:21 +msgid "Session" +msgstr "" + +#: views/elements/sql_log_panel.ctp:21 +msgid "Sql Logs" +msgstr "" + +#: views/elements/sql_log_panel.ctp:31 +msgid "toggle (%s) query explains for %s" +msgstr "" + +#: views/elements/sql_log_panel.ctp:39 +msgid "No slow queries!, or your database does not support EXPLAIN" +msgstr "" + +#: views/elements/sql_log_panel.ctp:44 +msgid "No active database connections" +msgstr "" + +#: views/elements/timer_panel.ctp:33 +msgid "Memory" +msgstr "" + +#: views/elements/timer_panel.ctp:35 +msgid "Current Memory Use" +msgstr "" + +#: views/elements/timer_panel.ctp:39 +msgid "Peak Memory Use" +msgstr "" + +#: views/elements/timer_panel.ctp:43 +msgid "Timers" +msgstr "" + +#: views/elements/timer_panel.ctp:45 +msgid "%s (ms)" +msgstr "" + +#: views/elements/timer_panel.ctp:46 +msgid "Total Request Time:" +msgstr "" + +#: views/elements/timer_panel.ctp:54 +msgid "Time in ms" +msgstr "" + +#: views/elements/timer_panel.ctp:54 +msgid "Graph" +msgstr "" + +#: views/elements/variables_panel.ctp:21 +msgid "View Variables" +msgstr "" + +#: views/helpers/simple_graph.php:79 +msgid "Starting %sms into the request, taking %sms" +msgstr "" \ No newline at end of file diff --git a/app/Plugin/DebugKit/Model/Behavior/TimedBehavior.php b/app/Plugin/DebugKit/Model/Behavior/TimedBehavior.php new file mode 100644 index 0000000..bf16ebb --- /dev/null +++ b/app/Plugin/DebugKit/Model/Behavior/TimedBehavior.php @@ -0,0 +1,102 @@ +settings[$Model->alias] = array_merge($this->_defaults, $settings); + } else { + $this->settings[$Model->alias] = $this->_defaults; + } + } + +/** + * beforeFind, starts a timer for a find operation. + * + * @param Model $Model + * @param array $queryData Array of query data (not modified) + * @return boolean true + */ + public function beforeFind(Model $Model, $queryData) { + DebugKitDebugger::startTimer($Model->alias . '_find', $Model->alias . '->find()'); + return true; + } + +/** + * afterFind, stops a timer for a find operation. + * + * @param Model $Model + * @param array $results Array of results + * @param $primary + * @return boolean true. + */ + public function afterFind(Model $Model, $results, $primary = false) { + DebugKitDebugger::stopTimer($Model->alias . '_find'); + return true; + } + +/** + * beforeSave, starts a time before a save is initiated. + * + * @param Model $Model + * @param array $options + * @return boolean true + */ + public function beforeSave(Model $Model, $options = array()) { + DebugKitDebugger::startTimer($Model->alias . '_save', $Model->alias . '->save()'); + return true; + } + +/** + * afterSave, stop the timer started from a save. + * + * @param \Model $Model + * @param string $created + * @return boolean Always true + */ + public function afterSave(Model $Model, $created, $options = array()) { + DebugKitDebugger::stopTimer($Model->alias . '_save'); + return true; + } + +} diff --git a/app/Plugin/DebugKit/Model/DebugKitAppModel.php b/app/Plugin/DebugKit/Model/DebugKitAppModel.php new file mode 100644 index 0000000..c8344f3 --- /dev/null +++ b/app/Plugin/DebugKit/Model/DebugKitAppModel.php @@ -0,0 +1,24 @@ +config['datasource']; + + $return = array(); + if (preg_match('/(Mysql|Postgres)$/', $datasource)) { + $explained = $db->query('EXPLAIN ' . $query); + if (preg_match('/Postgres$/', $datasource)) { + $queryPlan = array(); + foreach ($explained as $postgreValue) { + $queryPlan[] = array($postgreValue[0]['QUERY PLAN']); + } + $return = array_merge(array(array('')), $queryPlan); + } else { + $keys = array_keys($explained[0][0]); + foreach ($explained as $mysqlValue) { + $queryPlan[] = array_values($mysqlValue[0]); + } + $return = array_merge(array($keys), $queryPlan); + } + } + return $return; + } + +} diff --git a/app/Plugin/DebugKit/README.md b/app/Plugin/DebugKit/README.md new file mode 100644 index 0000000..1a7f67e --- /dev/null +++ b/app/Plugin/DebugKit/README.md @@ -0,0 +1,299 @@ +# CakePHP DebugKit [![Build Status](https://secure.travis-ci.org/cakephp/debug_kit.png?branch=master)](http://travis-ci.org/cakephp/debug_kit) + +DebugKit provides a debugging toolbar and enhanced debugging tools for CakePHP applications. + +## Requirements + +The master branch has the following requirements: + +* CakePHP 2.2.0 or greater. +* PHP 5.3.0 or greater. + +## Installation + +_[Using [Composer](http://getcomposer.org/)]_ + +Add the plugin to your project's `composer.json` - something like this: + +```javascript +{ + "require": { + "cakephp/debug_kit": "2.2.*" + } +} +``` + +Because this plugin has the type `cakephp-plugin` set in it's own `composer.json`, composer knows to install it inside your `/Plugin` directory, rather than in the usual vendors file. It is recommended that you add `/Plugin/DebugKit` to your .gitignore file. (Why? [read this](http://getcomposer.org/doc/faqs/should-i-commit-the-dependencies-in-my-vendor-directory.md).) + +> Consider using "require-dev" if you only want to include DebugKit for your development environment. + +_[Manual]_ + +* Download the [DebugKit archive](https://github.com/cakephp/debug_kit/zipball/master). +* Unzip that download. +* Rename the resulting folder to `DebugKit` +* Then copy this folder into `app/Plugin/` + +_[GIT Submodule]_ + +In your app directory type: + +```bash +git submodule add git://github.com/cakephp/debug_kit.git Plugin/DebugKit +git submodule init +git submodule update +``` + +_[GIT Clone]_ + +In your plugin directory type + +```bash +git clone git://github.com/cakephp/debug_kit.git DebugKit +``` + +### Enable plugin + +* In 2.x you need to enable the plugin your `app/Config/bootstrap.php` file. If you are already using `CakePlugin::loadAll();`, then the following is not necessary.: +```php + CakePlugin::load('DebugKit'); +``` +* Include the toolbar component in your `app/Controller/AppController.php`: +```php +class AppController extends Controller { + public $components = array('DebugKit.Toolbar'); +} +``` +* Set `Configure::write('debug', 1);` in `app/Config/core.php`. +* Make sure to remove the 'sql_dump' element from your layout (usually + `app/View/Layouts/default.ctp`), if you want to experience the awesome that is + the DebugKit SQL log. + +## Reporting Issues + +If you have a problem with DebugKit please open an issue on [GitHub](https://github.com/cakephp/debug_kit/issues). + +## Contributing + +If you'd like to contribute to DebugKit, check out the +[roadmap](https://github.com/cakephp/debug_kit/wiki/roadmap) for any +planned features. You can [fork](https://help.github.com/articles/fork-a-repo) +the project, add features, and send [pull +requests](https://help.github.com/articles/using-pull-requests) or open +[issues](https://github.com/cakephp/debug_kit/issues). + +## Versions + +DebugKit has several releases, each compatible with different releases of +CakePHP. Use the appropriate version by downloading a tag, or checking out the +correct branch. + +* `1.0, 1.1, 1.2` are compatible with CakePHP 1.2.x. These releases of DebugKit + will not work with CakePHP 1.3. You can also use the `1.2-branch` for the mos + recent updates and bugfixes. +* `1.3.0` is compatible with CakePHP 1.3.x only. It will not work with CakePHP + 1.2. You can also use the `1.3` branch to get the most recent updates and + bugfixes. +* `2.0.0` is compatible with CakePHP 2.0.x only. It will not work with previous + CakePHP versions. +* `2.2.0` is compatible with CakePHP 2.2.0 and greater. It will not work with + older versions of CakePHP as this release uses new API's available in 2.2. + You can also use the `master` branch to get the most recent updates. +* `2.2.x` are compatible with CakePHP 2.2.0 and greater. It is a necessary + upgrade for people using CakePHP 2.4 as the naming conventions around loggers + changed in that release. + +# Documentation + +## Toolbar Panels + +The DebugKit Toolbar is comprised of several panels, which are shown by clicking the +CakePHP icon in the upper right-hand corner of your browser after DebugKit has been +installed and loaded. Each panel is comprised of a panel class and view element. +Typically, a panel handles the collection and display of a single type of information +such as Logs or Request information. You can choose to panels from the toolbar or add +your own custom panels. + +### Built-in Panels + +There are several built-in panels, they are: + + * **History** Allows access to previous request information, useful when + debugging actions with redirects. + * **Request** Displays information about the current request, GET, POST, Cake + Parameters, Current Route information and Cookies if the `CookieComponent` + is in you controller's components. + * **Session** Display the information currently in the Session. + * **Timer** Display any timers that were set during the request see + `DebugKitDebugger` for more information. Also displays + memory use at component callbacks as well as peak memory used. + * **Sql Logs** Displays sql logs for each database connection. + * **Log** Display any entries made to the log files this request. + * **Variables** Display View variables set in controller. + * **Environment** Display environment variables related to PHP + CakePHP. + +## Configuration + +The toolbar has a few configuration settings. Settings are passed in the component declaration like normal component configuration. + +```php +public $components = array( + 'DebugKit.Toolbar' => array(/* array of settings */) +); +``` + +### Configuring Panels + +You can customize the toolbar to show your custom panels or hide any built-in panel when adding it toolbar to your components. +```php +public $components = array('DebugKit.Toolbar' => array( + 'panels' => array('MyCustom', 'timer'=>false) + ) +); +``` + +Would display your custom panel and all built-in panels except the 'Timer' panel. + +#### Controlling Panels + +Using the panels key you can specify which panels you want to load, as well as the order in which you want the panels loaded. +```php +public $components = array( + 'DebugKit.Toolbar' => array('panels' => array('MyCustom', 'timer' => false)) +); +``` + +Would add your custom panel `MyCustomPanel` to the toolbar and exclude the default `Timer` panel. In addition to choosing which panels you want, you can pass options into the `__construct` of the panels. For example the built-in `History` panel uses the `history` key to set the number of historical requests to track. +```php +public $components = array( + 'DebugKit.Toolbar' => array('history' => 10) +); +``` + +Would load the `History` panel and set its history level to 10. The `panels` key is not passed to the Panel constructor. + +#### forceEnable + +The `forceEnable` setting is new in DebugKit 1.1. It allows you to force the toolbar to display regardless of the value of `Configure::read('debug');`. This is useful when profiling an application with debug kit as you can enable the toolbar even when running the application in production mode. + +#### autoRun + +autoRun is a new configuration setting for DebugKit 1.2. It allows you to control whether or not the toolbar is displayed automatically or whether you would like to use a query string parameter to enable it. Set this configuration key to false to use query string parameter toggling of the toolbar. +```php +public $components = array( + 'DebugKit.Toolbar' => array('autoRun' => false) +); +``` + +When visiting a page you can add `?debug=true` to the url and the toolbar will be visible. Otherwise it will stay hidden and not execute. + +## Developing Your Own Panels + +You can create your own custom panels for DebugKit to help in debugging your applications. + +### Panel Classes + +Panel Classes simply need to be placed in`Panel` directory inside a `Lib` path. The filename should match the classname, so the class `MyCustomPanel` would be expected to have a filename of `app/Lib/Panel/MyCustomPanel.php`. +```php + +App::uses('DebugPanel', 'DebugKit.Lib'); + +/** + * My Custom Panel + */ +class MyCustomPanel extends DebugPanel { + ... +} +``` +See also the example `Test/test_app/Plugin/DebugkitTestPlugin/Lib/Panel/PluginTestPanel.php`. + +Notice that custom panels are required to subclass the `DebugPanel` class. Panels can define the +`css` and `javascript` properties to include additional CSS or javascript on the page. Both +properties should be an array. +```php +class MyCustomPanel extends DebugPanel { + public $javascript = array( + '/my_plugin/js/custom_panel.js' + ); +} +``` + +### Callbacks + +Panel objects have 2 callbacks, that allow them to hook into and introspect on the current request. +```php +startup(Controller $controller) +``` + +Each panel's `startup()` method is called during component `startup()` process. `$controller` is a reference to the current controller object. +```php +beforeRender(Controller $controller) +``` + +Much like `startup()` `beforeRender()` is called during the Component beforeRender() process. Again `$controller` is a reference to the current controller. Normally at this point you could do additional introspection on the controller. The return of a panels `beforeRender()` is automatically passed to the View by the Toolbar Component. Therefore, under normal use you do not need to explicitly set variables to the controller. + +#### Example of beforeRender Callback +```php +/** + * beforeRender callback - grabs request params + * + * @return array + */ + public function beforeRender(Controller $controller) { + return $controller->params; + } +``` + +This would return cake's internal params array. The return of a panel's `beforeRender()` is available in you Panel element as `$content` + +### Panel Elements + +Each Panel is expected to have a view element that renders the content from the panel. The element name must be the underscored inflection of the class name. For example `SessionPanel` has an element named `session_panel.ctp`, and sqllogPanel has an element named `sqllog_panel.ctp`. These elements should be located in the root of your `View/Elements` directory. + +#### Custom Titles and Elements + +Panels should pick up their title and element name by convention. However, if you need to choose a custom element name or title, there are properties to allow that configuration. + +- `$title` - Set a custom title for use in the toolbar. This title will be used as the panels button. +- `$elementName` - Set a custom element name to be used to render the panel. + +### Panels as Cake Plugins + +Panels provided by [Cake Plugins](http://book.cakephp.org/2.0/en/plugins.html) work almost entirely the same as other plugins, with one minor difference: You must set `public $plugin` to be the name of the plugin directory, so that the panel's Elements can be located at render time. +```php +class MyCustomPanel extends DebugPanel { + public $plugin = 'MyPlugin'; + ... +} +``` + +To use a plugin panel, use the common CakePHP dot notation for plugins. +```php +public $components = array('DebugKit.Toolbar' => array( + 'panels' => array('MyPlugin.MyCustom') +)); +``` +The above would load all the default panels as well as the custom panel from `MyPlugin`. + +## Cache Engine + +By default, DebugKit uses File as the engine for internal caching, but if you want to use another cache engine you can customize it by simply adding a cache key inside the components config array. +```php +public $components = array('DebugKit.Toolbar' => array( + 'cache' => array('engine' => 'Memcache', 'servers' => array('127.0.0.1:11211')) + ) +); +``` + +You can use any cache engine supported by CakePHP, the same way you set in both core.php and bootstrap.php files with the Cache::config() method. + +## Viewing the Toolbar for AJAX Requests + +When doing AJAX requests, you will not be able to see an HTML version of the toolbar. However, if you have a browser extension that supports FirePHP, you can view +the toolbar in your browser: + +- [FirePHP 4 chrome](https://chrome.google.com/webstore/detail/firephp4chrome/gpgbmonepdpnacijbbdijfbecmgoojma) +- [FirePHP for chrome](https://chrome.google.com/webstore/detail/firephp-for-chrome/goajlbdffkligccnfgibeilhdnnpaead) +- [FirePHP for firefox](https://addons.mozilla.org/en-US/firefox/addon/firephp/) + +Once you have installed the correct extension, you should see the toolbar data output on each AJAX request. diff --git a/app/Plugin/DebugKit/Test/Case/AllDebugKitTest.php b/app/Plugin/DebugKit/Test/Case/AllDebugKitTest.php new file mode 100644 index 0000000..a985caa --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/AllDebugKitTest.php @@ -0,0 +1,40 @@ +getTestFiles(); + $suite->addTestFiles($files); + + return $suite; + } +} diff --git a/app/Plugin/DebugKit/Test/Case/AllDebugKitViewTest.php b/app/Plugin/DebugKit/Test/Case/AllDebugKitViewTest.php new file mode 100644 index 0000000..971c57b --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/AllDebugKitViewTest.php @@ -0,0 +1,40 @@ +getTestFiles('View'); + $suite->addTestFiles($files); + + return $suite; + } +} diff --git a/app/Plugin/DebugKit/Test/Case/AllDebugKitWithoutViewTest.php b/app/Plugin/DebugKit/Test/Case/AllDebugKitWithoutViewTest.php new file mode 100644 index 0000000..3b1a93c --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/AllDebugKitWithoutViewTest.php @@ -0,0 +1,40 @@ +getTestFiles(null, 'View'); + $suite->addTestFiles($files); + + return $suite; + } +} diff --git a/app/Plugin/DebugKit/Test/Case/AllTestsTest.php b/app/Plugin/DebugKit/Test/Case/AllTestsTest.php new file mode 100644 index 0000000..1e6f263 --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/AllTestsTest.php @@ -0,0 +1,40 @@ +getTestFiles(); + $suite->addTestFiles($files); + + return $suite; + } +} diff --git a/app/Plugin/DebugKit/Test/Case/Controller/Component/ToolbarComponentTest.php b/app/Plugin/DebugKit/Test/Case/Controller/Component/ToolbarComponentTest.php new file mode 100644 index 0000000..9759a19 --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/Controller/Component/ToolbarComponentTest.php @@ -0,0 +1,524 @@ +_loadPanels($panels, $settings); + } +} + +/** + * ToolbarComponentTestCase Test case + * + */ +class ToolbarComponentTestCase extends CakeTestCase { + +/** + * fixtures + * + * @var array + */ + public $fixtures = array('core.article'); + +/** + * url for test + * + * @var string + */ + public $url; + +/** + * Start test callback + * + * @return void + */ + public function setUp() { + parent::setUp(); + + Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); + $this->_server = $_SERVER; + $this->_get = $_GET; + $this->_paths = array(); + $this->_paths['plugins'] = App::path('plugins'); + $this->_paths['views'] = App::path('views'); + $this->_paths['vendors'] = App::path('vendors'); + $this->_paths['controllers'] = App::path('controllers'); + Configure::write('Cache.disable', false); + + $this->url = '/'; + } + +/** + * endTest + * + * @return void + */ + public function tearDown() { + $_SERVER = $this->_server; + $_GET = $this->_get; + + parent::tearDown(); + + App::build(array( + 'plugins' => $this->_paths['plugins'], + 'views' => $this->_paths['views'], + 'controllers' => $this->_paths['controllers'], + 'vendors' => $this->_paths['vendors'] + ), true); + Configure::write('Cache.disable', true); + + unset($this->Controller); + ClassRegistry::flush(); + if (class_exists('DebugMemory')) { + DebugMemory::clear(); + } + if (class_exists('DebugTimer')) { + DebugTimer::clear(); + } + Router::reload(); + } + +/** + * loading test controller + * + * @param array $settings + * @return Controller + */ + protected function _loadController($settings = array()) { + $request = new CakeRequest($this->url); + $request->addParams(Router::parse($this->url)); + $this->Controller = new Controller($request); + $this->Controller->uses = null; + $this->Controller->components = array('Toolbar' => $settings + array('className' => 'TestToolbar')); + $this->Controller->constructClasses(); + $this->Controller->Components->trigger('initialize', array($this->Controller)); + return $this->Controller; + } + +/** + * test Loading of panel classes + * + * @return void + */ + public function testLoadPanels() { + $this->_loadController(); + + $this->Controller->Toolbar->loadPanels(array('session', 'request')); + $this->assertInstanceOf('SessionPanel', $this->Controller->Toolbar->panels['session']); + $this->assertInstanceOf('RequestPanel', $this->Controller->Toolbar->panels['request']); + + $this->Controller->Toolbar->loadPanels(array('history'), array('history' => 10)); + $this->assertEquals($this->Controller->Toolbar->panels['history']->history, 10); + } + +/** + * Test exceptions on bad panel names + * + * @expectedException PHPUnit_Framework_Error + * @return void + */ + public function testLoadPanelsError() { + $this->Controller->Toolbar->loadPanels(array('randomNonExisting', 'request')); + } + +/** + * test Loading of panel classes from a plugin + * + * @return void + */ + public function testLoadPluginPanels() { + $debugKitPath = App::pluginPath('DebugKit'); + $noDir = (empty($debugKitPath) || !file_exists($debugKitPath)); + if ($noDir) { + $this->markTestAsSkipped('Could not find DebugKit in plugin paths'); + } + + App::build(array( + 'Plugin' => array($debugKitPath . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) + )); + + CakePlugin::load('DebugkitTestPlugin'); + $this->_loadController(); + $this->Controller->Toolbar->loadPanels(array('DebugkitTestPlugin.PluginTest')); + $this->assertInstanceOf( + 'PluginTestPanel', + $this->Controller->Toolbar->panels['plugin_test'] + ); + } + +/** + * test loading of vendor panels from test_app folder + * + * @return void + */ + public function testLibPanels() { + $debugKitPath = App::pluginPath('DebugKit'); + $noDir = (empty($debugKitPath) || !file_exists($debugKitPath)); + if ($noDir) { + $this->markTestAsSkipped('Could not find DebugKit in plugin paths'); + } + + App::build(array( + 'Lib' => array($debugKitPath . 'Test' . DS . 'test_app' . DS . 'Lib' . DS) + )); + $this->_loadController(array( + 'panels' => array('test'), + 'className' => 'DebugKit.Toolbar', + )); + $this->assertTrue(isset($this->Controller->Toolbar->panels['test'])); + $this->assertInstanceOf('TestPanel', $this->Controller->Toolbar->panels['test']); + } + +/** + * test construct + * + * @return void + */ + public function testConstruct() { + $this->_loadController(); + + $this->assertFalse(empty($this->Controller->Toolbar->panels)); + + $memory = DebugMemory::getAll(); + $this->assertTrue(isset($memory['Component initialization'])); + + $events = $this->Controller->getEventManager(); + $this->assertNotEmpty($events->listeners('Controller.initialize')); + $this->assertNotEmpty($events->listeners('Controller.startup')); + $this->assertNotEmpty($events->listeners('Controller.beforeRender')); + $this->assertNotEmpty($events->listeners('Controller.shutdown')); + $this->assertNotEmpty($events->listeners('View.beforeRender')); + $this->assertNotEmpty($events->listeners('View.afterRender')); + $this->assertNotEmpty($events->listeners('View.beforeLayout')); + $this->assertNotEmpty($events->listeners('View.afterLayout')); + } + +/** + * test initialize w/ custom panels and defaults + * + * @return void + */ + public function testInitializeCustomPanelsWithDefaults() { + $this->_loadController(array( + 'panels' => array('test'), + )); + + $expected = array( + 'history', 'session', 'request', 'sql_log', 'timer', + 'log', 'variables', 'environment', 'include', 'test' + ); + $this->assertEquals($expected, array_keys($this->Controller->Toolbar->panels)); + } + +/** + * test syntax for removing panels + * + * @return void + */ + public function testInitializeRemovingPanels() { + $this->_loadController(array( + 'panels' => array( + 'session' => false, + 'history' => false, + ) + )); + + $expected = array('request', 'sql_log', 'timer', 'log', 'variables', 'environment', 'include'); + $this->assertEquals($expected, array_keys($this->Controller->Toolbar->panels)); + } + +/** + * ensure that Toolbar is not enabled when debug == 0 on initialize + * + * @return void + */ + public function testDebugDisableOnInitialize() { + $_debug = Configure::read('debug'); + Configure::write('debug', 0); + $this->_loadController(); + Configure::write('debug', $_debug); + + $this->assertFalse($this->Controller->Components->enabled('Toolbar')); + } + +/** + * test that passing in forceEnable will enable the toolbar even if debug = 0 + * + * @return void + */ + public function testForceEnable() { + $_debug = Configure::read('debug'); + Configure::write('debug', 0); + $this->_loadController(array( + 'forceEnable' => true, + )); + Configure::write('debug', $_debug); + + $this->assertTrue($this->Controller->Components->enabled('Toolbar')); + } + +/** + * Test disabling autoRunning of toolbar + * + * @return void + */ + public function testAutoRunSettingFalse() { + $this->_loadController(array( + 'autoRun' => false, + )); + $this->assertFalse($this->Controller->Components->enabled('Toolbar')); + } + +/** + * test autorun = false with query string param + * + * @return void + */ + public function testAutoRunSettingWithQueryString() { + $this->url = '/?debug=1'; + $_GET['debug'] = 1; + $this->_loadController(array( + 'autoRun' => false, + )); + $this->assertTrue($this->Controller->Components->enabled('Toolbar')); + } + +/** + * test startup + * + * @return void + */ + public function testStartup() { + $this->_loadController(array( + 'panels' => array('timer'), + )); + $MockPanel = $this->getMock('DebugPanel'); + $MockPanel->expects($this->once())->method('startup'); + $this->Controller->Toolbar->panels['timer'] = $MockPanel; + + $this->Controller->Toolbar->startup($this->Controller); + + $timers = DebugTimer::getAll(); + $this->assertTrue(isset($timers['controllerAction'])); + $memory = DebugMemory::getAll(); + $this->assertTrue(isset($memory['Controller action start'])); + } + +/** + * Test that cache config generation works. + * + * @return void + */ + public function testCacheConfigGeneration() { + $this->_loadController(); + $this->Controller->Components->trigger('startup', array($this->Controller)); + + $results = Cache::config('debug_kit'); + $this->assertTrue(is_array($results)); + } + +/** + * test state saving of toolbar + * + * @return void + */ + public function testStateSaving() { + $this->_loadController(); + $configName = 'debug_kit'; + $this->Controller->Toolbar->cacheKey = 'toolbar_history'; + + $this->Controller->Components->trigger('startup', array($this->Controller)); + $this->Controller->set('test', 'testing'); + $this->Controller->Components->trigger('beforeRender', array($this->Controller)); + + $result = Cache::read('toolbar_history', $configName); + $this->assertEquals($result[0]['variables']['content']['test'], 'testing'); + Cache::delete('toolbar_history', $configName); + } + +/** + * Test Before Render callback + * + * @return void + */ + public function testBeforeRender() { + $this->_loadController(array( + 'panels' => array('timer', 'session'), + )); + $MockPanel = $this->getMock('DebugPanel'); + $MockPanel->expects($this->once())->method('beforeRender'); + $this->Controller->Toolbar->panels['timer'] = $MockPanel; + $this->Controller->Toolbar->beforeRender($this->Controller); + + $this->assertTrue(isset($this->Controller->helpers['DebugKit.Toolbar'])); + $this->assertEquals($this->Controller->helpers['DebugKit.Toolbar']['output'], 'DebugKit.HtmlToolbar'); + $this->assertEquals($this->Controller->helpers['DebugKit.Toolbar']['cacheConfig'], 'debug_kit'); + $this->assertTrue(isset($this->Controller->helpers['DebugKit.Toolbar']['cacheKey'])); + + $this->assertTrue(isset($this->Controller->viewVars['debugToolbarPanels'])); + $vars = $this->Controller->viewVars['debugToolbarPanels']; + + $expected = array( + 'plugin' => 'DebugKit', + 'elementName' => 'session_panel', + 'content' => $this->Controller->Toolbar->Session->read(), + 'disableTimer' => true, + 'title' => '' + ); + $this->assertEquals($expected, $vars['session']); + + $memory = DebugMemory::getAll(); + $this->assertTrue(isset($memory['Controller render start'])); + } + +/** + * test that vars are gathered and state is saved on beforeRedirect + * + * @return void + */ + public function testBeforeRedirect() { + $this->_loadController(array( + 'panels' => array('session', 'history'), + )); + + $configName = 'debug_kit'; + $this->Controller->Toolbar->cacheKey = 'toolbar_history'; + Cache::delete('toolbar_history', $configName); + + DebugTimer::start('controllerAction', 'testing beforeRedirect'); + $MockPanel = $this->getMock('DebugPanel'); + $MockPanel->expects($this->once())->method('beforeRender'); + $this->Controller->Toolbar->panels['session'] = $MockPanel; + $this->Controller->Toolbar->beforeRedirect($this->Controller, '/another/url'); + + $result = Cache::read('toolbar_history', $configName); + $this->assertTrue(isset($result[0]['session'])); + $this->assertFalse(isset($result[0]['history'])); + + $timers = DebugTimer::getAll(); + $this->assertTrue(isset($timers['controllerAction'])); + } + +/** + * test that loading state (accessing cache) works. + * + * @return void + */ + public function testLoadState() { + $this->_loadController(); + $this->Controller->Toolbar->cacheKey = 'toolbar_history'; + + $data = array(0 => array('my data')); + Cache::write('toolbar_history', $data, 'debug_kit'); + $result = $this->Controller->Toolbar->loadState(0); + $this->assertEquals($result, $data[0]); + } + +/** + * Test that history state urls set prefix = null and admin = null so generated urls do not + * adopt these params. + * + * @return void + */ + public function testHistoryUrlGenerationWithPrefixes() { + $this->url = '/debugkit_url_with_prefixes_test'; + Router::connect($this->url, array( + 'controller' => 'posts', + 'action' => 'edit', + 'admin' => 1, + 'prefix' => 'admin', + 'plugin' => 'cms', + )); + $this->_loadController(); + $this->Controller->Toolbar->cacheKey = 'url_test'; + $this->Controller->Components->trigger('startup', array($this->Controller)); + $this->Controller->Components->trigger('beforeRender', array($this->Controller)); + + $result = $this->Controller->Toolbar->panels['history']->beforeRender($this->Controller); + $expected = array( + 'plugin' => 'debug_kit', + 'controller' => 'toolbar_access', + 'action' => 'history_state', + 0 => 1, + 'admin' => false, + ); + $this->assertEquals($result[0]['url'], $expected); + Cache::delete('url_test', 'debug_kit'); + } + +/** + * Test that the FireCake toolbar is used on AJAX requests + * + * @return void + */ + public function testAjaxToolbar() { + $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'; + $this->_loadController(); + $this->Controller->Components->trigger('startup', array($this->Controller)); + $this->Controller->Components->trigger('beforeRender', array($this->Controller)); + $this->assertEquals($this->Controller->helpers['DebugKit.Toolbar']['output'], 'DebugKit.FirePhpToolbar'); + } + +/** + * Test that the toolbar does not interfere with requestAction + * + * @return void + */ + public function testNoRequestActionInterference() { + $debugKitPath = App::pluginPath('DebugKit'); + $noDir = (empty($debugKitPath) || !file_exists($debugKitPath)); + if ($noDir) { + $this->markTestAsSkipped('Could not find DebugKit in plugin paths'); + } + + App::build(array( + 'Controller' => $debugKitPath . 'Test' . DS . 'test_app' . DS . 'Controller' . DS, + 'View' => array( + $debugKitPath . 'Test' . DS . 'test_app' . DS . 'View' . DS, + CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'View' . DS + ), + 'plugins' => $this->_paths['plugins'] + )); + Router::reload(); + $this->_loadController(); + + $result = $this->Controller->requestAction('/debug_kit_test/request_action_return', array('return')); + $this->assertEquals($result, 'I am some value from requestAction.'); + + $result = $this->Controller->requestAction('/debug_kit_test/request_action_render', array('return')); + $this->assertEquals($result, 'I have been rendered.'); + } +} diff --git a/app/Plugin/DebugKit/Test/Case/DebugkitGroupTestCase.php b/app/Plugin/DebugKit/Test/Case/DebugkitGroupTestCase.php new file mode 100644 index 0000000..3bb6125 --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/DebugkitGroupTestCase.php @@ -0,0 +1,79 @@ +valid()) { + + if (!$it->isDot()) { + $file = $it->key(); + + if ( + preg_match('|Test\.php$|', $file) && + $file !== __FILE__ && + !preg_match('|^All.+?\.php$|', basename($file)) && + ($excludes === null || !in_array($file, $excludes)) + ) { + $files[] = $file; + } + } + + $it->next(); + } + + return $files; + } +} diff --git a/app/Plugin/DebugKit/Test/Case/Lib/DebugKitDebuggerTest.php b/app/Plugin/DebugKit/Test/Case/Lib/DebugKitDebuggerTest.php new file mode 100644 index 0000000..039d37e --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/Lib/DebugKitDebuggerTest.php @@ -0,0 +1,76 @@ +firecake = FireCake::getInstance('TestFireCake'); + TestFireCake::reset(); + } + +/** + * tearDown method + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + Configure::write('log', true); + DebugKitDebugger::clearTimers(); + TestFireCake::reset(); + } + +/** + * test output switch to firePHP + * + * @return void + */ + public function testOutput() { + Debugger::getInstance('DebugKitDebugger'); + Debugger::addFormat('fb', array('callback' => 'DebugKitDebugger::fireError')); + Debugger::outputAs('fb'); + + set_error_handler('ErrorHandler::handleError'); + $foo .= ''; + restore_error_handler(); + + $result = $this->firecake->sentHeaders; + + $this->assertRegExp('/GROUP_START/', $result['X-Wf-1-1-1-1']); + $this->assertRegExp('/ERROR/', $result['X-Wf-1-1-1-2']); + $this->assertRegExp('/GROUP_END/', $result['X-Wf-1-1-1-5']); + + Debugger::getInstance('Debugger'); + Debugger::outputAs('html'); + } +} diff --git a/app/Plugin/DebugKit/Test/Case/Lib/DebugMemoryTest.php b/app/Plugin/DebugKit/Test/Case/Lib/DebugMemoryTest.php new file mode 100644 index 0000000..e45759b --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/Lib/DebugMemoryTest.php @@ -0,0 +1,65 @@ +assertTrue(is_int($result)); + + $result = DebugMemory::getPeak(); + $this->assertTrue(is_int($result)); + } + +/** + * test making memory use markers. + * + * @return void + */ + public function testMemorySettingAndGetting() { + DebugMemory::clear(); + $result = DebugMemory::record('test marker'); + $this->assertTrue($result); + + $result = DebugMemory::getAll(true); + $this->assertEquals(count($result), 1); + $this->assertTrue(isset($result['test marker'])); + $this->assertTrue(is_numeric($result['test marker'])); + + $result = DebugMemory::getAll(); + $this->assertTrue(empty($result)); + + DebugMemory::record('test marker'); + DebugMemory::record('test marker'); + $result = DebugMemory::getAll(); + + $this->assertEquals(count($result), 2); + $this->assertTrue(isset($result['test marker'])); + $this->assertTrue(isset($result['test marker #2'])); + } +} diff --git a/app/Plugin/DebugKit/Test/Case/Lib/DebugTimerTest.php b/app/Plugin/DebugKit/Test/Case/Lib/DebugTimerTest.php new file mode 100644 index 0000000..a182624 --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/Lib/DebugTimerTest.php @@ -0,0 +1,169 @@ +assertTrue(DebugTimer::start('test1', 'this is my first test')); + usleep(5000); + $this->assertTrue(DebugTimer::stop('test1')); + $elapsed = DebugTimer::elapsedTime('test1'); + $this->assertTrue($elapsed > 0.0050); + + $this->assertTrue(DebugTimer::start('test2', 'this is my second test')); + sleep(1); + $this->assertTrue(DebugTimer::stop('test2')); + $elapsed = DebugTimer::elapsedTime('test2'); + $expected = stripos(PHP_OS, 'win') === false ? 0.999: 0.95; // Windows timer's precision is bad + $this->assertTrue($elapsed >= $expected); + + DebugTimer::start('test3'); + $this->assertIdentical(DebugTimer::elapsedTime('test3'), 0); + $this->assertFalse(DebugTimer::stop('wrong')); + } + +/** + * test timers with no names. + * + * @return void + */ + public function testAnonymousTimers() { + $this->assertTrue(DebugTimer::start()); + usleep(2000); + $this->assertTrue(DebugTimer::stop()); + $timers = DebugTimer::getAll(); + + $this->assertEquals(2, count($timers)); + end($timers); + $key = key($timers); + $lineNo = __LINE__ - 8; + + $file = Debugger::trimPath(__FILE__); + $expected = $file . ' line ' . $lineNo; + $this->assertEquals($expected, $key); + + $timer = $timers[$expected]; + $this->assertTrue($timer['time'] > 0.0020); + $this->assertEquals($expected, $timers[$expected]['message']); + } + +/** + * Assert that nested anonymous timers don't get mixed up. + * + * @return void + */ + public function testNestedAnonymousTimers() { + $this->assertTrue(DebugTimer::start()); + usleep(100); + $this->assertTrue(DebugTimer::start()); + usleep(100); + $this->assertTrue(DebugTimer::stop()); + $this->assertTrue(DebugTimer::stop()); + + $timers = DebugTimer::getAll(); + $this->assertEquals(3, count($timers), 'incorrect number of timers %s'); + $firstTimerLine = __LINE__ - 9; + $secondTimerLine = __LINE__ - 8; + $file = Debugger::trimPath(__FILE__); + + $this->assertTrue(isset($timers[$file . ' line ' . $firstTimerLine]), 'first timer is not set %s'); + $this->assertTrue(isset($timers[$file . ' line ' . $secondTimerLine]), 'second timer is not set %s'); + + $firstTimer = $timers[$file . ' line ' . $firstTimerLine]; + $secondTimer = $timers[$file . ' line ' . $secondTimerLine]; + $this->assertTrue($firstTimer['time'] > $secondTimer['time']); + } + +/** + * test that calling start with the same name does not overwrite previous timers + * and instead adds new ones. + * + * @return void + */ + public function testRepeatTimers() { + DebugTimer::start('my timer', 'This is the first call'); + usleep(100); + DebugTimer::start('my timer', 'This is the second call'); + usleep(100); + + DebugTimer::stop('my timer'); + DebugTimer::stop('my timer'); + + $timers = DebugTimer::getAll(); + $this->assertEquals(3, count($timers), 'wrong timer count %s'); + + $this->assertTrue(isset($timers['my timer'])); + $this->assertTrue(isset($timers['my timer #2'])); + + $this->assertTrue($timers['my timer']['time'] > $timers['my timer #2']['time'], 'timer 2 is longer? %s'); + $this->assertEquals('This is the first call', $timers['my timer']['message']); + $this->assertEquals('This is the second call #2', $timers['my timer #2']['message']); + } + +/** + * testRequestTime + * + * @return void + */ + public function testRequestTime() { + $result1 = DebugTimer::requestTime(); + usleep(50); + $result2 = DebugTimer::requestTime(); + $this->assertTrue($result1 < $result2); + } + +/** + * test getting all the set timers. + * + * @return void + */ + public function testGetTimers() { + DebugTimer::start('test1', 'this is my first test'); + DebugTimer::stop('test1'); + usleep(50); + DebugTimer::start('test2'); + DebugTimer::stop('test2'); + $timers = DebugTimer::getAll(); + + $this->assertEquals(3, count($timers)); + $this->assertTrue(is_float($timers['test1']['time'])); + $this->assertTrue(isset($timers['test1']['message'])); + $this->assertTrue(isset($timers['test2']['message'])); + } +} diff --git a/app/Plugin/DebugKit/Test/Case/Lib/FireCakeTest.php b/app/Plugin/DebugKit/Test/Case/Lib/FireCakeTest.php new file mode 100644 index 0000000..e26516c --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/Lib/FireCakeTest.php @@ -0,0 +1,345 @@ +firecake = FireCake::getInstance('TestFireCake'); + TestFireCake::reset(); + } + +/** + * Reset the FireCake counters and headers. + * + * @return void + */ + public function tearDown() { + TestFireCake::reset(); + } + +/** + * Test getInstance cheat. + * + * If this fails the rest of the test is going to fail too. + * + * @return void + */ + public function testGetInstanceOverride() { + $instance = FireCake::getInstance(); + $instance2 = FireCake::getInstance(); + $this->assertReference($instance, $instance2); + $this->assertIsA($instance, 'FireCake'); + $this->assertIsA($instance, 'TestFireCake', 'Stored instance is not a copy of TestFireCake, test case is broken.'); + } + +/** + * Test setOptions + * + * @return void + */ + public function testSetOptions() { + FireCake::setOptions(array('includeLineNumbers' => false)); + $this->assertEquals($this->firecake->options['includeLineNumbers'], false); + } + +/** + * Test Log() + * + * @return void + */ + public function testLog() { + FireCake::setOptions(array('includeLineNumbers' => false)); + FireCake::log('Testing'); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-Protocol-1'])); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-1-Plugin-1'])); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-1-Structure-1'])); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-Index'], 1); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-1'], '26|[{"Type":"LOG"},"Testing"]|'); + + FireCake::log('Testing', 'log-info'); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-2'], '45|[{"Type":"LOG","Label":"log-info"},"Testing"]|'); + } + +/** + * Test info() + * + * @return void + */ + public function testInfo() { + FireCake::setOptions(array('includeLineNumbers' => false)); + FireCake::info('I have information'); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-Protocol-1'])); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-1-Plugin-1'])); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-1-Structure-1'])); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-Index'], 1); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-1'], '38|[{"Type":"INFO"},"I have information"]|'); + + FireCake::info('I have information', 'info-label'); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-2'], '59|[{"Type":"INFO","Label":"info-label"},"I have information"]|'); + } + +/** + * Test info() + * + * @return void + */ + public function testWarn() { + FireCake::setOptions(array('includeLineNumbers' => false)); + FireCake::warn('A Warning'); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-Protocol-1'])); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-1-Plugin-1'])); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-1-Structure-1'])); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-Index'], 1); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-1'], '29|[{"Type":"WARN"},"A Warning"]|'); + + FireCake::warn('A Warning', 'Bzzz'); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-2'], '44|[{"Type":"WARN","Label":"Bzzz"},"A Warning"]|'); + } + +/** + * Test error() + * + * @return void + */ + public function testError() { + FireCake::setOptions(array('includeLineNumbers' => false)); + FireCake::error('An error'); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-Protocol-1'])); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-1-Plugin-1'])); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-1-Structure-1'])); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-Index'], 1); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-1'], '29|[{"Type":"ERROR"},"An error"]|'); + + FireCake::error('An error', 'wonky'); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-2'], '45|[{"Type":"ERROR","Label":"wonky"},"An error"]|'); + } + +/** + * Test dump() + * + * @return void + */ + public function testDump() { + FireCake::dump('mydump', array('one' => 1, 'two' => 2)); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-2-1-1'], '28|{"mydump":{"one":1,"two":2}}|'); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-1-Structure-2'])); + } + +/** + * Test table() generation + * + * @return void + */ + public function testTable() { + $table[] = array('Col 1 Heading','Col 2 Heading'); + $table[] = array('Row 1 Col 1','Row 1 Col 2'); + $table[] = array('Row 2 Col 1','Row 2 Col 2'); + $table[] = array('Row 3 Col 1','Row 3 Col 2'); + FireCake::table('myTrace', $table); + $expected = '162|[{"Type":"TABLE","Label":"myTrace"},[["Col 1 Heading","Col 2 Heading"],["Row 1 Col 1","Row 1 Col 2"],["Row 2 Col 1","Row 2 Col 2"],["Row 3 Col 1","Row 3 Col 2"]]]|'; + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-1'], $expected); + } + +/** + * TestStringEncoding + * + * @return void + */ + public function testStringEncode() { + $vars = array(1,2,3); + $result = $this->firecake->stringEncode($vars); + $this->assertEquals($result, array(1,2,3)); + + $this->firecake->setOptions(array('maxArrayDepth' => 3)); + $deep = array(1 => array(2 => array(3))); + $result = $this->firecake->stringEncode($deep); + $this->assertEquals($result, array(1 => array(2 => '** Max Array Depth (3) **'))); + } + +/** + * Test object encoding + * + * @return void + */ + public function testStringEncodeObjects() { + $obj = FireCake::getInstance(); + $result = $this->firecake->stringEncode($obj); + + $this->assertTrue(is_array($result)); + $this->assertEquals($result['_defaultOptions']['useNativeJsonEncode'], true); + $this->assertEquals($result['_encodedObjects'][0], '** Recursion (TestFireCake) **'); + } + +/** + * Test trace() + * + * @return void + */ + public function testTrace() { + FireCake::trace('myTrace'); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-Protocol-1'])); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-1-Plugin-1'])); + $this->assertTrue(isset($this->firecake->sentHeaders['X-Wf-1-Structure-1'])); + $dump = $this->firecake->sentHeaders['X-Wf-1-1-1-1']; + $this->assertPattern('/"Message":"myTrace"/', $dump); + $this->assertPattern('/"Trace":\[/', $dump); + } + +/** + * Test enabling and disabling of FireCake output + * + * @return void + */ + public function testEnableDisable() { + FireCake::disable(); + FireCake::trace('myTrace'); + $this->assertTrue(empty($this->firecake->sentHeaders)); + + FireCake::enable(); + FireCake::trace('myTrace'); + $this->assertFalse(empty($this->firecake->sentHeaders)); + } + +/** + * Test correct line continuation markers on multi line headers. + * + * @return void + */ + public function testMultiLineOutput() { + FireCake::trace('myTrace'); + $this->assertGreaterThan(1, $this->firecake->sentHeaders['X-Wf-1-Index']); + $header = $this->firecake->sentHeaders['X-Wf-1-1-1-1']; + $this->assertEquals(substr($header, -2), '|\\'); + + $endIndex = $this->firecake->sentHeaders['X-Wf-1-Index']; + $header = $this->firecake->sentHeaders['X-Wf-1-1-1-' . $endIndex]; + $this->assertEquals(substr($header, -1), '|'); + } + +/** + * Test inclusion of line numbers + * + * @return void + */ + public function testIncludeLineNumbers() { + FireCake::setOptions(array('includeLineNumbers' => true)); + FireCake::info('Testing'); + $result = $this->firecake->sentHeaders['X-Wf-1-1-1-1']; + $this->assertPattern('/"File"\:".*FireCakeTest.php/', $result); + $this->assertPattern('/"Line"\:\d+/', $result); + } + +/** + * Test Group messages + * + * @return void + */ + public function testGroup() { + FireCake::setOptions(array('includeLineNumbers' => false)); + FireCake::group('test'); + FireCake::info('my info'); + FireCake::groupEnd(); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-1'], '63|[{"Collapsed":"true","Type":"GROUP_START","Label":"test"},null]|'); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-3'], '27|[{"Type":"GROUP_END"},null]|'); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-Index'], 3); + } + +/** + * Test fb() parameter parsing + * + * @return void + */ + public function testFbParameterParsing() { + FireCake::setOptions(array('includeLineNumbers' => false)); + FireCake::fb('Test'); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-1'], '23|[{"Type":"LOG"},"Test"]|'); + + FireCake::fb('Test', 'warn'); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-2'], '24|[{"Type":"WARN"},"Test"]|'); + + FireCake::fb('Test', 'Custom label', 'warn'); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-3'], '47|[{"Type":"WARN","Label":"Custom label"},"Test"]|'); + + $this->expectError('PHPUnit_Framework_Error'); + $this->assertFalse(FireCake::fb('Test', 'Custom label', 'warn', 'more parameters')); + + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-Index'], 3); + } + +/** + * Test defaulting to log if incorrect message type is used + * + * @return void + */ + public function testIncorrectMessageType() { + FireCake::setOptions(array('includeLineNumbers' => false)); + FireCake::fb('Hello World', 'foobared'); + $this->assertEquals($this->firecake->sentHeaders['X-Wf-1-1-1-1'], '30|[{"Type":"LOG"},"Hello World"]|'); + } + +/** + * Test DetectClientExtension. + * + * @return void + */ + public function testDetectClientExtension() { + $back = env('HTTP_USER_AGENT'); + $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 FirePHP/0.2.1'; + $this->assertTrue(FireCake::detectClientExtension()); + + $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 FirePHP/0.0.4'; + $this->assertFalse(FireCake::detectClientExtension()); + + $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4'; + $this->assertFalse(FireCake::detectClientExtension()); + $_SERVER['HTTP_USER_AGENT'] = $back; + } + +/** + * Test of Non Native JSON encoding. + * + * @return void + */ + public function testNonNativeEncoding() { + FireCake::setOptions(array('useNativeJsonEncode' => false)); + $json = FireCake::jsonEncode(array('one' => 1, 'two' => 2)); + $this->assertEquals($json, '{"one":1,"two":2}'); + + $json = FireCake::jsonEncode(array(1,2,3)); + $this->assertEquals($json, '[1,2,3]'); + + $json = FireCake::jsonEncode(FireCake::getInstance()); + $this->assertPattern('/"options"\:\{"maxObjectDepth"\:\d*,/', $json); + } + +} diff --git a/app/Plugin/DebugKit/Test/Case/Lib/Panel/LogPanelTest.php b/app/Plugin/DebugKit/Test/Case/Lib/Panel/LogPanelTest.php new file mode 100644 index 0000000..6422158 --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/Lib/Panel/LogPanelTest.php @@ -0,0 +1,63 @@ +panel = new LogPanel(); + } + +/** + * Test that logging configs are created. + * + * @return void + */ + public function testConstructor() { + $result = CakeLog::configured(); + $this->assertContains('debug_kit_log_panel', $result); + $this->assertTrue(count($result) > 1, 'Default loggers were not added.'); + } + +/** + * testBeforeRender + * + * @return void + */ + public function testBeforeRender() { + $controller = new Controller(); + + CakeLog::write('error', 'Test'); + + $result = $this->panel->beforeRender($controller); + $this->assertInstanceOf('DebugKitLog', $result); + $this->assertTrue(isset($result->logs)); + $this->assertCount(1, $result->logs['error']); + } +} diff --git a/app/Plugin/DebugKit/Test/Case/Lib/Panel/SqlLogPanelTest.php b/app/Plugin/DebugKit/Test/Case/Lib/Panel/SqlLogPanelTest.php new file mode 100644 index 0000000..b1770e0 --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/Lib/Panel/SqlLogPanelTest.php @@ -0,0 +1,59 @@ +panel = new SqlLogPanel(); + } + +/** + * test the parsing of source list. + * + * @return void + */ + public function testBeforeRender() { + $Article = ClassRegistry::init('Article'); + $Article->find('first', array('conditions' => array('Article.id' => 1))); + + $controller = new Controller(); + $result = $this->panel->beforeRender($controller); + + $this->assertTrue(isset($result['connections'][$Article->useDbConfig])); + $this->assertTrue(isset($result['threshold'])); + } +} diff --git a/app/Plugin/DebugKit/Test/Case/Model/Behavior/TimedBehaviorTest.php b/app/Plugin/DebugKit/Test/Case/Model/Behavior/TimedBehaviorTest.php new file mode 100644 index 0000000..491cdf7 --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/Model/Behavior/TimedBehaviorTest.php @@ -0,0 +1,89 @@ +Article = ClassRegistry::init('Article'); + $this->Article->Behaviors->attach('DebugKit.Timed'); + } + +/** + * End a test + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Article); + ClassRegistry::flush(); + DebugKitDebugger::clearTimers(); + } + +/** + * Test find timers + * + * @return void + */ + public function testFindTimers() { + $timers = DebugKitDebugger::getTimers(false); + $this->assertEquals(count($timers), 1); + + $this->Article->find('all'); + $result = DebugKitDebugger::getTimers(false); + $this->assertEquals(count($result), 2); + + $this->Article->find('all'); + $result = DebugKitDebugger::getTimers(false); + $this->assertEquals(count($result), 3); + } + +/** + * Test save timers + * + * @return void + */ + public function testSaveTimers() { + $timers = DebugKitDebugger::getTimers(false); + $this->assertEquals(count($timers), 1); + + $this->Article->save(array('user_id' => 1, 'title' => 'test', 'body' => 'test')); + $result = DebugKitDebugger::getTimers(false); + $this->assertEquals(count($result), 2); + } +} diff --git a/app/Plugin/DebugKit/Test/Case/Model/ToolbarAccessTest.php b/app/Plugin/DebugKit/Test/Case/Model/ToolbarAccessTest.php new file mode 100644 index 0000000..3c0cde7 --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/Model/ToolbarAccessTest.php @@ -0,0 +1,69 @@ +Model = new ToolbarAccess(); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Model); + } + +/** + * test that explain query returns arrays of query information. + * + * @return void + */ + public function testExplainQuery() { + $Post = new CakeTestModel(array('table' => 'posts', 'alias' => 'Post')); + $db = $Post->getDataSource(); + $sql = 'SELECT * FROM ' . $db->fullTableName('posts') . ';'; + $result = $this->Model->explainQuery($Post->useDbConfig, $sql); + + $this->assertTrue(is_array($result)); + $this->assertFalse(empty($result)); + } +} diff --git a/app/Plugin/DebugKit/Test/Case/TestFireCake.php b/app/Plugin/DebugKit/Test/Case/TestFireCake.php new file mode 100644 index 0000000..30b1950 --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/TestFireCake.php @@ -0,0 +1,65 @@ +sentHeaders[$name] = $value; + } + +/** + * Skip client detection as headers are not being sent. + * + * @return boolean Always true + */ + public static function detectClientExtension() { + return true; + } + +/** + * Reset FireCake + * + * @return void + */ + public static function reset() { + $_this = FireCake::getInstance(); + $_this->sentHeaders = array(); + $_this->_messageIndex = 1; + } +} diff --git a/app/Plugin/DebugKit/Test/Case/View/Helper/FirePhpToolbarHelperTest.php b/app/Plugin/DebugKit/Test/Case/View/Helper/FirePhpToolbarHelperTest.php new file mode 100644 index 0000000..c04fded --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/View/Helper/FirePhpToolbarHelperTest.php @@ -0,0 +1,152 @@ + 'pages', 'action' => 'display', 'home')); + Router::parse('/'); + + $this->Controller = new Controller($this->getMock('CakeRequest'), new CakeResponse()); + $this->View = new View($this->Controller); + $this->Toolbar = new ToolbarHelper($this->View, array('output' => 'DebugKit.FirePhpToolbar')); + $this->Toolbar->FirePhpToolbar = new FirePhpToolbarHelper($this->View); + + $this->firecake = FireCake::getInstance('TestFireCake'); + TestFireCake::reset(); + } + +/** + * Start test - switch view paths + * + * @return void + **/ + public static function setupBeforeClass() { + App::build(array( + 'View' => array( + CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'View' . DS, + APP . 'Plugin' . DS . 'DebugKit' . DS . 'View' . DS, + CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'View' . DS + )), true); + } + +/** + * End Test + * + * @return void + */ + public static function tearDownAfterClass() { + App::build(); + } + +/** + * TearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Toolbar, $this->Controller); + TestFireCake::reset(); + } + +/** + * Test neat array (dump)creation + * + * @return void + */ + public function testMakeNeatArray() { + $this->Toolbar->makeNeatArray(array(1,2,3)); + $result = $this->firecake->sentHeaders; + $this->assertTrue(isset($result['X-Wf-1-1-1-1'])); + $this->assertRegexp('/\[1,2,3\]/', $result['X-Wf-1-1-1-1']); + } + +/** + * Test afterlayout element rendering + * + * @return void + */ + public function testAfterLayout() { + $this->Controller->viewPath = 'Posts'; + $request = new CakeRequest('/posts/index'); + $request->addParams(Router::parse($request->url)); + $request->addPaths(array( + 'webroot' => '/', + 'base' => '/', + 'here' => '/posts/index', + )); + $this->Controller->setRequest($request); + $this->Controller->layout = 'default'; + $this->Controller->uses = null; + $this->Controller->components = array('DebugKit.Toolbar'); + $this->Controller->constructClasses(); + $this->Controller->Components->trigger('startup', array($this->Controller)); + $this->Controller->Components->trigger('beforeRender', array($this->Controller)); + $result = $this->Controller->render(); + $this->assertNotRegExp('/debug-toolbar/', (string)$result); + $result = $this->firecake->sentHeaders; + $this->assertTrue(is_array($result)); + } + +/** + * test starting a panel + * + * @return void + **/ + public function testPanelStart() { + $this->Toolbar->panelStart('My Panel', 'my_panel'); + $result = $this->firecake->sentHeaders; + $this->assertPattern('/GROUP_START.+My Panel/', $result['X-Wf-1-1-1-1']); + } + +/** + * test ending a panel + * + * @return void + **/ + public function testPanelEnd() { + $this->Toolbar->panelEnd(); + $result = $this->firecake->sentHeaders; + $this->assertPattern('/GROUP_END/', $result['X-Wf-1-1-1-1']); + } +} diff --git a/app/Plugin/DebugKit/Test/Case/View/Helper/HtmlToolbarHelperTest.php b/app/Plugin/DebugKit/Test/Case/View/Helper/HtmlToolbarHelperTest.php new file mode 100644 index 0000000..a2f6632 --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/View/Helper/HtmlToolbarHelperTest.php @@ -0,0 +1,452 @@ + array( + CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'View' . DS, + APP . 'Plugin' . DS . 'DebugKit' . DS . 'View' . DS, + CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'View' . DS + ) + ), true); + } + +/** + * Tear Down Test Case + */ + public static function tearDownAfterClass() { + App::build(); + } + +/** + * Setup + * + * @return void + */ + public function setUp() { + parent::setUp(); + + Router::connect('/:controller/:action'); + + $request = new CakeRequest(); + $request->addParams(array('controller' => 'pages', 'action' => 'display')); + + $this->Controller = new Controller($request, new CakeResponse()); + $this->View = new View($this->Controller); + $this->Toolbar = new ToolbarHelper($this->View, array('output' => 'DebugKit.HtmlToolbar')); + $this->Toolbar->HtmlToolbar = new HtmlToolbarHelper($this->View); + $this->Toolbar->HtmlToolbar->Html = new HtmlHelper($this->View); + $this->Toolbar->HtmlToolbar->Form = new FormHelper($this->View); + } + +/** + * Tear Down + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + unset($this->Toolbar, $this->Controller); + } + +/** + * Test makeNeatArray with basic types. + * + * @return void + */ + public function testMakeNeatArrayBasic() { + $in = false; + $result = $this->Toolbar->makeNeatArray($in); + $expected = array( + 'ul' => array('class' => 'neat-array depth-0'), + 'assertTags($result, $expected); + + $in = null; + $result = $this->Toolbar->makeNeatArray($in); + $expected = array( + 'ul' => array('class' => 'neat-array depth-0'), + 'assertTags($result, $expected); + + $in = true; + $result = $this->Toolbar->makeNeatArray($in); + $expected = array( + 'ul' => array('class' => 'neat-array depth-0'), + 'assertTags($result, $expected); + + $in = array(); + $result = $this->Toolbar->makeNeatArray($in); + $expected = array( + 'ul' => array('class' => 'neat-array depth-0'), + 'assertTags($result, $expected); + } + +/** + * Test that cyclic references can be printed. + * + * @return void + */ + public function testMakeNeatArrayCyclicObjects() { + $a = new StdClass; + $b = new StdClass; + $a->child = $b; + $b->parent = $a; + + $in = array('obj' => $a); + $result = $this->Toolbar->makeNeatArray($in); + $expected = array( + array('ul' => array('class' => 'neat-array depth-0')), + ' array('class' => 'neat-array depth-1')), + ' array('class' => 'neat-array depth-2')), + 'assertTags($result, $expected); + } + +/** + * Test Neat Array formatting + * + * @return void + */ + public function testMakeNeatArray() { + $in = array('key' => 'value'); + $result = $this->Toolbar->makeNeatArray($in); + $expected = array( + 'ul' => array('class' => 'neat-array depth-0'), + 'assertTags($result, $expected); + + $in = array('key' => null); + $result = $this->Toolbar->makeNeatArray($in); + $expected = array( + 'ul' => array('class' => 'neat-array depth-0'), + 'assertTags($result, $expected); + + $in = array('key' => 'value', 'foo' => 'bar'); + $result = $this->Toolbar->makeNeatArray($in); + $expected = array( + 'ul' => array('class' => 'neat-array depth-0'), + 'assertTags($result, $expected); + + $in = array( + 'key' => 'value', + 'foo' => array( + 'this' => 'deep', + 'another' => 'value' + ) + ); + $result = $this->Toolbar->makeNeatArray($in); + $expected = array( + 'ul' => array('class' => 'neat-array depth-0'), + ' array('class' => 'neat-array depth-1')), + 'assertTags($result, $expected); + + $in = array( + 'key' => 'value', + 'foo' => array( + 'this' => 'deep', + 'another' => 'value' + ), + 'lotr' => array( + 'gandalf' => 'wizard', + 'bilbo' => 'hobbit' + ) + ); + $result = $this->Toolbar->makeNeatArray($in, 1); + $expected = array( + 'ul' => array('class' => 'neat-array depth-0 expanded'), + ' array('class' => 'neat-array depth-1')), + ' array('class' => 'neat-array depth-1')), + 'assertTags($result, $expected); + + $result = $this->Toolbar->makeNeatArray($in, 2); + $expected = array( + 'ul' => array('class' => 'neat-array depth-0 expanded'), + ' array('class' => 'neat-array depth-1 expanded')), + ' array('class' => 'neat-array depth-1 expanded')), + 'assertTags($result, $expected); + + $in = array('key' => 'value', 'array' => array()); + $result = $this->Toolbar->makeNeatArray($in); + $expected = array( + 'ul' => array('class' => 'neat-array depth-0'), + 'assertTags($result, $expected); + } + +/** + * Test makeNeatArray with object inputs. + * + * @return void + */ + public function testMakeNeatArrayObjects() { + $in = new StdClass(); + $in->key = 'value'; + $in->nested = new StdClass(); + $in->nested->name = 'mark'; + + $result = $this->Toolbar->makeNeatArray($in); + $expected = array( + array('ul' => array('class' => 'neat-array depth-0')), + ' array('class' => 'neat-array depth-1')), + 'assertTags($result, $expected); + } + +/** + * Test injection of toolbar + * + * @return void + */ + public function testInjectToolbar() { + $this->Controller->viewPath = 'Posts'; + $request = new CakeRequest('/posts/index'); + $request->addParams(Router::parse($request->url)); + $request->addPaths(array( + 'webroot' => '/', + 'base' => '/', + 'here' => '/posts/index', + )); + $this->Controller->setRequest($request); + $this->Controller->helpers = array('Html', 'Js', 'Session', 'DebugKit.Toolbar'); + $this->Controller->layout = 'default'; + $this->Controller->uses = null; + $this->Controller->components = array('DebugKit.Toolbar'); + $this->Controller->constructClasses(); + $this->Controller->Components->trigger('startup', array($this->Controller)); + $this->Controller->Components->trigger('beforeRender', array($this->Controller)); + $result = $this->Controller->render(); + $result = str_replace(array("\n", "\r"), '', $result); + $this->assertPattern('#
.+
.*#', $result); + } + +/** + * test injection of javascript + * + * @return void + */ + public function testJavascriptInjection() { + $this->Controller->viewPath = 'Posts'; + $this->Controller->uses = null; + $request = new CakeRequest('/posts/index'); + $request->addParams(Router::parse($request->url)); + $request->addPaths(array( + 'webroot' => '/', + 'base' => '/', + 'here' => '/posts/index', + )); + $this->Controller->setRequest($request); + $this->Controller->helpers = array('Js', 'Html', 'Session'); + $this->Controller->components = array('DebugKit.Toolbar'); + $this->Controller->layout = 'default'; + $this->Controller->constructClasses(); + $this->Controller->Components->trigger('startup', array($this->Controller)); + $this->Controller->Components->trigger('beforeRender', array($this->Controller)); + $result = $this->Controller->render(); + $result = str_replace(array("\n", "\r"), '', $result); + $this->assertPattern('#\s?#', $result); + } + +/** + * test message creation + * + * @return void + */ + public function testMessage() { + $result = $this->Toolbar->message('test', 'one, two'); + $expected = array( + 'assertTags($result, $expected); + } + +/** + * Test Table generation + * + * @return void + */ + public function testTable() { + $rows = array( + array(1,2), + array(3,4), + ); + $result = $this->Toolbar->table($rows); + $expected = array( + 'table' => array('class' => 'debug-table'), + array('tr' => array('class' => 'odd')), + ' array('class' => 'even')), + 'assertTags($result, $expected); + } + +/** + * test starting a panel + * + * @return void + */ + public function testStartPanel() { + $result = $this->Toolbar->panelStart('My Panel', 'my_panel'); + $expected = array( + 'a' => array('href' => '#my_panel'), + 'My Panel', + '/a' + ); + $this->assertTags($result, $expected); + } + +/** + * test ending a panel + * + * @return void + */ + public function testPanelEnd() { + $result = $this->Toolbar->panelEnd(); + $this->assertNull($result); + } + +/** + * Test generating links for query explains. + * + * @return void + */ + public function testExplainLink() { + $sql = 'SELECT * FROM tasks'; + $result = $this->Toolbar->explainLink($sql, 'default'); + $expected = array( + 'form' => array('action' => '/debug_kit/toolbar_access/sql_explain', 'method' => 'post', + 'accept-charset' => 'utf-8', 'id'), + array('div' => array('style' => 'display:none;')), + array('input' => array('type' => 'hidden', 'name' => '_method', 'value' => 'POST')), + '/div', + array('input' => array('type' => 'hidden', 'id', 'name' => 'data[log][ds]', 'value' => 'default')), + array('input' => array('type' => 'hidden', 'id', 'name' => 'data[log][sql]', 'value' => $sql)), + array('input' => array('type' => 'hidden', 'id', 'name' => 'data[log][hash]', 'value')), + array('input' => array('class' => 'sql-explain-link', 'type' => 'submit', 'value' => 'Explain')), + '/form', + ); + $this->assertTags($result, $expected); + } + +} diff --git a/app/Plugin/DebugKit/Test/Case/View/Helper/ToolbarHelperTest.php b/app/Plugin/DebugKit/Test/Case/View/Helper/ToolbarHelperTest.php new file mode 100644 index 0000000..273f472 --- /dev/null +++ b/app/Plugin/DebugKit/Test/Case/View/Helper/ToolbarHelperTest.php @@ -0,0 +1,179 @@ +fullDebug = true; + + Configure::write('Cache.disable', false); + Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); + Router::parse('/'); + + $this->Controller = new Controller(null); + $this->View = new View($this->Controller); + $this->Toolbar = new ToolbarHelper($this->View, array( + 'output' => 'MockBackendHelper', + 'cacheKey' => 'debug_kit_toolbar_test_case', + 'cacheConfig' => 'default' + )); + $this->Toolbar->MockBackend = $this->getMock('Helper', array('testMethod'), array($this->View)); + + $this->_viewPaths = App::path('views'); + App::build(array( + 'View' => array( + CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'View' . DS, + APP . 'Plugin' . DS . 'DebugKit' . DS . 'View' . DS, + CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'View' . DS + )), true); + } + +/** + * tearDown + * + * @return void + */ + public function tearDown() { + parent::tearDown(); + Cache::delete('debug_kit_toolbar_test_case', 'default'); + unset($this->Toolbar, $this->Controller); + } + +/** + * test cache writing for views. + * + * @return void + */ + public function testCacheWrite() { + $result = $this->Toolbar->writeCache('test', array('stuff', 'to', 'cache')); + $this->assertTrue($result); + } + +/** + * Ensure that the cache writing only affects the + * top most level of the history stack. As this is where the current request is stored. + * + * @return void + */ + public function testOnlyWritingToFirstElement() { + $values = array( + array('test' => array('content' => array('first', 'values'))), + array('test' => array('content' => array('second', 'values'))), + ); + Cache::write('debug_kit_toolbar_test_case', $values, 'default'); + $this->Toolbar->writeCache('test', array('new', 'values')); + + $result = $this->Toolbar->readCache('test'); + $this->assertEquals($result, array('new', 'values')); + + $result = $this->Toolbar->readCache('test', 1); + $this->assertEquals($result, array('second', 'values')); + } + +/** + * test cache reading for views + * + * @return void + */ + public function testCacheRead() { + $result = $this->Toolbar->writeCache('test', array('stuff', 'to', 'cache')); + $this->assertTrue($result, 'Cache write failed %s'); + + $result = $this->Toolbar->readCache('test'); + $this->assertEquals($result, array('stuff', 'to', 'cache'), 'Cache value is wrong %s'); + + $result = $this->Toolbar->writeCache('test', array('new', 'stuff')); + $this->assertTrue($result, 'Cache write failed %s'); + + $result = $this->Toolbar->readCache('test'); + $this->assertEquals($result, array('new', 'stuff'), 'Cache value is wrong %s'); + } + +/** + * Test that reading/writing doesn't work with no cache config. + * + * @return void + */ + public function testNoCacheConfigPresent() { + $this->Toolbar = new ToolbarHelper($this->View, array('output' => 'MockBackendHelper')); + + $result = $this->Toolbar->writeCache('test', array('stuff', 'to', 'cache')); + $this->assertFalse($result, 'Writing to cache succeeded with no cache config %s'); + + $result = $this->Toolbar->readCache('test'); + $this->assertFalse($result, 'Reading cache succeeded with no cache config %s'); + } + +/** + * ensure that getQueryLogs works and writes to the cache so the history panel will + * work. + * + * @return void + */ + public function testGetQueryLogs() { + $model = new CakeTestModel(array('table' => 'posts', 'alias' => 'Post')); + $model->find('all'); + $model->find('first'); + + $result = $this->Toolbar->getQueryLogs($model->useDbConfig, array('cache' => false)); + $this->assertTrue(is_array($result)); + $this->assertTrue(count($result) >= 2, 'Should be more than 2 queries in the log %s'); + $this->assertTrue(isset($result['queries'][0]['actions'])); + + $model->find('first'); + Cache::delete('debug_kit_toolbar_test_case', 'default'); + $result = $this->Toolbar->getQueryLogs($model->useDbConfig, array('cache' => true)); + + $cached = $this->Toolbar->readCache('sql_log'); + $this->assertTrue(isset($cached[$model->useDbConfig])); + $this->assertEquals($cached[$model->useDbConfig]['queries'][0], $result['queries'][0]); + } + +} diff --git a/app/Plugin/DebugKit/Test/test_app/Controller/DebugKitTestController.php b/app/Plugin/DebugKit/Test/test_app/Controller/DebugKitTestController.php new file mode 100644 index 0000000..60196b4 --- /dev/null +++ b/app/Plugin/DebugKit/Test/test_app/Controller/DebugKitTestController.php @@ -0,0 +1,63 @@ +autoRender = false; + return 'I am some value from requestAction.'; + } + +/** + * Render Request Action + */ + public function request_action_render() { + $this->set('test', 'I have been rendered.'); + } +} diff --git a/app/Plugin/DebugKit/Test/test_app/Lib/Panel/TestPanel.php b/app/Plugin/DebugKit/Test/test_app/Lib/Panel/TestPanel.php new file mode 100644 index 0000000..9b69812 --- /dev/null +++ b/app/Plugin/DebugKit/Test/test_app/Lib/Panel/TestPanel.php @@ -0,0 +1,37 @@ +testPanel = true; + } + +} diff --git a/app/Plugin/DebugKit/Test/test_app/Plugin/DebugkitTestPlugin/Lib/Panel/PluginTestPanel.php b/app/Plugin/DebugKit/Test/test_app/Plugin/DebugkitTestPlugin/Lib/Panel/PluginTestPanel.php new file mode 100644 index 0000000..3d3b083 --- /dev/null +++ b/app/Plugin/DebugKit/Test/test_app/Plugin/DebugkitTestPlugin/Lib/Panel/PluginTestPanel.php @@ -0,0 +1,26 @@ + + \ No newline at end of file diff --git a/app/Plugin/DebugKit/VERSION.txt b/app/Plugin/DebugKit/VERSION.txt new file mode 100644 index 0000000..21bb5e1 --- /dev/null +++ b/app/Plugin/DebugKit/VERSION.txt @@ -0,0 +1 @@ +2.2.5 diff --git a/app/Plugin/DebugKit/View/Elements/debug_toolbar.ctp b/app/Plugin/DebugKit/View/Elements/debug_toolbar.ctp new file mode 100644 index 0000000..9f2d530 --- /dev/null +++ b/app/Plugin/DebugKit/View/Elements/debug_toolbar.ctp @@ -0,0 +1,59 @@ + +
+ +

+ + + +
diff --git a/app/Plugin/DebugKit/View/Elements/environment_panel.ctp b/app/Plugin/DebugKit/View/Elements/environment_panel.ctp new file mode 100644 index 0000000..5d8d5f0 --- /dev/null +++ b/app/Plugin/DebugKit/View/Elements/environment_panel.ctp @@ -0,0 +1,84 @@ + +

+ $val) { + $cakeRows[] = array( + $key, + $val + ); + } + $headers = array('Constant', 'Value'); + echo $this->Toolbar->table($cakeRows, $headers, array('title' => 'Application Environment Vars')); + } else { + echo "No application environment available."; + } ?> + +

+ $val) { + $cakeRows[] = array( + h($key), + h($val) + ); + } + $headers = array('Constant', 'Value'); + echo $this->Toolbar->table($cakeRows, $headers, array('title' => 'CakePHP Environment Vars')); + } else { + echo "CakePHP environment unavailable."; + } ?> + +

+ $val) { + $phpRows[] = array( + h(Inflector::humanize(strtolower($key))), + h($val) + ); + } + echo $this->Toolbar->table($phpRows, $headers, array('title' => 'CakePHP Environment Vars')); + } else { + echo "PHP environment unavailable."; + } + + if (isset($content['hidef'])) { + echo '

' . __d('debug_kit', 'Hidef Environment') . '

'; + if (!empty($content['hidef'])) { + $cakeRows = array(); + foreach ($content['hidef'] as $key => $val) { + $cakeRows[] = array( + h($key), + h($val) + ); + } + $headers = array('Constant', 'Value'); + echo $this->Toolbar->table($cakeRows, $headers, array('title' => 'Hidef Environment Vars')); + } else { + echo "No Hidef environment available."; + } + } diff --git a/app/Plugin/DebugKit/View/Elements/history_panel.ctp b/app/Plugin/DebugKit/View/Elements/history_panel.ctp new file mode 100644 index 0000000..1c36a74 --- /dev/null +++ b/app/Plugin/DebugKit/View/Elements/history_panel.ctp @@ -0,0 +1,32 @@ + +

+ +

+ + +
    +
  • Html->link(__d('debug_kit', 'Restore to current request'), + '#', array('class' => 'history-link', 'id' => 'history-restore-current')); ?> +
  • + +
  • Html->link($previous['title'], $previous['url'], array('class' => 'history-link')); ?>
  • + +
+ +

+ +

Include Paths

+ $path) { + if (strstr($path, CAKE)) { + $content['paths'][$i] = '-> ' . $path; + break; + } + } + echo $this->Toolbar->makeNeatArray(array_filter($content['paths'])); + unset($content['paths']); +?> + +

Included Files

+Toolbar->makeNeatArray($content); \ No newline at end of file diff --git a/app/Plugin/DebugKit/View/Elements/log_panel.ctp b/app/Plugin/DebugKit/View/Elements/log_panel.ctp new file mode 100644 index 0000000..1a1efe4 --- /dev/null +++ b/app/Plugin/DebugKit/View/Elements/log_panel.ctp @@ -0,0 +1,41 @@ + +

+
+ + logs as $logName => $logs): ?> +

+ 0): + $headers = array(__d('debug_kit', 'Time'), __d('debug_kit', 'Message')); + $rows = array(); + for ($i = 0; $i < $len; $i++): + $rows[] = array( + $logs[$i][0], h($logs[$i][1]) + ); + endfor; + echo $this->Toolbar->table($rows, $headers, array('title' => $logName)); + endif; ?> + + logs)): ?> +

+ + +
diff --git a/app/Plugin/DebugKit/View/Elements/request_panel.ctp b/app/Plugin/DebugKit/View/Elements/request_panel.ctp new file mode 100644 index 0000000..9cbc93f --- /dev/null +++ b/app/Plugin/DebugKit/View/Elements/request_panel.ctp @@ -0,0 +1,50 @@ + +

+ +

Cake Params

+Toolbar->makeNeatArray($content['params']); ?> + +

Post data

+' . __d('debug_kit', 'No post data.') . '

'; +else: + echo $this->Toolbar->makeNeatArray($content['data']); +endif; +?> + +

Query string

+' . __d('debug_kit', 'No querystring data.') . '

'; +else: + echo $this->Toolbar->makeNeatArray($content['query']); +endif; +?> + +

Cookie

+ + Toolbar->makeNeatArray($content['cookie']); ?> + +

To view Cookies, add CookieComponent to Controller

+ + +

+Toolbar->makeNeatArray($content['currentRoute']); diff --git a/app/Plugin/DebugKit/View/Elements/session_panel.ctp b/app/Plugin/DebugKit/View/Elements/session_panel.ctp new file mode 100644 index 0000000..a4797f2 --- /dev/null +++ b/app/Plugin/DebugKit/View/Elements/session_panel.ctp @@ -0,0 +1,20 @@ + +

+Toolbar->makeNeatArray($content); diff --git a/app/Plugin/DebugKit/View/Elements/sql_log_panel.ctp b/app/Plugin/DebugKit/View/Elements/sql_log_panel.ctp new file mode 100644 index 0000000..b34600c --- /dev/null +++ b/app/Plugin/DebugKit/View/Elements/sql_log_panel.ctp @@ -0,0 +1,80 @@ +Toolbar->readCache('sql_log', $this->request->params['pass'][0]); +} +?> +

+ + $explain): ?> +
+

+ Toolbar->getQueryLogs($dbName, array( + 'explain' => $explain, 'threshold' => $content['threshold'] + )); + else: + $queryLog = $content[$dbName]; + endif; + if (empty($queryLog['queries'])): + if (Configure::read('debug') < 2): + echo ' ' . __d('debug_kit', 'No query logs when debug < 2.'); + else: + echo ' ' . __d('debug_kit', 'No query logs.'); + endif; + else: + $hashes = array(); + $duplicate = 0; + foreach ($queryLog['queries'] as $key => $val) { + $hash = sha1($val['query']); + if (!isset($hashes[$hash]) || $hashes[$hash] !== $val['affected']) { + $hashes[$hash] = $val['affected']; + continue; + } + $duplicate++; + + $queryLog['queries'][$key]['query'] = '' . $val['query'] . ''; + } + + echo '
'; + echo __d( + 'debug_kit', + 'Total Time: %s ms
Total Queries: %s queries', + $queryLog['time'], + $queryLog['count'] + ); + echo '
'; + echo $this->Toolbar->table($queryLog['queries'], $headers, array('title' => 'SQL Log ' . $dbName)); + if ($duplicate) { + echo '

' . __d('debug_kit', '%s duplicate queries run.', $duplicate) . '

'; + } + ?> +

+
+ +

+
+ +
+ +Toolbar->message('Warning', __d('debug_kit', 'No active database connections')); +endif; diff --git a/app/Plugin/DebugKit/View/Elements/timer_panel.ctp b/app/Plugin/DebugKit/View/Elements/timer_panel.ctp new file mode 100644 index 0000000..928f278 --- /dev/null +++ b/app/Plugin/DebugKit/View/Elements/timer_panel.ctp @@ -0,0 +1,110 @@ +Number = $this->Helpers->load('Number'); +$this->SimpleGraph = $this->Helpers->load('DebugKit.SimpleGraph'); + +if (!isset($debugKitInHistoryMode)): + $timers = DebugTimer::getAll(true); + $currentMemory = DebugKitDebugger::getMemoryUse(); + $peakMemory = DebugKitDebugger::getPeakMemoryUse(); + $requestTime = DebugTimer::requestTime(); +else: + $content = $this->Toolbar->readCache('timer', $this->request->params['pass'][0]); + if (is_array($content)): + extract($content); + endif; +endif; +?> +
+

+
+ Toolbar->message(__d('debug_kit', 'Peak Memory Use'), $this->Number->toReadableSize($peakMemory)); ?> +
+ + $value): + $rows[] = array($key, $this->Number->toReadableSize($value)); + endforeach; + + echo $this->Toolbar->table($rows, $headers); + ?> +
+ +
+

+
+ Number->precision($requestTime * 1000, 0)); ?> + Toolbar->message(__d('debug_kit', 'Total Request Time:'), $totalTime)?> +
+ $timeInfo): + $indent = 0; + for ($j = 0; $j < $i; $j++) { + if (($values[$j]['end'] > $timeInfo['start']) && ($values[$j]['end']) > ($timeInfo['end'])) { + $indent++; + } + } + $indent = str_repeat(' » ', $indent); + $rows[] = array( + $indent . $timeInfo['message'], + $this->Number->precision($timeInfo['time'] * 1000, 2), + $this->SimpleGraph->bar( + $this->Number->precision($timeInfo['time'] * 1000, 2), + $this->Number->precision($timeInfo['start'] * 1000, 2), + array( + 'max' => $maxTime * 1000, + 'requestTime' => $requestTime * 1000, + ) + ) + ); + $i++; +endforeach; + +if (strtolower($this->Toolbar->getName()) === 'firephptoolbar'): + for ($i = 0, $len = count($rows); $i < $len; $i++): + unset($rows[$i][2]); + endfor; + unset($headers[2]); +endif; + +echo $this->Toolbar->table($rows, $headers, array('title' => 'Timers')); + +if (!isset($debugKitInHistoryMode)): + $this->Toolbar->writeCache('timer', compact('timers', 'currentMemory', 'peakMemory', 'requestTime')); +endif; +?> +
diff --git a/app/Plugin/DebugKit/View/Elements/variables_panel.ctp b/app/Plugin/DebugKit/View/Elements/variables_panel.ctp new file mode 100644 index 0000000..31d4fbc --- /dev/null +++ b/app/Plugin/DebugKit/View/Elements/variables_panel.ctp @@ -0,0 +1,23 @@ + +

+validationErrors'] = $this->validationErrors; +$content['Loaded Helpers'] = $this->Helpers->attached(); +echo $this->Toolbar->makeNeatArray($content); diff --git a/app/Plugin/DebugKit/View/Helper/DebugTimerHelper.php b/app/Plugin/DebugKit/View/Helper/DebugTimerHelper.php new file mode 100644 index 0000000..4b6c12d --- /dev/null +++ b/app/Plugin/DebugKit/View/Helper/DebugTimerHelper.php @@ -0,0 +1,90 @@ +_renderComplete) { + return; + } + DebugTimer::start( + 'render_' . basename($viewFile), + __d('debug_kit', 'Rendering %s', + Debugger::trimPath($viewFile)) + ); + } + +/** + * Stops the timer point before rendering a file. + * + * @param string $viewFile The view being rendered + * @param string $content The contents of the view. + */ + public function afterRenderFile($viewFile, $content) { + if ($this->_renderComplete) { + return; + } + DebugTimer::stop('render_' . basename($viewFile)); + } + +/** + * Stop timers for rendering. + * + * @param string $layoutFile + */ + public function afterLayout($layoutFile) { + DebugTimer::stop('viewRender'); + DebugTimer::stop('controllerRender'); + DebugMemory::record(__d('debug_kit', 'View render complete')); + $this->_renderComplete = true; + } + +} diff --git a/app/Plugin/DebugKit/View/Helper/FirePhpToolbarHelper.php b/app/Plugin/DebugKit/View/Helper/FirePhpToolbarHelper.php new file mode 100644 index 0000000..f46f241 --- /dev/null +++ b/app/Plugin/DebugKit/View/Helper/FirePhpToolbarHelper.php @@ -0,0 +1,106 @@ + 'firePHP', 'forceEnable' => false); + +/** + * send method + * + * @return void + */ + public function send() { + $view = $this->_View; + $view->element('debug_toolbar', array('disableTimer' => true), array('plugin' => 'DebugKit')); + } + +/** + * makeNeatArray. + * + * wraps FireCake::dump() allowing panel elements to continue functioning + * + * @param string $values + * @return void + */ + public function makeNeatArray($values) { + FireCake::info($values); + } + +/** + * Create a simple message + * + * @param string $label Label of message + * @param string $message Message content + * @return void + */ + public function message($label, $message) { + FireCake::log($message, $label); + } + +/** + * Generate a table with FireCake + * + * @param array $rows Rows to print + * @param array $headers Headers for table + * @param array $options Additional options and params + * @return void + */ + public function table($rows, $headers, $options = array()) { + $title = $headers[0]; + if (isset($options['title'])) { + $title = $options['title']; + } + foreach ($rows as $i => $row) { + $rows[$i] = array_values($row); + } + array_unshift($rows, $headers); + FireCake::table($title, $rows); + } + +/** + * Start a panel which is a 'Group' in FirePHP + * + * @param $title + * @param $anchor + * @return void + */ + public function panelStart($title, $anchor) { + FireCake::group($title); + } + +/** + * End a panel (Group) + * + * @return void + */ + public function panelEnd() { + FireCake::groupEnd(); + } + +} diff --git a/app/Plugin/DebugKit/View/Helper/HtmlToolbarHelper.php b/app/Plugin/DebugKit/View/Helper/HtmlToolbarHelper.php new file mode 100644 index 0000000..52f2d22 --- /dev/null +++ b/app/Plugin/DebugKit/View/Helper/HtmlToolbarHelper.php @@ -0,0 +1,238 @@ + 'html', 'forceEnable' => false); + +/** + * Recursively goes through an array and makes neat HTML out of it. + * + * @param mixed $values Array to make pretty. + * @param integer $openDepth Depth to add open class + * @param integer $currentDepth current depth. + * @param boolean $doubleEncode + * @return string + */ + public function makeNeatArray($values, $openDepth = 0, $currentDepth = 0, $doubleEncode = false) { + static $printedObjects = null; + if ($currentDepth === 0) { + $printedObjects = new SplObjectStorage(); + } + $className = "neat-array depth-$currentDepth"; + if ($openDepth > $currentDepth) { + $className .= ' expanded'; + } + $nextDepth = $currentDepth + 1; + $out = "
    "; + if (!is_array($values)) { + if (is_bool($values)) { + $values = array($values); + } + if ($values === null) { + $values = array(null); + } + } + if (empty($values)) { + $values[] = '(empty)'; + } + foreach ($values as $key => $value) { + $out .= '
  • ' . h($key, $doubleEncode) . ''; + if (is_array($value) && count($value) > 0) { + $out .= '(array)'; + } elseif (is_object($value)) { + $out .= '(object)'; + } + if ($value === null) { + $value = '(null)'; + } + if ($value === false) { + $value = '(false)'; + } + if ($value === true) { + $value = '(true)'; + } + if (empty($value) && $value != 0) { + $value = '(empty)'; + } + if ($value instanceof Closure) { + $value = 'function'; + } + + $isObject = is_object($value); + if ($isObject && $printedObjects->contains($value)) { + $isObject = false; + $value = ' - recursion'; + } + + if ($isObject) { + $printedObjects->attach($value); + } + + if ( + ( + $value instanceof ArrayAccess || + $value instanceof Iterator || + is_array($value) || + $isObject + ) && !empty($value) + ) { + $out .= $this->makeNeatArray($value, $openDepth, $nextDepth, $doubleEncode); + } else { + $out .= h($value, $doubleEncode); + } + $out .= '
  • '; + } + $out .= '
'; + return $out; + } + +/** + * Create an HTML message + * + * @param string $label label content + * @param string $message message content + * @return string + */ + public function message($label, $message) { + return sprintf('

%s %s

', $label, $message); + } + +/** + * Start a panel. + * Make a link and anchor. + * + * @param $title + * @param $anchor + * @return string + */ + public function panelStart($title, $anchor) { + $link = $this->Html->link($title, '#' . $anchor); + return $link; + } + +/** + * Create a table. + * + * @param array $rows Rows to make. + * @param array $headers Optional header row. + * @return string + */ + public function table($rows, $headers = array()) { + $out = ''; + if (!empty($headers)) { + $out .= $this->Html->tableHeaders($headers); + } + $out .= $this->Html->tableCells($rows, array('class' => 'odd'), array('class' => 'even'), false, false); + $out .= '
'; + return $out; + } + +/** + * Send method + * + * @return void + */ + public function send() { + if (!$this->settings['forceEnable'] && Configure::read('debug') == 0) { + return; + } + $view = $this->_View; + $head = ''; + if (isset($view->viewVars['debugToolbarCss']) && !empty($view->viewVars['debugToolbarCss'])) { + $head .= $this->Html->css($view->viewVars['debugToolbarCss']); + } + + $js = sprintf('window.DEBUGKIT_JQUERY_URL = "%s";', $this->webroot('/debug_kit/js/jquery.js')); + $head .= $this->Html->scriptBlock($js); + + if (isset($view->viewVars['debugToolbarJavascript'])) { + foreach ($view->viewVars['debugToolbarJavascript'] as $script) { + if ($script) { + $head .= $this->Html->script($script); + } + } + } + $search = ''; + $pos = strpos($view->output, $search); + if ($pos !== false) { + $view->output = substr_replace($view->output, $head . "\n", $pos, strlen($search)); + } + $toolbar = $view->element('debug_toolbar', array('disableTimer' => true), array('plugin' => 'DebugKit')); + $search = ''; + $pos = strrpos($view->output, $search); + if ($pos !== false) { + $view->output = substr_replace($view->output, $toolbar . "\n", $pos, strlen($search)); + } + } + +/** + * Generates a SQL explain link for a given query + * + * @param string $sql SQL query string you want an explain link for. + * @param $connection + * @return string Rendered Html link or '' if the query is not a select/describe + */ + public function explainLink($sql, $connection) { + if (!preg_match('/^[\s()]*SELECT/i', $sql)) { + return ''; + } + $sql = str_replace(array("\n", "\t"), ' ', $sql); + $hash = Security::hash($sql . $connection, 'sha1', true); + $url = array( + 'plugin' => 'debug_kit', + 'controller' => 'toolbar_access', + 'action' => 'sql_explain' + ); + foreach (Router::prefixes() as $prefix) { + $url[$prefix] = false; + } + $this->explainLinkUid = (isset($this->explainLinkUid) ? $this->explainLinkUid + 1 : 0); + $uid = $this->explainLinkUid . '_' . rand(0, 10000); + $form = $this->Form->create('log', array('url' => $url, 'id' => "logForm{$uid}")); + $form .= $this->Form->hidden('log.ds', array('id' => "logDs{$uid}", 'value' => $connection)); + $form .= $this->Form->hidden('log.sql', array('id' => "logSql{$uid}", 'value' => $sql)); + $form .= $this->Form->hidden('log.hash', array('id' => "logHash{$uid}", 'value' => $hash)); + $form .= $this->Form->submit(__d('debug_kit', 'Explain'), array( + 'div' => false, + 'class' => 'sql-explain-link' + )); + $form .= $this->Form->end(); + return $form; + } + +} diff --git a/app/Plugin/DebugKit/View/Helper/SimpleGraphHelper.php b/app/Plugin/DebugKit/View/Helper/SimpleGraphHelper.php new file mode 100644 index 0000000..1c7543b --- /dev/null +++ b/app/Plugin/DebugKit/View/Helper/SimpleGraphHelper.php @@ -0,0 +1,88 @@ + (int) Maximum value in the graphs + * - width => (int) + * - valueType => string (value, percentage) + * - style => array + * + * @var array + */ + protected $_defaultSettings = array( + 'max' => 100, + 'width' => 350, + 'valueType' => 'value', + ); + +/** + * bar method + * + * @param $value Value to be graphed + * @param $offset how much indentation + * @param array|\Graph $options Graph options + * @return string Html graph + */ + public function bar($value, $offset, $options = array()) { + $settings = array_merge($this->_defaultSettings, $options); + extract($settings); + + $graphValue = ($value / $max) * $width; + $graphValue = max(round($graphValue), 1); + + if ($valueType === 'percentage') { + $graphOffset = 0; + } else { + $graphOffset = ($offset / $max) * $width; + $graphOffset = round($graphOffset); + } + return $this->Html->div( + 'debug-kit-graph-bar', + $this->Html->div( + 'debug-kit-graph-bar-value', + ' ', + array( + 'style' => "margin-left: {$graphOffset}px; width: {$graphValue}px", + 'title' => __d('debug_kit', "Starting %sms into the request, taking %sms", $offset, $value), + ) + ), + array('style' => "width: {$width}px;"), + false + ); + } + +} diff --git a/app/Plugin/DebugKit/View/Helper/TidyHelper.php b/app/Plugin/DebugKit/View/Helper/TidyHelper.php new file mode 100644 index 0000000..cae688a --- /dev/null +++ b/app/Plugin/DebugKit/View/Helper/TidyHelper.php @@ -0,0 +1,171 @@ +tidyErrors($html, $out); + + if (!$errors) { + return array(); + } + $result = array('Error' => array(), 'Warning' => array(), 'Misc' => array()); + $errors = explode("\n", $errors); + $markup = explode("\n", $out); + foreach ($errors as $error) { + preg_match('@line (\d+) column (\d+) - (\w+): (.*)@', $error, $matches); + if ($matches) { + list($original, $line, $column, $type, $message) = $matches; + $line = $line - 1; + + $string = ''; + if (isset($markup[$line - 1])) { + $string .= h($markup[$line - 1]); + } + $string .= '' . h(@$markup[$line]) . ''; + if (isset($markup[$line + 1])) { + $string .= h($markup[$line + 1]); + } + $string .= ''; + + $result[$type][$string][] = h($message); + } elseif ($error) { + $message = $error; + $result['Misc'][h($message)][] = h($message); + } + } + $this->results = $result; + return $result; + } + +/** + * report method + * + * Call process if a string is passed, or no prior results exist - and return the results using + * the toolbar helper to generate a nested navigatable array + * + * @param mixed $html null + * @return string + */ + public function report($html = null) { + if ($html) { + $this->process($html); + } elseif ($this->results === null) { + $this->process($this->_View->output); + } + if (!$this->results) { + return '

' . __d('debug_kit', 'No markup errors found') . '

'; + } + foreach ($this->results as &$results) { + foreach ($results as $type => &$messages) { + foreach ($messages as &$message) { + $message = html_entity_decode($message, ENT_COMPAT, Configure::read('App.encoding')); + } + } + } + return $this->Toolbar->makeNeatArray(array_filter($this->results), 0, 0, false); + } + +/** + * Run the html string through tidy, and return the (raw) errors. pass back a reference to the + * normalized string so that the error messages can be linked to the line that caused them. + * + * @param string $in '' + * @param string $out '' + * @return string + */ + public function tidyErrors($in = '', &$out = '') { + $out = preg_replace('@>\s*<@s', ">\n<", $in); + + // direct access? windows etc + if (function_exists('tidy_parse_string')) { + $tidy = tidy_parse_string($out, array(), 'UTF8'); + $tidy->cleanRepair(); + $errors = $tidy->errorBuffer . "\n"; + return $errors; + } + + // cli + $File = new File(rtrim(TMP, DS) . DS . rand() . '.html', true); + $File->write($out); + $path = $File->pwd(); + $errors = $path . '.err'; + $this->_exec("tidy -eq -utf8 -f $errors $path"); + $File->delete(); + + if (!file_exists($errors)) { + return ''; + } + $Error = new File($errors); + $errors = $Error->read(); + $Error->delete(); + return $errors; + } + +/** + * exec method + * + * @param mixed $cmd + * @param mixed $out null + * @return boolean True if successful + */ + protected function _exec($cmd, &$out = null) { + if (DS === '/') { + $_out = exec($cmd . ' 2>&1', $out, $return); + } else { + $_out = exec($cmd, $out, $return); + } + + if (Configure::read('debug')) { + $source = Debugger::trace(array('depth' => 1, 'start' => 2)) . "\n"; + //CakeLog::write('system_calls_' . date('Y-m-d'), "\n" . $source . Debugger::exportVar(compact('cmd','out','return'))); + //CakeLog::write('system_calls', "\n" . $source . Debugger::exportVar(compact('cmd','out','return'))); + } + if ($return) { + return false; + } + return $_out ? $_out : true; + } +} diff --git a/app/Plugin/DebugKit/View/Helper/ToolbarHelper.php b/app/Plugin/DebugKit/View/Helper/ToolbarHelper.php new file mode 100644 index 0000000..275fe63 --- /dev/null +++ b/app/Plugin/DebugKit/View/Helper/ToolbarHelper.php @@ -0,0 +1,226 @@ +_myName = strtolower(get_class($this)); + $this->settings = array_merge($this->settings, $options); + + if ($this->_myName !== 'toolbarhelper') { + parent::__construct($View, $options); + return; + } + + if (!isset($options['output'])) { + $options['output'] = 'DebugKit.HtmlToolbar'; + } + $className = $options['output']; + if (strpos($options['output'], '.') !== false) { + list($plugin, $className) = explode('.', $options['output']); + } + $this->_backEndClassName = $className; + $this->helpers[$options['output']] = $options; + if (isset($options['cacheKey']) && isset($options['cacheConfig'])) { + $this->_cacheKey = $options['cacheKey']; + $this->_cacheConfig = $options['cacheConfig']; + $this->_cacheEnabled = true; + } + + parent::__construct($View, $options); + } + +/** + * afterLayout callback + * + * @param string $layoutFile + * @return void + */ + public function afterLayout($layoutFile) { + if (!$this->request->is('requested')) { + $this->send(); + } + } + +/** + * Get the name of the backend Helper + * used to conditionally trigger toolbar output + * + * @return string + */ + public function getName() { + return $this->_backEndClassName; + } + +/** + * call__ + * + * Allows method calls on backend helper + * + * @param string $method + * @param mixed $params + * @return mixed|void + */ + public function __call($method, $params) { + if (method_exists($this->{$this->_backEndClassName}, $method)) { + return $this->{$this->_backEndClassName}->dispatchMethod($method, $params); + } + } + +/** + * Allows for writing to panel cache from view. + * Some panels generate all variables in the view by + * necessity ie. Timer. Using this method, will allow you to replace in full + * the content for a panel. + * + * @param string $name Name of the panel you are replacing. + * @param string $content Content to write to the panel. + * @return boolean Success of write. + */ + public function writeCache($name, $content) { + if (!$this->_cacheEnabled) { + return false; + } + $existing = (array)Cache::read($this->_cacheKey, $this->_cacheConfig); + $existing[0][$name]['content'] = $content; + return Cache::write($this->_cacheKey, $existing, $this->_cacheConfig); + } + +/** + * Read the toolbar + * + * @param string $name Name of the panel you want cached data for + * @param integer $index + * @return mixed Boolean false on failure, array of data otherwise. + */ + public function readCache($name, $index = 0) { + if (!$this->_cacheEnabled) { + return false; + } + $existing = (array)Cache::read($this->_cacheKey, $this->_cacheConfig); + if (!isset($existing[$index][$name]['content'])) { + return false; + } + return $existing[$index][$name]['content']; + } + +/** + * Gets the query logs for the given connection names. + * + * ### Options + * + * - explain - Whether explain links should be generated for this connection. + * - cache - Whether the toolbar_state Cache should be updated. + * - threshold - The threshold at which a visual 'maybe slow' flag should be added. + * results with rows/ms lower than $threshold will be marked. + * + * @param string $connection Connection name to get logs for. + * @param array $options Options for the query log retrieval. + * @return array Array of data to be converted into a table. + */ + public function getQueryLogs($connection, $options = array()) { + $options += array('explain' => false, 'cache' => true, 'threshold' => 20); + $db = ConnectionManager::getDataSource($connection); + + if (!method_exists($db, 'getLog')) { + return array(); + } + + $log = $db->getLog(); + + $out = array( + 'queries' => array(), + 'count' => $log['count'], + 'time' => $log['time'] + ); + foreach ($log['log'] as $i => $query) { + $query += array('query' => null); + $isSlow = ( + $query['took'] > 0 && + $query['numRows'] / $query['took'] != 1 && + $query['numRows'] / $query['took'] <= $options['threshold'] + ); + $query['actions'] = ''; + $isHtml = ($this->getName() === 'HtmlToolbar'); + if ($isSlow && $isHtml) { + $query['actions'] = sprintf( + '%s', + __d('debug_kit', 'maybe slow') + ); + } elseif ($isSlow) { + $query['actions'] = '*'; + } + if ($options['explain'] && $isHtml) { + $query['actions'] .= $this->explainLink($query['query'], $connection); + } + if ($isHtml) { + $query['query'] = h($query['query']); + if (!empty($query['params']) && is_array($query['params'])) { + $bindParam = $bindType = null; + if (preg_match('/.+ :.+/', $query['query'])) { + $bindType = true; + } + foreach ($query['params'] as $bindKey => $bindVal) { + if ($bindType === true) { + $bindParam .= h($bindKey) . " => " . h($bindVal) . ", "; + } else { + $bindParam .= h($bindVal) . ", "; + } + } + $query['query'] .= " [ " . rtrim($bindParam, ', ') . " ]"; + } + } + unset($query['params']); + $out['queries'][] = $query; + } + if ($options['cache']) { + $existing = $this->readCache('sql_log'); + $existing[$connection] = $out; + $this->writeCache('sql_log', $existing); + } + return $out; + } + +} diff --git a/app/Plugin/DebugKit/View/ToolbarAccess/history_state.ctp b/app/Plugin/DebugKit/View/ToolbarAccess/history_state.ctp new file mode 100644 index 0000000..e78e0df --- /dev/null +++ b/app/Plugin/DebugKit/View/ToolbarAccess/history_state.ctp @@ -0,0 +1,30 @@ + $panel) { + if (!empty($panel) && !empty($panel['elementName'])) { + $panels[$panelName] = $this->element($panel['elementName'], array( + 'content' => $panel['content'] + ), array( + 'plugin' => Inflector::camelize($panel['plugin']) + )); + } +} +echo json_encode($panels); +Configure::write('debug', 0); diff --git a/app/Plugin/DebugKit/View/ToolbarAccess/sql_explain.ctp b/app/Plugin/DebugKit/View/ToolbarAccess/sql_explain.ctp new file mode 100644 index 0000000..bb0a269 --- /dev/null +++ b/app/Plugin/DebugKit/View/ToolbarAccess/sql_explain.ctp @@ -0,0 +1,11 @@ + +Html->tableHeaders($headers); +echo $this->Html->tableCells($result); +?> +
+=5.3.0", + "composer/installers": "*" + }, + "extra": { + "branch-alias": { + "dev-master": "2.2.x-dev" + }, + "installer-name": "DebugKit" + } +} diff --git a/app/Plugin/DebugKit/webroot/css/debug_toolbar.css b/app/Plugin/DebugKit/webroot/css/debug_toolbar.css new file mode 100644 index 0000000..3691003 --- /dev/null +++ b/app/Plugin/DebugKit/webroot/css/debug_toolbar.css @@ -0,0 +1,387 @@ +/* @override http://localhost/mark_story/site/debug_kit/css/debug_toolbar.css */ +#debug-kit-toolbar { + position: fixed; + top: 0; + right:0px; + width: 100%; + height: 1%; + overflow: visible; + z-index:10000; + font-family: helvetica, arial, sans-serif; + font-size: 12px; + direction: ltr; +} +#debug-kit-toolbar img { + border:0; + outline:0; +} + +/* panel tabs */ +#debug-kit-toolbar #panel-tabs { + float: right; + list-style: none; + margin: 0; + padding: 0; + box-shadow: 0 5px 6px rgba(0, 0, 0, 0.5); + border-radius: 8px 0 0 8px; +} +#debug-kit-toolbar .panel-tab { + clear: none; + float: left; + margin: 0; + padding: 0; + list-style: none; +} +#debug-kit-toolbar .panel-tab > a { + float: left; + clear: none; + background: #efefef; + background: -webkit-gradient(linear, left top, left bottom, from(#efefef), to(#cacaca)); + background: -moz-linear-gradient(top, #efefef, #cacaca); + color: #222; + padding: 6px; + border-right: 1px solid #ccc; + border-bottom: 1px solid #aaa; + font-size: 12px; + line-height: 16px; + margin: 0; + display: block; + text-decoration:none; + text-shadow:1px 1px #eee; + -moz-text-shadow:1px 1px #eee; + -webkit-text-shadow:1px 1px #eee; +} +#debug-kit-toolbar .panel-tab .active { + background: #fff; + background: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#fff)); + background: -moz-linear-gradient(top, #f5f5f5, #fff); +} +#debug-kit-toolbar .panel-tab > a:hover { + background: #fff; + background: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#fff)); + background: -moz-linear-gradient(top, #f5f5f5, #fff); + text-decoration:underline; +} +#debug-kit-toolbar .panel-tab.icon a { + padding: 4px; +} +#debug-kit-toolbar .panel-tab a.edit-value { + float: none; + display: inline; +} + +/* Hovering over link shows tab, useful for no js */ +#debug-kit-toolbar .panel-tab a:hover + .panel-content, +#debug-kit-toolbar .panel-tab a + .panel-content:hover { + display: block; +} +#debug-kit-toolbar .panel-tab.icon a { + border-radius: 8px 0 0 8px; +} +#debug-kit-toolbar .panel-tab.icon img { + display:block; +} + +/* panel content */ +#debug-kit-toolbar .panel-content { + position: absolute; + text-align: left; + width: auto; + top:28px; + right:0px; + background: #fff; + color: #000; + width:100%; + box-shadow:0px 5px 6px rgba(0, 0, 0, 0.5); + height: 200px; + overflow: hidden; +} + +#debug-kit-toolbar .panel-resize-region { + padding:15px; + position: absolute; + top: 0; + bottom: 14px; + left: 0; + right: 0; + overflow: auto; +} + +#debug-kit-toolbar .ui-control { + background:#ccc; + background: -webkit-gradient(linear, left top, left bottom, from(#d6d6d6), to(#c2c2c2)); + background: -moz-linear-gradient(top, #d6d6d6, #c2c2c2); + text-align:center; + border-top:1px solid #afafaf; + border-bottom:1px solid #7c7c7c; + color:#666; + text-shadow: 1px 1px #eee; + -webkit-text-shadow: 1px 1px #eee; + -moz-text-shadow: 1px 1px #eee; +} +#debug-kit-toolbar .ui-button { + border-radius: 5px; +} +#debug-kit-toolbar .ui-button:hover { + text-decoration: none; + background:#ccc; + background: -webkit-gradient(linear, left top, left bottom, from(#c2c2c2), to(#d6d6d6)); + background: -moz-linear-gradient(top, #c2c2c2, #d6d6d6); +} +#debug-kit-toolbar .panel-resize-handle { + cursor: row-resize; + height:14px; + line-height: 14px; + position: absolute; + bottom: 0; + left: 0; + right: 0; +} +#debug-kit-toolbar .panel-toggle { + float: right; + display: block; + width: 16px; + height: 16px; + font-size: 16px; + line-height: 14px; + border-left: 1px solid #afafaf; + border-right: 1px solid #7c7c7c; + text-decoration: none; + margin: 10px 20px 0 0; + z-index: 999; + position: relative; +} + +/* Hide panel content by default */ +#debug-kit-toolbar .panel-content { + display: none; +} +#debug-kit-toolbar .panel-content p { + margin: 1em 0; +} +#debug-kit-toolbar .panel-content h2 { + padding: 0; + margin-top:0; +} +#debug-kit-toolbar .panel-content h3 { + padding: 0; + margin-top: 1em; +} +#debug-kit-toolbar .panel-content .info { + padding: 4px; + border-top: 1px dashed #6c6cff; + border-bottom: 1px dashed #6c6cff; +} +#debug-kit-toolbar h1, +#debug-kit-toolbar h2, +#debug-kit-toolbar h3, +#debug-kit-toolbar h4, +#debug-kit-toolbar h5, +#debug-kit-toolbar th { + color: #5d1717; + font-family: Arial, sans-serif; + margin-bottom:0.6em; + background:none; +} +#debug-kit-toolbar h1 { + font-size: 18px; +} +#debug-kit-toolbar h2 { + font-size: 16px; +} +#debug-kit-toolbar h4 { + font-size: 14px; +} + + +/* panel tables */ +#debug-kit-toolbar .debug-table { + width: 100%; + border: 1px solid #eee; + border-left: 0; + clear:both; + margin-bottom: 20px; + border-spacing: 0; +} +#debug-kit-toolbar .debug-table td, +#debug-kit-toolbar .debug-table th { + text-align: left; + border: 0; + border-left: 1px solid #eee; + padding: 3px; + margin: 0; +} +#debug-kit-toolbar table.debug-table th { + border-bottom: 1px solid #bbb; + border-left: 1px solid #bbb; + background: -webkit-linear-gradient(top, #d4d4d4, #c1c1c1); + background: -moz-linear-gradient(top, #d4d4d4, #c1c1c1); + color: #222; + font-weight: bold; + line-height: 16px; +} +#debug-kit-toolbar .debug-table tr:nth-child(2n) td { + background: #f6f6f6; +} +#debug-kit-toolbar .debug-timers .debug-table td:nth-child(2), +#debug-kit-toolbar .debug-timers .debug-table th:nth-child(2) { + text-align:right; +} + +/** code tables **/ +#debug-kit-toolbar .code-table td { + white-space: pre; + font-family: monaco, Consolas, "courier new", courier, monospaced; +} +#debug-kit-toolbar .code-table td:first-child { + width: 15%; +} +#debug-kit-toolbar .code-table td:last-child { + width: 80%; +} +#debug-kit-toolbar .panel-content.request { + display: block; +} + +/** Neat Array styles **/ +#debug-kit-toolbar .neat-array, +#debug-kit-toolbar .neat-array li { + list-style:none; + list-style-image:none; +} +#debug-kit-toolbar .neat-array { + padding: 1px 2px 1px 20px; + background: #CE9E23; + list-style: none; + margin: 0 0 1em 0; +} +#debug-kit-toolbar .neat-array .neat-array { + padding: 0 0 0 20px; + margin: 0; + border-top:1px solid #CE9E23; +} +#debug-kit-toolbar .neat-array li { + background: #FEF6E5; + border-top: 1px solid #CE9E23; + border-bottom: 1px solid #CE9E23; + margin: 0; + line-height: 1.5em; +} +#debug-kit-toolbar .neat-array li:hover { + background: #fff; +} +#debug-kit-toolbar .neat-array li strong { + padding: 0 8px; + font-weight: bold; +} + + +/* expandable sections */ +#debug-kit-toolbar .neat-array li.expandable { + cursor: pointer; +} +#debug-kit-toolbar .neat-array .expanded { + border-bottom:0; +} +#debug-kit-toolbar .neat-array li.expandable.expanded > strong:before { + content: 'v '; +} +#debug-kit-toolbar .neat-array li.expandable.collapsed > strong:before, +#debug-kit-toolbar .neat-array li.expandable.expanded .expandable.collapsed > strong:before { + content: '> '; +} +#debug-kit-toolbar .neat-array li { + cursor: default; +} + +#debug-kit-toolbar .debug-kit-graph-bar, +#debug-kit-toolbar .debug-kit-graph-bar-value { + margin: 0; + padding: 0; + border: none; + overflow: hidden; + height: 10px; +} +#debug-kit-toolbar .debug-kit-graph-bar { + background: #ddd; + padding: 2px; + border-radius: 2px; + height: 12px; +} +#debug-kit-toolbar .debug-kit-graph-bar-value { + background: -webkit-linear-gradient(top, #77D124, #4B9406); + background: -moz-linear-gradient(top, #77D124, #4B9406); + border-radius: 3px; + border: 1px solid #4B9406; +} + +/* Sql Log */ +#sqllog-tab td, +#sqllog-tab .slow-query-container p { + font-family: Monaco, 'Consolas', "Courier New", Courier, monospaced; +} +#debug-kit-toolbar #sqllog-tab a.show-slow { + display:block; + margin: 3px; + float:none; +} +#sqllog-tab .slow-query-container p { + display:block; + clear:both; + margin: 20px 0 5px; +} +#debug-kit-toolbar #sqllog-tab .panel-content-data a { + background: none; + border:none; +} +#sqllog-tab .slow-query { + background:#e79302; + font-size:9px; + color:#fff; + padding: 2px; + white-space:nowrap; +} +#sqllog-tab input[type=submit] { + border: 0; + background: transparent; + cursor: pointer; + font-size: 12px; + font-family: Monaco, 'Consolas', "Courier New", Courier, monospaced; +} +#sqllog-tab input[type=submit]:hover { + color: darkred; +} +#debug-kit-toolbar .alert-duplicate { + color: red; +} + +/* previous panels */ +#debug-kit-toolbar .panel-history { + display: none; + background:#eeffff; +} +#debug-kit-toolbar #history-tab ul { + margin: 20px 0 0 20px; +} +#debug-kit-toolbar #history-tab li { + margin: 0 0 5px 0; +} +#debug-kit-toolbar #history-tab .panel-content-data a { + float: none; + display:block; +} +#debug-kit-toolbar #history-tab a.active { + background: #FEF6E5; +} +#debug-kit-toolbar #history-tab a.loading:after { + content : ' Loading...'; + font-style:italic; +} + +/* Minimized mode */ +#debug-kit-toolbar.minimized { + opacity: 0.75; +} +#debug-kit-toolbar.minimized:hover { + opacity: inherit; +} diff --git a/app/Plugin/DebugKit/webroot/img/cake.icon.png b/app/Plugin/DebugKit/webroot/img/cake.icon.png new file mode 100644 index 0000000000000000000000000000000000000000..394fa42d5131cdc7b0b1246af93b92179f3c887e GIT binary patch literal 943 zcmV;g15o^lP)9q)cr7> zIGsQFGn3| zCzs2iP$-yfVPOGVTU&6sT(-5fwHb2tVsLP9#{Vr9Ct?R7q(rf?v2A5#W$OI=e1YUJ zQ1YRnA&iWSQ1XYAm__>aYb6XIhMiYVD+-z8_pYi6+CsH{*^m;vOjqvbr=H&DFkeqxHQBh$Scsoy0Glw(T zsaSG*ok62V;~yXYNgP*DUw;o98^+0@vGFb{HC+As}XJ=;xg=B7N_;-mKbHH{|lXs_o+aPcs5~J?s%^P2Odb)Uz z$GvY6^!N9(C2-h?28B$qx7%_yHnt2eU%nQ0qThbl6a_+b)EirjBgQ`g1_07Fr&6R? RzIgxu002ovPDHLkV1mdlwUYn< literal 0 HcmV?d00001 diff --git a/app/Plugin/DebugKit/webroot/js/jquery.js b/app/Plugin/DebugKit/webroot/js/jquery.js new file mode 100644 index 0000000..73f33fb --- /dev/null +++ b/app/Plugin/DebugKit/webroot/js/jquery.js @@ -0,0 +1,4 @@ +/*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="
",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f +}}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML="
a",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/\s*$/g,sb={option:[1,""],legend:[1,"
","
"],area:[1,"",""],param:[1,"",""],thead:[1,"","
"],tr:[2,"","
"],col:[2,"","
"],td:[3,"","
"],_default:l.htmlSerialize?[0,"",""]:[1,"X
","
"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?""!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("