Beispiel #1
0
 function ocd_restore()
 {
     $file = $this->GetGP("file");
     $appRoot = $this->sitePath;
     $dumper = new Dumper(DbName, $appRoot . "data/backups/");
     $file_name = $dumper->restore($file);
     if ($file_name != "") {
         $this->Redirect($this->pageUrl . "?ec=restore_ok&fn={$file_name}");
     } else {
         $this->Redirect($this->pageUrl . "?ec=restore_error");
     }
 }
Beispiel #2
0
    public function testDumpSubsections()
    {
        $data = array('main' => array('explore' => true, 'sub' => array('sub' => array('value' => 5))));
        $dumper = new Dumper();
        $result = $dumper->dump($data);
        $expected = <<<EOT
[main]
explore=true

[main.sub]

[main.sub.sub]
value=5

EOT;
        $this->assertEquals($expected, $result);
    }
Beispiel #3
0
 /**
  * Renders debug bar.
  * @return void
  */
 public function render()
 {
     $useSession = $this->dispatched && session_status() === PHP_SESSION_ACTIVE;
     $redirectQueue =& $_SESSION['_tracy']['redirect'];
     if (!Helpers::isHtmlMode() && !Helpers::isAjax()) {
         return;
     } elseif (Helpers::isAjax()) {
         $rows[] = (object) ['type' => 'ajax', 'panels' => $this->renderPanels('-ajax')];
         $dumps = Dumper::fetchLiveData();
         $contentId = $useSession ? $_SERVER['HTTP_X_TRACY_AJAX'] . '-ajax' : NULL;
     } elseif (preg_match('#^Location:#im', implode("\n", headers_list()))) {
         // redirect
         $redirectQueue = array_slice((array) $redirectQueue, -10);
         Dumper::fetchLiveData();
         Dumper::$livePrefix = count($redirectQueue) . 'p';
         $redirectQueue[] = ['panels' => $this->renderPanels('-r' . count($redirectQueue)), 'dumps' => Dumper::fetchLiveData()];
         return;
     } else {
         $rows[] = (object) ['type' => 'main', 'panels' => $this->renderPanels()];
         $dumps = Dumper::fetchLiveData();
         foreach (array_reverse((array) $redirectQueue) as $info) {
             $rows[] = (object) ['type' => 'redirect', 'panels' => $info['panels']];
             $dumps += $info['dumps'];
         }
         $redirectQueue = NULL;
         $contentId = $useSession ? substr(md5(uniqid('', TRUE)), 0, 10) : NULL;
     }
     ob_start(function () {
     });
     require __DIR__ . '/assets/Bar/panels.phtml';
     require __DIR__ . '/assets/Bar/bar.phtml';
     $content = Helpers::fixEncoding(ob_get_clean());
     if ($contentId) {
         $queue =& $_SESSION['_tracy']['bar'];
         $queue = array_slice(array_filter((array) $queue), -5, NULL, TRUE);
         $queue[$contentId] = ['content' => $content, 'dumps' => $dumps];
     }
     if (Helpers::isHtmlMode()) {
         $stopXdebug = extension_loaded('xdebug') ? ['XDEBUG_SESSION_STOP' => 1, 'XDEBUG_PROFILE' => 0, 'XDEBUG_TRACE' => 0] : [];
         $path = isset($_SERVER['REQUEST_URI']) ? explode('?', $_SERVER['REQUEST_URI'])[0] : '/';
         $lpath = strtolower($path);
         $script = isset($_SERVER['SCRIPT_NAME']) ? strtolower($_SERVER['SCRIPT_NAME']) : '';
         if ($lpath !== $script) {
             $max = min(strlen($lpath), strlen($script));
             for ($i = 0; $i < $max && $lpath[$i] === $script[$i]; $i++) {
             }
             $path = $i ? substr($path, 0, strrpos($path, '/', $i - strlen($path) - 1) + 1) : '/';
             $cookiePath = session_get_cookie_params()['path'];
             if (substr($cookiePath, 0, strlen($path)) === $path) {
                 $path = rtrim($cookiePath, '/') . '/';
             }
         }
         require __DIR__ . '/assets/Bar/loader.phtml';
     }
 }
Beispiel #4
0
 /**
  * Output pretty-printed backtrace.
  *
  * @see \Dumper::backtrace
  *
  * @param  mixed $var
  * @return string
  */
 public function printBacktrace($depth = 15)
 {
     if ($this->safe) {
         return null;
     }
     if ($this->app['config']->get('general/debug')) {
         return \Dumper::backtrace($depth, true);
     } else {
         return '';
     }
 }
