Exemplo n.º 1
0
function data_graphviz($data, $params)
{
    $data = trim($data);
    $data = html_entity_decode($data);
    $storageurl = STORAGE_PKG_URL . 'GraphViz/';
    $storagepath = STORAGE_PKG_PATH . 'GraphViz/';
    $temppath = TEMP_PKG_PATH . 'GraphViz/';
    if (!is_dir($temppath)) {
        mkdir_p($temppath);
    }
    if (!is_dir($storagepath)) {
        mkdir_p($storagepath);
    }
    $file = md5($data);
    $dotFile = $temppath . $file . '.dot';
    $pngFile = $storagepath . $file . '.png';
    $pngURL = $storageurl . $file . '.png';
    if (!file_exists($pngFile)) {
        if (@(include_once 'PEAR.php')) {
            if (@(include_once 'Image/GraphViz.php')) {
                $graph = new Image_GraphViz();
                $error = '<div class=error>' . tra("Unable to write temporary file. Please check your server configuration.") . '</div>';
                if (!($fp = fopen($dotFile, 'w'))) {
                    return $error;
                }
                if (fwrite($fp, $data) === false) {
                    return $error;
                }
                fclose($fp);
                $graph->renderDotFile($dotFile, $pngFile, 'png');
                // No need to keep this lying around
                unlink($dotFile);
                // If it still isn't there....
                if (!file_exists($pngFile)) {
                    return '<div class=error>' . tra("Unable to generate graphviz image file. Please check your data.") . '</div>';
                }
            } else {
                return "<div class=error>" . tra("The Image_Graphviz pear plugin is not installed. Install with `pear install Image_Graphviz`.") . "</div>";
            }
        } else {
            return "<div class=error>" . tra("PEAR and the Image_Graphviz pear plugin are not installed.") . "</div>";
        }
    }
    return "<img src=\"{$pngURL}\"/> ";
}
Exemplo n.º 2
0
function renderCablingPlan()
{
    // Build cabling plan
    // Select edges
    $sql = "SELECT oa.id AS source, ob.id AS target, CONCAT(pa.name, _utf8' <> ', pb.name) AS label, 0 AS weight " . "FROM ((Link l JOIN Port pa ON l.porta = pa.id) JOIN RackObject oa ON pa.object_id = oa.id " . "JOIN Port pb ON l.portb = pb.id JOIN RackObject ob ON pb.object_id = ob.id)";
    $result = usePreparedSelectBlade($sql);
    $edges = array();
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        $found = FALSE;
        foreach ($edges as $key => $edge) {
            if ($edge['source'] == $row['source'] && $edge['target'] == $row['target']) {
                // Edge already exists ("Parallel"). Alter label and add weight
                $edges[$key]['label'] .= "\n" . $row['label'];
                $edges[$key]['weight']++;
                $found = TRUE;
            }
        }
        if (!$found) {
            $edges[] = $row;
        }
    }
    // Select nodes
    $sql = "SELECT DISTINCT o.id AS id, o.name AS label, '' AS url " . "FROM Port p JOIN RackObject o ON p.object_id = o.id " . "WHERE (p.id IN (SELECT Link.porta AS porta FROM Link) OR p.id IN " . "(SELECT Link.portb AS portb FROM Link))";
    $result = usePreparedSelectBlade($sql);
    $nodes = $result->fetchAll(PDO::FETCH_ASSOC);
    $graph = new Image_GraphViz(TRUE, array(), 'Cabling Plan', FALSE, FALSE);
    foreach ($nodes as $node) {
        $graph->addNode($node['id'], array('label' => $node['label'], 'shape' => 'box3d'));
    }
    foreach ($edges as $edge) {
        $graph->addEdge(array($edge['source'] => $edge['target']), array('label' => $edge['label'], 'weight' => floatval($edge['weight']), 'fontsize' => 8.0, 'arrowhead' => 'dot', 'arrowtail' => 'dot', 'arrowsize' => 0.5));
    }
    if (in_array($_REQUEST['format'], array('svg', 'png'))) {
        $graph->image($_REQUEST['format']);
    }
}
Exemplo n.º 3
0
 /**
  * Returns GraphViz/dot markup for the graph.
  *
  * @param  optional boolean $returnObject
  * @return mixed
  * @access public
  */
 function toGraph($returnObject = false)
 {
     if (!@(include_once 'Image/GraphViz.php')) {
         phpOpenTracker::handleError('Could not find PEAR Image_GraphViz package, exiting.', E_USER_ERROR);
     }
     $graph = new Image_GraphViz();
     for ($i = 0; $i < $this->length - 1; $i++) {
         $graph->addNode($i, array('url' => $this->document_urls[$i], 'label' => $this->documents[$i], 'shape' => 'box'));
         $graph->addNode($i + 1, array('url' => $this->document_urls[$i + 1], 'label' => $this->documents[$i + 1], 'shape' => 'box'));
         if (isset($this->statistics[$i]['count'])) {
             $label = sprintf('count: %d\\naverage time: %d seconds', $this->statistics[$i]['count'], $this->statistics[$i]['time_spent']);
         } else {
             $label = sprintf('time spent: %d seconds', $this->statistics[$i]);
         }
         $graph->addEdge(array($i => $i + 1), array('label' => $label));
     }
     if ($returnObject) {
         return $graph;
     } else {
         return $graph->parse();
     }
 }
