This repository has been archived by the owner on Dec 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
API.php
817 lines (703 loc) · 30.1 KB
/
API.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
<?php
/**
* @package Piwik.Counter
* @copyright Copyright (C) 2010 Libra.ms. All rights reserved.
* @license GNU General Public License version 3 or later
* @url http://xn--80aeqbhthr9b.com/en/others/piwik/10-piwik-graphical-counter.html
* @url http://киноархив.com/ru/разное/piwik/9-piwik-графический-счетчик.html
*/
namespace Piwik\Plugins\Counter;
use Piwik\Access;
use Piwik\API\Request;
use Piwik\Common;
use Piwik\Config;
use Piwik\Db;
use Piwik\Notification;
use Piwik\Piwik;
use Piwik\Plugin\Manager as Manager;
use Piwik\Plugins\SitesManager\API as SitesManager;
/**
* Display Hits/Visits on image. Display Hits/Visits/from Countries stats as text via ajax requests.
*/
class API extends \Piwik\Plugin\API
{
/**
* Method to get a list of counters.
*
* @return array
* @throws \Exception
*/
public function getItems()
{
return $this->getModel()->getItems();
}
/**
* Method to get a counter data.
*
* @return mixed Array on success, false otherwise
* @throws \Exception
*/
public function getItem()
{
$id = Common::getRequestVar('id', array(), 'array');
if (empty($id)) {
$id[] = Common::getRequestVar('id', 0, 'int');
if (empty($id)) {
return false;
}
}
$this->checkAccess();
return $this->getModel()->getItem($id);
}
/**
* Method to check if counter exists for that site
*
* @param integer $idsite Site ID
*
* @return string|boolean
* @throws \Exception
*/
public function counterExists($idsite)
{
if (empty($idsite)) {
return false;
}
return $this->getModel()->counterExists($idsite);
}
/**
* Method to check if file exists.
*
* @return string
* @throws \Exception
*/
public function checkPath()
{
clearstatcache();
$path = trim(Common::getRequestVar('path', '', 'string'));
$path = $this->getModel()->cleanPath($path);
// Search under the Piwik document root only
if (stripos($path, PIWIK_DOCUMENT_ROOT, 0) !== false || stripos(PIWIK_DOCUMENT_ROOT . $path, PIWIK_DOCUMENT_ROOT, 0) !== false) {
if (is_file($path)) {
return true;
}
}
return false;
}
/**
* Enqueue message in the session and display it.
*
* @param string $message The text to display
* @param string $style Style of the message. See CONTEXT_* in core/Notification.php fot valid message styles.
* @param string $type Message type. See TYPE_* in core/Notification.php fot valid message types.
* @param integer $priority Priority. See PRIORITY_* in core/Notification.php fot valid message priorities.
*
* @return void
* @throws \Exception
*/
public function enqueueMessage($message, $style = 'info', $type = 'transient', $priority = 0)
{
$notification = new Notification($message);
switch (strtolower($style)) {
case 'success':
$notification->context = Notification::CONTEXT_SUCCESS;
break;
case 'error':
$notification->context = Notification::CONTEXT_ERROR;
break;
case 'warning':
$notification->context = Notification::CONTEXT_WARNING;
break;
case 'info':
default:
$notification->context = Notification::CONTEXT_INFO;
break;
}
if (!empty($type) || !is_null($type)) {
if ($type == 'persistent') {
$notification->type = Notification::TYPE_PERSISTENT;
} elseif ($type == 'toast') {
$notification->type = Notification::TYPE_TOAST;
} else {
$notification->type = Notification::TYPE_TRANSIENT;
}
}
if (!empty($priority)) {
if ($priority === 1) {
$notification->priority = Notification::PRIORITY_MIN;
} elseif ($priority === 25) {
$notification->priority = Notification::PRIORITY_LOW;
} elseif ($priority === 50) {
$notification->priority = Notification::PRIORITY_HIGH;
} elseif ($priority === 100) {
$notification->priority = Notification::PRIORITY_MAX;
}
}
Notification\Manager::notify('myUniqueNotificationId', $notification);
}
/**
* Check the user access rights. Request it inly via controller not an API, because user session won't start.
*
* @param boolean $is_index True if counter data requested from frontpage
*
* @return boolean
* @throws \Exception
*/
public function checkAccess($is_index = false)
{
$sites_manager = SitesManager::getInstance();
$access = Access::getInstance();
$sites_ids = $sites_manager->getSitesIdWithAdminAccess();
$action = Common::getRequestVar('action', '', 'string');
if ($action == 'show' || $action == 'live') {
return true;
}
// Checking the user access rights. If the user not an admin for at least one site when throw an error
if (count($sites_ids) <= 0) {
throw new \Exception(Piwik::translate('General_ExceptionPrivilegeAtLeastOneWebsite', array('admin')));
} else {
// Don't perfom checking for index
if ($is_index === false) {
if ($access->hasSuperUserAccess()) {
return true;
}
$ids = Common::getRequestVar('id', array(), 'array');
$ids = $this->toInteger($ids);
if (empty($ids) && $action == 'counter_exists') {
return true;
}
if (!empty($ids) && ($action != 'save' || $action != 'apply' || $action != 'remove' || $action != 'publish' || $action != 'unpublish')) {
$login = $access->getLogin();
$result = Db::fetchAll("SELECT idsite"
. "\n FROM " . Common::prefixTable('access')
. "\n WHERE idsite IN (SELECT idsite FROM " . Common::prefixTable('counter_sites') . " WHERE id IN (" . implode(',', $ids) . ")) AND access = 'admin' AND login = '" . $login . "'");
if (count($result) > 0) {
return true;
} else {
throw new \Exception(Piwik::translate('General_ExceptionPrivilegeAtLeastOneWebsite', array('admin')));
}
} else {
return true;
}
}
}
return false;
}
/**
* Clear cache for custom counter
*
* @param array $params An array with the counter data.
*
* @return mixed
* @throws \Exception
*/
private function createImage($params = array())
{
$params = count($params) > 0 ? $params : $this->getItem();
$date_request = Common::getRequestVar('date', '', 'string');
$date_start = $params['params']['start_date'];
$date_start_period = $params['params']['start_date_period'];
if (!empty($date_request)) {
$_date = $date_request;
} else {
if (!empty($date_start)) {
$_date = $date_start;
} else {
if ($date_start_period != 'none') {
$_date = $date_start_period;
} else {
$_date = 'day';
}
}
}
if ($_date == 'day') {
$date = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d'), date('Y')));
} elseif ($_date == 'yesterday') {
$date = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')));
} elseif ($_date == 'week') {
$date = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - 7, date('Y')));
} elseif ($_date == 'month') {
$date = date('Y-m-d', mktime(0, 0, 0, date('m') - 1, date('d'), date('Y')));
} elseif ($_date == 'year') {
$date = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d'), date('Y') - 1));
} else {
$date = $_date;
}
$request = new Request('method=VisitsSummary.get&idSite=' . (int) $params['idsite'] . '&period=range&date=' . $date . ',' . date('Y-m-d') . '&format=json&&filter_limit=-1&token_auth=' . $params['params']['token']);
$result = $request->process();
$result = json_decode($result,true);
$visits = 0;
$views = 0;
if (isset($result['result']) && $result['result'] == 'error') {
echo $result['message'];
return false;
}
if (isset($result['nb_visits'])) {
$visits = $result['nb_visits'];
$views = $result['nb_actions'];
} else {
$c_visits = 0;
$c_views = 0;
foreach ($result as $value) {
$visits = $c_visits + $value['nb_visits'];
$views = $c_views + $value['nb_actions'];
}
}
// Add or subtract initial values
if ($params['visits'] != 0) {
if ($params['visits'] < 0 && $visits > abs($params['visits'])) {
$visits = $visits - abs($params['visits']);
} elseif ($params['visits'] > 0) {
$visits = $visits + abs($params['visits']);
}
}
if ($params['views'] != 0) {
if ($params['views'] < 0 && $views > abs($params['views'])) {
$views = $views - abs($params['views']);
} elseif ($params['views'] > 0) {
$views = $views + abs($params['views']);
}
}
// Format numbers to human readable
if (array_key_exists('format_numbers', $params['params']) && $params['params']['format_numbers'] == 1) {
$data = array($this->formatNumber($visits), $this->formatNumber($views));
} else {
$data = array($visits, $views);
}
if (!empty($params['params']['img_path']) && is_file($params['params']['img_path'])) {
header_remove('X-Powered-By');
$mime = $this->getMime($params['params']['img_path']);
$dst_im = imagecreatetruecolor($params['params']['img_size_x'], $params['params']['img_size_y']);
if ($mime == 'image/png') {
$src_im = imagecreatefrompng($params['params']['img_path']);
imagealphablending($src_im, true);
imagesavealpha($src_im, true);
} elseif ($mime == 'image/gif') {
$src_im = imagecreatefromgif($params['params']['img_path']);
} elseif ($mime == 'image/jpeg') {
$src_im = imagecreatefromjpeg($params['params']['img_path']);
} else { // Unsupported image type
// Output an 1x1 transparent gif
$im = imagecreatetruecolor(1, 1);
imagecolortransparent($im, imagecolorallocate($im, 0, 0, 0));
header('Content-type: image/gif');
imagegif($im);
imagedestroy($im);
exit();
}
list($w, $h) = getimagesize($params['params']['img_path']);
if (!empty($params['params']['font_path']) && is_file($params['params']['font_path'])) {
// Draw sitename
if (!empty($params['title']) && $params['params']['show_sitename'] == 1) {
$rgb_arr_sitename = $this->rgb2array($params['params']['color_sitename']);
$color_sitename = imagecolorallocate($src_im, $rgb_arr_sitename['r'], $rgb_arr_sitename['g'], $rgb_arr_sitename['b']);
imagettftext($src_im, $params['params']['sitename_font_size'], 0, $params['params']['sitename_pos_x'], $params['params']['sitename_pos_y'], $color_sitename, $params['params']['font_path'], $params['title']);
}
// Draw visits
if ($params['params']['show_visits'] == 1) {
$rgb_arr_visits = $this->rgb2array($params['params']['color_visits']);
$color_visits = imagecolorallocate($src_im, $rgb_arr_visits['r'], $rgb_arr_visits['g'], $rgb_arr_visits['b']);
imagettftext($src_im, $params['params']['visits_font_size'], 0, $params['params']['visitors_pos_x'], $params['params']['visitors_pos_y'], $color_visits, $params['params']['font_path'], $data[0]);
}
// Draw views
if ($params['params']['show_views'] == 1) {
$rgb_arr_views = $this->rgb2array($params['params']['color_views']);
$color_views = imagecolorallocate($src_im, $rgb_arr_views['r'], $rgb_arr_views['g'], $rgb_arr_views['b']);
imagettftext($src_im, $params['params']['hits_font_size'], 0, $params['params']['views_pos_x'], $params['params']['views_pos_y'], $color_views, $params['params']['font_path'], $data[1]);
}
} else {
// Draw sitename
if (!empty($params['title']) && $params['params']['show_sitename'] == 1) {
$rgb_arr_sitename = $this->rgb2array($params['params']['color_sitename']);
// Text must be only in Latin2!
imagestring($src_im, $params['params']['sitename_font_size'] - 5, $params['params']['sitename_pos_x'], $params['params']['sitename_pos_y'] - 10, $params['title'], imagecolorallocate($src_im, $rgb_arr_sitename['r'], $rgb_arr_sitename['g'], $rgb_arr_sitename['b']));
}
// Draw visits
if ($params['params']['show_visits'] == 1) {
$rgb_arr_visits = $this->rgb2array($params['params']['color_visits']);
imagestring($src_im, $params['params']['visits_font_size'] - 5, $params['params']['visitors_pos_x'], $params['params']['visitors_pos_y'] - 10, $data[0], imagecolorallocate($src_im, $rgb_arr_visits['r'], $rgb_arr_visits['g'], $rgb_arr_visits['b']));
}
// Draw views
if ($params['params']['show_views'] == 1) {
$rgb_arr_views = $this->rgb2array($params['params']['color_views']);
imagestring($src_im, $params['params']['hits_font_size'] - 5, $params['params']['views_pos_x'] + 5, $params['params']['views_pos_y'] - 10, $data[1], imagecolorallocate($src_im, $rgb_arr_views['r'], $rgb_arr_views['g'], $rgb_arr_views['b']));
}
}
imagecopyresampled($dst_im, $src_im, 0, 0, 0, 0, $params['params']['img_size_x'], $params['params']['img_size_y'], $w, $h);
header('Content-type: ' . $mime);
if ($mime == 'image/png') {
imagepng($src_im);
} elseif ($mime == 'image/gif') {
imagegif($src_im);
} else {
imagejpeg($src_im, null, 75);
}
imagedestroy($src_im);
}
return false;
}
/**
* Show image from cache or create if it not exists
*
* @return void
* @throws \Exception
*/
public function showImage()
{
$id = Common::getRequestVar('id', 0, 'int');
$params = $this->getItem();
$cacheId = 'counter_image_' . md5($id) . '_' . $id;
// If the counter has not been published - output an 1x1 transparent gif
if ($params['published'] != 1) {
$im = imagecreatetruecolor(1, 1);
imagecolortransparent($im, imagecolorallocate($im, 0, 0, 0));
header('Content-type: image/gif');
imagegif($im);
imagedestroy($im);
exit();
}
if ($params['params']['cache'] == 1) {
require_once __DIR__ . '/Cache.php';
$cache = new Cache(
array(
'cacheDir' => $this->getModel()->cleanPath(PIWIK_DOCUMENT_ROOT . '/tmp/cache/'),
'cacheId' => $cacheId
)
);
// Test if cache is available
if ($cache->validate()) {
$mime = $this->getMime($params['params']['img_path']);
header('Content-type: ' . $mime);
// Load and output image from cache
echo $cache->load();
}
else
{
// Build new image and save into cache
if (!$cache->start((int)$params['params']['cache_time'])) {
$this->createImage();
$cache->end();
}
}
} else {
$this->createImage();
}
}
/**
* Create image for preview while editing counter data. For backend only. This method do not use cache.
*
* @return void
* @throws \Exception
*/
public function previewImage()
{
$this->checkAccess();
@set_time_limit(0);
$this->createImage($this->getModel()->getForm());
}
/**
* Method to get live visitors count.
*
* @return void
* @throws \Exception
*/
public function getLiveVisitorsCount()
{
$type = Common::getRequestVar('type', '', 'string');
$id = Common::getRequestVar('id', 0, 'int');
$params = $this->getItem();
if ($params['published'] != 1) exit();
if ($type == 'js') {
if (!empty($params['params']['tpl_by_countries'])) {
$dom_elem_id = $params['params']['tpl_by_countries_elem_id'];
} else {
$dom_elem_id = $params['params']['livestat_elem_id'];
}
$data_ajax_url = (Config::getInstance()->General['force_ssl'] === 1 ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '?module=Counter&action=live&id=' . $id;
header('Content-type: text/javascript');
echo 'var elem = "' . $dom_elem_id . '", url = "' . $data_ajax_url . '"; function createXHR(){var a;if(window.ActiveXObject){try{a=new ActiveXObject("Microsoft.XMLHTTP")}catch(b){document.getElementById(elem).innerHTML=b.message;a=null}}else{a=new XMLHttpRequest}return a}function sendRequest(){var a=createXHR();a.onreadystatechange=function(){if(a.readyState===4){document.getElementById(elem).innerHTML=a.responseText}};a.open("GET",url,true);a.send()}sendRequest();';
echo ($params['params']['static'] == 0) ? 'setInterval(sendRequest, ' . (int)$params['params']['check_interval'] . ');' : '';
} else {
$nbv_m = '';
$nbc_m = '';
$nba_m = '';
$format = '';
if (!empty($params['params']['tpl_by_countries'])) {
// Search for start_date value for period
if (preg_match('#\[date(.*?)\]#', $params['params']['tpl_by_countries'], $matches)) {
preg_match('#\[date(\sstart="(?P<start_date>.+?)")?(\sformat="(?P<date_format>.+?)")?(\send="(?P<end_date>.+?)")?\]#i', $params['params']['tpl_by_countries'], $m);
if (isset($m['start_date']) && !empty($m['start_date'])) {
$start_date = $m['start_date'];
} else {
$start_date = $params['params']['start_date'];
}
$end_date = (isset($m['end_date']) && !empty($m['end_date'])) ? $m['end_date'] : date('Y-m-d');
if (isset($m['date_format']) && !empty($m['date_format'])) {
$format = date($m['date_format'], strtotime($start_date));
} else {
$format = $start_date;
}
$date_range = $start_date . ',' . $end_date;
} else {
$date_range = $params['params']['start_date'] . ',' . date('Y-m-d'); // default date range
}
// Process offsets
// Visits
if (preg_match('#\[nb_visits(.*?)\]#', $params['params']['tpl_by_countries'], $nbv_matches)) {
preg_match('#\[nb_visits(\soffset="(?P<offset>.+?)")\]#i', $params['params']['tpl_by_countries'], $nbv_m);
}
// Countries
if (preg_match('#\[nb_countries(.*?)\]#', $params['params']['tpl_by_countries'], $nbc_matches)) {
preg_match('#\[nb_countries(\soffset="(?P<offset>.+?)")\]#i', $params['params']['tpl_by_countries'], $nbc_m);
}
if (preg_match('#\[nb_actions(.*?)\]#', $params['params']['tpl_by_countries'], $nbc_matches)) {
preg_match('#\[nb_actions(\soffset="(?P<offset>.+?)")\]#i', $params['params']['tpl_by_countries'], $nba_m);
}
$request = new Request('method=UserCountry.getCountry&idSite=' . $params['idsite'] . '&period=range&date=' . $date_range . '&format=JSON&token_auth=' . $params['params']['token']);
$result = json_decode($request->process());
} else {
$request = new Request('method=Live.getCounters&idSite=' . $params['idsite'] . '&lastMinutes=' . (int)$params['params']['last_minutes'] . '&format=JSON&token_auth=' . $params['params']['token']);
$result = json_decode($request->process());
}
/* Cross-Origin Resource Sharing (CORS) */
/* if piwik is hosted on a different site than the
* page calling the js, then the browser will break
* the script. This is unless a proper CORS is returned.
* this is done by checking which the head 'Origin' with
* the list of $params['origins'] and if there's a match
* to return the proper 'Access-Control-Allow-Origin' header
*
* Limitations: Unsure how to distringuish/restrict http/https
* at the moment, there's no checks on that. We only check
* the hostname provided. Let's assume the counter in itself
* isn't too much of a sensitive data anyway.
*/
if (!function_exists('getallheaders')) {
// See http://www.php.net/manual/en/function.getallheaders.php#84262
$headers = '';
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
} else {
$headers = getallheaders();
}
$protocol = array('/http:\/\//', '/https:\/\//');
$r = array('', '');
if (array_key_exists('Origin', $headers)) {
$origin = $headers['Origin'];
if (in_array(preg_replace($protocol, $r, $origin), $params['origins'])) {
header('Access-Control-Allow-Origin: ' . $origin);
}
}
if (!empty($params['params']['tpl_by_countries'])) {
$nb_countries = count($result);
$nb_visits = 0;
$nb_actions = 0;
foreach ($result as $data) {
$nb_visits = $nb_visits + (int)$data->nb_visits;
$nb_actions = $nb_actions + (int)$data->nb_actions;
}
// Offsets for visitors
if (is_array($nbv_m)) {
if (array_key_exists('offset', $nbv_m) && substr($nbv_m['offset'], 0, 1) == '-') { // Negative offset
if ($nb_visits > 0) {
$nb_visits = $nb_visits - (int)substr($nbv_m['offset'], 1);
}
} elseif (array_key_exists('offset', $nbv_m) && substr($nbv_m['offset'], 0, 1) == '+') { // Positive offset
$nb_visits = $nb_visits + (int)substr($nbv_m['offset'], 1);
}
}
// Offsets for countries
if (is_array($nbc_m)) {
if (array_key_exists('offset', $nbc_m) && substr($nbc_m['offset'], 0, 1) == '-') { // Negative offset
if ($nb_countries > 0) {
$nb_countries = $nb_countries - (int)substr($nbc_m['offset'], 1);
}
} elseif (array_key_exists('offset', $nbc_m) && substr($nbc_m['offset'], 0, 1) == '+') { // Positive offset
$nb_countries = $nb_countries + (int)substr($nbc_m['offset'], 1);
}
}
// Offsets for actions
if (is_array($nba_m)) {
if (array_key_exists('offset', $nba_m) && substr($nba_m['offset'], 0, 1) == '-') { // Negative offset
if ($nb_actions > 0) {
$nb_actions = $nb_actions - (int)substr($nba_m['offset'], 1);
}
} elseif (array_key_exists('offset', $nba_m) && substr($nba_m['offset'], 0, 1) == '+') { // Positive offset
$nb_actions = $nb_actions + (int)substr($nba_m['offset'], 1);
}
}
$patterns = array(
'nb_visits' => '#\[nb_visits(.*?)\]#',
'nb_countries' => '#\[nb_countries(.*?)\]#',
'nb_actions' => '#\[nb_actions(.*?)\]#',
'date' => '#\[date(.*?)\]#'
);
$data = array(
'nb_visits' => $nb_visits,
'nb_actions' => $nb_actions,
'nb_countries' => $nb_countries,
'date' => $format
);
ksort($data);
ksort($patterns);
$str = preg_replace($patterns, $data, $params['params']['tpl_by_countries']);
header('Content-type: text/html');
echo $str;
} else {
header('Content-type: text/html');
echo $result[0]->visits;
}
}
}
/**
* Clear cache for custom counter
*
* @param array $ids A list of the primary keys.
*
* @return boolean True on success.
* @throws \Exception
*/
public function clearCache($ids)
{
if (empty($ids)) {
return false;
}
if (Common::getRequestVar('action', '', 'string') !== 'remove') {
$this->checkAccess();
}
require_once __DIR__ . '/Cache.php';
$errors = array();
$cache = new Cache(
array(
'cacheDir' => $this->getModel()->cleanPath(PIWIK_DOCUMENT_ROOT . '/tmp/cache/')
)
);
foreach ($ids as $id) {
if (!$cache->remove('counter_image_' . md5($id) . '_' . $id)) {
$errors[] = $id;
}
}
if (!empty($errors)) {
return false;
}
return true;
}
/**
* Get plugin information
*
* @return array
*/
public function getPluginInfo()
{
$plugins = Manager::getInstance()->loadAllPluginsAndGetTheirInfo();
return $plugins['Counter'];
}
/**
* Method to get proper MIME type
*
* @param string $path Absolute path to file
*
* @return string
*/
private function getMime($path)
{
if (!empty($path) && is_file($path)) {
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
finfo_close($finfo);
} elseif (function_exists('mime_content_type')) {
$mime = mime_content_type($path);
} else {
$ext = pathinfo($path, PATHINFO_EXTENSION);
if ($ext == 'png') {
$mime = 'image/png';
} elseif ($ext == 'gif') {
$mime = 'image/gif';
} elseif ($ext == 'jpg' || $ext == 'jpeg') {
$mime = 'image/jpeg';
} elseif ($ext == 'bmp') {
$mime = 'image/bmp';
} else {
$mime = 'text/html';
}
}
} else {
$mime = 'image/jpeg';
}
return $mime;
}
/**
* Format number to a human readable.
*
* @param integer $number Number
*
* @return string
*/
private function formatNumber($number)
{
if ($number > 1000000000000) {
$number = round(($number / 1000000000000), 1) . 'T';
} else if ($number > 1000000000) {
$number = round(($number / 1000000000), 1) . 'B';
} else if ($number > 1000000) {
$number = round(($number / 1000000), 1) . 'M';
} else if ($number > 1000) {
$number = round(($number / 1000), 1) . 'K';
} else {
$number = number_format($number);
}
return $number;
}
/**
* Convert hex color to rgb.
*
* @param string $rgb Color code
*
* @return array
*/
private function rgb2array($rgb)
{
$rgb = str_replace('#', '', $rgb);
return array(
'r' => base_convert(substr($rgb, 0, 2), 16, 10),
'g' => base_convert(substr($rgb, 2, 2), 16, 10),
'b' => base_convert(substr($rgb, 4, 2), 16, 10)
);
}
/**
* Init plugin model.
*
* @return object
*/
private function getModel()
{
return new Model();
}
/**
* Convert array to integer values.
*
* @param array $array The source array to convert
* @param int|array $default A default value to assign if $array is not an array
*
* @return array
*/
public function toInteger($array, $default = null)
{
if (is_array($array))
{
return array_map('intval', $array);
}
if ($default === null)
{
return array();
}
if (is_array($default))
{
return static::toInteger($default);
}
return array((int) $default);
}
}