Esempio n. 1
0
function json_encode2($data)
{
    switch (gettype($data)) {
        case 'boolean':
            return $data ? 'true' : 'false';
        case 'integer':
        case 'double':
            return $data;
        case 'string':
            return '"' . strtr($data, array('\\' => '\\\\', '"' => '\\"')) . '"';
        case 'array':
            $rel = false;
            // relative array?
            $key = array_keys($data);
            foreach ($key as $v) {
                if (!is_int($v)) {
                    $rel = true;
                    break;
                }
            }
            $arr = array();
            foreach ($data as $k => $v) {
                $arr[] = ($rel ? '"' . strtr($k, array('\\' => '\\\\', '"' => '\\"')) . '":' : '') . json_encode2($v);
            }
            return $rel ? '{' . join(',', $arr) . '}' : '[' . join(',', $arr) . ']';
        default:
            return '""';
    }
}
Esempio n. 2
0
 /**
  * @param Array $data Overview data from ClientsAction
  * @return string: HTML
  */
 protected function showOverview($data)
 {
     $context = $this->getContext();
     $request = $context->getRequest();
     $overview = $data['overview'];
     $clients = $data['clients'];
     $sortField = $request->getVal('sort', 'name');
     $sortDir = $request->getVal('sort_dir', 'asc');
     $navigationSort = array();
     foreach (array('name', 'updated') as $field) {
         $navigationSort[$field] = array('toggleQuery' => array('sort' => $field, 'sort_dir' => $sortDir === 'asc' ? 'desc' : null), 'arrowHtml' => $sortField !== $field ? '<b class="swarm-arrow-muted">' : ($sortDir === 'asc' ? '<b class="swarm-arrow-up">' : '<b class="swarm-arrow-down">'));
     }
     $html = '<table class="table table-striped">' . '<thead><tr>' . '<th class="swarm-toggle" data-toggle-query="' . htmlspecialchars(json_encode2($navigationSort['name']['toggleQuery'])) . '">User ' . $navigationSort['name']['arrowHtml'] . '</b></th>' . '<th>Clients</th>' . '<th class="span4 swarm-toggle" data-toggle-query="' . htmlspecialchars(json_encode2($navigationSort['updated']['toggleQuery'])) . '">Last ping ' . $navigationSort['updated']['arrowHtml'] . '</b></th>' . '</tr></thead>' . '<tbody>';
     foreach ($overview as $item) {
         $clientsHtml = '';
         if (!count($item['clientIDs'])) {
             $clientsHtml .= '<span class="muted">N/A</span>';
         } else {
             foreach ($item['clientIDs'] as $clientID) {
                 $clientsHtml .= html_tag_open('a', array('href' => $clients[$clientID]['viewUrl'])) . BrowserInfo::buildIconHtml($clients[$clientID]['uaData']['displayInfo'], array('size' => 'small', 'wrap' => false)) . '</a>';
             }
         }
         $html .= '<tr>' . '<td><a href="' . htmlspecialchars($item['viewUrl']) . '" title="View ' . htmlspecialchars($item['name']) . ' clients">' . htmlspecialchars($item['name']) . '</a></td>' . '<td>' . $clientsHtml . '</td>' . '<td>' . $this->getPrettyDateHtml($item, 'updated') . ' </td>' . '</tr>';
     }
     $html .= '</tbody></table>';
     return $html;
 }
Esempio n. 3
0
 protected function initContent()
 {
     $request = $this->getContext()->getRequest();
     $auth = $this->getContext()->getAuth();
     $this->setTitle("Job status");
     $this->setRobots('noindex,nofollow');
     $this->bodyScripts[] = swarmpath("js/job.js");
     $error = $this->getAction()->getError();
     $data = $this->getAction()->getData();
     $html = '';
     if ($error) {
         $html .= html_tag('div', array('class' => 'alert alert-error'), $error['info']);
     }
     if (!isset($data["info"])) {
         return $html;
     }
     $this->setSubTitle('#' . $data["info"]["id"]);
     $project = $data['info']['project'];
     $isOwner = $auth && $auth->project->id === $project['id'];
     $html .= '<h2>' . $data["info"]["nameHtml"] . '</h2>' . '<p><em>Submitted by ' . html_tag('a', array('href' => $project['viewUrl']), $project['display_title']) . ' ' . self::getPrettyDateHtml($data["info"], 'created') . '</em>.</p>';
     if ($isOwner) {
         $html .= '<script>SWARM.jobInfo = ' . json_encode2($data["info"]) . ';</script>';
         $action_bar = '<div class="form-actions swarm-item-actions">' . ' <button class="swarm-reset-runs-failed btn btn-info">Reset failed runs</button>' . ' <button class="swarm-reset-runs btn btn-info">Reset all runs</button>' . ' <button class="swarm-delete-job btn btn-danger">Delete job</button>' . '</div>' . '<div class="swarm-wipejob-error alert alert-error" style="display: none;"></div>';
     } else {
         $action_bar = '';
     }
     $html .= $action_bar;
     $html .= '<table class="table table-bordered swarm-results swarm-results-unbound-auth"><thead>' . self::getUaHtmlHeader($data['userAgents']) . '</thead><tbody>' . self::getUaRunsHtmlRows($data['runs'], $data['userAgents'], $isOwner) . '</tbody></table>';
     $html .= $action_bar;
     return $html;
 }