Exemplo n.º 4
0
 function get_graph($oWorkflow)
 {
     $fontsize = 11.0;
     $fontname = "Times-Roman";
     $opts = array('fontsize' => $fontsize, 'fontname' => $fontname);
     $graph = new Image_GraphViz(true, $opts);
     $graph->dotCommand = $this->dotCommand;
     // we need all states & transitions
     // FIXME do we want guards?
     // we want to enable link-editing, and indicate that transitions "converge"
     // so we use a temporary "node" for transitions
     // we also use a "fake" URL which we catch later
     // so we can give good "alt" tags.
     $states = KTWorkflowState::getByWorkflow($oWorkflow);
     $transitions = KTWorkflowTransition::getByWorkflow($oWorkflow);
     $this->state_names = array();
     $this->transition_names = array();
     $state_opts = array('shape' => 'box', 'fontsize' => $fontsize, 'fontname' => $fontname);
     $transition_opts = array('shape' => 'box', 'color' => '#ffffff', 'fontsize' => $fontsize, 'fontname' => $fontname);
     $finaltransition_opts = array('color' => '#333333');
     $sourcetransition_opts = array('color' => '#999999');
     // to make this a little more useful, we want to cascade our output from
     // start to end states - this will tend to give a better output.
     //
     // to do this, we need to order our nodes in terms of "nearness" to the
     // initial node.
     $processing_nodes = array();
     $sorted_ids = array();
     $availability = array();
     $sources = array();
     $destinations = array();
     $states = KTUtil::keyArray($states);
     $transitions = KTUtil::keyArray($transitions);
     foreach ($transitions as $tid => $oTransition) {
         $sources[$tid] = KTWorkflowAdminUtil::getSourceStates($oTransition, array('ids' => true));
         $destinations[$tid] = $oTransition->getTargetStateId();
         foreach ($sources[$tid] as $sourcestateid) {
             $av = (array) KTUtil::arrayGet($availability, $sourcestateid, array());
             $av[] = $tid;
             $availability[$sourcestateid] = $av;
         }
     }
     //var_dump($sources); exit(0);
     //var_dump($availability); exit(0);
     $processing = array($oWorkflow->getStartStateId());
     while (!empty($processing)) {
         $active = array_shift($processing);
         if (!$processing_nodes[$active]) {
             // mark that we've seen this node
             $processing_nodes[$active] = true;
             $sorted[] = $active;
             // now add all reachable nodes to the *end* of the queue.
             foreach ((array) $availability[$active] as $tid) {
                 $next = $destinations[$tid];
                 if (!$processing_nodes[$next]) {
                     $processing[] = $next;
                 }
             }
         }
         //var_dump($processing);
     }
     //var_dump($sorted); exit(0);
     foreach ($sorted as $sid) {
         $oState = $states[$sid];
         $this->state_names[$oState->getId()] = $oState->getHumanName();
         $local_opts = array('URL' => sprintf("s%d", $oState->getId()), 'label' => $oState->getHumanName(), 'color' => '#666666');
         if ($oState->getId() == $oWorkflow->getStartStateId()) {
             $local_opts['color'] = '#000000';
             $local_opts['style'] = 'filled';
             $local_opts['fillcolor'] = '#cccccc';
         }
         $graph->addNode(sprintf('state%d', $oState->getId()), KTUtil::meldOptions($state_opts, $local_opts));
     }
     foreach ($transitions as $tid => $oTransition) {
         $name = sprintf('transition%d', $tid);
         $this->transition_names[$oTransition->getId()] = $oTransition->getHumanName();
         // we "cheat" and use
         $graph->addNode($name, KTUtil::meldOptions($transition_opts, array('URL' => sprintf("t%d", $tid), 'label' => $oTransition->getHumanName())));
         $dest = sprintf("state%d", $oTransition->getTargetStateId());
         $graph->addEdge(array($name => $dest), $finaltransition_opts);
         foreach ($sources[$tid] as $source_id) {
             $source_name = sprintf("state%d", $source_id);
             $graph->addEdge(array($source_name => $name), $sourcetransition_opts);
         }
     }
     // some simple analysis
     $errors = array();
     $info = array();
     $sourceless_transitions = array();
     foreach ($transitions as $tid => $oTransition) {
         if (empty($sources[$tid])) {
             $sourceless_transitions[] = $oTransition->getHumanName();
         }
     }
     if (!empty($sourceless_transitions)) {
         $errors[] = sprintf(_kt("Some transitions have no source states: %s"), implode(', ', $sourceless_transitions));
     }
     $unlinked_states = array();
     foreach ($states as $sid => $oState) {
         if (!$processing_nodes[$sid]) {
             // quick sanity check
             $unlinked_states[] = $oState->getHumanName();
         }
     }
     if (!empty($unlinked_states)) {
         $errors[] = sprintf(_kt("Some states cannot be reached from the initial state (<strong>%s</strong>): %s"), $states[$oWorkflow->getStartStateId()]->getHumanName(), implode(', ', $unlinked_states));
     }
     $data = array('graph' => $graph, 'errors' => $errors, 'info' => $info);
     return $data;
 }
Exemplo n.º 5
0
 /**
  * Converts an FSM to an instance of Image_GraphViz
  *
  * @param string $name Name for the graph
  * @param boolean $strict Whether to collapse multiple edges between
  *                        same nodes.
  *
  * @return Image_GraphViz instance or PEAR_Error on failure
  * @access public
  */
 function &export($name = 'FSM', $strict = true)
 {
     if (!is_a($this->_fsm, 'FSM')) {
         $error = PEAR::raiseError('Not a FSM instance');
         return $error;
     }
     $g = new Image_GraphViz(true, null, $name, $strict);
     // Initial state
     $attr = array('shape' => 'invhouse');
     $g->addNode($this->_fsm->_initialState, $attr);
     $nodes = array($this->_fsm->_initialState => $this->_fsm->_initialState);
     $_t = '_transitions';
     do {
         foreach ($this->_fsm->{$_t} as $input => $t) {
             if ($_t == '_transitions') {
                 list($symbol, $state) = explode(',', $input, 2);
             } else {
                 $state = $input;
                 $symbol = '';
             }
             list($nextState, $action) = $t;
             if (!array_key_exists($nextState, $nodes)) {
                 $g->addNode($nextState);
                 $nodes[$nextState] = $nextState;
             }
             if (!array_key_exists($state, $nodes)) {
                 $g->addNode($state);
                 $nodes[$state] = $state;
             }
             if (strlen($symbol)) {
                 $g->addEdge(array($state => $nextState), array('label' => $symbol));
             } else {
                 $g->addEdge(array($state => $nextState));
             }
             $this->_addAction($g, $nodes, $action, $nextState);
         }
         if ($_t == '_transitions') {
             $_t = '_transitionsAny';
         } else {
             $_t = false;
         }
     } while ($_t);
     // Add default transition
     if ($this->_defaultTransition) {
         list($nextState, $action) = $this->_defaultTransition;
         if (!array_key_exists($nextState, $nodes)) {
             $g->addNode($nextState, array('style' => 'dotted'));
             $nodes[$nextState] = $nextState;
         }
         $this->_addAction($g, $nodes, $action, $nextState, true);
     }
     return $g;
 }
