Project

General

Profile

1
<?php
2
/**
3
* includestatsnumbercountry plugin
4
* This plugin allows you to insert a statistics number to any joomla article. This is a 
5
* modified version that computes statistics per country.
6
* Author: dimitra
7
* License: GNU/GPL http://www.gnu.org/copyleft/gpl.html
8
*/
9

    
10
defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );
11

    
12
jimport( 'joomla.plugin.plugin' );
13
jimport( 'joomla.log.log' );
14

    
15
$GLOBALS['PREDIS_ROOT'] = dirname(__FILE__) . DS . 'predis';
16

    
17
 
18
class plgContentIncludestatsnumberscountry extends JPlugin {
19
	private $cache;
20
	private $codes = array();
21
	private $db;
22

    
23
	public function __construct(&$subject, $config) {
24
		parent::__construct($subject, $config);
25
		JLog :: addLogger(array('text_file' => 'openaire.log'), JLog :: ALL, array('openaire'));
26
		
27
		if(!class_exists("Predis\Client")) {
28
			require $GLOBALS['PREDIS_ROOT'] . DS ."autoload.php";				
29
		}
30
		
31
			try {
32
				
33
			 
34
				$this->cache = new Predis\Client(array( 
35
					"scheme" => $this->params->get('cachescheme'),
36
        				"host" => $this->params->get('cacheserver'),
37
        				"port" => $this->params->get('cacheport')));
38
        			
39
        		$this->cache->connect();
40
		
41
			} catch(Exception $e) {
42
				JLog :: add("Stats Plugin:  Error connecting to Redis server: ".$e->getMessage(), JLog :: ERROR, 'openaire');
43
				$this->cache = null;
44
			}
45
		
46
		
47
		JLog :: add('Stats Plugin:  Include country number Plugin!', JLog :: DEBUG, 'openaire');
48
	}
49

    
50
	public function onContentPrepare( $context, &$article, &$params, $page = 0 ) {
51
		$regex_base = '\{(include_countrynumber)\s+([[:alpha:]]+)\s+([[:alpha:]\s]+)\}';
52
		$regex = "/$regex_base/";
53

    
54
		$contents = $article->text;
55
		$found = preg_match_all($regex, $contents, $matches, PREG_SET_ORDER);
56
		
57
		 //JLog::add("found matches in cache: " . print_r($matches, true), JLog::INFO, 'openaire');	
58
		
59
		if (!$found) {
60
			return true;
61
		}
62
		
63
		foreach ($matches as $match) {
64
			try {
65
				$result = $this->getStatistic($match);
66
				$article->text = str_replace($match[0], $result, $article->text);
67
			} catch (Exception $e) {
68
				JLog :: add('Error getting log for: '. $match[0] . '. ' . $e->getMessage(), JLog :: ERROR, 'openaire');
69
				
70
				return false;
71
			}
72
		}
73
		
74
		return true;
75
	}
76
	
77
	private function getStatistic($match) {
78
	 JLog::add("Stats Plugin: getting stats for match: " . $match[0], JLog::INFO, 'openaire');
79
		$res = 0;
80
		
81
		if ($this->cache != null) {
82
		
83
			if($this->cache->exists(base64_encode($match[0]))) {
84
		        $res = $this->cache->hget(base64_encode($match[0]),'results');
85
		        
86
		        
87
                        JLog::add(" Stats Plugin:  $res: ". $res , JLog::INFO, 'openaire');
88
                        $res= str_replace('[','',$res);
89
                        $res= str_replace(']','',$res);
90
                         JLog::add(" Stats Plugin:  cleaned: ".$res  , JLog::INFO, 'openaire');
91
                            
92
			  
93
          //  return  json_decode($t[0]);
94
      
95
			} else {
96
			  
97
                                 $query=$this->getQuery($match[2], $match[3]);
98
                                 $res = $this->makeQuery($query);
99
                                 JLog::add("!!!decoded key: " .json_decode($res), JLog::INFO, 'openaire');
100
          
101
                              
102
                                 JLog::add("Stats Plugin:  added in cache -> key: " . base64_encode($match[0]) . " results " . $res . " query " . $query ." persistent 1 fetchMode 3", JLog::INFO, 'openaire');
103
                                if (!$this->cache->hmset(base64_encode($match[0]),array("results" =>$res,"query" =>$query ,"persistent" => '1',"fetchMode" => '3'))){
104
			
105
                                JLog::add("Stats Plugin:  Error adding key: " . $match[0], JLog::ERROR, 'openaire');
106
				} else {
107
					$this->cache->save();
108
				}
109
			}
110
		} else {
111
			 	
112
    		        $query=$this->getQuery($match[2], $match[3]);
113
                        $res = $this->makeQuery($query);
114
                         $res= str_replace('[','',$res);
115
                         $res= str_replace(']','',$res);
116
 
117
		}
118
		
119
		return $res;
120
	}
121
	
122
private function getQuery($type, $country) {
123

    
124
		switch ($type) {
125
//			case "PUB":
126
				$query = "select count (distinct rd.id) from result_datasources rd join datasource d on d.id=rd.datasource join organization_datasources od on od.datasource=d.id join organization o on o.id=od.id where o.country='" . $country . "'";
127
		
128
	$query=" SELECT  count(result.number) as field0 FROM result JOIN (select distinct result_datasources.id, datasource.name from result_datasources join datasource on datasource.id=result_datasources.datasource join datasource_organizations on datasource_organizations.id=datasource.datasource_organizations join organization on organization.id=datasource_organizations.organization and (organization.country='".$country."') ) as result_datasources ON result.result_datasources = result_datasources.id";							
129
break;
130
			case "DATASRC":
131
				$query = "select count(distinct d.id) from datasource d join datasource_results dr on dr.id=d.id join datasource_organizations dos on dos.id=d.id join organization o on o.id=dos.organization where o.country='" . $country . "'";
132
				break;
133
}
134

    
135
JLog::add("generated query for country stats: " . $query, JLog::INFO, 'openaire');
136

    
137
return $query ;
138
}
139

    
140
	
141
	
142
	private function makeQuery($query) {
143
		$res = 0;
144
		$str = 'pgsql:host='.$this->params->get('dbhost').';port='.$this->params->get('dbport').';dbname='.$this->params->get('dbname').';user='.$this->params->get('dbuser').';password='.$this->params->get('dbpass');
145
		$this->db = new PDO($str);
146
		
147
	 
148
		JLog::add("Stats Plugin:  Executing query: " . $query, JLog::INFO, 'openaire');
149
		$res = $this->doQuery($query);
150
		
151
		return $res;
152
	}
153
	
154
	private function doQuery($query){
155
		$stmt = $this->db->query($query); 
156
		
157
		if (!$stmt) {
158
			$arr = $this->db->errorInfo();
159
			JLog :: add("Stats Plugin:  Error executing query: ".$query." ".$arr[2], JLog :: ERROR, 'openaire');
160
			
161
			return "-";
162
		}
163
		
164
		$t = $stmt->fetch();
165
      
166
	 	return number_format($t[0]);
167
	}
168
}
169

    
170
?>
(1-1/4)