Esempio n. 4
0
function json_encode2($array, $NoNeedOpenList = false)
{
    $size = count($array);
    $current = 1;
    $json = "";
    if ($NoNeedOpenList == false) {
        $json .= '{';
    }
    foreach ($array as $key => $value) {
        if (!is_numeric($key)) {
            $json .= '"' . $key . '":{';
        }
        if (is_array($value)) {
            if (substr($json, -1) == "{") {
                $json .= json_encode2($value, true);
            } else {
                $json .= json_encode2($value);
            }
        } else {
            $json .= '"' . $value . '"';
        }
        if ($current < $size) {
            $json .= ",";
        }
        $current++;
    }
    $json .= "}";
    return $json;
}
Esempio n. 5
0
 /**
  * Produce JSON compliant content given a module object.\n
  * @param ModuleObject $oModule the module object
  * @return string
  */
 function toDoc(&$oModule)
 {
     $variables = $oModule->getVariables();
     $variables['error'] = $oModule->getError();
     $variables['message'] = $oModule->getMessage();
     $json = str_replace(array("\r\n", "\n", "\t"), array('\\n', '\\n', '\\t'), json_encode2($variables));
     return $json;
 }
    /**
     * Produce JSCallback compliant content given a module object.\n
     * @param ModuleObject $oModule the module object
     * @return string
     */
    function toDoc(&$oModule)
    {
        $variables = $oModule->getVariables();
        $variables['error'] = $oModule->getError();
        $variables['message'] = $oModule->getMessage();
        $json = str_replace(array("\r\n", "\n", "\t"), array('\\n', '\\n', '\\t'), json_encode2($variables));
        return sprintf('<script type="text/javascript">
//<![CDATA[
%s(%s);
//]]>
</script>', Context::getJSCallbackFunc(), $json);
    }
Esempio n. 7
0
 protected function initContent()
 {
     $browserInfo = $this->getContext()->getBrowserInfo();
     $conf = $this->getContext()->getConf();
     $request = $this->getContext()->getRequest();
     $this->setTitle('Test runner');
     $runToken = null;
     if ($conf->client->requireRunToken) {
         $runToken = $request->getVal("run_token");
         if (!$runToken) {
             return '<div class="alert alert-error">This swarm has restricted access to join the swarm.</div>';
         }
     }
     $this->bodyScripts[] = swarmpath("js/run.js?" . time());
     $client = Client::newFromContext($this->getContext(), $runToken);
     $html = '<script>' . 'SWARM.client_id = ' . json_encode2($client->getClientRow()->id) . ';' . 'SWARM.run_token = ' . json_encode2($runToken) . ';' . '</script>';
     $html .= '<div class="row">' . '<div class="span2">' . $browserInfo->getIconHtml() . '</div>' . '<div class="span7">' . '<h2>' . htmlspecialchars($client->getClientRow()->name) . '</h2>' . '<p><strong>Status:</strong> <span id="msg"></span></p>' . '</div>' . '</div>' . '<div class="well">' . '<h3>History</h3>' . '<ul id="history"></ul>' . '</div>' . '<div id="iframes"></div>';
     return $html;
 }
Esempio n. 8
0
 public function output()
 {
     switch ($this->format) {
         case 'json':
             header('Content-Type: application/json; charset=utf-8');
             echo json_encode2($this->response);
             break;
             // http://stackoverflow.com/a/8811412/319266
         // http://stackoverflow.com/a/8811412/319266
         case 'jsonp':
             header('Content-Type: text/javascript; charset=utf-8');
             $callback = $this->context->getRequest()->getVal('callback', '');
             echo preg_replace("/[^][.\\'\\\"_A-Za-z0-9]/", '', $callback) . '(' . json_encode2($this->response) . ')';
             break;
         case 'debug':
             $debugPage = ApiDebugPage::newFromContext($this->context);
             $debugPage->setApiResponse($this->response);
             $debugPage->output();
             break;
     }
 }
Esempio n. 9
0
    /**
     * Be careful to never throw exceptions from here if we're already
     * on the Error500Page. e.g. if content of FooPage is empty, this throws
     * an exception but then index.php instantiates a new page (Error500Page),
     * which does have content. So any exception thrown from here (either directly
     * or indirectly from an Action class), should either be caught or made sure
     * that it doesn't occurr for a Error500Page).
     */
    public function output()
    {
        $this->execute();
        if (!$this->getContent()) {
            throw new SwarmException('Page `content` must not be empty.');
        }
        if (!$this->getTitle()) {
            throw new SwarmException('Page `title` must not be empty.');
        }
        if (headers_sent($filename, $linenum)) {
            throw new SwarmException("Headers already sent in `{$filename}` on line {$linenum}.");
        }
        header('Content-Type: text/html; charset=UTF-8');
        $frameOptions = $this->getFrameOptions();
        if ($frameOptions) {
            header('X-Frame-Options: ' . $frameOptions, true);
        }
        $context = $this->getContext();
        $request = $context->getRequest();
        $auth = $context->getAuth();
        // ProjectsAction could throw an exception, which needs to be caught here,
        // since Error500Page (exception handler) also uses Page::output() eventually.
        // @todo: Find a cleaner way to deal with exceptions in the final page out,
        // because page output is also used on the Error500Page.
        $projects = array();
        if (!isset($this->exceptionObj)) {
            try {
                $projectsAction = ProjectsAction::newFromContext($context);
                $projectsAction->doAction();
                $projects = $projectsAction->getData();
            } catch (Exception $e) {
                $pageObj = Error500Page::newFromContext($context);
                $pageObj->setExceptionObj($e);
                $pageObj->output();
                exit;
            }
        }
        ?>
<!DOCTYPE html>
<html lang="en" dir="ltr" class="no-js">
<head>
<?php 
        foreach ($this->metaTags as $metaTag) {
            echo "\t" . html_tag('meta', $metaTag) . "\n";
        }
        $subTitleSuffix = $this->getSubTitle() ? ": {$this->getSubTitle()}" : "";
        $htmlTitle = $this->getTitle() . $subTitleSuffix . ' - ' . $context->getConf()->web->title;
        $displayTitleHtml = $this->getDisplayTitleHtml();
        ?>
	<title><?php 
        echo htmlentities($htmlTitle);
        ?>
</title>
	<link rel="stylesheet" href="<?php 
        echo swarmpath('external/bootstrap/css/bootstrap.css');
        ?>
">
	<link rel="stylesheet" href="<?php 
        echo swarmpath('external/bootstrap/css/bootstrap-responsive.css');
        ?>
">
	<link rel="stylesheet" href="<?php 
        echo swarmpath('css/testswarm.css');
        ?>
">
	<script>
	(function (h) { h.className = h.className.replace(/\bno-js\b/,'js')})(document.documentElement);
	SWARM = <?php 
        $infoAction = InfoAction::newFromContext($context);
        $infoAction->doAction();
        echo json_encode2($infoAction->getData());
        ?>
;
	SWARM.auth = <?php 
        echo json_encode2($auth);
        ?>
;
	</script>
<?php 
        foreach ($this->styleSheets as $styleSheet) {
            echo "\t" . html_tag('link', array('rel' => 'stylesheet', 'href' => $styleSheet)) . "\n";
        }
        foreach ($this->headScripts as $headScript) {
            echo "\t" . html_tag('script', array('src' => $headScript)) . "\n";
        }
        ?>
</head>
<body>
	<div class="navbar navbar-fixed-top">
		<div class="navbar-inner">
			<div class="container">
				<a class="brand" href="<?php 
        echo swarmpath('');
        ?>
"><?php 
        echo htmlspecialchars($context->getConf()->web->title);
        ?>
</a>
				<ul class="nav">
					<?php 
        echo $this->getPageLink('home', 'Home');
        ?>
					<li class="dropdown<?php 
        if (strpos($this->getSelfPath(), 'projects') === 0) {
            echo ' active';
        }
        ?>
">
						<a href="<?php 
        echo swarmpath('projects');
        ?>
" class="dropdown-toggle" data-toggle="dropdown">
							Projects
							<b class="caret"></b>
						</a>
						<ul class="dropdown-menu">
							<?php 
        echo $this->getPageLink('projects', 'All projects');
        ?>
							<li class="divider"></li>
							<li class="nav-header">Projects</li>
<?php 
        foreach ($projects as $project) {
            echo $this->getPageLink("project/{$project['id']}", $project['displayTitle']);
        }
        ?>
						</ul>
					</li>
					<?php 
        echo $this->getPageLink('clients', 'Clients');
        ?>
					<?php 
        echo $this->getPageLink('info', 'Info');
        ?>
				</ul>
				<ul class="nav pull-right">
<?php 
        if ($auth) {
            ?>
					<li><a href="<?php 
            echo htmlspecialchars(swarmpath("project/{$auth->project->id}"));
            ?>
"><?php 
            echo htmlspecialchars($auth->project->display_title);
            ?>
</a></li>
					<li><a href="<?php 
            echo swarmpath("addjob");
            ?>
">Add job</a></li>
					<li><a href="<?php 
            echo swarmpath('logout');
            ?>
" class="swarm-logout-link">Logout</a></li>
<?php 
        } else {
            echo $this->getPageLink('login', 'Login');
        }
        ?>
				</ul>
			</div>
		</div>
	</div>

	<div class="container">
		<div class="hero-unit">
			<h1><?php 
        echo $displayTitleHtml;
        ?>
</h1>
		</div>
<?php 
        echo $this->getContent();
        ?>

		<hr>
		<footer class="swarm-page-footer">
			<p>Powered by <a href="https://github.com/jquery/testswarm">TestSwarm</a>:
			<a href="https://github.com/jquery/testswarm">Source Code</a>
			| <a href="https://github.com/jquery/testswarm/issues">Issue Tracker</a>
			| <a href="https://github.com/jquery/testswarm/wiki">About</a>
			| <a href="https://twitter.com/testswarm">Twitter</a>
			</p>
		</footer>
	</div>
	<script src="<?php 
        echo swarmpath('external/jquery/jquery.js');
        ?>
"></script>
	<script src="<?php 
        echo swarmpath('external/bootstrap/js/bootstrap-dropdown.js');
        ?>
"></script>
	<script src="<?php 
        echo swarmpath('js/pretty.js');
        ?>
"></script>
	<script src="<?php 
        echo swarmpath('js/testswarm.js');
        ?>
"></script><?php 
        foreach ($this->bodyScripts as $bodyScript) {
            echo "\n\t" . html_tag('script', array('src' => $bodyScript));
        }
        if ($context->getConf()->debug->dbLogQueries) {
            $queryLog = $context->getDB()->getQueryLog();
            $queryLogHtml = '<hr><h3>Database query log</h3><div class="well"><ul class="unstyled">';
            foreach ($queryLog as $i => $queryInfo) {
                if ($i !== 0) {
                    $queryLogHtml .= '<hr>';
                }
                $queryLogHtml .= '<li>' . '<pre>' . htmlspecialchars($queryInfo["sql"]) . '</pre>' . '<table class="table table-bordered table-condensed"><tbody><tr>' . '<td>Caller: <code>' . htmlspecialchars($queryInfo['caller']) . '</code></td>' . '<td>Num rows: <code>' . htmlspecialchars($queryInfo['numRows']) . '</code></td>' . '<td>Insert ID: <code>' . htmlspecialchars($queryInfo['insertId']) . '</code></td>' . '<td>Affected rows: <code>' . htmlspecialchars($queryInfo['affectedRows']) . '</code></td>' . '<td>Query time: <code>' . htmlspecialchars(substr($queryInfo['queryTime'], 0, 8)) . '</code></td>' . '</tr></table>' . '</li>';
            }
            $queryLogHtml .= '</ul>';
            echo $queryLogHtml;
        }
        ?>
</body>
</html>
<?php 
        // End of Page::output
    }
    }
    $isList = true;
    for ($i = 0, reset($a); $i < count($a); $i++, next($a)) {
        if (key($a) !== $i) {
            $isList = false;
            break;
        }
    }
    $result = array();
    if ($isList) {
        foreach ($a as $v) {
            $result[] = json_encode($v);
        }
        return '[' . join(',', $result) . ']';
    } else {
        foreach ($a as $k => $v) {
            $result[] = json_encode($k) . ':' . json_encode($v);
        }
        return '{' . join(',', $result) . '}';
    }
}
$conn = new mysqli(DB_Host, DB_User, DB_Password, DB_Name) or die("Connection failed: " . $conn->connect_error);
$sql = "select *\n        from visualization3_t0 \n        union\n        select *\n        from visualization3_t1 \n        union\n        select *\n        from visualization3_t2 \n        union\n        select *\n        from visualization3_t3";
$records = array();
if ($result = mysqli_query($conn, $sql) or die(mysqli_error($conn))) {
    while ($obj = mysqli_fetch_object($result)) {
        $records[] = $obj;
    }
}
print json_encode2($records);
mysqli_close($conn);
Esempio n. 11
0
File: safe.php Progetto: rair/yacs
 /**
  * serialize an array the JSON way
  *
  * @param mixed the array to serialize
  * @return mixed a string, or FALSE on error
  */
 public static function json_encode($data)
 {
     global $context;
     // maybe we have a native extension
     if (is_callable('json_encode')) {
         return json_encode($data);
     }
     // load the PHP library
     if (file_exists($context['path_to_root'] . 'included/json.php')) {
         include_once $context['path_to_root'] . 'included/json.php';
         return json_encode2($data);
     }
     // tough luck
     return FALSE;
 }