Exemplo n.º 6
0
function show_bgpmap($data)
{
    // return a bgp map in a png file
    global $graph, $nodes, $edges;
    $graph = new Image_GraphViz(true, array(), "BGPMAP");
    $nodes = array();
    $edges = array();
    function escape($label)
    {
        $label = str_replace("&", "&amp;", $label);
        $label = str_replace(">", "&gt;", $label);
        $label = str_replace("<", "&lt;", $label);
        return $label;
    }
    function add_node($_as, $fillcolor = NULL, $label = NULL, $shape = NULL)
    {
        global $nodes, $graph;
        if (!array_key_exists($_as, $nodes)) {
            if (!$label) {
                $label = "AS" . $_as;
            }
            $label = '<table cellborder="0" border="0" cellpadding="0" cellspacing="0"><tr><td align="center">' . str_replace("\r", "<br/>", escape($label)) . '</td></tr></table>';
            $attrs = array('style' => 'filled', 'fontsize' => '10', 'label' => $label);
            if ($shape) {
                $attrs['shape'] = $shape;
            }
            if ($fillcolor) {
                $attrs['fillcolor'] = $fillcolor;
            }
            $nodes[$_as] = $attrs;
            $graph->addNode($_as, $nodes[$_as]);
        }
        return $nodes[$_as];
    }
    function add_edge($_previous_as, $_as, $attrs = array())
    {
        global $edges, $graph;
        $edge_array = array($_previous_as => $_as);
        if (!array_key_exists(gek($_previous_as, $_as), $edges)) {
            $attrs['splines'] = "true";
            $edge = array($edge_array, $attrs);
            $graph->addEdge($edge_array, $attrs);
            $edges[gek($_previous_as, $_as)] = $edge;
        } else {
            if (array_key_exists('label', $attrs)) {
                $e =& $edges[gek($_previous_as, $_as)];
                $label_without_star = str_replace("*", "", $attrs['label']);
                $labels = explode("\r", $e[1]['label']);
                if (!in_array($label_without_star . "*", $labels)) {
                    $tmp_labels = array();
                    foreach ($labels as $l) {
                        if (!startsWith($l, $label_without_star)) {
                            $labels[] = $l;
                        }
                    }
                    $labels = array_merge(array($attrs['label']), $tmp_labels);
                    $cmp = function ($a, $b) {
                        return endsWith($a, "*") ? -1 : 1;
                    };
                    usort($labels, $cmp);
                    $label = escape(implode("\r", $labels));
                    $e[1]['label'] = $label;
                }
            }
        }
        return $edges[gek($_previous_as, $_as)];
    }
    function gek($_previous_as, $_as)
    {
        // Generate Edge Key
        return $_previous_as . '_' . $_as;
    }
    foreach ($data as $host => $asmaps) {
        add_node($host, "#F5A9A9", strtoupper($host), "box");
        if ($host == Config::NODE_NAME) {
            $node = add_node(Config::ASN, "#F5A9A9");
            $edge = add_edge(Config::ASN, $host, array('color' => "red", 'style' => "bold"));
        }
    }
    $previous_as = NULL;
    $hosts = array_keys($data);
    foreach ($data as $host => $asmaps) {
        $first = true;
        foreach ($asmaps as $asmap) {
            $previous_as = $host;
            $color = "#" . dechex(rand(0, 16777215));
            $hop = false;
            $hop_label = "";
            foreach ($asmap as $_as) {
                if ($_as == $previous_as) {
                    continue;
                }
                if (!$hop) {
                    $hop = true;
                    if (!in_array($_as, $hosts)) {
                        $hop_label = $_as;
                        if ($first) {
                            $hop_label = $hop_label . "*";
                        }
                        continue;
                    } else {
                        $hop_label = "";
                    }
                }
                if (!strpos($_as, '.')) {
                    add_node($_as, $first ? "#F5A9A9" : "white");
                } else {
                    add_node($_as, $first ? "#F5A9A9" : "white", NULL, "box");
                }
                if ($hop_label) {
                    $attrs = array('fontsize' => "7", 'label' => $hop_label);
                } else {
                    $attrs = array('fontsize' => "7");
                }
                $hop_label = "";
                if ($first) {
                    $attrs['style'] = "bold";
                    $attrs['color'] = "red";
                } else {
                    if (!array_key_exists(gek($previous_as, $_as), $edges) || $edges[gek($previous_as, $_as)][1]['color'] != "red") {
                        $attrs['style'] = "dashed";
                        $attrs['color'] = $color;
                    }
                }
                add_edge($previous_as, $_as, $attrs);
                $previous_as = $_as;
            }
            $first = false;
        }
    }
    return $graph->image("jpeg");
}
 /**
  * Runs the phpOpenTracker API call.
  *
  * @param  array $parameters
  * @return mixed
  * @access public
  */
 function run($parameters)
 {
     $parameters['document_color'] = isset($parameters['document_color']) ? $parameters['document_color'] : 'black';
     $parameters['exit_targets'] = isset($parameters['exit_targets']) ? $parameters['exit_targets'] : false;
     $parameters['exit_target_color'] = isset($parameters['exit_target_color']) ? $parameters['exit_target_color'] : 'red';
     $parameters['from'] = isset($parameters['from']) ? crc32($parameters['from']) : 0;
     $parameters['length'] = isset($parameters['length']) ? $parameters['length'] : false;
     $parameters['referers'] = isset($parameters['referers']) ? $parameters['referers'] : false;
     $parameters['referer_color'] = isset($parameters['referer_color']) ? $parameters['referer_color'] : 'green';
     $parameters['result_format'] = isset($parameters['result_format']) ? $parameters['result_format'] : 'graphviz';
     $parameters['subpaths'] = isset($parameters['subpaths']) ? $parameters['subpaths'] : false;
     $parameters['to'] = isset($parameters['to']) ? crc32($parameters['to']) : 0;
     if ($parameters['api_call'] == 'all_paths') {
         $parameters['subpaths'] = true;
     }
     $this->_paths = array();
     $this->_subpathStatistics = array();
     switch ($parameters['result_format']) {
         case 'graphviz':
         case 'graphviz_object':
             $result = new Image_GraphViz();
             if ($parameters['exit_targets']) {
                 $result->addCluster('exit_targets', 'Exit Targets');
             }
             if ($parameters['referers']) {
                 $result->addCluster('referers', 'Referers');
             }
             break;
         default:
             $result = array();
     }
     $accesslogID = 0;
     $visitor = -1;
     $this->db->query(sprintf("SELECT accesslog.accesslog_id AS accesslog_id,\r\n                accesslog.document_id  AS document_id,\r\n                accesslog.timestamp    AS timestamp,\r\n                documents.string       AS document,\r\n                documents.document_url AS document_url\r\n           FROM %s accesslog,\r\n                %s visitors,\r\n                %s documents\r\n          WHERE visitors.client_id    = '%d'\r\n            AND visitors.accesslog_id = accesslog.accesslog_id\r\n            AND accesslog.document_id = documents.data_id\r\n                %s\r\n                %s\r\n          ORDER BY accesslog.accesslog_id,\r\n                   accesslog.timestamp", $this->config['accesslog_table'], $this->config['visitors_table'], $this->config['documents_table'], $parameters['client_id'], $this->_constraint($parameters['constraints']), $this->_whereTimerange($parameters['start'], $parameters['end'], 'accesslog')));
     while ($row = $this->db->fetchRow()) {
         if (!isset($this->_documents[$row['document_id']])) {
             $this->_documents[$row['document_id']] = array($row['document'], $row['document_url'], 'document');
         }
         if ($accesslogID != $row['accesslog_id']) {
             $accesslogID = $row['accesslog_id'];
             $node = 0;
             $visitor++;
             unset($previousTimestamp);
             $accesslog_ids[$visitor] = $row['accesslog_id'];
         }
         $clickpaths[$visitor][$node]['document'] = $row['document_id'];
         $clickpaths[$visitor][$node]['time_spent'] = 1;
         if (isset($previousTimestamp)) {
             $clickpaths[$visitor][$node - 1]['time_spent'] = $row['timestamp'] - $previousTimestamp;
         }
         $previousTimestamp = $row['timestamp'];
         $node++;
     }
     if (!isset($clickpaths)) {
         return $result;
     }
     $numClickpaths = sizeof($clickpaths) - 1;
     if ($parameters['exit_targets']) {
         for ($i = 0; $i <= $numClickpaths; $i++) {
             $this->db->query(sprintf("SELECT accesslog.document_id    AS document_id,\r\n                    accesslog.exit_target_id AS exit_target_id,\r\n                    exit_targets.string      AS exit_target\r\n               FROM %s accesslog,\r\n                    %s exit_targets\r\n              WHERE accesslog.accesslog_id   = '%d'\r\n                AND accesslog.exit_target_id = exit_targets.data_id", $this->config['accesslog_table'], $this->config['exit_targets_table'], $accesslog_ids[$i]));
             while ($row = $this->db->fetchRow()) {
                 $this->_documents[$row['exit_target_id']] = array($row['exit_target'], 'http://' . $row['exit_target'], 'exit_target');
                 $visitor = sizeof($clickpaths);
                 $clickpaths[$visitor][0]['document'] = $row['document_id'];
                 $clickpaths[$visitor][0]['time_spent'] = 0;
                 $clickpaths[$visitor][1]['document'] = $row['exit_target_id'];
                 $clickpaths[$visitor][1]['time_spent'] = 0;
             }
         }
     }
     for ($i = 0; $i < sizeof($clickpaths) - 1; $i++) {
         $pathLength = sizeof($clickpaths[$i]);
         if ($parameters['referers'] && $i <= $numClickpaths) {
             $this->db->query(sprintf("SELECT referers.string     AS referer,\r\n                    visitors.referer_id AS referer_id\r\n               FROM %s visitors,\r\n                    %s referers\r\n              WHERE visitors.accesslog_id = '%d'\r\n                AND visitors.referer_id   = referers.data_id", $this->config['visitors_table'], $this->config['referers_table'], $accesslog_ids[$i]));
             if ($row = $this->db->fetchRow()) {
                 $this->_documents[$row['referer_id']] = array($row['referer'], 'http://' . $row['referer'], 'referer');
                 array_unshift($clickpaths[$i], array('document' => $row['referer_id'], 'time_spent' => 0));
             }
         }
         if (!$parameters['subpaths']) {
             $this->_processPath($clickpaths[$i], $parameters['from'], $parameters['to'], $parameters['length']);
         } else {
             for ($j = 2; $j <= $pathLength; $j++) {
                 $subpath = array_slice($clickpaths[$i], 0, $j);
                 $subpathLength = sizeof($subpath);
                 for ($k = 2; $k <= $subpathLength; $k++) {
                     $this->_processPath(array_slice($subpath, 0 - $k), $parameters['from'], $parameters['to'], $parameters['length']);
                 }
             }
         }
     }
     if (empty($this->_paths)) {
         return $result;
     }
     foreach ($this->_subpathStatistics as $fromNode => $toNodes) {
         foreach ($toNodes as $toNode => $data) {
             if ($parameters['api_call'] == 'all_paths') {
                 $fromColor = $parameters['document_color'];
                 $fromGroup = 'default';
                 $fromID = $this->_documents[$fromNode][0];
                 $fromRank = 'same';
                 $toColor = $parameters['document_color'];
                 $toGroup = 'default';
                 $toID = $this->_documents[$toNode][0];
                 $toRank = 'same';
                 $edgeColor = $parameters['document_color'];
                 if ($this->_documents[$toNode][2] == 'exit_target') {
                     $toColor = $parameters['exit_target_color'];
                     $toGroup = 'exit_targets';
                     $toID = 'exit_target_' . $toID;
                     $toRank = 'sink';
                     $edgeColor = $parameters['exit_target_color'];
                 }
                 if ($this->_documents[$fromNode][2] == 'referer') {
                     $fromColor = $parameters['referer_color'];
                     $fromGroup = 'referers';
                     $fromID = 'referer_' . $fromID;
                     $fromRank = 'source';
                     $edgeColor = $parameters['referer_color'];
                 }
                 $result->addNode($fromID, array('label' => $this->_documents[$fromNode][0], 'url' => $this->_documents[$fromNode][1], 'color' => $fromColor, 'rank' => $fromRank, 'shape' => 'box'), $fromGroup);
                 $result->addNode($toID, array('label' => $this->_documents[$toNode][0], 'url' => $this->_documents[$toNode][1], 'color' => $toColor, 'rank' => $toRank, 'shape' => 'box'), $toGroup);
                 $result->addEdge(array($fromID => $toID), array('color' => $edgeColor, 'label' => $data['count']));
             } else {
                 if (isset($data['count'])) {
                     $this->_subpathStatistics[$fromNode][$toNode]['time_spent'] = floor($data['time_spent'] / $data['count']);
                 }
             }
         }
     }
     if ($parameters['api_call'] != 'all_paths') {
         switch ($parameters['api_call']) {
             case 'shortest_paths':
                 $field = 'length';
                 $sort = SORT_ASC;
                 break;
             case 'longest_paths':
                 $field = 'length';
                 $sort = SORT_DESC;
                 break;
             case 'top_paths':
                 $field = 'count';
                 $sort = SORT_DESC;
                 break;
         }
         foreach ($this->_paths as $path) {
             $tmp[] = $path[$field];
         }
         array_multisort($tmp, $sort, $this->_paths);
         if ($parameters['limit'] && sizeof($this->_paths) > $parameters['limit']) {
             $this->_paths = array_slice($this->_paths, 0, $parameters['limit']);
         }
         $rank = 1;
         foreach ($this->_paths as $path => $statistics) {
             $documents = array();
             $documentURLs = array();
             $path = explode(':', $path);
             $pathLength = sizeof($path);
             $where = '';
             if ($parameters['subpaths']) {
                 $subpathStatistics = array();
                 for ($i = 0; $i < $pathLength - 1; $i++) {
                     $subpathStatistics[] = array('count' => intval($this->_subpathStatistics[$path[$i]][$path[$i + 1]]['count']), 'time_spent' => intval($this->_subpathStatistics[$path[$i]][$path[$i + 1]]['time_spent']));
                 }
             } else {
                 $subpathStatistics = false;
             }
             for ($i = 0; $i < $pathLength; $i++) {
                 $documents[$i] = $this->_documents[$path[$i]][0];
                 $documentURLs[$i] = $this->_documents[$path[$i]][1];
             }
             if ($parameters['result_format'] == 'array') {
                 $result[] = new phpOpenTracker_Clickpath($documents, $documentURLs, $subpathStatistics, intval($statistics['count']));
             } else {
                 $result->addCluster($rank, sprintf('%s. Taken by %s visitors.', $rank, $statistics['count']));
                 for ($i = 0; $i < $pathLength - 1; $i++) {
                     $fromID = $rank . '_' . $documents[$i];
                     $toID = $rank . '_' . $documents[$i + 1];
                     $result->addNode($fromID, array('label' => $documents[$i], 'url' => $documentURLs[$i], 'color' => $parameters['document_color'], 'shape' => 'box'), $rank);
                     $result->addNode($toID, array('label' => $documents[$i + 1], 'url' => $documentURLs[$i + 1], 'color' => $parameters['document_color'], 'shape' => 'box'), $rank);
                     $result->addEdge(array($fromID => $toID), array('color' => $parameters['document_color']));
                 }
             }
             $rank++;
         }
     }
     if ($parameters['result_format'] == 'graphviz') {
         return $result->parse();
     } else {
         return $result;
     }
 }