Beispiel #5
0
 private function renderHtml()
 {
     $res = '<style>code, pre {white-space:nowrap} a {text-decoration:none} pre {color:gray;display:inline} big {color:red}</style><code>';
     foreach ($this->list as $item) {
         $stack = [];
         foreach (array_slice($item[3], 1) as $t) {
             $t += ['class' => '', 'type' => '', 'function' => ''];
             $stack[] = "{$t['class']}{$t['type']}{$t['function']}()" . (isset($t['file'], $t['line']) ? ' in ' . basename($t['file']) . ":{$t['line']}" : '');
         }
         $res .= Helpers::editorLink($item[0], $item[1]) . ' ' . '<span title="' . htmlspecialchars(implode("\n", $stack), ENT_IGNORE | ENT_QUOTES, 'UTF-8') . '">' . str_replace(self::BOM, '<big>BOM</big>', Dumper::toHtml($item[2])) . "</span><br>\n";
     }
     return $res . '</code>';
 }
Beispiel #6
0
 /**
  * @param  string|\Exception|\Throwable
  * @return string
  */
 protected function formatMessage($message)
 {
     if ($message instanceof \Exception || $message instanceof \Throwable) {
         while ($message) {
             $tmp[] = ($message instanceof \ErrorException ? 'Fatal error: ' . $message->getMessage() : get_class($message) . ': ' . $message->getMessage()) . ' in ' . $message->getFile() . ':' . $message->getLine();
             $message = $message->getPrevious();
         }
         $message = implode($tmp, "\ncaused by ");
     } elseif (!is_string($message)) {
         $message = Dumper::toText($message);
     }
     return trim($message);
 }
Beispiel #7
0
 /**
  * @param  string|\Exception|\Throwable
  * @return string
  */
 protected function formatMessage($message)
 {
     if ($message instanceof \Exception || $message instanceof \Throwable) {
         while ($message) {
             $tmp[] = ($message instanceof \ErrorException ? Helpers::errorTypeToString($message->getSeverity()) . ': ' . $message->getMessage() : Helpers::getClass($message) . ': ' . $message->getMessage() . ($message->getCode() ? ' #' . $message->getCode() : '')) . ' in ' . $message->getFile() . ':' . $message->getLine();
             $message = $message->getPrevious();
         }
         $message = implode("\ncaused by ", $tmp);
     } elseif (!is_string($message)) {
         $message = Dumper::toText($message);
     }
     return trim($message);
 }
Beispiel #8
0
 /**
  * Runs the test case.
  * @return void
  */
 public function run($method = NULL)
 {
     $rc = new \ReflectionClass($this);
     $methods = $method ? array($rc->getMethod($method)) : $rc->getMethods(\ReflectionMethod::IS_PUBLIC);
     foreach ($methods as $method) {
         if (!preg_match('#^test[A-Z]#', $method->getName())) {
             continue;
         }
         $data = array();
         $info = Helpers::parseDocComment($method->getDocComment()) + array('dataprovider' => NULL, 'throws' => NULL);
         if ($info['throws'] === '') {
             throw new TestCaseException("Missing class name in @throws annotation for {$method->getName()}().");
         } elseif (is_array($info['throws'])) {
             throw new TestCaseException("Annotation @throws for {$method->getName()}() can be specified only once.");
         } else {
             $throws = preg_split('#\\s+#', $info['throws'], 2) + array(NULL, NULL);
         }
         foreach ((array) $info['dataprovider'] as $provider) {
             $res = $this->getData($provider);
             if (!is_array($res)) {
                 throw new TestCaseException("Data provider {$provider}() doesn't return array.");
             }
             $data = array_merge($data, $res);
         }
         if (!$info['dataprovider']) {
             if ($method->getNumberOfRequiredParameters()) {
                 throw new TestCaseException("Method {$method->getName()}() has arguments, but @dataProvider is missing.");
             }
             $data[] = array();
         }
         foreach ($data as $args) {
             try {
                 if ($info['throws']) {
                     $tmp = $this;
                     $e = Assert::error(function () use($tmp, $method, $args) {
                         $tmp->runTest($method->getName(), $args);
                     }, $throws[0], $throws[1]);
                     if ($e instanceof AssertException) {
                         throw $e;
                     }
                 } else {
                     $this->runTest($method->getName(), $args);
                 }
             } catch (AssertException $e) {
                 $e->message .= " in {$method->getName()}" . substr(Dumper::toLine($args), 5);
                 throw $e;
             }
         }
     }
 }
