json_encode() public static method

JSON encode wrapper - missing or broken in some php 5.x versions
Deprecation:
public static json_encode ( mixed $value ) : string
$value mixed
return string
Example #1
0
 public function index()
 {
     $view = new View('@Widgetize/index');
     $view->availableWidgets = Common::json_encode(WidgetsList::get());
     $this->setGeneralVariablesView($view);
     return $view->render();
 }
 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;
 }
Example #3
0
 public function index()
 {
     $view = new View('@ScheduledReports/index');
     $this->setGeneralVariablesView($view);
     $view->countWebsites = count(APISitesManager::getInstance()->getSitesIdWithAtLeastViewAccess());
     // get report types
     $reportTypes = API::getReportTypes();
     $view->reportTypes = $reportTypes;
     $view->defaultReportType = self::DEFAULT_REPORT_TYPE;
     $view->defaultReportFormat = ScheduledReports::DEFAULT_REPORT_FORMAT;
     $view->displayFormats = ScheduledReports::getDisplayFormats();
     $reportsByCategoryByType = array();
     $reportFormatsByReportType = array();
     $allowMultipleReportsByReportType = array();
     foreach ($reportTypes as $reportType => $reportTypeIcon) {
         // get report formats
         $reportFormatsByReportType[$reportType] = API::getReportFormats($reportType);
         $allowMultipleReportsByReportType[$reportType] = API::allowMultipleReports($reportType);
         // get report metadata
         $reportsByCategory = array();
         $availableReportMetadata = API::getReportMetadata($this->idSite, $reportType);
         foreach ($availableReportMetadata as $reportMetadata) {
             $reportsByCategory[$reportMetadata['category']][] = $reportMetadata;
         }
         $reportsByCategoryByType[$reportType] = $reportsByCategory;
     }
     $view->reportsByCategoryByReportType = $reportsByCategoryByType;
     $view->reportFormatsByReportType = $reportFormatsByReportType;
     $view->allowMultipleReportsByReportType = $allowMultipleReportsByReportType;
     $reports = array();
     $reportsById = array();
     if (!Piwik::isUserIsAnonymous()) {
         $reports = API::getInstance()->getReports($this->idSite, $period = false, $idReport = false, $ifSuperUserReturnOnlySuperUserReports = true);
         foreach ($reports as &$report) {
             $report['recipients'] = API::getReportRecipients($report);
             $reportsById[$report['idreport']] = $report;
         }
     }
     $view->reports = $reports;
     $view->reportsJSON = Common::json_encode($reportsById);
     $view->downloadOutputType = API::OUTPUT_INLINE;
     $view->periods = ScheduledReports::getPeriodToFrequency();
     $view->defaultPeriod = ScheduledReports::DEFAULT_PERIOD;
     $view->defaultHour = ScheduledReports::DEFAULT_HOUR;
     $view->language = LanguagesManager::getLanguageCodeForCurrentUser();
     $view->segmentEditorActivated = false;
     if (API::isSegmentEditorActivated()) {
         $savedSegmentsById = array();
         foreach (APISegmentEditor::getInstance()->getAll($this->idSite) as $savedSegment) {
             $savedSegmentsById[$savedSegment['idsegment']] = $savedSegment['name'];
         }
         $view->savedSegmentsById = $savedSegmentsById;
         $view->segmentEditorActivated = true;
     }
     return $view->render();
 }
Example #4
0
    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) {
        }
    }