Esempio n. 12
0
File: json.php Progetto: rair/yacs
/** function _name_value
 * array-walking function for use in generating JSON-formatted name-value pairs
 *
 * @param	string	$name	name of key to use
 * @param	mixed	$value	reference to an array element to be encoded
 *
 * @return	 string  JSON-formatted name-value pair, like '"name":value'
 * @access	 private
*/
function _name_value($name, $value)
{
    return sprintf("%s:%s", json_encode2(strval($name)), json_encode2($value));
}
Esempio n. 13
0
 /**
  * Get the current TestSwarm version (cached for 5 minutes).
  *
  * @param $options string|array: 'bypass-cache'
  * @return array (see also calculateVersionInfo)
  */
 public function getVersionInfo($options = array())
 {
     $options = (array) $options;
     if (in_array('bypass-cache', $options)) {
         return $this->calculateVersionInfo();
     }
     // Cache within the class, never calculate more than once per request
     if ($this->versionInfo !== null) {
         return $this->versionInfo;
     }
     // Deal with cache expiration
     $versionCacheFile = $this->getConf()->storage->cacheDir . '/version_info.json';
     if (is_readable($versionCacheFile)) {
         $versionCacheFileUpdated = filemtime($versionCacheFile);
         if ($versionCacheFileUpdated < strtotime('5 minutes ago')) {
             unlink($versionCacheFile);
         }
     }
     // If cache file (still) exists it means we can use it
     if (is_readable($versionCacheFile)) {
         $this->versionInfo = json_decode(file_get_contents($versionCacheFile), true);
         return $this->versionInfo;
     }
     // Calculate it and populate the class cache and file cache
     $this->versionInfo = $this->calculateVersionInfo();
     $isWritten = file_put_contents($versionCacheFile, json_encode2($this->versionInfo));
     if ($isWritten === false) {
         throw new SwarmException('Writing to cache directory failed.');
     }
     return $this->versionInfo;
 }