Beispiel #9
0
 /**
  * Renders debug bar.
  * @return void
  */
 public function render()
 {
     @session_start();
     // @ session may be already started or it is not possible to start session
     $session =& $_SESSION['__NF']['tracybar-2.3'];
     $redirect = preg_match('#^Location:#im', implode("\n", headers_list()));
     if ($redirect) {
         Dumper::fetchLiveData();
         Dumper::$livePrefix = count($session) . 'p';
     }
     $obLevel = ob_get_level();
     $panels = array();
     foreach ($this->panels as $id => $panel) {
         $idHtml = preg_replace('#[^a-z0-9]+#i', '-', $id);
         try {
             $tab = (string) $panel->getTab();
             $panelHtml = $tab ? (string) $panel->getPanel() : NULL;
             if ($tab && $panel instanceof \Nette\Diagnostics\IBarPanel) {
                 $panelHtml = preg_replace('~(["\'.\\s#])nette-(debug|inner|collapsed|toggle|toggle-collapsed)(["\'\\s])~', '$1tracy-$2$3', $panelHtml);
                 $panelHtml = str_replace('tracy-toggle-collapsed', 'tracy-toggle tracy-collapsed', $panelHtml);
             }
             $panels[] = array('id' => $idHtml, 'tab' => $tab, 'panel' => $panelHtml);
         } catch (\Throwable $e) {
         } catch (\Exception $e) {
         }
         if (isset($e)) {
             $panels[] = array('id' => "error-{$idHtml}", 'tab' => "Error in {$id}", 'panel' => '<h1>Error: ' . $id . '</h1><div class="tracy-inner">' . nl2br(htmlSpecialChars($e, ENT_IGNORE, 'UTF-8')) . '</div>');
             while (ob_get_level() > $obLevel) {
                 // restore ob-level if broken
                 ob_end_clean();
             }
         }
     }
     if ($redirect) {
         $session[] = array('panels' => $panels, 'liveData' => Dumper::fetchLiveData());
         return;
     }
     $liveData = Dumper::fetchLiveData();
     foreach (array_reverse((array) $session) as $reqId => $info) {
         $panels[] = array('tab' => '<span title="Previous request before redirect">previous</span>', 'panel' => NULL, 'previous' => TRUE);
         foreach ($info['panels'] as $panel) {
             $panel['id'] .= '-' . $reqId;
             $panels[] = $panel;
         }
         $liveData += $info['liveData'];
     }
     $session = NULL;
     require __DIR__ . '/assets/Bar/bar.phtml';
 }
Beispiel #10
0
 public function dump($subject, $nestLevel = 0)
 {
     $elements = [];
     foreach (get_object_vars($subject) as $key => $value) {
         $elements[] = sprintf("'%s' => %s", $key, $this->masterDumper->dump($value, $nestLevel));
     }
     $methods = get_class_methods($subject);
     $approvedMethods = array_filter($methods, function ($method) use($subject) {
         if (preg_match("/^(get|has|is)[A-Z]/", $method) > 0) {
             $reflection = new \ReflectionMethod(get_class($subject), $method);
             if ($reflection->getNumberOfParameters() === 0) {
                 return true;
             }
             return false;
         }
     });
     foreach ($approvedMethods as $method) {
         $key = lcfirst(preg_replace("/^(get|has|is)/", '', $method));
         $value = call_user_func([$subject, $method]);
         //            $value = $method;
         $elements[] = sprintf("'%s' => %s", $key, $this->masterDumper->dump($value, $nestLevel));
     }
     return "[\n\t" . implode(",\n\t", preg_replace("/\n/", "\n\t", $elements)) . "\n],\n";
 }
