本文整理汇总了PHP中Piwik\Common::json_encode方法的典型用法代码示例。如果您正苦于以下问题:PHP Common::json_encode方法的具体用法?PHP Common::json_encode怎么用?PHP Common::json_encode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Piwik\Common
的用法示例。
在下文中一共展示了Common::json_encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: index
public function index()
{
$view = new View('@Widgetize/index');
$view->availableWidgets = Common::json_encode(WidgetsList::get());
$this->setGeneralVariablesView($view);
return $view->render();
}
示例2: getSelector
public function getSelector()
{
$view = new View('@SegmentEditor/getSelector');
$idSite = Common::getRequestVar('idSite');
$this->setGeneralVariablesView($view);
$segments = APIMetadata::getInstance()->getSegmentsMetadata($idSite);
$segmentsByCategory = $customVariablesSegments = array();
foreach ($segments as $segment) {
if ($segment['category'] == Piwik::translate('General_Visit') && ($segment['type'] == 'metric' && $segment['segment'] != 'visitIp')) {
$metricsLabel = Piwik::translate('General_Metrics');
$metricsLabel[0] = strtolower($metricsLabel[0]);
$segment['category'] .= ' (' . $metricsLabel . ')';
}
$segmentsByCategory[$segment['category']][] = $segment;
}
uksort($segmentsByCategory, array($this, 'sortSegmentCategories'));
$view->segmentsByCategory = $segmentsByCategory;
$savedSegments = API::getInstance()->getAll($idSite);
foreach ($savedSegments as &$savedSegment) {
$savedSegment['name'] = Common::sanitizeInputValue($savedSegment['name']);
}
$view->savedSegmentsJson = Common::json_encode($savedSegments);
$view->authorizedToCreateSegments = !Piwik::isUserIsAnonymous();
$view->segmentTranslations = Common::json_encode($this->getTranslations());
$out = $view->render();
return $out;
}
示例3: update
static function update()
{
Updater::updateDatabase(__FILE__, self::getSql());
if (!\Piwik\Plugin\Manager::getInstance()->isPluginLoaded('ScheduledReports')) {
return;
}
try {
// Common::prefixTable('pdf') has been heavily refactored to be more generic
// The following actions are taken in this update script :
// - create the new generic report table Common::prefixTable('report')
// - migrate previous reports, if any, from Common::prefixTable('pdf') to Common::prefixTable('report')
// - delete Common::prefixTable('pdf')
$reports = Db::fetchAll('SELECT * FROM `' . Common::prefixTable('pdf') . '`');
foreach ($reports as $report) {
$idreport = $report['idreport'];
$idsite = $report['idsite'];
$login = $report['login'];
$description = $report['description'];
$period = $report['period'];
$format = $report['format'];
$display_format = $report['display_format'];
$email_me = $report['email_me'];
$additional_emails = $report['additional_emails'];
$reports = $report['reports'];
$ts_created = $report['ts_created'];
$ts_last_sent = $report['ts_last_sent'];
$deleted = $report['deleted'];
$parameters = array();
if (!is_null($additional_emails)) {
$parameters[ScheduledReports::ADDITIONAL_EMAILS_PARAMETER] = preg_split('/,/', $additional_emails);
}
$parameters[ScheduledReports::EMAIL_ME_PARAMETER] = is_null($email_me) ? ScheduledReports::EMAIL_ME_PARAMETER_DEFAULT_VALUE : (bool) $email_me;
$parameters[ScheduledReports::DISPLAY_FORMAT_PARAMETER] = $display_format;
Db::query('INSERT INTO `' . Common::prefixTable('report') . '` SET
idreport = ?, idsite = ?, login = ?, description = ?, period = ?,
type = ?, format = ?, reports = ?, parameters = ?, ts_created = ?,
ts_last_sent = ?, deleted = ?', array($idreport, $idsite, $login, $description, is_null($period) ? ScheduledReports::DEFAULT_PERIOD : $period, ScheduledReports::EMAIL_TYPE, is_null($format) ? ScheduledReports::DEFAULT_REPORT_FORMAT : $format, Common::json_encode(preg_split('/,/', $reports)), Common::json_encode($parameters), $ts_created, $ts_last_sent, $deleted));
}
Db::query('DROP TABLE `' . Common::prefixTable('pdf') . '`');
} catch (\Exception $e) {
}
}
示例4: startOverlaySession
/**
* Start an Overlay session: Redirect to the tracked website. The Piwik
* tracker will recognize this referrer and start the session.
*/
public function startOverlaySession()
{
$idSite = Common::getRequestVar('idSite', 0, 'int');
Piwik::checkUserHasViewAccess($idSite);
$sitesManager = APISitesManager::getInstance();
$site = $sitesManager->getSiteFromId($idSite);
$urls = $sitesManager->getSiteUrlsFromId($idSite);
@header('Content-Type: text/html; charset=UTF-8');
return '
<html><head><title></title></head><body>
<script type="text/javascript">
function handleProtocol(url) {
if (' . (ProxyHttp::isHttps() ? 'true' : 'false') . ') {
return url.replace(/http:\\/\\//i, "https://");
} else {
return url.replace(/https:\\/\\//i, "http://");
}
}
function removeUrlPrefix(url) {
return url.replace(/http(s)?:\\/\\/(www\\.)?/i, "");
}
if (window.location.hash) {
var match = false;
var urlToRedirect = window.location.hash.substr(1);
var urlToRedirectWithoutPrefix = removeUrlPrefix(urlToRedirect);
var knownUrls = ' . Common::json_encode($urls) . ';
for (var i = 0; i < knownUrls.length; i++) {
var testUrl = removeUrlPrefix(knownUrls[i]);
if (urlToRedirectWithoutPrefix.substr(0, testUrl.length) == testUrl) {
match = true;
if (navigator.appName == "Microsoft Internet Explorer") {
// internet explorer loses the referrer if we use window.location.href=X
var referLink = document.createElement("a");
referLink.href = handleProtocol(urlToRedirect);
document.body.appendChild(referLink);
referLink.click();
} else {
window.location.href = handleProtocol(urlToRedirect);
}
break;
}
}
if (!match) {
var idSite = window.location.href.match(/idSite=([0-9]+)/i)[1];
window.location.href = "index.php?module=Overlay&action=showErrorWrongDomain"
+ "&idSite=" + idSite
+ "&url=" + encodeURIComponent(urlToRedirect);
}
}
else {
window.location.href = handleProtocol("' . $site['main_url'] . '");
};
</script>
</body></html>
';
}
示例5: index
public function index()
{
$view = $this->getOverviewView();
// unsanitize goal names and other text data (not done in API so as not to break
// any other code/cause security issues)
$goals = $this->goals;
foreach ($goals as &$goal) {
$goal['name'] = Common::unsanitizeInputValue($goal['name']);
if (isset($goal['pattern'])) {
$goal['pattern'] = Common::unsanitizeInputValue($goal['pattern']);
}
}
$view->goalsJSON = Common::json_encode($goals);
$view->userCanEditGoals = Piwik::isUserHasAdminAccess($this->idSite);
$view->ecommerceEnabled = $this->site->isEcommerceEnabled();
$view->displayFullReport = true;
return $view->render();
}
示例6: addSendMailHook
public static function addSendMailHook()
{
Piwik::addAction('Test.Mail.send', function ($mail) {
$outputFile = PIWIK_INCLUDE_PATH . '/tmp/' . Common::getRequestVar('module', '') . '.' . Common::getRequestVar('action', '') . '.mail.json';
$outputContent = str_replace("=\n", "", $mail->getBodyText($textOnly = true));
$outputContent = str_replace("=0A", "\n", $outputContent);
$outputContent = str_replace("=3D", "=", $outputContent);
$outputContents = array('from' => $mail->getFrom(), 'to' => $mail->getRecipients(), 'subject' => $mail->getSubject(), 'contents' => $outputContent);
file_put_contents($outputFile, Common::json_encode($outputContents));
});
}
示例7: getJavascriptTranslations
/**
* Generate javascript translations array
*/
public static function getJavascriptTranslations()
{
$translations =& $GLOBALS['Piwik_translations'];
$clientSideTranslations = array();
foreach (self::getClientSideTranslationKeys() as $key) {
list($plugin, $stringName) = explode("_", $key, 2);
$clientSideTranslations[$key] = $translations[$plugin][$stringName];
}
$js = 'var translations = ' . Common::json_encode($clientSideTranslations) . ';';
$js .= "\n" . 'if (typeof(piwik_translations) == \'undefined\') { var piwik_translations = new Object; }' . 'for(var i in translations) { piwik_translations[i] = translations[i];} ';
return $js;
}
示例8: getJavascriptTranslations
/**
* Generate javascript translations array
*/
public static function getJavascriptTranslations()
{
$translations =& $GLOBALS['Piwik_translations'];
$clientSideTranslations = array();
foreach (self::getClientSideTranslationKeys() as $key) {
list($plugin, $stringName) = explode("_", $key, 2);
$clientSideTranslations[$key] = $translations[$plugin][$stringName];
}
$js = 'var translations = ' . Common::json_encode($clientSideTranslations) . ';';
$js .= "\n" . 'if(typeof(piwik_translations) == \'undefined\') { var piwik_translations = new Object; }' . 'for(var i in translations) { piwik_translations[i] = translations[i];} ';
$js .= 'function _pk_translate(translationStringId) { ' . 'if( typeof(piwik_translations[translationStringId]) != \'undefined\' ){ return piwik_translations[translationStringId]; }' . 'return "The string "+translationStringId+" was not loaded in javascript. Make sure it is added in the Translate.getClientSideTranslationKeys hook.";}';
return $js;
}
示例9: end
/**
* Cleanup
*/
protected function end()
{
if ($this->usingBulkTracking) {
$result = array('status' => 'success', 'tracked' => $this->countOfLoggedRequests);
Common::sendHeader('Content-Type: application/json');
echo Common::json_encode($result);
exit;
}
switch ($this->getState()) {
case self::STATE_LOGGING_DISABLE:
$this->outputTransparentGif();
Common::printDebug("Logging disabled, display transparent logo");
break;
case self::STATE_EMPTY_REQUEST:
Common::printDebug("Empty request => Piwik page");
echo "<a href='/'>Piwik</a> is a free/libre web <a href='http://piwik.org'>analytics</a> that lets you keep control of your data.";
break;
case self::STATE_NOSCRIPT_REQUEST:
case self::STATE_NOTHING_TO_NOTICE:
default:
$this->outputTransparentGif();
Common::printDebug("Nothing to notice => default behaviour");
break;
}
Common::printDebug("End of the page.");
if ($GLOBALS['PIWIK_TRACKER_DEBUG'] === true) {
if (isset(self::$db)) {
self::$db->recordProfiling();
Profiler::displayDbTrackerProfile(self::$db);
}
}
self::disconnectDatabase();
}
示例10: copyDashboardToUser
public function copyDashboardToUser()
{
$this->checkTokenInUrl();
if (!Piwik::hasUserSuperUserAccess()) {
return '0';
}
$login = Piwik::getCurrentUserLogin();
$name = urldecode(Common::getRequestVar('name', '', 'string'));
$user = urldecode(Common::getRequestVar('user', '', 'string'));
$idDashboard = Common::getRequestVar('dashboardId', 0, 'int');
$layout = $this->dashboard->getLayoutForUser($login, $idDashboard);
if ($layout !== false) {
$nextId = $this->getModel()->createNewDashboardForUser($user, $name, $layout);
Json::sendHeaderJSON();
return Common::json_encode($nextId);
}
}
示例11: downloadMissingGeoIpDb
/**
* Starts or continues a download for a missing GeoIP database. A database is missing if
* it has an update URL configured, but the actual database is not available in the misc
* directory.
*
* Input:
* 'url' - The URL to download the database from.
* 'continue' - 1 if we're continuing a download, 0 if we're starting one.
*
* Output:
* 'error' - If an error occurs this describes the error.
* 'to_download' - The URL of a missing database that should be downloaded next (if any).
* 'to_download_label' - The label to use w/ the progress bar that describes what we're
* downloading.
* 'current_size' - Size of the current file on disk.
* 'expected_file_size' - Size of the completely downloaded file.
*/
public function downloadMissingGeoIpDb()
{
$this->dieIfGeolocationAdminIsDisabled();
Piwik::checkUserHasSuperUserAccess();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
try {
$this->checkTokenInUrl();
Json::sendHeaderJSON();
// based on the database type (provided by the 'key' query param) determine the
// url & output file name
$key = Common::getRequestVar('key', null, 'string');
$url = GeoIPAutoUpdater::getConfiguredUrl($key);
$ext = GeoIPAutoUpdater::getGeoIPUrlExtension($url);
$filename = GeoIp::$dbNames[$key][0] . '.' . $ext;
if (substr($filename, 0, 15) == 'GeoLiteCity.dat') {
$filename = 'GeoIPCity.dat' . substr($filename, 15);
}
$outputPath = GeoIp::getPathForGeoIpDatabase($filename);
// download part of the file
$result = Http::downloadChunk($url, $outputPath, Common::getRequestVar('continue', true, 'int'));
// if the file is done
if ($result['current_size'] >= $result['expected_file_size']) {
GeoIPAutoUpdater::unzipDownloadedFile($outputPath, $unlink = true);
$info = $this->getNextMissingDbUrlInfo();
if ($info !== false) {
return Common::json_encode($info);
}
}
return Common::json_encode($result);
} catch (Exception $ex) {
return Common::json_encode(array('error' => $ex->getMessage()));
}
}
}
示例12: encodeLayout
public function encodeLayout($layout)
{
return Common::json_encode($layout);
}
示例13: setupDashboards
/** Creates two dashboards that split the widgets up into different groups. */
public function setupDashboards()
{
$dashboardColumnCount = 3;
$dashboardCount = 4;
$layout = array();
for ($j = 0; $j != $dashboardColumnCount; ++$j) {
$layout[] = array();
}
$dashboards = array();
for ($i = 0; $i != $dashboardCount; ++$i) {
$dashboards[] = $layout;
}
$oldGet = $_GET;
$_GET['idSite'] = 1;
// collect widgets & sort them so widget order is not important
$allWidgets = array();
foreach (WidgetsList::get() as $category => $widgets) {
$allWidgets = array_merge($allWidgets, $widgets);
}
usort($allWidgets, function ($lhs, $rhs) {
return strcmp($lhs['uniqueId'], $rhs['uniqueId']);
});
$widgetsPerDashboard = ceil(count($allWidgets) / $dashboardCount);
// group widgets so they will be spread out across 3 dashboards
$groupedWidgets = array();
$dashboard = 0;
foreach ($allWidgets as $widget) {
if ($widget['uniqueId'] == 'widgetSEOgetRank' || $widget['uniqueId'] == 'widgetReferrersgetKeywordsForPage' || $widget['uniqueId'] == 'widgetLivegetVisitorProfilePopup' || $widget['uniqueId'] == 'widgetActionsgetPageTitles' || strpos($widget['uniqueId'], 'widgetExample') === 0) {
continue;
}
$widgetEntry = array('uniqueId' => $widget['uniqueId'], 'parameters' => $widget['parameters']);
// dashboard images must have height of less than 4000px to avoid odd discoloration of last line of image
$widgetEntry['parameters']['filter_limit'] = 5;
$groupedWidgets[$dashboard][] = $widgetEntry;
if (count($groupedWidgets[$dashboard]) >= $widgetsPerDashboard) {
$dashboard = $dashboard + 1;
}
// sanity check
if ($dashboard >= $dashboardCount) {
throw new Exception("Unexpected error: Incorrect dashboard widget placement logic. Something's wrong w/ the code.");
}
}
// distribute widgets in each dashboard
$column = 0;
foreach ($groupedWidgets as $dashboardIndex => $dashboardWidgets) {
foreach ($dashboardWidgets as $widget) {
$column = ($column + 1) % $dashboardColumnCount;
$dashboards[$dashboardIndex][$column][] = $widget;
}
}
foreach ($dashboards as $id => $layout) {
if ($id == 0) {
$_GET['name'] = self::makeXssContent('dashboard name' . $id);
} else {
$_GET['name'] = 'dashboard name' . $id;
}
$_GET['layout'] = Common::json_encode($layout);
$_GET['idDashboard'] = $id + 1;
FrontController::getInstance()->fetchDispatch('Dashboard', 'saveLayout');
}
// create empty dashboard
$dashboard = array(array(array('uniqueId' => "widgetVisitsSummarygetEvolutionGraphcolumnsArray", 'parameters' => array('module' => 'VisitsSummary', 'action' => 'getEvolutionGraph', 'columns' => 'nb_visits'))), array(), array());
$_GET['name'] = 'D4';
$_GET['layout'] = Common::json_encode($dashboard);
$_GET['idDashboard'] = 5;
$_GET['idSite'] = 2;
FrontController::getInstance()->fetchDispatch('Dashboard', 'saveLayout');
$_GET = $oldGet;
}
示例14: validateRequestedReports
private static function validateRequestedReports($idSite, $reportType, $requestedReports)
{
if (!self::allowMultipleReports($reportType)) {
//sms can only contain one report, we silently discard all but the first
$requestedReports = array_slice($requestedReports, 0, 1);
}
// retrieve available reports
$availableReportMetadata = self::getReportMetadata($idSite, $reportType);
$availableReportIds = array();
foreach ($availableReportMetadata as $reportMetadata) {
$availableReportIds[] = $reportMetadata['uniqueId'];
}
foreach ($requestedReports as $report) {
if (!in_array($report, $availableReportIds)) {
throw new Exception("Report {$report} is unknown or not available for report type '{$reportType}'.");
}
}
return Common::json_encode($requestedReports);
}
示例15: copyDashboardToUser
public function copyDashboardToUser()
{
$this->checkTokenInUrl();
if (!Piwik::hasUserSuperUserAccess()) {
return '0';
}
$login = Piwik::getCurrentUserLogin();
$name = urldecode(Common::getRequestVar('name', '', 'string'));
$user = urldecode(Common::getRequestVar('user', '', 'string'));
$idDashboard = Common::getRequestVar('dashboardId', 0, 'int');
$layout = $this->dashboard->getLayoutForUser($login, $idDashboard);
if ($layout !== false) {
$nextId = $this->getNextIdDashboard($user);
$query = sprintf('INSERT INTO %s (login, iddashboard, name, layout) VALUES (?, ?, ?, ?)', Common::prefixTable('user_dashboard'));
Db::query($query, array($user, $nextId, $name, $layout));
Json::sendHeaderJSON();
return Common::json_encode($nextId);
}
}