Esempio n. 14
0
 /**
  * @param $data mixed
  */
 protected final function setData($data)
 {
     // Recursively convert objects to arrays using json_decode/json_encode
     $this->data = json_decode(json_encode2($data), true);
 }
Esempio n. 15
0
File: tables.php Progetto: rair/yacs
 /**
  * build one table
  *
  * Accept following variants:
  * - csv - to provide a downloadable csv page
  * - json - to provide all values in one column
  * - inline - to render tables within articles
  * - simple - the legacy fixed table
  * - sortable - click on column to sort the row
  *
  * @param the id of the table to build
  * @param string the variant to provide - default is 'simple'
  * @return a displayable string
  */
 public static function build($id, $variant = 'simple')
 {
     global $context;
     // split parameters
     $attributes = preg_split("/\\s*,\\s*/", $id, 3);
     $id = $attributes[0];
     // get the table object
     if (!($table = Tables::get($id))) {
         return NULL;
     }
     // do the SELECT statement
     if (!($rows = SQL::query($table['query']))) {
         Logger::error(sprintf(i18n::s('Error in table query %s'), $id) . BR . htmlspecialchars($table['query']) . BR . SQL::error());
         return NULL;
     }
     // build the resulting string
     $text = '';
     switch ($variant) {
         // produce a table readable into MS-Excel
         case 'csv':
             // comma separated values
             $separator = ",";
             // one row for the title
             if ($table['title']) {
                 $label = preg_replace('/\\s/', ' ', $table['title']);
                 // encode to ASCII
                 $label = utf8::to_ascii($label, PRINTABLE_SAFE_ALPHABET);
                 // escape quotes to preserve them in the data
                 $label = str_replace('"', '""', $label);
                 $text .= '"' . $label . '"';
                 $text .= "\n";
             }
             // one row for header fields
             $index = 0;
             while ($field = SQL::fetch_field($rows)) {
                 if ($index++) {
                     $text .= $separator;
                 }
                 $label = trim(preg_replace('/\\s/', ' ', ucfirst($field->name)));
                 // encode
                 $label = utf8::to_ascii($label, PRINTABLE_SAFE_ALPHABET);
                 // escape quotes to preserve them in the data
                 $label = str_replace('"', '""', $label);
                 $text .= '"' . $label . '"';
             }
             $text .= "\n";
             // process every table row
             $row_index = 0;
             while ($row = SQL::fetch($rows)) {
                 // one cell at a time
                 $index = 0;
                 foreach ($row as $name => $value) {
                     // glue cells
                     if ($index++) {
                         $text .= $separator;
                     }
                     // remove HTML tags
                     $value = strip_tags(str_replace('</', ' </', str_replace(BR, ' / ', $value)));
                     // clean spaces
                     $label = trim(preg_replace('/\\s+/', ' ', $value));
                     // encode
                     $label = utf8::to_ascii($label, PRINTABLE_SAFE_ALPHABET);
                     // escape quotes to preserve them in the data
                     $label = str_replace('"', '""', $label);
                     // make a link if this is a reference
                     if ($index == 1 && $table['with_zoom'] == 'Y') {
                         $label = $context['url_to_home'] . $context['url_to_root'] . $label;
                     }
                     // quote data
                     $text .= '"' . $label . '"';
                 }
                 // new line
                 $text .= "\n";
             }
             return $text;
             // a JSON set of values
         // a JSON set of values
         case 'json':
             // get header labels
             $labels = array();
             while ($field = SQL::fetch_field($rows)) {
                 $labels[] = trim(preg_replace('/[^\\w]+/', '', ucfirst($field->name)));
             }
             // all items
             $data = array();
             $data['items'] = array();
             while ($row = SQL::fetch_row($rows)) {
                 // all rows
                 $datum = array();
                 $label = FALSE;
                 $index = 0;
                 $link = NULL;
                 foreach ($row as $name => $value) {
                     $index++;
                     // first column is only a link
                     if ($index == 1 && $table['with_zoom'] == 'Y') {
                         $link = $context['url_to_home'] . $context['url_to_root'] . ltrim($value, '/');
                         continue;
                     }
                     // adjust types to not fool the json encoder
                     if (preg_match('/^(\\+|-){0,1}[0-9]+$/', $value)) {
                         $value = intval($value);
                     } elseif (preg_match('/^(\\+|-){0,1}[0-9\\.,]+$/', $value)) {
                         $value = floatval($value);
                     } elseif (preg_match('/^(true|false)$/i', $value)) {
                         $value = intval($value);
                     }
                     // ensure we have some label for SIMILE Exhibit
                     if (!$label) {
                         $label = $value;
                     }
                     // combine first and second columns
                     if ($index == 2 && $link) {
                         $value = Skin::build_link($link, $value, 'basic');
                     }
                     // save this value
                     $datum[$labels[$name]] = utf8::to_ascii($value, PRINTABLE_SAFE_ALPHABET);
                 }
                 if ($label && !in_array('label', $labels)) {
                     $datum['label'] = utf8::to_ascii($label, PRINTABLE_SAFE_ALPHABET);
                 }
                 // add a tip, if any
                 $data['items'][] = $datum;
             }
             include_once $context['path_to_root'] . 'included/json.php';
             $text .= json_encode2($data);
             return $text;
             // list of facets for SIMILE Exhibit
         // list of facets for SIMILE Exhibit
         case 'json-facets':
             // columns are actual facets
             $facets = array();
             $index = 0;
             while ($field = SQL::fetch_field($rows)) {
                 $index++;
                 // first column is only a link
                 if ($index == 1 && $table['with_zoom'] == 'Y') {
                     continue;
                 }
                 // first column has a link
                 if ($index == 2 && $table['with_zoom'] == 'Y') {
                     continue;
                 }
                 // column is a facet
                 $label = '.' . trim(preg_replace('/[^\\w]+/', '', ucfirst($field->name)));
                 $title = trim(str_replace(',', '', ucfirst($field->name)));
                 $facets[] = '<div ex:role="facet" ex:expression="' . $label . '" ex:facetLabel="' . $title . '"></div>';
                 // only last columns can be faceted
                 if (count($facets) > 7) {
                     array_shift($facets);
                 }
             }
             // reverse facet order
             $facets = array_reverse($facets);
             // job done
             $text = join("\n", $facets);
             return $text;
             // list of columns for SIMILE Exhibit
         // list of columns for SIMILE Exhibit
         case 'json-labels':
             // get header labels
             $labels = array();
             $index = 0;
             while ($field = SQL::fetch_field($rows)) {
                 $index++;
                 // first column is only a link
                 if ($index == 1 && $table['with_zoom'] == 'Y') {
                     continue;
                 }
                 // column id
                 $labels[] = '.' . trim(preg_replace('/[^\\w]+/', '', ucfirst($field->name)));
                 // limit the number of columns put on screen
                 if (count($labels) >= 7) {
                     break;
                 }
             }
             // job done
             $text = join(', ', $labels);
             return $text;
             // titles of columns for SIMILE Exhibit
         // titles of columns for SIMILE Exhibit
         case 'json-titles':
             // get header labels
             $labels = array();
             $index = 0;
             while ($field = SQL::fetch_field($rows)) {
                 $index++;
                 // first column is only a link
                 if ($index == 1 && $table['with_zoom'] == 'Y') {
                     continue;
                 }
                 // column header
                 $labels[] = trim(str_replace(',', '', ucfirst($field->name)));
             }
             $text = join(', ', $labels);
             return $text;
             // produce an HTML table
         // produce an HTML table
         default:
         case 'inline':
         case 'sortable':
             // a table with a grid
             $text .= Skin::table_prefix('grid');
             // the title, with a menu to download the table into Excel
             if ($variant == 'inline') {
                 $item_bar = array();
                 $item_bar += array(Tables::get_url($id) => $table['title']);
                 $item_bar += array(Tables::get_url($id, 'fetch_as_csv') => 'CSV (Excel)');
                 if (Surfer::is_associate()) {
                     $item_bar += array(Tables::get_url($id, 'edit') => i18n::s('edit'));
                 }
                 if (count($item_bar)) {
                     $text .= '<caption>' . Skin::build_list($item_bar, 'menu') . "</caption>\n";
                 }
             }
             // column headers are clickable links
             $cells = array();
             $index = 0;
             while ($field = SQL::fetch_field($rows)) {
                 if ($index++ != 0 || $table['with_zoom'] != 'Y') {
                     $cells[] = ucfirst($field->name);
                 }
             }
             $text .= "\t\t" . Skin::table_row($cells, 'sortable');
             // the table body
             $count = 0;
             $row_index = 0;
             while ($row = SQL::fetch_row($rows)) {
                 $cells = array();
                 $link = '';
                 for ($index = 0; $index < count($row); $index++) {
                     if ($index == 0 && $table['with_zoom'] == 'Y') {
                         $link = $row[$index];
                     } elseif ($link) {
                         $cells[] = Skin::build_link($link, $row[$index]);
                         $link = '';
                     } else {
                         $cells[] = $row[$index];
                     }
                 }
                 $text .= "\t\t" . Skin::table_row($cells, $count++);
             }
             $text .= Skin::table_suffix();
             return $text;
             // adapted to open chart flash
         // adapted to open chart flash
         case 'chart':
             // get title for y series
             $y_title = $y2_title = $y3_title = NULL;
             $y_index = $y2_index = $y3_index = 0;
             $index = 0;
             while ($field = SQL::fetch_field($rows)) {
                 // time will be used for x labels
                 if ($index == 0 && $table['with_zoom'] == 'T') {
                 } elseif ($index == 0 && $table['with_zoom'] == 'Y') {
                 } elseif (!$y_title) {
                     $y_title = '"' . ucfirst($field->name) . '"';
                     $y_index = $index;
                 } elseif (!$y2_title) {
                     $y2_title = '"' . ucfirst($field->name) . '"';
                     $y2_index = $index;
                 } elseif (!$y3_title) {
                     $y3_title = '"' . ucfirst($field->name) . '"';
                     $y3_index = $index;
                     break;
                 }
                 $index++;
             }
             // process every table row
             $x_labels = array();
             $y_values = array();
             $y2_values = array();
             $y3_values = array();
             $y_min = $y_max = NULL;
             $count = 1;
             while ($row = SQL::fetch($rows)) {
                 // one cell at a time
                 $index = 0;
                 foreach ($row as $name => $value) {
                     // clean spaces
                     $label = trim(preg_replace('/\\s/', ' ', $value));
                     // encode in iso8859
                     $label = utf8::to_iso8859($label);
                     // escape quotes to preserve them in the data
                     $label = str_replace('"', '""', $label);
                     // quote data
                     if (preg_match('/-*[^0-9\\,\\.]/', $label)) {
                         $label = '"' . $label . '"';
                     }
                     // x labels
                     if ($index == 0) {
                         if ($table['with_zoom'] == 'T') {
                             array_unshift($x_labels, $label);
                         } else {
                             $x_labels[] = $count++;
                         }
                         // y value
                     } elseif ($index == $y_index) {
                         if ($table['with_zoom'] == 'T') {
                             array_unshift($y_values, $label);
                         } else {
                             $y_values[] = $label;
                         }
                         if (!isset($y_min) || intval($label) < $y_min) {
                             $y_min = intval($label);
                         }
                         if (!isset($y_max) || intval($label) > $y_max) {
                             $y_max = intval($label);
                         }
                         // y2 value
                     } elseif ($index == $y2_index) {
                         if ($table['with_zoom'] == 'T') {
                             array_unshift($y2_values, $label);
                         } else {
                             $y_values[] = $label;
                         }
                         if (!isset($y_min) || intval($label) < $y_min) {
                             $y_min = intval($label);
                         }
                         if (!isset($y_max) || intval($label) > $y_max) {
                             $y_max = intval($label);
                         }
                         // y3 value
                     } elseif ($index == $y3_index) {
                         if ($table['with_zoom'] == 'T') {
                             array_unshift($y3_values, $label);
                         } else {
                             $y_values[] = $label;
                         }
                         if (!isset($y_min) || intval($label) < $y_min) {
                             $y_min = intval($label);
                         }
                         if (!isset($y_max) || intval($label) > $y_max) {
                             $y_max = intval($label);
                         }
                         // we won't process the rest
                         break;
                     }
                     // next column
                     $index++;
                 }
             }
             // y minimum
             if ($y_min > 0) {
                 $y_min = 0;
             }
             // y maximum
             $y_max = strval($y_max);
             if (strlen($y_max) == 1) {
                 $y_max = 10;
             } elseif (strlen($y_max) == 2) {
                 $y_max = (intval(substr($y_max, 0, 1)) + 1) * 10;
             } elseif (strlen($y_max) == 3) {
                 $y_max = (intval(substr($y_max, 0, 2)) + 1) * 10;
             } else {
                 $y_max = strval(intval(substr($y_max, 0, 2)) + 1) . substr('0000000000000000000000000000000000000000000000000000', 0, strlen($y_max) - 2);
             }
             // data series
             $elements = array();
             if (count($y_values)) {
                 $elements[] = '{ "type":"bar_glass", "colour":"#BF3B69", "values": [ ' . join(',', $y_values) . ' ], "text": ' . $y_title . ', "font-size": 12 }';
             }
             if (count($y2_values)) {
                 $elements[] = '{ "type": "line", "width": 1, "colour": "#5E4725", "values": [ ' . join(',', $y2_values) . ' ], "text": ' . $y2_title . ', "font-size": 12 }';
             }
             if (count($y3_values)) {
                 $elements[] = '{ "type":"bar_glass", "colour":"#5E0722", "values": [ ' . join(',', $y3_values) . ' ], "text": ' . $y3_title . ', "font-size": 12 }';
             }
             // the full setup
             $text = '{ "elements": [ ' . join(',', $elements) . ' ], "x_axis": { "offset": false, "steps": 1, "labels": { "steps": 3, "rotate": 310, "labels": [ ' . join(',', $x_labels) . ' ] } }, "y_axis": { "min": ' . $y_min . ', "max": ' . $y_max . ' } }';
             return $text;
             // first number
         // first number
         case 'column':
             // comma separated values
             $separator = ",";
             // process every table row
             while ($row = SQL::fetch($rows)) {
                 // not always the first column
                 $index = 0;
                 foreach ($row as $name => $value) {
                     $index++;
                     // skip dates and links
                     if ($index == 1 && $table['with_zoom'] != 'N') {
                         continue;
                     }
                     // glue cells
                     if ($text) {
                         $text .= $separator;
                     }
                     // clean spaces
                     $label = trim(preg_replace('/\\s/', ' ', $value));
                     // encode in iso8859
                     $label = utf8::to_iso8859($label);
                     // escape quotes to preserve them in the data
                     $label = str_replace('"', '""', $label);
                     // quote data
                     if (preg_match('/[^a-zA-Z0-9\\,\\.\\-_]/', $label)) {
                         $text .= '"' . $label . '"';
                     } else {
                         $text .= $label;
                     }
                     // only first column
                     break;
                 }
             }
             return $text;
             // produce a raw table
         // produce a raw table
         case 'raw':
             // comma separated values
             $separator = ",";
             // process every table row
             while ($row = SQL::fetch($rows)) {
                 // one cell at a time
                 $index = 0;
                 foreach ($row as $name => $value) {
                     // glue cells
                     if ($index++) {
                         $text .= $separator;
                     }
                     // clean spaces
                     $label = trim(preg_replace('/\\s/', ' ', $value));
                     // encode in iso8859
                     $label = utf8::to_iso8859($label);
                     // escape quotes to preserve them in the data
                     $label = str_replace('"', '""', $label);
                     // make a link if this is a reference
                     if ($index == 0 && $table['with_zoom'] == 'Y') {
                         $label = $context['url_to_home'] . $context['url_to_root'] . $label;
                     }
                     // quote data
                     if (preg_match('/[^a-zA-Z0-9\\-_]/', $label)) {
                         $text .= '"' . $label . '"';
                     } else {
                         $text .= $label;
                     }
                 }
                 // new line
                 $text .= "\n";
             }
             return $text;
             // a simple table
         // a simple table
         case 'simple':
             $text .= Skin::table_prefix('table');
             // columns headers
             $index = 0;
             while ($field = SQL::fetch_field($rows)) {
                 $cells[] = ucfirst($field->name);
             }
             $text .= Skin::table_row($cells, 'header');
             // other rows
             while ($row = SQL::fetch_row($rows)) {
                 $text .= Skin::table_row($row, $count++);
             }
             $text .= Skin::table_suffix();
             return $text;
             // xml table
         // xml table
         case 'xml':
             $text = '';
             while ($row = SQL::fetch($rows)) {
                 $text .= '	<item>' . "\n";
                 foreach ($row as $name => $value) {
                     $type = preg_replace('/[^a-z0-9]+/i', '_', $name);
                     if (preg_match('/^[^a-z]/i', $type)) {
                         $type = '_' . $type;
                     }
                     $text .= '		<' . $type . '>' . preg_replace('/&(?!(amp|#\\d+);)/i', '&amp;', utf8::transcode(str_replace(array('left=', 'right='), '', $value))) . '</' . $type . '>' . "\n";
                 }
                 $text .= '	</item>' . "\n\n";
             }
             return '<?xml version="1.0" encoding="' . $context['charset'] . '"?>' . "\n" . '<items>' . "\n" . $text . '</items>' . "\n";
     }
 }
 /**
  * @brief RequestMethod가 JSON이면 JSON 데이터로 컨텐츠 생성
  **/
 function _toJSON(&$oModule)
 {
     $variables = $oModule->getVariables();
     $variables['error'] = $oModule->getError();
     $variables['message'] = $oModule->getMessage();
     $json = preg_replace("(\r\n|\n)", '\\n', json_encode2($variables));
     return $json;
 }