Beispiel #11
0
 /**
  * Renders debug bar.
  * @return void
  */
 public function render()
 {
     $useSession = $this->useSession && session_status() === PHP_SESSION_ACTIVE;
     $redirectQueue =& $_SESSION['_tracy']['redirect'];
     foreach (['bar', 'redirect', 'bluescreen'] as $key) {
         $queue =& $_SESSION['_tracy'][$key];
         $queue = array_slice((array) $queue, -10, NULL, TRUE);
         $queue = array_filter($queue, function ($item) {
             return isset($item['time']) && $item['time'] > time() - 60;
         });
     }
     if (!Helpers::isHtmlMode() && !Helpers::isAjax()) {
         return;
     } elseif (Helpers::isAjax()) {
         $rows[] = (object) ['type' => 'ajax', 'panels' => $this->renderPanels('-ajax')];
         $dumps = Dumper::fetchLiveData();
         $contentId = $useSession ? $_SERVER['HTTP_X_TRACY_AJAX'] . '-ajax' : NULL;
     } elseif (preg_match('#^Location:#im', implode("\n", headers_list()))) {
         // redirect
         Dumper::fetchLiveData();
         Dumper::$livePrefix = count($redirectQueue) . 'p';
         $redirectQueue[] = ['panels' => $this->renderPanels('-r' . count($redirectQueue)), 'dumps' => Dumper::fetchLiveData(), 'time' => time()];
         return;
     } else {
         $rows[] = (object) ['type' => 'main', 'panels' => $this->renderPanels()];
         $dumps = Dumper::fetchLiveData();
         foreach (array_reverse((array) $redirectQueue) as $info) {
             $rows[] = (object) ['type' => 'redirect', 'panels' => $info['panels']];
             $dumps += $info['dumps'];
         }
         $redirectQueue = NULL;
         $contentId = $useSession ? substr(md5(uniqid('', TRUE)), 0, 10) : NULL;
     }
     ob_start(function () {
     });
     require __DIR__ . '/assets/Bar/panels.phtml';
     require __DIR__ . '/assets/Bar/bar.phtml';
     $content = Helpers::fixEncoding(ob_get_clean());
     if ($contentId) {
         $_SESSION['_tracy']['bar'][$contentId] = ['content' => $content, 'dumps' => $dumps, 'time' => time()];
     }
     if (Helpers::isHtmlMode()) {
         require __DIR__ . '/assets/Bar/loader.phtml';
     }
 }
 /**
  *
  * @param mixed     $source     DataURI source
  * @param boolean   $strict     Use strict mode (length output)
  * @param string    $mime       the mime type
  * @param array     $parameters Extra parameters, see rfc
  * @return null
  */
 public function dataUri($source, $strict = true, $mime = null, $parameters = array())
 {
     $data = null;
     try {
         switch (true) {
             case is_resource($source):
                 $data = $this->getDataFromRessource($source, $strict, $mime, $parameters);
                 break;
             case is_scalar($source):
                 $data = $this->getDataFromScalar($source, $strict, $mime, $parameters);
                 break;
             default:
                 trigger_error("Tried to convert an unsupported source format", E_USER_WARNING);
                 break;
         }
     } catch (Exception\Exception $e) {
         trigger_error(sprintf("Error while building DataUri : %s", $e->getMessage()), E_USER_WARNING);
     }
     if ($data) {
         return Dumper::dump($data);
     }
     return null;
 }
            $a->buildFromDirectory(dirname(__FILE__) . '/' . $backupFolder);
            file_put_contents($backupFolder . '.tar.gz', gzencode(file_get_contents($backupFolder . '.tar'), 9));
            fwrite(STDERR, "Compresion complete!" . PHP_EOL);
            fwrite(STDERR, "Removing temp folders and files.." . PHP_EOL);
            //remove other files
            unlink(realpath($backupFolder . '.tar'));
            deleteDir(realpath($backupFolder));
            fwrite(STDERR, "Temp folders and files removed!" . PHP_EOL);
        }
    } catch (Exception $e) {
        fwrite(STDERR, "{$e}" . PHP_EOL);
    }
    return;
    //exit(1);
} else {
    $dumper = new Dumper($host, $port, $database, $noHistory, $callbackFile, $inlineAttachment, $binaryAttachments, $prettyJsonOutput, $separateFiles, $timeStamp, $callbackFilter);
    $dumper->download();
}
function deleteDir($dirPath)
{
    if (!is_dir($dirPath)) {
        throw new InvalidArgumentException("{$dirPath} must be a directory");
    }
    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }
    $files = glob($dirPath . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file)) {
            deleteDir($file);
        } else {
Beispiel #14
0
<?php

include "../../class.dumper.php";
$fp = fopen(__FILE__, "r");
$a = array('first' => $fp, 'last' => new bar(), 'null_var' => NULL, 'float' => pi(), 'bool' => true, ' leading_space' => 6 * 8, 'trailing_space ' => 'grapes', 'middle space' => 'Mt. Rushmore', 'phones' => array(5036541278, 8714077831, 'x253'), 'long_str' => "This is a really long string full of a\n bunch of crap that should eventually wrap. There once was a man from New Mexico...", 'empty_arr' => array(), 'func_str' => 'preg_replace', 'address' => array('street' => '123 Fake Street', 'city' => 'Portland', 'state' => 'Maine'), 'unixtime' => 1231241234, 'microtime' => microtime(1));
if (isset($_GET['short'])) {
    Dumper::$expand_all = 1;
    kd($a);
}
print "<h2>Dumper capture</h2>\n";
$str = k(array('foo' => 'bar'), KRUMO_CAPTURE);
print $str;
print "<h2>Dumper</h2>\n";
k(array('likes', 'kittens', 'and', 'dogs'));
print "<h2>Dumper passing multiple args</h2>\n";
k('likes', 'kittens', 'and', 'dogs');
print "<h2>Dumper + die()</h2>\n";
kd($a);
print "If you see this something is broken";
$k = new Dumper();
class bar
{
    public $b = 'bb';
    public $a = 'aa';
    function foo()
    {
        return 'bar';
    }
}
Beispiel #15
0
 /**
  * Runs the test method.
  * @return void
  */
 private function runMethod($method)
 {
     $method = new \ReflectionMethod($this, $method);
     if (!$method->isPublic()) {
         throw new TestCaseException("Method {$method->getName()} is not public. Make it public or rename it.");
     }
     $data = array();
     $info = Helpers::parseDocComment($method->getDocComment()) + array('dataprovider' => NULL, 'throws' => NULL);
     if ($info['throws'] === '') {
         throw new TestCaseException("Missing class name in @throws annotation for {$method->getName()}().");
     } elseif (is_array($info['throws'])) {
         throw new TestCaseException("Annotation @throws for {$method->getName()}() can be specified only once.");
     } else {
         $throws = preg_split('#\\s+#', $info['throws'], 2) + array(NULL, NULL);
     }
     $defaultParams = array();
     foreach ($method->getParameters() as $param) {
         $defaultParams[$param->getName()] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : NULL;
     }
     foreach ((array) $info['dataprovider'] as $provider) {
         $res = $this->getData($provider);
         if (!is_array($res)) {
             throw new TestCaseException("Data provider {$provider}() doesn't return array.");
         }
         foreach ($res as $set) {
             $data[] = is_string(key($set)) ? array_merge($defaultParams, $set) : $set;
         }
     }
     if (!$info['dataprovider']) {
         if ($method->getNumberOfRequiredParameters()) {
             throw new TestCaseException("Method {$method->getName()}() has arguments, but @dataProvider is missing.");
         }
         $data[] = array();
     }
     foreach ($data as $args) {
         try {
             if ($info['throws']) {
                 $tmp = $this;
                 $e = Assert::error(function () use($tmp, $method, $args) {
                     $tmp->runTest($method->getName(), $args);
                 }, $throws[0], $throws[1]);
                 if ($e instanceof AssertException) {
                     throw $e;
                 }
             } else {
                 $this->runTest($method->getName(), $args);
             }
         } catch (AssertException $e) {
             throw $e->setMessage("{$e->origMessage} in {$method->getName()}" . substr(Dumper::toLine($args), 5));
         }
     }
 }
Beispiel #16
0
 /**
  * Returns syntax highlighted source code.
  * @param  string
  * @param  int
  * @param  int
  * @return string
  */
 public static function highlightPhp($source, $line, $lines = 15, array $vars = NULL)
 {
     if (function_exists('ini_set')) {
         ini_set('highlight.comment', '#998; font-style: italic');
         ini_set('highlight.default', '#000');
         ini_set('highlight.html', '#06B');
         ini_set('highlight.keyword', '#D24; font-weight: bold');
         ini_set('highlight.string', '#080');
     }
     $source = str_replace(["\r\n", "\r"], "\n", $source);
     $source = explode("\n", highlight_string($source, TRUE));
     $out = $source[0];
     // <code><span color=highlight.html>
     $source = str_replace('<br />', "\n", $source[1]);
     $out .= static::highlightLine($source, $line, $lines);
     if ($vars) {
         $out = preg_replace_callback('#">\\$(\\w+)(&nbsp;)?</span>#', function ($m) use($vars) {
             return array_key_exists($m[1], $vars) ? '" title="' . str_replace('"', '&quot;', trim(strip_tags(Dumper::toHtml($vars[$m[1]], [Dumper::DEPTH => 1])))) . $m[0] : $m[0];
         }, $out);
     }
     $out = str_replace('&nbsp;', ' ', $out);
     return "<pre class='php'><div>{$out}</div></pre>";
 }
Beispiel #17
0
 /** @internal */
 public static function handleException(\Exception $e)
 {
     self::$checkAssertions = FALSE;
     echo self::$debugMode ? Dumper::dumpException($e) : "\nError: {$e->getMessage()}\n";
     exit($e instanceof AssertException ? Runner\Job::CODE_FAIL : Runner\Job::CODE_ERROR);
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function putLocations()
 {
     $json = \Input::all();
     $key = \Input::get('key');
     $json['mode'] = 'edit';
     $batch = \Input::get('batch');
     \Dumper::insert($json);
 }
Beispiel #19
0
 protected function walkHash($type, &$a, $len)
 {
     if ('array:0' === $type) {
         $this->line .= '[]';
     } else {
         $is_array = 0 === strncmp($type, 'array:', 6);
         if ($is_array) {
             $this->line .= '[';
             //$this->dumpString(substr($type, 6), false, 'note');
         } else {
             $this->dumpString($type, false, 'note');
             $this->line .= '{';
         }
         $this->line .= ' ' . $this->style('ref', "#{$this->counter}");
         $startCounter = $this->counter;
         $refs = parent::walkHash($type, $a, $len);
         if ($this->counter !== $startCounter) {
             $this->dumpLine(1);
         }
         $this->line .= $is_array ? ']' : '}';
         if ($refs) {
             $col1 = 0;
             $type = array();
             foreach ($refs as $k => $v) {
                 if (isset($this->valPool[$k])) {
                     $v = $this->valPool[$k];
                     $type[$k] = gettype($v);
                     switch ($type[$k]) {
                         case 'object':
                             $type[$k] = get_class($v);
                             break;
                         case 'unknown type':
                         case 'resource':
                             $type[$k] = 'resource:' . get_resource_type($v);
                             break;
                     }
                     $col1 = max($col1, strlen($type[$k]));
                 }
             }
             $col2 = strlen($this->counter);
             foreach ($refs as $k => $v) {
                 $this->dumpLine(0);
                 $this->line .= str_repeat(' ', $col2 - strlen($k));
                 $this->line .= $this->style('ref', "#{$k}");
                 if ($col1) {
                     $this->line .= sprintf(" % -{$col1}s", isset($type[$k]) ? $type[$k] : 'array');
                 }
                 $this->line .= ':';
                 foreach ($v as $v) {
                     $this->line .= ' ' . $this->style('note', $v < 0 ? '#' . -$v : "@{$v}");
                 }
             }
         }
     }
 }
Beispiel #20
0
            $end = $start + $delta - 1;
            $tmpname1 = tempnam('', '');
            $tmpname2 = tempnam('', '');
            $file_name1 = 'files/' . str_pad($i * $delta, 8, '0', STR_PAD_LEFT) . '.json.gz';
            $file_name2 = 'files/bussiness-' . str_pad($i * $delta, 8, '0', STR_PAD_LEFT) . '.json.gz';
            $fp[1] = $fp[3] = gzopen($tmpname1, 'w');
            $fp[2] = gzopen($tmpname2, 'w');
            $unit_id = null;
            $unit = new StdClass();
            foreach (UnitData::search("`id` >= {$start} AND `id` <= {$end}")->order("`id`, `column_id`")->volumemode(10000) as $unit_data) {
                if (!is_null($unit_id) and $unit_data->id != $unit_id) {
                    fwrite($fp[$this->getType($unit_id)], str_pad($unit_id, 8, '0', STR_PAD_LEFT) . ',' . json_encode($unit, JSON_UNESCAPED_UNICODE) . "\n");
                    $unit = new StdClass();
                }
                $unit_id = $unit_data->id;
                $unit->{$columns[$unit_data->column_id]} = json_decode($unit_data->value);
            }
            if (!is_null($unit_id)) {
                fwrite($fp[$this->getType($unit_id)], str_pad($unit_id, 8, '0', STR_PAD_LEFT) . ',' . json_encode($unit, JSON_UNESCAPED_UNICODE) . "\n");
            }
            fclose($fp[1]);
            fclose($fp[2]);
            DropboxLib::putFile($tmpname1, $file_name1);
            DropboxLib::putFile($tmpname2, $file_name2);
            unlink($tmpname1);
            unlink($tmpname2);
        }
    }
}
$dumper = new Dumper();
$dumper->dump();
Beispiel #21
0
 /**
  * Dump containers.
  *
  * @param array $containers An array of containers.
  *
  * @api
  */
 public function dumpContainers(array $containers)
 {
     // output
     foreach ($containers as $container) {
         foreach ($container->getDefinitions() as $name => $definition) {
             $output = $definition->getOutput($name);
             $dir = $output->getDir();
             $file = $dir . DIRECTORY_SEPARATOR . str_replace('\\', '/', $definition->getClass()) . '.php';
             $path = dirname($file);
             if (!file_exists($path) && false === @mkdir($path, 0777, true)) {
                 throw new \RuntimeException(sprintf('Unable to create the %s directory.', $path));
             }
             if (!is_writable($path)) {
                 throw new \RuntimeException(sprintf('Unable to write in the %s directory.', $path));
             }
             if (!file_exists($file) || $output->getOverride()) {
                 $dumper = new Dumper($definition);
                 $content = $dumper->dump();
                 $tmpFile = tempnam(dirname($file), basename($file));
                 if (false === @file_put_contents($tmpFile, $content) || !@rename($tmpFile, $file)) {
                     throw new \RuntimeException(sprintf('Failed to write the file "%s".', $file));
                 }
                 @chmod($file, 0666 & ~umask());
             }
         }
     }
 }
