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
				//Predis\Autoloader::register();
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("Error connecting to Redis server: ".$e->getMessage(), JLog :: ERROR, 'openaire');
43
				$this->cache = null;
44
			}
45
		
46
		
47
		JLog :: add('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("!!!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("!!!$res: ". $res , JLog::INFO, 'openaire');
88
                        $res= str_replace('[','',$res);
89
                        $res= str_replace(']','',$res);
90
                         JLog::add("!!!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("!!!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("!!!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(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";		
127
			
128
				break;
129
			case "DATASRC":
130
				$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 . "'";
131
				break;
132
}
133

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

    
136
return $query ;
137
}
138

    
139
	
140
	
141
	private function makeQuery($query) {
142
		$res = 0;
143
		$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');
144
		$this->db = new PDO($str);
145
		
146
	 
147
		JLog::add("Executing query: " . $query, JLog::INFO, 'openaire');
148
		$res = $this->doQuery($query);
149
		
150
		return $res;
151
	}
152
	
153
	private function doQuery($query){
154
		$stmt = $this->db->query($query); 
155
		
156
		if (!$stmt) {
157
			$arr = $this->db->errorInfo();
158
			JLog :: add("Error executing query: ".$query." ".$arr[2], JLog :: ERROR, 'openaire');
159
			
160
			return "-";
161
		}
162
		
163
		$t = $stmt->fetch();
164
      
165
	 	return number_format($t[0]);
166
	}
167
}
168

    
169
?>
(1-1/4)