Esempio n. 17
0
/**
 * @file keyword_link.addon.php
 * @author sol (sol@ngleader.com)
 * @brief 키워드 링크 애드온
 **/
if ($called_position == 'after_module_proc' && Context::getResponseMethod() != "XMLRPC" && Context::getResponseMethod() != "JSON") {
    $json = array();
    $arg = array();
    for ($i = 1; $i <= 5; $i++) {
        $arg = array();
        $ii = sprintf("%02d", $i);
        $keyword = $addon_info->{"keyword" . $ii};
        $url = $addon_info->{"url" . $ii};
        if ($keyword && $url) {
            $arg['url'] = $url;
            $keyword = explode(",", $keyword);
            for ($j = 0, $c = count($keyword); $j < $c; $j++) {
                if (trim($keyword[$j]) == "") {
                    continue;
                }
                $arg['keyword'] = trim($keyword[$j]);
                $json[] = $arg;
            }
        }
    }
    if (count($json) > 0) {
        $addon_keyword_link = json_encode2($json);
        Context::addHtmlHeader("<script type=\"text/javascript\">//<![CDATA[\nvar addon_keyword_link={$addon_keyword_link};\nvar addon_keyword_link_cssquery='{$addon_info->cssquery}';\nvar addon_keyword_link_reg_type='{$addon_info->reg_type}';\n//]]></script>");
        Context::addJsFile('./addons/keyword_link/keyword_link.js');
    }
}