Commit 1059988c authored by ale's avatar ale Committed by lucha

[auto] Plugin: wp-piwik 1.0.3

parent 0474baa7
<?php
namespace WP_Piwik;
abstract class Admin {
protected static $wpPiwik, $pageID, $settings;
public function __construct($wpPiwik, $settings) {
self::$wpPiwik = $wpPiwik;
self::$settings = $settings;
}
abstract public function show();
abstract public function printAdminScripts();
abstract public function extendAdminHeader();
public function printAdminStyles() {
wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css', array(), self::$wpPiwik->getPluginVersion());
}
public function onLoad() {}
}
\ No newline at end of file
<?php
namespace WP_Piwik\Admin;
class Network extends \WP_Piwik\Admin\Statistics {
public function show() {
parent::show();
}
public function printAdminScripts() {
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script('wp-piwik-jqplot', self::$wpPiwik->getPluginURL().'js/jqplot/wp-piwik.jqplot.js',array('jquery'), self::$wpPiwik->getPluginVersion());
}
public function extendAdminHeader() {
echo '<!--[if IE]><script language="javascript" type="text/javascript" src="'.(parent::$wpPiwik->getPluginURL()).'js/jqplot/excanvas.min.js"></script><![endif]-->';
echo '<link rel="stylesheet" href="'.(parent::$wpPiwik->getPluginURL()).'js/jqplot/jquery.jqplot.min.css" type="text/css"/>';
echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
}
public function onLoad() {
self::$wpPiwik->onloadStatsPage(self::$pageID);
}
}
\ No newline at end of file
<?php
namespace WP_Piwik\Admin;
if (! class_exists ( 'WP_List_Table' ))
require_once (ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
class Sitebrowser extends \WP_List_Table {
private $data = array (), $wpPiwik;
public function __construct($wpPiwik) {
$this->wpPiwik = $wpPiwik;
$cnt = $this->prepare_items ();
global $status, $page;
parent::__construct ( array (
'singular' => __ ( 'site', 'wp-piwik' ),
'plural' => __ ( 'sites', 'wp-piwik' ),
'ajax' => false
) );
if ($cnt > 0)
$this->display ();
else
echo '<p>' . __ ( 'No site configured yet.', 'wp-piwik' ) . '</p>';
}
public function get_columns() {
$columns = array (
'id' => __ ( 'Blog ID', 'wp-piwik' ),
'name' => __ ( 'Title', 'wp-piwik' ),
'siteurl' => __ ( 'URL', 'wp-piwik' ),
'piwikid' => __ ( 'Site ID (Piwik)', 'wp-piwik' )
);
return $columns;
}
public function prepare_items() {
$current_page = $this->get_pagenum ();
$per_page = 10;
global $blog_id;
global $wpdb;
global $pagenow;
if (is_plugin_active_for_network ( 'wp-piwik/wp-piwik.php' )) {
$total_items = $wpdb->get_var ( 'SELECT COUNT(*) FROM ' . $wpdb->blogs );
$blogs = \WP_Piwik\Settings::getBlogList($per_page, $current_page);
foreach ( $blogs as $blog ) {
$blogDetails = get_blog_details ( $blog['blog_id'], true );
$this->data [] = array (
'name' => $blogDetails->blogname,
'id' => $blogDetails->blog_id,
'siteurl' => $blogDetails->siteurl,
'piwikid' => $this->wpPiwik->getPiwikSiteId ( $blogDetails->blog_id )
);
}
} else {
$blogDetails = get_bloginfo ();
$this->data [] = array (
'name' => get_bloginfo ( 'name' ),
'id' => '-',
'siteurl' => get_bloginfo ( 'url' ),
'piwikid' => $this->wpPiwik->getPiwikSiteId ()
);
$total_items = 1;
}
$columns = $this->get_columns ();
$hidden = array ();
$sortable = array ();
$this->_column_headers = array (
$columns,
$hidden,
$sortable
);
$this->set_pagination_args ( array (
'total_items' => $total_items,
'per_page' => $per_page
) );
foreach ( $this->data as $key => $dataset ) {
if (empty ( $dataset ['piwikid'] ) || $dataset ['piwikid'] == 'n/a')
$this->data [$key] ['piwikid'] = __ ( 'Site not created yet.', 'wp-piwik' );
if ($this->wpPiwik->isNetworkMode ())
$this->data [$key] ['name'] = '<a href="index.php?page=wp-piwik_stats&wpmu_show_stats=' . $dataset ['id'] . '">' . $dataset ['name'] . '</a>';
}
$this->items = $this->data;
return count ( $this->items );
}
public function column_default($item, $column_name) {
switch ($column_name) {
case 'id' :
case 'name' :
case 'siteurl' :
case 'piwikid' :
return $item [$column_name];
default :
return print_r ( $item, true );
}
}
}
\ No newline at end of file
<?php
namespace WP_Piwik\Admin;
class Statistics extends \WP_Piwik\Admin {
public function show() {
global $screen_layout_columns;
if (empty($screen_layout_columns)) $screen_layout_columns = 2;
if (self::$settings->getGlobalOption('disable_timelimit')) set_time_limit(0);
echo '<div id="wp-piwik-stats-general" class="wrap">';
echo '<h2>'.(self::$settings->getGlobalOption('plugin_display_name') == 'WP-Piwik'?'Piwik '.__('Statistics', 'wp-piwik'):self::$settings->getGlobalOption('plugin_display_name')).'</h2>';
if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && is_super_admin()) {
if (isset($_GET['wpmu_show_stats'])) {
switch_to_blog((int) $_GET['wpmu_show_stats']);
} else {
new \WP_Piwik\Admin\Sitebrowser(self::$wpPiwik);
return;
}
echo '<p>'.__('Currently shown stats:').' <a href="'.get_bloginfo('url').'">'.(int) $_GET['wpmu_show_stats'].' - '.get_bloginfo('name').'</a>.'.' <a href="?page=wp-piwik_stats">Show site overview</a>.</p>';
echo '</form>'."\n";
}
echo '<form action="admin-post.php" method="post"><input type="hidden" name="action" value="save_wp-piwik_stats_general" /><div id="dashboard-widgets" class="metabox-holder columns-'.$screen_layout_columns.(2 <= $screen_layout_columns?' has-right-sidebar':'').'">';
wp_nonce_field('wp-piwik_stats-general');
wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
$columns = array('normal', 'side', 'column3');
for ($i = 0; $i < 3; $i++) {
echo '<div id="postbox-container-'.($i+1).'" class="postbox-container">';
do_meta_boxes(self::$wpPiwik->statsPageId, $columns[$i], null);
echo '</div>';
}
echo '</div></form></div>';
echo '<script type="text/javascript">//<![CDATA['."\n";
echo 'jQuery(document).ready(function($) {$(".if-js-closed").removeClass("if-js-closed").addClass("closed"); postboxes.add_postbox_toggles("'.self::$wpPiwik->statsPageId.'");});'."\n";
echo '//]]></script>'."\n";
if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && is_super_admin()) {
restore_current_blog();
}
}
public function printAdminScripts() {
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script('wp-piwik-jqplot', self::$wpPiwik->getPluginURL().'js/jqplot/wp-piwik.jqplot.js',array('jquery'), self::$wpPiwik->getPluginVersion());
}
public function extendAdminHeader() {
echo '<!--[if IE]><script language="javascript" type="text/javascript" src="'.(self::$wpPiwik->getPluginURL()).'js/jqplot/excanvas.min.js"></script><![endif]-->';
echo '<link rel="stylesheet" href="'.(self::$wpPiwik->getPluginURL()).'js/jqplot/jquery.jqplot.min.css" type="text/css"/>';
echo '<script type="text/javascript">var $j = jQuery.noConflict();</script>';
}
}
\ No newline at end of file
<?php
namespace WP_Piwik;
abstract class Logger {
private $loggerName = 'unnamed';
private $loggerContent = array();
private $startMicrotime = null;
abstract function loggerOutput($loggerTime, $loggerMessage);
public function __construct($loggerName) {
$this->setName($loggerName);
$this->setStartMicrotime(microtime(true));
$this->log('Logging started -------------------------------');
}
public function __destruct() {
$this->log('Logging finished ------------------------------');
}
public function log($loggerMessage) {
$this->loggerOutput($this->getElapsedMicrotime(), $loggerMessage);
}
private function setName($loggerName) {
$this->loggerName = $loggerName;
}
public function getName() {
return $this->loggerName;
}
private function setStartMicrotime($startMicrotime) {
$this->startMicrotime = $startMicrotime;
}
public function getStartMicrotime() {
return $this->startMicrotime;
}
public function getElapsedMicrotime() {
return microtime(true) - $this->getStartMicrotime();
}
}
\ No newline at end of file
<?php
namespace WP_Piwik\Logger;
class Dummy extends \WP_Piwik\Logger {
public function loggerOutput($loggerTime, $loggerMessage) {}
}
\ No newline at end of file
<?php
namespace WP_Piwik\Logger;
class File extends \WP_Piwik\Logger {
private $loggerFile = null;
private function encodeFilename($fileName) {
$fileName = str_replace (' ', '_', $fileName);
preg_replace('/[^0-9^a-z^_^.]/', '', $fileName);
return $fileName;
}
private function setFilename() {
$this->loggerFile = WP_PIWIK_PATH.'logs'.DIRECTORY_SEPARATOR.
date('Ymd').'_'.$this->encodeFilename($this->getName()).'.log';
}
private function getFilename() {
return $this->loggerFile;
}
private function openFile() {
if (!$this->loggerFile)
$this->setFilename();
return fopen($this->getFilename(), 'a');
}
private function closeFile($fileHandle) {
fclose($fileHandle);
}
private function writeFile($fileHandle, $fileContent) {
fwrite($fileHandle, $fileContent."\n");
}
private function formatMicrotime($loggerTime) {
return sprintf('[%6s sec]',number_format($loggerTime,3));
}
public function loggerOutput($loggerTime, $loggerMessage) {
if ($fileHandle = $this->openFile()) {
$this->writeFile($fileHandle, $this->formatMicrotime($loggerTime).' '.$loggerMessage);
$this->closeFile($fileHandle);
}
}
}
\ No newline at end of file
<?php
namespace WP_Piwik\Logger;
class Screen extends \WP_Piwik\Logger {
private $logs = array();
private function formatMicrotime($loggerTime) {
return sprintf('[%6s sec]',number_format($loggerTime,3));
}
public function __construct($loggerName) {
add_action(is_admin()?'admin_footer':'wp_footer', array($this, 'echoResults'));
parent::__construct($loggerName);
}
public function loggerOutput($loggerTime, $loggerMessage) {
$this->logs[] = $this->formatMicrotime($loggerTime).' '.$loggerMessage;
}
public function echoResults() {
echo '<pre>';
print_r($this->logs);
echo '</pre>';
}
}
\ No newline at end of file
<?php
namespace WP_Piwik;
abstract class Request {
protected static $wpPiwik, $settings, $debug, $requests = array(), $results = array(), $isCacheable = array(), $piwikVersion;
public function __construct($wpPiwik, $settings) {
self::$wpPiwik = $wpPiwik;
self::$settings = $settings;
self::register('API.getPiwikVersion', array());
}
public function reset() {
self::$debug = null;
self::$requests = array();
self::$results = array();
self::$isCacheable = array();
self::$piwikVersion = null;
}
public static function register($method, $parameter) {
if ($method == 'API.getPiwikVersion')
$id = 'global.getPiwikVersion';
else
$id = 'method='.$method.self::parameterToString($parameter);
if (
in_array( $method, array( 'API.getPiwikVersion', 'SitesManager.getJavascriptTag', 'SitesManager.getSitesWithAtLeastViewAccess', 'SitesManager.getSitesIdFromSiteUrl', 'SitesManager.addSite', 'SitesManager.updateSite', 'SitesManager.getSitesWithAtLeastViewAccess' ) ) ||
!isset( $parameter['date'] ) ||
!isset( $parameter['period'] ) ||
substr($parameter['date'], 0, 4) == 'last' ||
$parameter['date'] == 'today' ||
( $parameter['period'] == 'day' && $parameter['date'] == date('Ymd') ) ||
( $parameter['period'] == 'month' && $parameter['date'] == date('Ym') ) ||
( $parameter['period'] == 'week' && $parameter['date'] == date( 'Ymd', strtotime( "last Monday" ) ) )
) self::$isCacheable[$id] = false;
else self::$isCacheable[$id] = $method.'-'.$parameter['period'].'-'.$parameter['date'];
if (!isset(self::$requests[$id]))
self::$requests[$id] = array('method' => $method, 'parameter' => $parameter);
return $id;
}
private static function parameterToString($parameter) {
$return = '';
if (is_array($parameter))
foreach ($parameter as $key => $value)
$return .= '&'.$key.'='.$value;
return $return;
}
public function perform($id) {
if ( self::$settings->getGlobalOption('cache') && false !== ( $cached = get_transient( 'wp-piwik_c_'.md5(self::$isCacheable[$id] ) ) ) ) {
if (!empty ( $cached ) && !(! empty ( $cached['result'] ) && $cached['result'] == 'error') ) {
self::$wpPiwik->log("Deliver cached data: ".$id);
return $cached;
}
}
self::$wpPiwik->log("Perform request: ".$id);
if (!isset(self::$requests[$id]))
return array('result' => 'error', 'message' => 'Request '.$id.' was not registered.');
elseif (!isset(self::$results[$id])) {
$this->request($id);
}
if ( isset ( self::$results[$id] ) ) {
if ( self::$settings->getGlobalOption('cache') && self::$isCacheable[$id] ) {
set_transient( 'wp-piwik_c_'.md5(self::$isCacheable[$id]) , self::$results[$id], WEEK_IN_SECONDS );
}
return self::$results[$id];
} else return false;
}
public function getDebug($id) {
return isset( self::$debug[$id] )? self::$debug[$id] : false;
}
protected function buildURL($config, $urlDecode = false) {
$url = 'method='.($config['method']).'&idSite='.self::$settings->getOption('site_id');
foreach ($config['parameter'] as $key => $value)
$url .= '&'.$key.'='.($urlDecode?urldecode($value):$value);
return $url;
}
protected function unserialize($str) {
self::$wpPiwik->log("Result string: ".$str);
return ($str == json_decode(false, true) || @json_decode($str, true) !== false)?json_decode($str, true):array();
}
abstract protected function request($id);
}
\ No newline at end of file
<?php
namespace WP_Piwik\Request;
class Php extends \WP_Piwik\Request {
private static $piwikEnvironment = false;
protected function request($id) {
$count = 0;
$url = self::$settings->getGlobalOption('piwik_url');
foreach (self::$requests as $requestID => $config) {
if (!isset(self::$results[$requestID])) {
$params = 'module=API&format=json&'.$this->buildURL($config);
$map[$count] = $requestID;
$result = $this->call($id, $url, $params);
self::$results[$map[$count]] = $result;
$count++;
}
}
}
private function call($id, $url, $params) {
if (!defined('PIWIK_INCLUDE_PATH'))
return false;
if (PIWIK_INCLUDE_PATH === FALSE)
return array('result' => 'error', 'message' => __('Could not resolve','wp-piwik').' &quot;'.htmlentities(self::$settings->getGlobalOption('piwik_path')).'&quot;: '.__('realpath() returns false','wp-piwik').'.');
if (file_exists(PIWIK_INCLUDE_PATH . "/index.php"))
require_once PIWIK_INCLUDE_PATH . "/index.php";
if (file_exists(PIWIK_INCLUDE_PATH . "/core/API/Request.php"))
require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php";
if (class_exists('\Piwik\Application\Environment') && !self::$piwikEnvironment) {
// Piwik 2.14.* compatibility fix
self::$piwikEnvironment = new \Piwik\Application\Environment(null);
self::$piwikEnvironment->init();
}
if (class_exists('Piwik\FrontController'))
\Piwik\FrontController::getInstance()->init();
else return array('result' => 'error', 'message' => __('Class Piwik\FrontController does not exists.','wp-piwik'));
if (class_exists('Piwik\API\Request'))
$request = new \Piwik\API\Request($params.'&token_auth='.self::$settings->getGlobalOption('piwik_token'));
else return array('result' => 'error', 'message' => __('Class Piwik\API\Request does not exists.','wp-piwik'));
if (isset($request))
$result = $request->process();
else $result = null;
if (!headers_sent())
header("Content-Type: text/html", true);
$result = $this->unserialize($result);
if ($GLOBALS ['wp-piwik_debug'])
self::$debug[$id] = array ( $params.'&token_auth=...' );
return $result;
}
}
\ No newline at end of file
<?php
namespace WP_Piwik\Request;
class Rest extends \WP_Piwik\Request {
protected function request($id) {
$count = 0;
$url = self::$settings->getGlobalOption('piwik_mode') == 'http'?
self::$settings->getGlobalOption('piwik_url'):
'https://'.self::$settings->getGlobalOption('piwik_user').'.piwik.pro/';
$params = 'module=API&method=API.getBulkRequest&format=json';
foreach (self::$requests as $requestID => $config) {
if (!isset(self::$results[$requestID])) {
$params .= '&urls['.$count.']='.urlencode($this->buildURL($config));
$map[$count] = $requestID;
$count++;
}
}
$results = ((function_exists('curl_init') && ini_get('allow_url_fopen') && self::$settings->getGlobalOption('http_connection') == 'curl') || (function_exists('curl_init') && !ini_get('allow_url_fopen')))?$this->curl($id, $url, $params):$this->fopen($id, $url, $params);
if (is_array($results))
foreach ($results as $num => $result)
self::$results[$map[$num]] = $result;
}
private function curl($id, $url, $params) {
if (self::$settings->getGlobalOption('http_method')=='post') {
$c = curl_init($url);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, $params.'&token_auth='.self::$settings->getGlobalOption('piwik_token'));
} else $c = curl_init($url.'?'.$params.'&token_auth='.self::$settings->getGlobalOption('piwik_token'));
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, !self::$settings->getGlobalOption('disable_ssl_verify'));
curl_setopt($c, CURLOPT_USERAGENT, self::$settings->getGlobalOption('piwik_useragent')=='php'?ini_get('user_agent'):self::$settings->getGlobalOption('piwik_useragent_string'));
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_HEADER, $GLOBALS ['wp-piwik_debug'] );
curl_setopt($c, CURLOPT_TIMEOUT, self::$settings->getGlobalOption('connection_timeout'));
$httpProxyClass = new \WP_HTTP_Proxy();
if ($httpProxyClass->is_enabled() && $httpProxyClass->send_through_proxy($strURL)) {
curl_setopt($c, CURLOPT_PROXY, $httpProxyClass->host());
curl_setopt($c, CURLOPT_PROXYPORT, $httpProxyClass->port());
if ($httpProxyClass->use_authentication())
curl_setopt($c, CURLOPT_PROXYUSERPWD, $httpProxyClass->username().':'.$httpProxyClass->password());
}
$result = curl_exec($c);
if ($GLOBALS ['wp-piwik_debug']) {
$header_size = curl_getinfo($c, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);
$result = $this->unserialize($body);