Beispiel #22
0
 /**
  * Runs the test method.
  * @param  string  test method name
  * @param  array  test method parameters (dataprovider bypass)
  * @return void
  */
 public function runTest($method, array $args = NULL)
 {
     if (!method_exists($this, $method)) {
         throw new TestCaseException("Method '{$method}' does not exist.");
     } elseif (!preg_match(self::METHOD_PATTERN, $method)) {
         throw new TestCaseException("Method '{$method}' is not a testing method.");
     }
     $method = new \ReflectionMethod($this, $method);
     if (!$method->isPublic()) {
         throw new TestCaseException("Method {$method->getName()} is not public. Make it public or rename it.");
     }
     $info = Helpers::parseDocComment($method->getDocComment()) + ['dataprovider' => NULL, 'throws' => NULL];
     if ($info['throws'] === '') {
         throw new TestCaseException("Missing class name in @throws annotation for {$method->getName()}().");
     } elseif (is_array($info['throws'])) {
         throw new TestCaseException("Annotation @throws for {$method->getName()}() can be specified only once.");
     } else {
         $throws = preg_split('#\\s+#', $info['throws'], 2) + [NULL, NULL];
     }
     $data = [];
     if ($args === NULL) {
         $defaultParams = [];
         foreach ($method->getParameters() as $param) {
             $defaultParams[$param->getName()] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : NULL;
         }
         foreach ((array) $info['dataprovider'] as $provider) {
             $res = $this->getData($provider);
             if (!is_array($res) && !$res instanceof \Traversable) {
                 throw new TestCaseException("Data provider {$provider}() doesn't return array or Traversable.");
             }
             foreach ($res as $set) {
                 $data[] = is_string(key($set)) ? array_merge($defaultParams, $set) : $set;
             }
         }
         if (!$info['dataprovider']) {
             if ($method->getNumberOfRequiredParameters()) {
                 throw new TestCaseException("Method {$method->getName()}() has arguments, but @dataProvider is missing.");
             }
             $data[] = [];
         }
     } else {
         $data[] = $args;
     }
     if ($this->prevErrorHandler === FALSE) {
         $this->prevErrorHandler = set_error_handler(function ($severity) {
             if ($this->handleErrors && ($severity & error_reporting()) === $severity) {
                 $this->handleErrors = FALSE;
                 $this->silentTearDown();
             }
             return $this->prevErrorHandler ? call_user_func_array($this->prevErrorHandler, func_get_args()) : FALSE;
         });
     }
     foreach ($data as $params) {
         try {
             $this->setUp();
             $this->handleErrors = TRUE;
             try {
                 if ($info['throws']) {
                     $e = Assert::error(function () use($method, $params) {
                         call_user_func_array([$this, $method->getName()], $params);
                     }, $throws[0], $throws[1]);
                     if ($e instanceof AssertException) {
                         throw $e;
                     }
                 } else {
                     call_user_func_array([$this, $method->getName()], $params);
                 }
             } catch (\Exception $e) {
                 $this->handleErrors = FALSE;
                 $this->silentTearDown();
                 throw $e;
             }
             $this->handleErrors = FALSE;
             $this->tearDown();
         } catch (AssertException $e) {
             throw $e->setMessage("{$e->origMessage} in {$method->getName()}(" . substr(Dumper::toLine($params), 1, -1) . ')');
         }
     }
 }