Example #5
0
 /**
  * Main view showing listing of websites and settings
  */
 public function index()
 {
     $view = new View('@SitesManager/index');
     Site::clearCache();
     $sites = API::getInstance()->getSitesWithAdminAccess();
     foreach ($sites as &$site) {
         $site['alias_urls'] = API::getInstance()->getSiteUrlsFromId($site['idsite']);
         $site['excluded_ips'] = explode(',', $site['excluded_ips']);
         $site['excluded_parameters'] = explode(',', $site['excluded_parameters']);
         $site['excluded_user_agents'] = explode(',', $site['excluded_user_agents']);
     }
     $view->adminSites = $sites;
     $view->adminSitesCount = count($sites);
     $timezones = API::getInstance()->getTimezonesList();
     $view->timezoneSupported = SettingsServer::isTimezoneSupportEnabled();
     $view->timezones = Common::json_encode($timezones);
     $view->defaultTimezone = API::getInstance()->getDefaultTimezone();
     $view->currencies = Common::json_encode(API::getInstance()->getCurrencyList());
     $view->defaultCurrency = API::getInstance()->getDefaultCurrency();
     $view->utcTime = Date::now()->getDatetime();
     $excludedIpsGlobal = API::getInstance()->getExcludedIpsGlobal();
     $view->globalExcludedIps = str_replace(',', "\n", $excludedIpsGlobal);
     $excludedQueryParametersGlobal = API::getInstance()->getExcludedQueryParametersGlobal();
     $view->globalExcludedQueryParameters = str_replace(',', "\n", $excludedQueryParametersGlobal);
     $globalExcludedUserAgents = API::getInstance()->getExcludedUserAgentsGlobal();
     $view->globalExcludedUserAgents = str_replace(',', "\n", $globalExcludedUserAgents);
     $view->globalSearchKeywordParameters = API::getInstance()->getSearchKeywordParametersGlobal();
     $view->globalSearchCategoryParameters = API::getInstance()->getSearchCategoryParametersGlobal();
     $view->isSearchCategoryTrackingEnabled = \Piwik\Plugin\Manager::getInstance()->isPluginActivated('CustomVariables');
     $view->allowSiteSpecificUserAgentExclude = API::getInstance()->isSiteSpecificUserAgentExcludeEnabled();
     $view->globalKeepURLFragments = API::getInstance()->getKeepURLFragmentsGlobal();
     $view->currentIpAddress = IP::getIpFromHeader();
     $view->showAddSite = (bool) Common::getRequestVar('showaddsite', false);
     $this->setBasicVariablesView($view);
     return $view->render();
 }
Example #6
0
    /**
     * 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>
		';
    }
 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();
 }
Example #8
0
 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));
     });
 }
Example #9
0
 /**
  * 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;
 }
Example #10
0
 /**
  * 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;
 }
Example #11
0
 /**
  * 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();
 }
Example #12
0
 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);
     }
 }
Example #13
0
 /**
  * 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()));
         }
     }
 }
Example #14
0
 public function encodeLayout($layout)
 {
     return Common::json_encode($layout);
 }
Example #15
0
 /** 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;
 }
Example #16
0
 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);
 }
Example #17
0
 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);
     }
 }
Example #18
0
 private function getEnrichedRequest($params, $encode = true)
 {
     $params['format'] = 'json';
     $params['showRawMetrics'] = 1;
     if (empty($params['segment'])) {
         $segment = \Piwik\API\Request::getRawSegmentFromRequest();
         if (!empty($segment)) {
             $params['segment'] = urldecode($segment);
         }
     }
     if ($encode) {
         $params = Common::json_encode($params);
     }
     return $params;
 }
Example #19
0
 private function setUserSettings($user, $settings)
 {
     Option::set($user . MobileMessaging::USER_SETTINGS_POSTFIX_OPTION, Common::json_encode($settings));
 }
Example #20
0
 function getSitesForAutocompleter()
 {
     $pattern = Common::getRequestVar('term');
     $sites = API::getInstance()->getPatternMatchSites($pattern);
     $pattern = str_replace('%', '', $pattern);
     if (!count($sites)) {
         $results[] = array('label' => Piwik::translate('SitesManager_NotFound') . "&nbsp;<span class='autocompleteMatched'>{$pattern}</span>.", 'id' => '#');
     } else {
         if (strpos($pattern, '/') !== false && strpos($pattern, '\\/') === false) {
             $pattern = str_replace('/', '\\/', $pattern);
         }
         foreach ($sites as $s) {
             $siteName = Site::getNameFor($s['idsite']);
             $label = $siteName;
             if (strlen($pattern) > 0) {
                 @preg_match_all("/{$pattern}+/i", $label, $matches);
                 if (is_array($matches[0]) && count($matches[0]) >= 1) {
                     foreach ($matches[0] as $match) {
                         $label = str_replace($match, '<span class="autocompleteMatched">' . $match . '</span>', $siteName);
                     }
                 }
             }
             $results[] = array('label' => $label, 'id' => $s['idsite'], 'name' => $siteName);
         }
     }
     Json::sendHeaderJSON();
     print Common::json_encode($results);
 }