Exemplo n.º 8
0
 public function createGraph()
 {
     $graph = new Image_GraphViz();
     $attributes = array('rankdir' => "LR");
     $graph->addAttributes($attributes);
     $graph->addNode($this->title);
     foreach ($this->members as $member) {
         $this->addAndLinkNodeForRemoteObject($graph, $member, "A comme membre", "member");
     }
     foreach ($this->definitions as $definition) {
         $this->addAndLinkNodeForRemoteObject($graph, $definition, "A comme définition", "definition");
     }
     foreach ($this->ingredients as $ingredient) {
         $this->addAndLinkNodeForRemoteObject($graph, $ingredient, "A comme ingrédient", "ingredient");
     }
     foreach ($this->projects as $project) {
         $this->addAndLinkNodeForRemoteObject($graph, $project, "A comme projet", "project");
     }
     $this->linkWithString($graph, $this->theme, "A comme theme", "theme");
     //$graph->image();
     return $graph;
 }
Exemplo n.º 9
0
 /**
  * Returns the dependencies between the classes of this project
  * as GraphViz/DOT markup.
  *
  * @return Image_GraphViz
  * @since  Method available since Release 3.2.2
  */
 public function getDependenciesAsDOT()
 {
     if (PHPUnit_Util_Filesystem::fileExistsInIncludePath('Image/GraphViz.php')) {
         require_once 'Image/GraphViz.php';
     } else {
         throw new RuntimeException('Image_GraphViz is not available.');
     }
     $graph = new Image_GraphViz(TRUE, array('overlap' => 'scale', 'splines' => 'true', 'sep' => '.1', 'fontsize' => '8'));
     foreach (array_keys($this->dependencies) as $className) {
         $graph->addNode($className);
     }
     foreach ($this->dependencies as $from => $dependencies) {
         foreach ($dependencies as $to => $flag) {
             if ($flag === 1) {
                 $graph->addEdge(array($from => $to));
             }
         }
     }
     return $graph;
 }