Beispiel #23
0
<?php

require "parts/header.php";
require_once "lib/includes.php";
$d = new Dumper();
$filters = !empty($_GET['filter']) ? explode(',', $_GET['filter']) : [];
$queries = $d->getQueriesRaw($filters);
?>
<!-- Small boxes (Stat box) -->
<div class="row">

    <div class="box">
        <div class="box-header">
            <h3 class="box-title">DNS Queries</h3>
            <div id="example1_filter" class="dataTables_filter pull-right" style="padding-right: 10px">
                <form method="GET">
                    <label>Filter: <input class="form-control" type="search" name="filter" placeholder="Separate by commas" /></label>
                </form>
            </div>
        </div>
        <!-- /.box-header -->
        <div class="box-body">
            <div class="row">

            </div>
            <div id="example2_wrapper" class="dataTables_wrapper form-inline dt-bootstrap">
                <div class="row">
                    <div class="col-sm-6"></div>
                    <div class="col-sm-6"></div>
                </div>
                <div class="row">
Beispiel #24
0
 public function setMessage($message)
 {
     $this->origMessage = $message;
     $this->message = strtr($message, array('%1' => Dumper::toLine($this->actual), '%2' => Dumper::toLine($this->expected)));
     return $this;
 }
Beispiel #25
0
 /** @internal */
 public static function dumpException(\Exception $e)
 {
     $trace = $e->getTrace();
     array_splice($trace, 0, $e instanceof \ErrorException ? 1 : 0, array(array('file' => $e->getFile(), 'line' => $e->getLine())));
     $testFile = NULL;
     foreach (array_reverse($trace) as $item) {
         if (isset($item['file'])) {
             // in case of shutdown handler, we want to skip inner-code blocks and debugging calls
             $testFile = $item['file'];
             break;
         }
     }
     if ($e instanceof AssertException) {
         if (is_object($e->expected) || is_array($e->expected) || is_string($e->expected) && strlen($e->expected) > self::$maxLength || is_object($e->actual) || is_array($e->actual) || is_string($e->actual) && strlen($e->actual) > self::$maxLength) {
             $args = isset($_SERVER['argv'][1]) ? '.[' . preg_replace('#[^a-z0-9-. ]+#i', '_', $_SERVER['argv'][1]) . ']' : '';
             $stored[] = self::saveOutput($testFile, $e->expected, $args . '.expected');
             $stored[] = self::saveOutput($testFile, $e->actual, $args . '.actual');
         }
         if (is_string($e->actual) && is_string($e->expected)) {
             for ($i = 0; $i < strlen($e->actual) && isset($e->expected[$i]) && $e->actual[$i] === $e->expected[$i]; $i++) {
             }
             $i = max(0, min($i, max(strlen($e->actual), strlen($e->expected)) - self::$maxLength + 3));
             for (; $i && $i < count($e->actual) && $e->actual[$i - 1] >= "€" && $e->actual[$i] >= "€" && $e->actual[$i] < "À"; $i--) {
             }
             if ($i) {
                 $e->expected = substr_replace($e->expected, '...', 0, $i);
                 $e->actual = substr_replace($e->actual, '...', 0, $i);
             }
         }
         $message = 'Failed: ' . $e->getMessage();
         if (is_string($e->actual) && is_string($e->expected) || is_array($e->actual) && is_array($e->expected)) {
             preg_match('#^(.*)(%\\d)(.*)(%\\d.*)\\z#', $message, $m);
             if (($delta = strlen($m[1]) - strlen($m[3])) >= 3) {
                 $message = "{$m['1']}{$m['2']}\n" . str_repeat(' ', $delta - 3) . "...{$m['3']}{$m['4']}";
             } else {
                 $message = "{$m['1']}{$m['2']}{$m['3']}\n" . str_repeat(' ', strlen($m[1]) - 4) . "... {$m['4']}";
             }
         }
         $message = strtr($message, array('%1' => "" . Dumper::toLine($e->actual) . "", '%2' => "" . Dumper::toLine($e->expected) . ""));
     } else {
         $message = ($e instanceof \ErrorException ? Helpers::errorTypeToString($e->getSeverity()) : get_class($e)) . ": {$e->getMessage()}";
     }
     $s = "{$message}\n\n" . (isset($stored) ? "diff " . escapeshellarg($stored[0]) . " " . escapeshellarg($stored[1]) . "\n\n" : '');
     foreach ($trace as $item) {
         $item += array('file' => NULL);
         $s .= 'in ' . ($item['file'] === $testFile ? "" : '') . ($item['file'] ? implode(DIRECTORY_SEPARATOR, array_slice(explode(DIRECTORY_SEPARATOR, $item['file']), -3)) . "({$item['line']})" : '[internal function]') . " " . (isset($item['class']) ? $item['class'] . $item['type'] : '') . (isset($item['function']) ? $item['function'] . '()' : '') . "\n";
     }
     if ($e->getPrevious()) {
         $s .= "\n(previous) " . static::dumpException($e->getPrevious());
     }
     return $s;
 }
 /**
  * Returns string representation.
  *
  * @return string The string representation.
  */
 public function __toString()
 {
     return Dumper::toString($this);
 }
Beispiel #27
0
 /**
  * Runs the test method.
  * @param  string  test method name
  * @param  array  test method parameters (dataprovider bypass)
  * @return void
  */
 public function runTest($method, array $args = NULL)
 {
     $method = new \ReflectionMethod($this, $method);
     if (!$method->isPublic()) {
         throw new TestCaseException("Method {$method->getName()} is not public. Make it public or rename it.");
     }
     $info = Helpers::parseDocComment($method->getDocComment()) + array('dataprovider' => NULL, 'throws' => NULL);
     if ($info['throws'] === '') {
         throw new TestCaseException("Missing class name in @throws annotation for {$method->getName()}().");
     } elseif (is_array($info['throws'])) {
         throw new TestCaseException("Annotation @throws for {$method->getName()}() can be specified only once.");
     } else {
         $throws = preg_split('#\\s+#', $info['throws'], 2) + array(NULL, NULL);
     }
     $data = array();
     if ($args === NULL) {
         $defaultParams = array();
         foreach ($method->getParameters() as $param) {
             $defaultParams[$param->getName()] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : NULL;
         }
         foreach ((array) $info['dataprovider'] as $provider) {
             $res = $this->getData($provider);
             if (!is_array($res)) {
                 throw new TestCaseException("Data provider {$provider}() doesn't return array.");
             }
             foreach ($res as $set) {
                 $data[] = is_string(key($set)) ? array_merge($defaultParams, $set) : $set;
             }
         }
         if (!$info['dataprovider']) {
             if ($method->getNumberOfRequiredParameters()) {
                 throw new TestCaseException("Method {$method->getName()}() has arguments, but @dataProvider is missing.");
             }
             $data[] = array();
         }
     } else {
         $data[] = $args;
     }
     $me = $this;
     $errorHandler = function () use($me, &$prev) {
         restore_error_handler();
         $rm = new \ReflectionMethod($me, 'tearDown');
         $rm->setAccessible(TRUE);
         set_error_handler(function () {
         });
         // mute all errors
         $rm->invoke($me);
         restore_error_handler();
         return $prev ? call_user_func_array($prev, func_get_args()) : FALSE;
     };
     foreach ($data as $params) {
         try {
             $this->setUp();
             $prev = set_error_handler($errorHandler);
             try {
                 if ($info['throws']) {
                     $tmp = $this;
                     $e = Assert::error(function () use($tmp, $method, $params) {
                         call_user_func_array(array($tmp, $method->getName()), $params);
                     }, $throws[0], $throws[1]);
                     if ($e instanceof AssertException) {
                         throw $e;
                     }
                 } else {
                     call_user_func_array(array($this, $method->getName()), $params);
                 }
             } catch (\Exception $testException) {
             }
             restore_error_handler();
             try {
                 $this->tearDown();
             } catch (\Exception $tearDownException) {
             }
             if (isset($testException)) {
                 throw $testException;
             } elseif (isset($tearDownException)) {
                 throw $tearDownException;
             }
         } catch (AssertException $e) {
             throw $e->setMessage("{$e->origMessage} in {$method->getName()}" . substr(Dumper::toLine($params), 5));
         }
     }
 }
 /**
  * Dumps a PHP array to a YAML string.
  *
  * The dump method, when supplied with an array, will do its best
  * to convert the array into friendly YAML.
  *
  * @param array   $array PHP array
  * @param integer $inline The level where you switch to inline YAML
  *
  * @return string A YAML string representing the original PHP array
  */
 public static function dump($array, $inline = 2)
 {
     $yaml = new Dumper();
     return $yaml->dump($array, $inline);
 }
Beispiel #29
0
 /**
  * Output pretty-printed backtrace.
  *
  * @see \Dumper::backtrace
  *
  * @param  mixed $var
  * @return string
  */
 public function printBacktrace($depth = 15)
 {
     return \Dumper::backtrace($depth, true);
 }