Exemplo n.º 10
0
    die;
}
// connect to db
$mid = mysqli_connect($gixlg['db_host'], $gixlg['db_user'], $gixlg['db_password'], $gixlg['db_database']);
if (mysqli_connect_errno()) {
    printError("Could not connect: " . mysqli_connect_error());
    break;
}
if ($ipnet == 1) {
    $res = mysqli_query($mid, "SELECT * FROM `prefixes` WHERE (`prefix`='{$prefix}')");
} else {
    $int_ip = inet_ptoi($prefix);
    $res = mysqli_query($mid, "SELECT * FROM `prefixes` WHERE (MBRCONTAINS(ip_poly, POINTFROMWKB(POINT({$int_ip}, 0))))");
}
$graph = array('edgesFrom' => array(), 'nodes' => array(), 'attributes' => array(), 'clusters' => array(), 'subgraphs' => array(), 'bgcolor' => '#ffffff');
$gv = new Image_GraphViz(true, $graph);
while ($d = mysqli_fetch_assoc($res)) {
    // for each record check if we know that neighbor
    // and also lookup for nexthop information
    if ($gixlg['mode'] == "rc") {
        // route collector mode
        if ($d['type'] == 4) {
            $res_memb = mysqli_query($mid, "SELECT * FROM `members` WHERE `neighbor`='" . $d['neighbor'] . "'");
            $d_memb = mysqli_fetch_assoc($res_memb);
            $res_node = mysqli_query($mid, "SELECT * FROM `nodes` WHERE `ip4`='" . $d['neighbor'] . "'");
            $d_node = mysqli_fetch_assoc($res_node);
            $ip_int = ip2long($d['nexthop']);
            $res_next = mysqli_query($mid, "SELECT * FROM `nexthops` WHERE ({$ip_int}>=`ip4_start` && {$ip_int}<=`ip4_end`)");
            $d_next = mysqli_fetch_assoc($res_next);
        } else {
            $res_node = mysqli_query($mid, "SELECT * FROM `nodes` WHERE `ip6`='" . $d['neighbor'] . "'");
Exemplo n.º 11
0
 /**
  * drawRequirementsGraph Will draw a requirement graph if PEAR::Image_GraphViz is installed
  *
  * @param boolean $pInstallVersion Use the actual installed version instead of the version that will be in bitweaver after the upgrade
  * @param string $pFormat dot output format
  * @param string $pCommand dot or neato
  * @access public
  * @return boolean TRUE on success, FALSE on failure - mErrors will contain reason for failure
  */
 function drawRequirementsGraph($pInstallVersion = FALSE, $pFormat = 'png', $pCommand = 'dot')
 {
     global $gBitSmarty, $gBitThemes;
     // only do this if we can load PEAR GraphViz interface
     if (@(include_once 'Image/GraphViz.php')) {
         ksort($this->mPackages);
         $deps = $this->calculateRequirements($pInstallVersion);
         $delKeys = $matches = array();
         // crazy manipulation of hash to remove duplicate version matches.
         // we do this that we can use double headed arrows in the graph below.
         foreach ($deps as $key => $req) {
             foreach ($deps as $k => $d) {
                 if ($req['requires'] == $d['package'] && $req['package'] == $d['requires'] && $req['result'] == 'ok' && $d['result'] == 'ok') {
                     $deps[$key]['dir'] = 'both';
                     $matches[$key] = $k;
                 }
             }
         }
         // get duplicates
         foreach ($matches as $key => $match) {
             unset($delKeys[$match]);
             $delKeys[$key] = $match;
         }
         // remove dupes from hash
         foreach ($delKeys as $key) {
             unset($deps[$key]);
         }
         // start drawing stuff
         $graph = new Image_GraphViz(TRUE, $gBitThemes->getGraphvizGraphAttributes(), 'Requirements', TRUE);
         $fromattributes = $toattributes = $gBitThemes->getGraphvizNodeAttributes();
         foreach ($deps as $node) {
             //$fromNode = ucfirst( $node['package'] )."\n".$node['package_version'];
             //$toNode   = ucfirst( $node['requires'] )."\n".$node['required_version']['min'];
             $fromNode = ucfirst($node['package']);
             $toNode = ucfirst($node['requires']);
             switch ($node['result']) {
                 case 'max_dep':
                     $edgecolor = 'chocolate3';
                     $label = 'Maximum version\\nexceeded';
                     $toNode .= "\n" . $node['required_version']['min'] . " - " . $node['required_version']['max'];
                     $toattributes['fillcolor'] = 'khaki';
                     break;
                 case 'min_dep':
                     $edgecolor = 'crimson';
                     $label = 'Minimum version\\nnot met';
                     $toNode .= "\n" . $node['required_version']['min'];
                     if (!empty($node['required_version']['max'])) {
                         $toNode .= " - " . $node['required_version']['max'];
                     }
                     $toattributes['fillcolor'] = 'pink';
                     break;
                 case 'missing':
                     $edgecolor = 'crimson';
                     $label = 'Not installed\\nor activated';
                     $toNode .= "\n" . $node['required_version']['min'];
                     if (!empty($node['required_version']['max'])) {
                         $toNode .= " - " . $node['required_version']['max'];
                     }
                     $toattributes['fillcolor'] = 'pink';
                     break;
                 default:
                     $edgecolor = '';
                     $label = '';
                     $toattributes['fillcolor'] = 'white';
                     break;
             }
             $fromattributes['URL'] = "http://www.bitweaver.org/wiki/" . ucfirst($node['package']) . "Package";
             $graph->addNode($fromNode, $fromattributes);
             $toattributes['URL'] = "http://www.bitweaver.org/wiki/" . ucfirst($node['requires']) . "Package";
             $graph->addNode($toNode, $toattributes);
             $graph->addEdge(array($fromNode => $toNode), $gBitThemes->getGraphvizEdgeAttributes(array('dir' => !empty($node['dir']) ? $node['dir'] : '', 'color' => $edgecolor, 'fontcolor' => $edgecolor, 'label' => $label)));
         }
         if (preg_match("#(png|gif|jpe?g|bmp|svg|tif)#i", $pFormat)) {
             $graph->image($pFormat, $pCommand);
         } else {
             return $graph->fetch($pFormat, $pCommand);
         }
     } else {
         return FALSE;
     }
 }
Exemplo n.º 12
0
 public function createGraph()
 {
     $graph = new Image_GraphViz(true, array('size' => "17,17", "ratio" => "true"));
     $attributes = array('rankdir' => "LR");
     $graph->addAttributes($attributes);
     $graph->addNode($this->title);
     //var_dump($this->nonFuncReqs);
     foreach ($this->nonFuncReqs as $nonFuncReq) {
         $this->addAndLinkNodeForRemoteObject($graph, $nonFuncReq, "A comme besoin non fonctionnel", "nonfuncreq");
     }
     foreach ($this->members as $member) {
         $this->addAndLinkNodeForRemoteObject($graph, $member, "A comme membre", "member");
     }
     foreach ($this->definitions as $definition) {
         $this->addAndLinkNodeForRemoteObject($graph, $definition, "A comme définition", "definition");
     }
     foreach ($this->ingredients as $ingredient) {
         $this->addAndLinkNodeForRemoteObject($graph, $ingredient, "A comme ingrédient", "ingredient");
     }
     foreach ($this->funcReqs as $funcReq) {
         $this->addAndLinkNodeForFuncReq($graph, $funcReq);
     }
     return $graph;
     //$graph->image();
     //$graph->image();
 }
Exemplo n.º 13
0
 function imprimir_afd()
 {
     $this->layout = 'empty';
     $this->thompson->generarAFND();
     $this->thompson->AFNDaAFD();
     $AFD = $this->thompson->getAFD();
     $estados = $AFD->getEstados();
     $graph = new Image_GraphViz(true, array(), 'AFD', false);
     $graph->setAttributes(array('size' => '8,5', 'rankdir' => 'LR'));
     $transiciones = array();
     foreach ($estados as $estado) {
         if (!$estado->esFinal()) {
             $graph->addNode('q' . $estado->getID(), array('shape' => 'circle'));
         } else {
             $graph->addNode('q' . $estado->getID(), array('shape' => 'doublecircle'));
         }
         if ($estado->esInicial()) {
             $graph->addNode('null', array('shape' => 'plaintext', 'label' => ''));
             $graph->addEdge(array('null' => 'q' . $estado->getID()), array('label' => ''));
         }
         $transiciones = $estado->getArregloTransiciones();
         if (!empty($transiciones)) {
             foreach ($transiciones as $simbolo => $destinos) {
                 foreach ($destinos as $destino) {
                     $graph->addEdge(array('q' . $estado->getID() => 'q' . $destino), array('label' => $simbolo));
                 }
             }
         }
     }
     $graph->image();
 }
Exemplo n.º 14
0
$unit_atts = $default_node_settings;
$unit_atts['bgcolor'] = 'ff0000';
$unit_atts['color'] = 'green';
$arrow_atts = $default_settings;
$arrow_atts['arrowType'] = 'normal';
$arrow_atts['fontsize'] = '6';
$grayarrow_atts = $arrow_atts;
$grayarrow_atts['color'] = 'gray';
define('UNIT_PREFIX', '[U] ');
define('TECHNOLOGY_PREFIX', '[T] ');
define('BUILDING_PREFIX', '[B] ');
define('EQUIPMENT_PREFIX', '[E] ');
$show_equipment = Neuron_Core_Tools::getInput('_GET', 'equipment', 'int', 0) == 1;
$show_technology = Neuron_Core_Tools::getInput('_GET', 'technology', 'int', 0) == 1;
$show_units = Neuron_Core_Tools::getInput('_GET', 'units', 'int', 0) == 1;
$gv = new Image_GraphViz(true, array('label' => $race->getName(), 'labelloc' => 't'));
// All buildings
$gv->addCluster("BUILDINGS", "Buildings");
if ($show_technology) {
    $gv->addCluster("TECHNOLOGY", "Technology");
}
//$gv->addCluster ("EQUIPMENT", "Equipment");
if ($show_equipment) {
    $gv->addCluster("weapon", "Weapons", array('rotate' => '90'));
    $gv->addCluster("armour", "Armour", array());
}
if ($show_units) {
    $gv->addCluster("UNITS", "Units");
}
$buildings = Dolumar_Buildings_Building::getBuildingObjects($race);
foreach ($buildings as $building) {
Exemplo n.º 15
0
 protected function buildGraphNode(Image_GraphViz $graph, $nodes, $parent = null)
 {
   foreach($nodes as $node => $children)
   {
     $node_array = explode('\\', $node);
     $graph->addNode(md5($node), array('label' => end($node_array), 'shape' => 'box'));
     if ($parent !== null)
     {
       $graph->addEdge(array(md5($node) => md5($parent)), array('arrowhead' => 'empty', 'minlen' => '2'));
     }
     $this->buildGraphNode($graph, $children, $node);
   }
 }
 /**
  * This method returns a list of absolute paths containing the location of
  * images that inlustrate a specific workflow. Such images are generated
  * each workflow specification.
  * If any requested image is not present or if it's older than the
  * workflow's configuration file, all images for such workflow are
  * generated.
  *
  * @warning This method requires GraphViz.
  *
  * @param string $workflowName Workflow name to look for.
  * @return string[string] Returns a list of paths containing these keys:
  * WKFL_AFIELD_FILE, WKFL_AFIELD_THUMB (these are defined constants).
  */
 public function graphPath($workflowName)
 {
     //
     // Defautl values.
     $out = false;
     //
     // Checking and including library.
     if (@(require_once 'Image/GraphViz.php')) {
         //
         // Checking required directories permissions.
         $this->checkGraphsDirectories();
         //
         // Global dependencies.
         global $WKFLDefaults;
         //
         // Default values.
         $generateIt = false;
         //
         // Retrieving the workflow.
         $workflow = $this->getWorkflow($workflowName);
         //
         // Guessing paths.
         $graphPath = Sanitizer::DirPath("{$WKFLDefaults[WKFL_DEFAULTS_GRAPHS_PATH]}/{$workflowName}.png");
         $graphThumbPath = Sanitizer::DirPath("{$WKFLDefaults[WKFL_DEFAULTS_GRAPHS_PATH]}/{$workflowName}-256px.png");
         //
         // Checking paths existence.
         if (!$generateIt && (!is_file($graphPath) || !is_file($graphThumbPath))) {
             $generateIt = true;
         }
         //
         // Checking paths' last modification dates.
         if (!$generateIt) {
             $workflowTime = filemtime($workflow->path());
             $generateIt = filemtime($graphPath) < $workflowTime || filemtime($graphThumbPath) < $workflowTime;
         }
         //
         // Do these images have to be generated?
         if ($generateIt) {
             //
             // Logging pre-generation information.
             $this->_log->log(LGGR_LOG_LEVEL_INFO, "Gereating graph for '{$workflowName}'.");
             $this->_log->log(LGGR_LOG_LEVEL_DEBUG, "Workflow '{$workflowName}' graph path: '{$graphPath}'");
             $this->_log->log(LGGR_LOG_LEVEL_DEBUG, "                           thumb path: '{$graphThumbPath}'");
             //
             // Creating an image.
             $graph = new \Image_GraphViz();
             //
             // Addind begining node.
             $graph->addNode('BEGIN', ['shape' => 'circle', 'label' => '', 'color' => 'black']);
             //
             // Configuration shortcut.
             $workflowConfig = $workflow->config();
             //
             // Creating a squared node for each step.
             foreach ($workflowConfig->steps as $stepName => $step) {
                 $graph->addNode($stepName, array('label' => $stepName, 'shape' => 'box'));
             }
             //
             // Addind ending node.
             $graph->addNode('END', ['shape' => 'circle', 'label' => '', 'color' => 'black', 'style' => 'filled']);
             //
             // Linking the beginning node to the first step.
             $graph->addEdge(['BEGIN' => $workflowConfig->startsAt]);
             //
             // Linking all steps based on connections
             // confiugrations.
             foreach ($workflowConfig->steps as $stepName => $step) {
                 //
                 // Checking each connection for current
                 // step.
                 foreach ($step->connections as $connName => $conn) {
                     //
                     // Checking if this connection
                     // either changes the flow status
                     // or sets the next step.
                     if (isset($conn->status)) {
                         //
                         // Checking what change is taking.
                         switch ($conn->status) {
                             case WKFL_ITEM_FLOW_STATUS_FAILED:
                             case WKFL_ITEM_FLOW_STATUS_DONE:
                                 //
                                 // These statuses link to the end.
                                 $graph->addEdge([$stepName => 'END'], ['label' => $connName, 'fontcolor' => 'brown', 'color' => 'brown']);
                                 break;
                             case WKFL_ITEM_FLOW_STATUS_WAIT:
                                 //
                                 // Basic attributes for each link.
                                 $attrs = ['label' => "{$connName}\n[wait]", 'color' => 'orange', 'fontcolor' => 'orange', 'style' => 'dashed'];
                                 //
                                 // Checking if this waiting has some extra
                                 // configuration.
                                 if (isset($conn->wait)) {
                                     //
                                     // This status creates a vitual node
                                     // representing the waiting step.
                                     $nodeName = "wait_{$stepName}";
                                     $graph->addNode($nodeName, ['shape' => 'box', 'label' => "wait:{$stepName}", 'fontcolor' => 'orange', 'color' => 'orange']);
                                     //
                                     // Linking the current step to this
                                     // virtual node.
                                     $graph->addEdge([$stepName => $nodeName], $attrs);
                                     //
                                     // Linking the virtual node to the current
                                     // one for less attempts than a limit.
                                     $attrs['label'] = "{$connName}\n[wait<={$conn->wait->attempts}]";
                                     $graph->addEdge([$nodeName => $stepName], $attrs);
                                     //
                                     // Linking the virtual node something else
                                     // for more attempts than a limit.
                                     $attrs['label'] = "{$connName}\n[wait>{$conn->wait->attempts}]";
                                     if (isset($conn->wait->status)) {
                                         //
                                         // Linking to the end.
                                         $graph->addEdge([$nodeName => 'END'], $attrs);
                                     } elseif (isset($conn->wait->step)) {
                                         //
                                         // Linking to another step.
                                         $graph->addEdge([$nodeName => $conn->wait->step], $attrs);
                                     }
                                 } else {
                                     $nextStep = isset($conn->step) ? $conn->step : $stepName;
                                     $graph->addEdge([$stepName => $nextStep], $attrs);
                                 }
                                 break;
                         }
                     } elseif (isset($conn->step)) {
                         //
                         // Linking this step to
                         // the next one.
                         $graph->addEdge([$stepName => $conn->step], ['label' => $connName, 'fontcolor' => 'darkgreen', 'color' => 'darkgreen']);
                     }
                 }
             }
             //
             // Saving the generated graphic in two locations,
             // one for the actual image and other for 256
             // pixels thumbnail.
             file_put_contents($graphPath, $graph->fetch('png'));
             file_put_contents($graphThumbPath, $graph->fetch('png'));
             //
             // Croping thumbnail.
             self::CropImage($graphThumbPath, 256);
         }
         //
         // Building the returning information.
         $out = array(WKFL_AFIELD_FILE => $graphPath, WKFL_AFIELD_THUMB => $graphThumbPath);
     } else {
         //
         // Logging the error of not having the proper library.
         $this->_log->log(LGGR_LOG_LEVEL_ERROR, "Pear GraphViz plugin hasn't been installed.");
     }
     return $out;
 }
Exemplo n.º 17
0
 /**
  * Recursive method which builds the actual node for use in the Image_Graphviz object.
  *
  * @param Image_GraphViz $graph
  * @param array          $nodes
  * @param array|null     $parent
  *
  * @return void
  */
 protected function buildGraphNode(Image_GraphViz $graph, $nodes, $parent = null)
 {
     foreach ($nodes as $node => $children) {
         $node_array = explode('\\', $node);
         $properties = array('label' => end($node_array), 'shape' => 'box', 'style' => 'filled', 'fillcolor' => 'white');
         if (isset($this->class_paths[$node])) {
             $properties['URL'] = $this->class_paths[$node];
             $properties['target'] = '_top';
         } else {
             $properties['fontcolor'] = 'gray';
         }
         $graph->addNode(md5($node), $properties);
         if ($parent !== null) {
             $graph->addEdge(array(md5($node) => md5($parent)), array('arrowhead' => 'empty', 'minlen' => '2'));
         }
         $this->buildGraphNode($graph, $children, $node);
     }
 }
Exemplo n.º 18
0
<?php

include_once 'includes/common.php';
include_once 'includes/logic.php';
include_once 'graphviz/GraphViz.php';
Logic::load();
$graph = new Image_GraphViz();
$i = 0;
foreach (Logic::$contacts as $contact) {
    if (strlen($contact->nombre) > 0) {
        $nodeName = camelCase($contact->nombre);
        $nodeLabel = $contact->nombre;
        if (strlen($contact->empresa) > 0) {
            $nodeLabel .= "\n" . $contact->empresa;
        }
    } elseif (strlen($contact->empresa) > 0) {
        $nodeName = camelCase($contact->empresa);
        $nodeLabel = $contact->empresa;
    } else {
        $nodeName = "node{$i}";
        $nodeLabel = '(nada)';
    }
    $graph->addNode($nodeName, array('label' => $nodeLabel, 'shape' => 'octagon', 'fontsize' => '8'));
    if (sizeof($contact->relations) > 0) {
        foreach ($contact->relations as $relation) {
            if ($relation->meetInPerson) {
                $colorRelation = 'black';
            } else {
                $colorRelation = 'grey';
            }
            if (strlen($relation->nombre) > 0) {
Exemplo n.º 19
0
 public function getOutput()
 {
     //echo get_include_path ();
     require_once 'Image/GraphViz.php';
     $race = Dolumar_Races_Race::getFromId(Neuron_Core_Tools::getInput('_GET', 'race', 'int', 1));
     $default_settings = array('fontsize' => 8);
     $default_node_settings = $default_settings;
     $default_node_settings['shape'] = 'box';
     $tech_atts = $default_node_settings;
     $tech_atts['bgcolor'] = 'ff0000';
     $tech_atts['color'] = 'blue';
     $equip_atts = $default_node_settings;
     $equip_atts['bgcolor'] = 'ff0000';
     $equip_atts['color'] = 'red';
     $equip_atts['rankdir'] = 'tb';
     $equip_atts['constraint'] = false;
     $unit_atts = $default_node_settings;
     $unit_atts['bgcolor'] = 'ff0000';
     $unit_atts['color'] = 'green';
     $arrow_atts = $default_settings;
     $arrow_atts['arrowType'] = 'normal';
     $arrow_atts['fontsize'] = '6';
     $grayarrow_atts = $arrow_atts;
     $grayarrow_atts['color'] = 'gray';
     define('UNIT_PREFIX', '[U] ');
     define('TECHNOLOGY_PREFIX', '[T] ');
     define('BUILDING_PREFIX', '[B] ');
     define('EQUIPMENT_PREFIX', '[E] ');
     $show_equipment = Neuron_Core_Tools::getInput('_GET', 'equipment', 'int', 0) == 1;
     $show_technology = Neuron_Core_Tools::getInput('_GET', 'technology', 'int', 0) == 1;
     $show_units = Neuron_Core_Tools::getInput('_GET', 'units', 'int', 0) == 1;
     $gv = new Image_GraphViz(true, array('label' => $race->getName(), 'labelloc' => 't'));
     // All buildings
     $gv->addCluster("BUILDINGS", "Buildings");
     if ($show_technology) {
         $gv->addCluster("TECHNOLOGY", "Technology");
     }
     //$gv->addCluster ("EQUIPMENT", "Equipment");
     if ($show_equipment) {
         $gv->addCluster("weapon", "Weapons", array('rotate' => '90'));
         $gv->addCluster("armour", "Armour", array());
     }
     if ($show_units) {
         $gv->addCluster("UNITS", "Units");
     }
     $buildings = Dolumar_Buildings_Building::getBuildingObjects($race);
     foreach ($buildings as $building) {
         $building->setVillage(new Dolumar_Players_DummyVillage($race));
         //$building->setRace ($race);
         // Add building
         $gv->addNode(BUILDING_PREFIX . $building->getName(), $default_node_settings, "BUILDINGS");
         // Add building requirements
         foreach ($building->getRequiredBuildings() as $req) {
             $label = $req['amount'] . '+';
             $gv->addEdge(array(BUILDING_PREFIX . $req['building']->getName() => BUILDING_PREFIX . $building->getName()), array_merge($arrow_atts, array('label' => $label)));
         }
         // Technologies
         if ($show_technology) {
             foreach ($building->getTechnologies() as $tech) {
                 $label = 'Level ' . $tech->getMinLevel();
                 $gv->addNode(TECHNOLOGY_PREFIX . $tech->getName(), $tech_atts, "TECHNOLOGY");
                 $gv->addEdge(array(BUILDING_PREFIX . $building->getName() => TECHNOLOGY_PREFIX . $tech->getName()), array_merge($arrow_atts, array('label' => $label)));
                 // requirements for the technologies?
                 foreach ($tech->getRequiredTechnologies() as $req) {
                     $label = null;
                     $gv->addEdge(array(TECHNOLOGY_PREFIX . $req->getName() => TECHNOLOGY_PREFIX . $tech->getName()), array_merge($arrow_atts, array('label' => $label)));
                 }
             }
         }
         // Equipment
         if ($building instanceof Dolumar_Buildings_Crafting && $show_equipment) {
             foreach ($building->getEquipment() as $equip) {
                 //$gv->addNode (EQUIPMENT_PREFIX . $equip->getName (), $equip_atts, "EQUIPMENT");
                 $gv->addNode(EQUIPMENT_PREFIX . $equip->getName(), $equip_atts, $equip->getItemType());
                 // Arrow to this building
                 $label = $equip->getRequiredLevel() > 0 ? 'Level ' . $equip->getRequiredLevel() : null;
                 //$gv->addEdge (array (BUILDING_PREFIX . $building->getName () => EQUIPMENT_PREFIX . $equip->getName ()), array_merge ($arrow_atts, array ('label' => $label)));
                 $gv->addEdge(array(BUILDING_PREFIX . $building->getName() => EQUIPMENT_PREFIX . $equip->getName()), array_merge($grayarrow_atts, array('label' => $label, 'ltail' => 'EQUIPMENT')));
                 // Required technologies?
                 foreach ($equip->getRequiredTechnologies() as $tech) {
                     $label = null;
                     $gv->addEdge(array(TECHNOLOGY_PREFIX . $tech->getName() => EQUIPMENT_PREFIX . $equip->getName()), array_merge($grayarrow_atts, array('label' => $label)));
                 }
             }
         }
         // Units
         if ($building instanceof Dolumar_Buildings_Training && $show_units) {
             foreach ($building->getUnits() as $unit) {
                 // Units!
                 $gv->addNode(UNIT_PREFIX . $unit->getName(), $unit_atts, "UNITS");
                 // Arrow to this building
                 $label = null;
                 $gv->addEdge(array(BUILDING_PREFIX . $building->getName() => UNIT_PREFIX . $unit->getName()), array_merge($grayarrow_atts, array('label' => $label)));
                 // Required technologies?
                 foreach ($unit->getRequiredTechnologies() as $tech) {
                     $label = null;
                     $gv->addEdge(array(TECHNOLOGY_PREFIX . $tech->getName() => UNIT_PREFIX . $unit->getName()), array_merge($grayarrow_atts, array('label' => $label)));
                 }
             }
         }
     }
     // All equipment
     /*
     $gv->addCluster ("EQUIPMENT", "Equipment");
     $eqs = Dolumar_Players_Equipment::getAllEquipment();
     foreach ($eqs as $building)
     {
     	$gv->addNode ($building->getName (), $equip_atts, "EQUIPMENT");
     	
     	// Required technologies?
     	foreach ($building->getRequiredTechnologies () as $tech)
     	{
     		$label = null;
     		$gv->addEdge (array ($tech->getName () => $building->getName ()), array_merge ($arrow_atts, array ('label' => $label)));
     	}
     }
     */
     // All units
     $output = Neuron_Core_Tools::getInput('_GET', 'engine', 'varchar');
     switch ($output) {
         case "dot":
         case "neato":
             break;
         default:
             $output = "dot";
             break;
     }
     if (!$gv->image("png", $output)) {
         echo "Error... Is Graphviz installed?";
     }
 }
Exemplo n.º 20
0
 /**
  * Returns the dependencies between the classes of this project
  * as GraphViz/DOT markup.
  *
  * @return Image_GraphViz
  * @access public
  * @since  Method available since Release 3.2.2
  */
 public function getDependenciesAsDOT()
 {
     if (class_exists('Image_GraphViz', FALSE)) {
         $graph = new Image_GraphViz(TRUE, array('overlap' => 'scale', 'splines' => 'true', 'sep' => '.1', 'fontsize' => '8'));
         foreach (array_keys($this->dependencies) as $className) {
             $graph->addNode($className);
         }
         foreach ($this->dependencies as $from => $dependencies) {
             foreach ($dependencies as $to => $flag) {
                 if ($flag === 1) {
                     $graph->addEdge(array($from => $to));
                 }
             }
         }
         return $graph;
     } else {
         throw new RuntimeException();
     }
 }
Exemplo n.º 21
0
 /**
  * @param  PHPUnit_Framework_Test $test
  * @param  string                  $color
  * @access private
  */
 private function addTestNode(PHPUnit_Framework_Test $test, $color)
 {
     $name = PHPUnit_Util_Test::describe($test, FALSE);
     $this->graph->addNode($name[1], array('color' => $color), $this->testSuites[$this->testSuiteLevel]);
     $this->graph->addEdge(array($this->testSuites[$this->testSuiteLevel] => $name[1]));
 }
Exemplo n.º 22
0
 /**
  * Constructor.
  *
  * Setting the name of the Graph is useful for including multiple image
  * maps on one page. If not set, the graph will be named 'G'.
  *
  * @param boolean $directed    Directed (TRUE) or undirected (FALSE) graph.
  *                             Note: You MUST pass a boolean, and not just
  *                             an  expression that evaluates to TRUE or
  *                             FALSE (i.e. NULL, empty string, 0 will NOT
  *                             work)
  * @param array   $attributes  Attributes of the graph
  * @param string  $name        Name of the Graph
  * @param boolean $strict      Whether to collapse multiple edges between
  *                             same nodes
  * @param boolean $returnError Set to TRUE to return PEAR_Error instances
  *                             on failures instead of FALSE
  *
  * @access public
  */
 public function __construct($directed = false, $attributes = array(), $name = 'G', $strict = true, $returnError = false)
 {
     $attributes['overlap'] = 'prism';
     parent::__construct($directed, $attributes, $name, $strict, $returnError);
     $this->fillUp();
 }