Project

General

Profile

« Previous | Next » 

Revision 51836

Clear the component - leave only widget code

View differences:

modules/uoa-joomla/trunk/joomla-3.4/com_openaire_beta/site/models/alerts.php
1
<?php
2

  
3
defined('_JEXEC') or die('Access denied');
4

  
5
jimport('joomla.application.component.helper');
6
jimport('joomla.application.component.model');
7
jimport('joomla.base.object');
8
jimport('joomla.cache.cache');
9
jimport('joomla.http.http');
10
jimport('joomla.log.log');
11
if(!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
12
$GLOBALS['THRIFT_ROOT'] = dirname(__FILE__) . DS . 'thrift';
13
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'Thrift.php');
14
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'protocol' . DS . 'TBinaryProtocol.php');
15
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'transport' . DS . 'TSocket.php');
16
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'transport' . DS . 'TBufferedTransport.php');
17
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'packages' . DS . 'OpenAIREConnector' . DS . 'OpenAIREConnector.php');
18

  
19
// This model manages alerts using DB and Thrift.
20
class OpenAireModelAlerts extends JModelItem {
21
	const SUBSCRIPTIONS_CACHE_ID = 'subscriptions';
22
	const TOPICS_CACHE_ID = 'topics';
23
	const ALERT_MODES_CACHE_ID = 'alert.modes';
24
	const CACHE_GROUP = 'openaire.alerts';
25
	const LOG = 'openaire';
26

  
27
	private $databasePrefix;
28
	private $pageSize;
29
	private $atomUrn;
30
	private $jdbcUri;
31
	private $newsCategory;
32
	private $newsUser;
33
	private $twitterAccessToken;
34
	private $twitterAccessTokenSecret;
35
	private $transport;
36
	private $client;
37
	private $cache;
38

  
39
	// Construct a new OpenAireModelSearch.
40
	// $configuration the configuration to use		
41
	public function __construct($configuration = array()) {
42
		parent :: __construct($configuration);
43
		$this -> db = JFactory :: getDBO();
44
		$this -> databasePrefix = JFactory :: getApplication() -> getCfg('dbprefix');
45
		$parameters = JComponentHelper :: getParams('com_openaire');
46
		$this -> pageSize = intval($parameters -> get('alertsPageSize'));
47
		$this -> atomUrn = $parameters -> get('alertsAtomUrn');
48
		$this -> jdbcUri = $parameters -> get('alertsJdbcUri');
49
		$this -> newsCategory = intval($parameters -> get('alertsNewsCategory'));
50
		$this -> newsUser = intval($parameters -> get('alertsNewsUser'));
51
		$this -> twitterAccessToken = $parameters -> get('alertsTwitterAcccessToken');
52
		$this -> twitterAccessTokenSecret = $parameters -> get('alertsTwitterAccessTokenSecret');
53
		$socket = new TSocket($parameters -> get('thriftHost'), intval($parameters -> get('thriftPort')));
54
		$socket -> setRecvTimeout(intval($parameters -> get('thriftTimeout')));
55
		$this -> transport = new TBufferedTransport($socket);
56
		$this -> client = new OpenAireConnectorClient(new TBinaryProtocol($this -> transport));
57
		$this -> transport -> open();
58
		$this -> cache = JCache :: getInstance();
59
	}
60
	
61
	// Close Thrift transport.
62
	public function __destruct() {
63
		$this -> transport -> close();
64
	}
65
	
66
	// Retrieve the subscriptions of a user using cache if enabled.
67
	// $user the user to retrieve subscriptions for
68
	// return the subscriptions of the user specified (array)
69
	public function getSubscriptions($user) {
70
		if ($this -> cache -> getCaching()) {
71
			$id = self :: SUBSCRIPTIONS_CACHE_ID . '.' . $user -> get('username');
72
			$subscriptions = $this -> cache -> get($id, self :: CACHE_GROUP);
73
			if ($subscriptions === FALSE) {
74
				$subscriptions = $this -> _getSubscriptions($user);
75
				if ($subscriptions !== NULL)
76
					$this -> cache -> store($subscriptions, $id, self :: CACHE_GROUP);
77
			}
78
		} else
79
			$subscriptions = $this -> _getSubscriptions($user);
80
		return $subscriptions;
81
	}
82
	
83
	// Retrieve alert topics using cache if enabled.
84
	// $parent the id of the parent topic of the topics to retrieve
85
	// $name retrieve only topics whose name contains this substring
86
	// $limit the maximum number of topics to retrieve
87
	// return the alert topics matching the criteria specified (array)
88
	public function getTopics($parent, $name, $limit) {
89
		if ($this -> cache -> getCaching()) {
90
			$id = self :: TOPICS_CACHE_ID . '.' . $parent . '.' . $name . '.' . $limit;
91
			$topics = $this -> cache -> get($id, self :: CACHE_GROUP);
92
			if ($topics === FALSE) {
93
				$topics = $this -> _getTopics($parent, $name, $limit);
94
				if ($topics !== NULL)
95
					$this -> cache -> store($topics, $id, self :: CACHE_GROUP);
96
			}
97
		} else
98
			$topics = $this -> _getTopics($parent, $name, $limit);
99
		return $topics;
100
	}
101
	
102
	// Retrieve the alert modes available to a user using cache if enabled.
103
	// $user the user to retrieve alert modes for
104
	// return the alert modes available to the user specified (array)
105
	public function getAlertModes($user) {
106
		if ($this -> cache -> getCaching()) {
107
			$id = self :: ALERT_MODES_CACHE_ID . '.' . $user -> get('username');
108
			$alertModes = $this -> cache -> get($id, self :: CACHE_GROUP);
109
			if ($alertModes === FALSE) {
110
				$alertModes = $this -> _getAlertModes($user);
111
				if ($alertModes !== NULL)
112
					$this -> cache -> store($alertModes, $id, self :: CACHE_GROUP);
113
			}
114
		} else
115
			$alertModes = $this -> _getAlertModes($user);
116
		return $alertModes;
117
	}
118
	
119
	// Add a new subcsription using cache if enabled.
120
	// $templateId the unique identifier of the template of the new subscription
121
	// $notificationService the notification service of the new subscription
122
	// $queryId the unique identifier of the query of the new subscription
123
	// $resultId the unique identifier of the result of the new subscription
124
	// $alertMode the alert mode of the new subscription
125
	// $batchPeriod the batch period of the new subscription
126
	// $user the user to add the new subscription for
127
	public function addSubscription($templateId, $notificationService, $queryId, $resultId, $alertMode, $batchPeriod, $user) {
128
		$this -> _addSubscription($templateId, $notificationService, $queryId, $resultId, $alertMode, $batchPeriod, $user);
129
		if ($this -> cache -> getCaching()) {
130
			$id = self :: SUBSCRIPTIONS_CACHE_ID . $user -> get('username');
131
			$this -> cache -> remove($id, self :: CACHE_GROUP);
132
		}
133
	}
134
	
135
	// Remove a subscription using cache if enabled.
136
	// $templateId the unique identifier of the template of the subscription to remove
137
	// $notificationService the notification service of the subscription to remove
138
	// $queryId the unique identifier of the query of the subscription to remove
139
	// $resultId the unique identifier of the result of the subscription to remove
140
	// $alertMode the alert mode of the subscription to remove
141
	// $subscriber the subscriber URI of the subscription to remove
142
	// $user the user whose subscription to remove
143
	public function removeSubscription($templateId, $notificationService, $queryId, $resultId, $alertMode, $subscriber, $user) {
144
		$this -> _removeSubscription($templateId, $notificationService, $queryId, $resultId, $alertMode, $subscriber);
145
		if ($this -> cache -> getCaching()) {
146
			$id = self :: SUBSCRIPTIONS_CACHE_ID . $user -> get('username');
147
			$this -> cache -> remove($id, self :: CACHE_GROUP);
148
		}
149
	}
150
	
151
	// Retrieve the subscriptions of a user using cache if enabled.
152
	// $user the user to retrieve subscriptions for
153
	// return the subscriptions of the user specified (array) or NULL if any errors occur
154
	private function _getSubscriptions($user) {
155
		try {	
156
			$result = array();
157
			foreach ($this -> getAlertModes($user) as $alertMode) { // for each alert mode that the current user may use
158
				list($alertMode -> id, $subscriber) = $this -> getAlertModeAndSubscriber($alertMode -> id, 0, $user);
159
				for ($offset = 0; ; $offset += $this -> pageSize) {
160
					$subscriptions = $this -> client -> getSubscriptions($alertMode -> id, $subscriber, $this -> pageSize, $offset);
161
					foreach ($subscriptions as $subscription) {
162
						$subscription -> topic = $this -> getFullTopicName($subscription -> templateId, $subscription -> notificationService, $subscription -> queryId, $subscription -> resultId);
163
						list($subscription -> alertModeName, $subscription -> batchPeriod) = $this -> getAlertModeNameAndBatchPeriod($subscription -> alertMode, $subscription -> subscriber);
164
						$result[] = $subscription;
165
					}
166
					if (count($subscriptions) < $this -> pageSize)
167
						break;
168
				}
169
				if ($alertMode -> batch) { // alert mode is a batch alert mode too
170
					list($alertMode -> id, $subscriber) = $this -> getAlertModeAndSubscriber($alertMode -> id, NULL, $user);
171
					for ($offset = 0; ; $offset += $this -> pageSize) {
172
						$subscriptions = $this -> client -> getSubscriptions($alertMode -> id, $subscriber, $this -> pageSize, $offset);
173
						foreach ($subscriptions as $subscription) {
174
							$subscription -> topic = $this -> getFullTopicName($subscription -> templateId, $subscription -> notificationService, $subscription -> queryId, $subscription -> resultId);
175
							list($subscription -> alertModeName, $subscription -> batchPeriod) = $this -> getAlertModeNameAndBatchPeriod($subscription -> alertMode, $subscription -> subscriber);
176
							$result[] = $subscription;
177
						}
178
						if (count($subscriptions) < $this -> pageSize)
179
							break;
180
					}
181
				}
182
			}
183
			// sort subscriptions
184
			usort($result, function ($subscription1, $subscription2) {
185
				$topicComparison = strcmp($subscription1 -> topic, $subscription2 -> topic);
186
				$alertModeComparison = strcmp($subscription1 -> alertModeName, $subscription2 -> alertModeName);
187
				$batchPeriodComparison = strcmp($subscription1 -> batchPeriod, $subscription2 -> batchPeriod);
188
				return ($topicComparison == 0) ? (($alertModeComparison == 0) ? $batchPeriodComparison : $alertModeComparison) : $topicComparison;			
189
			});
190
			JLog :: add ('Retrieved ' . count($result) . ' subscriptions (user: ' . $user -> get('username') . ')', JLog :: INFO, self :: LOG);
191
			return $result;
192
		} catch (Exception $e) {
193
			JLog :: add('Error retrieving subscriptions (user: ' . $user -> get('username') . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
194
			return NULL;
195
		}
196
	}
197

  
198
	// Retrieve alert topics.
199
	// $parent the id of the parent topic of the topcis to retrieve
200
	// $name retrieve only topics whose name contains this substring
201
	// $limit the maximum number of topics to retrieve
202
	// return the alert topics matching the criteria specified (array) or NULL if any errors occur
203
	private function _getTopics($parent, $name, $limit) {
204
		try {
205
			$query = $this -> db -> getQuery(TRUE);
206
			$query -> select('id, name, description, templateId, notificationService, queryId, resultId');
207
			$query -> from('#__openaire_topic_hierarchy');
208
			$query -> where(($parent == NULL) ? 'parent IS NULL' : ('parent = ' . intval($parent)));
209
			$query -> where('name LIKE CONCAT(\'%\', ' . $this -> db -> quote($name) . ', \'%\')');
210
			$query -> order('id');
211
			$this -> db -> setQuery($query, 0, intval($limit));
212
			$topics = $this -> db -> loadObjectList();
213
			if ($topics === NULL)
214
				throw new Exception($this -> db -> getErrorMsg() . ' (' . $this -> db -> getErrorNum() . ')');
215
			JLog :: add('Retrieved ' . count($topics) . ' topics (parent: ' . (($parent == NULL) ? 'NULL' : $parent) . ', name: ' . $name . ', limit: ' . $limit . ')', JLog :: INFO, self :: LOG);
216
			return $topics;
217
		} catch (Exception $e) {
218
			JLog :: add('Error retrieving topics (parent: ' . (($parent == NULL) ? 'NULL' : $parent) . ', name: ' . $name . ', limit: ' . $limit . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
219
			return NULL;
220
		}
221
	}
222
	
223
	// Retrieve the alert modes available to a user.
224
	// $user the user to retrieve alert modes for
225
	// return the alert modes available to the user specified (array) or NULL if any errors occur
226
	private function _getAlertModes($user) {
227
		try {
228
			$query = $this -> db -> getQuery(TRUE);
229
			$query -> select(array('id', 'name', 'description', 'batch'));
230
			$query -> from('#__openaire_alert_modes');
231
			if ($user -> username != 'admin')
232
				$query -> where('NOT `adminOnly`');
233
			$this -> db -> setQuery($query);
234
			$alertModes = $this -> db -> loadObjectList();
235
			if ($alertModes === NULL)
236
				throw new Exception($this -> db -> getErrorMsg() . ' (' . $this -> db -> getErrorNum() . ')');
237
			JLog :: add('Retrieved ' . count($alertModes) . ' alert modes (user: ' . $user -> get('username') . ')', JLog :: INFO, self :: LOG);
238
			return $alertModes;
239
		} catch (Exception $e) {
240
			JLog :: add('Error retrieving alert modes (user: ' . $user -> get('username') . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
241
			return NULL;
242
		}
243
	}
244
	
245
	// Add a new subscription.
246
	// $templateId the unique identifier of the template of the new subscription
247
	// $notificationService the notification service of the new subscription
248
	// $queryId the unique identifier of the query of the new subscription
249
	// $resultId the unique identifier of the result of the new subscription
250
	// $alertMode the alert mode of the new subscription
251
	// $batchPeriod the batch period of the new subscription
252
	// $user the user to add the new subscription for
253
	private function _addSubscription($templateId, $notificationService, $queryId, $resultId, $alertMode, $batchPeriod, $user) {
254
		try {
255
			list($alertMode, $subscriber) = $this -> getAlertModeAndSubscriber($alertMode, $batchPeriod, $user);
256
			$this -> client -> addSubscription(new AlertSubscription(array('templateId' => $templateId, 'notificationService' => $notificationService, 'queryId' => $queryId, 'resultId' => $resultId, 'alertMode' => $alertMode, 'subscriber' => $subscriber)));
257
			JLog :: add('Added subscription (template: ' . $templateId . ', notification service: ' . $notificationService . ', query: ' . $queryId . ', result: ' . $resultId . ', alert mode: ' . $alertMode . ', batch period: ' . $batchPeriod . ', user: ' . $user -> get('username') . ')', JLog :: INFO, self :: LOG);
258
		} catch (Exception $e) {
259
			JLog :: add('Error adding subscription (template: ' . $templateId . ', notification service: ' . $notificationService . ', query: ' . $queryId . ', result: ' . $resultId . ', alert mode: ' . $alertMode . ', batch period: ' . $batchPeriod . ', user: ' . $user -> get('username') . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
260
		}	
261
	}
262
	
263
	// Remove a subscription.
264
	// $templateId the unique identifier of the template of the subscription to remove
265
	// $notificationService the notification service of the subscription to remove
266
	// $queryId the unique identifier of the query of the subscription to remove
267
	// $resultId the unique identifier of the result of the subscription to remove
268
	// $alertMode the alert mode of the subscription to remove
269
	// $subscriber the subscriber URI of the subscription to remove
270
	private function _removeSubscription($templateId, $notificationService, $queryId, $resultId, $alertMode, $subscriber) {
271
		try {
272
			$this -> client -> removeSubscription(new AlertSubscription(array('templateId' => $templateId, 'notificationService' => $notificationService, 'queryId' => $queryId, 'resultId' => $resultId, 'alertMode' => $alertMode, 'subscriber' => $subscriber)));
273
			JLog :: add('Removed subscription (template: ' . $templateId . ', notification service: ' . $notificationService . ', query: ' . $queryId . ', result: ' . $resultId . ', alert mode: ' . $alertMode . ', subscriber: ' . $subscriber . ')', JLog :: INFO, self :: LOG);
274
		} catch (Exception $e) {
275
			JLog :: add('Error removing subscription (template: ' . $templateId . ', notification service: ' . $notificationService . ', query: ' . $queryId . ', result: ' . $resultId . ', alert mode: ' . $alertMode . ', subscriber: ' . $subscriber . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
276
		}
277
	}
278

  
279
	private function getAlertModeAndSubscriber($alertMode, $batchPeriod, $user) {
280
		switch($alertMode) {
281
		case 'Atom':
282
			$subscriber = $this -> atomUrn;
283
			break;
284
		case 'JDBC':
285
			$subscriber = $this -> jdbcUri . '&table=' . urlencode($this -> databasePrefix . 'openaire_alerts') . '&username=' . urlencode($user -> get('username')) . '&time=' . urlencode('$time') . '&title=' . urlencode('$title') . '&message=' . urlencode('$message') . '&link=' . urlencode('$link');
286
			break;
287
		case 'Joomla!':
288
			$subscriber = $this -> jdbcUri . '&tablePrefix=' . urlencode($this -> databasePrefix) . '&category=' . urlencode($this -> newsCategory) . '&userId=' . urlencode($this -> newsUser);
289
			break;
290
		case 'SMTP':
291
			$subscriber = 'mailto:' . $user -> get('email');
292
			break;
293
		case 'twitter':
294
			$subscriber = 'data:accessToken=' . urlencode($this -> twitterAccessToken) . '&accessTokenSecret=' . urlencode($this -> twitterAccessTokenSecret);
295
			break;
296
		}
297
		if (($batchPeriod !== 0) && ($batchPeriod !== '0')) { // convert alert mode to batch alert mode
298
			$alertMode = 'Batch ' . $alertMode;
299
			$subscriber = 'batch:' . $subscriber . '#' . $batchPeriod;
300
		}
301
		return array($alertMode, $subscriber);
302
	}
303
	
304
	private function getAlertModeNameAndBatchPeriod($alertMode, $subscriberUri) {
305
		if ((strpos($alertMode, 'Batch ') === 0) && (strpos($subscriberUri, 'batch:') === 0)) { // alert mode is a batch alert mode
306
			$alertMode = substr($alertMode, strlen('Batch ')); // ommit 'Batch ' to get alert mode
307
			$batchPeriod = substr($subscriberUri, strpos($subscriberUri, '#') + 1); // find batch period
308
			switch ($batchPeriod) {
309
			case 30 * 24 * 60:
310
				$batchPeriod = 'monthly';
311
				break;
312
			case 15 * 24 * 60:
313
				$batchPeriod = 'bi-monthly';
314
				break;
315
			case 7 * 24 * 60:
316
				$batchPeriod = 'weekly';
317
				break;
318
			case 24 * 60:
319
				$batchPeriod = 'daily';
320
				break;
321
			case 0: // batch period is either zero or null; make it non-batch
322
			case '0':
323
			case NULL:
324
				$batchPeriod = 'as it happens';
325
				break;
326
			default:
327
				$batchPeriod = 'every ' . $batchPeriod . ' minute(s)';
328
			}
329
		} else // alert mode is not a batch alert mode
330
			$batchPeriod = 'as it happens';
331
		$query = $this -> db -> getQuery(TRUE);
332
		$query -> select('name');
333
		$query -> from('#__openaire_alert_modes');
334
		$query -> where('id = ' . $this -> db -> quote($alertMode));
335
		$this -> db -> setQuery($query);
336
		$alertModeName = $this -> db -> loadResult();
337
		if ($alertModeName === NULL)
338
			throw new Exception($this -> db -> getErrorMsg() . ' (' . $this -> db -> getErrorNum() . ')');
339
		return array($alertModeName, $batchPeriod);
340
	}
341
	
342
	private function getFullTopicName($templateId, $notificationService, $queryId, $resultId) {
343
		$query = $this -> db -> getQuery(TRUE);
344
		$query -> select('parent, name');
345
		$query -> from('#__openaire_topic_hierarchy');
346
		$query -> where('templateId = ' . $this -> db -> quote($templateId));
347
		$query -> where('notificationService = ' . $this -> db -> quote($notificationService));
348
		$query -> where('queryId = ' . $this -> db -> quote($queryId));
349
		$query -> where('resultId = ' . $this -> db -> quote($resultId));
350
		$this -> db -> setQuery($query);
351
		$topic = $this -> db -> loadObject();
352
		if ($topic === NULL)
353
			throw new Exception($this -> db -> getErrorMsg() . ' (' . $this -> db -> getErrorNum() . ')');
354
		return ($topic -> parent == NULL) ? $topic -> name : ($this -> getTopicNameById($topic -> parent) . ' ' . $topic -> name);
355
	}
356
	
357
	private function getTopicNameById($id) {
358
		$query = $this -> db -> getQuery(TRUE);
359
		$query -> select('parent, name');
360
		$query -> from('#__openaire_topic_hierarchy');
361
		$query -> where('id = ' . intval($id));
362
		$this -> db -> setQuery($query);
363
		$topic = $this -> db -> loadObject();		
364
		if ($topic === NULL)
365
			throw new Exception($this -> db -> getErrorMsg() . ' (' . $this -> db -> getErrorNum() . ')');
366
		return ($topic -> parent == NULL) ? $topic -> name : ($this -> getTopicNameById($topic -> parent) . ' ' . $topic -> name);
367
	}
368
}
369

  
modules/uoa-joomla/trunk/joomla-3.4/com_openaire_beta/site/models/statistics.php
1
<?php
2

  
3
defined('_JEXEC') or die('Access denied');
4

  
5
jimport('joomla.application.component.helper');
6
jimport('joomla.application.component.model');
7
jimport('joomla.base.object');
8
jimport('joomla.cache.cache');
9
jimport('joomla.log.log');
10

  
11
$GLOBALS['THRIFT_ROOT'] = dirname(__FILE__) . DS . 'thrift';
12
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'Thrift.php');
13
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'protocol' . DS . 'TBinaryProtocol.php');
14
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'transport' . DS . 'TSocket.php');
15
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'transport' . DS . 'TBufferedTransport.php');
16
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'packages' . DS . 'OpenAIREConnector' . DS . 'OpenAIREConnector.php');
17

  
18
// This model manages statistics.
19
class OpenAireModelStatistics extends JModelItem {
20
	const STATISTICS_CACHE_ID = 'statistics';
21
	const PUBLICATIONS_BY_PROGRAMME_CACHE_ID = 'publications.programme';
22
	const PUBLICATIONS_BY_SCIENTIFIC_AREA_CACHE_ID = 'publications.scientific.area';
23
	const PUBLICATIONS_BY_COUNTRY_CACHE_ID = 'publications.country';
24
	const PUBLICATIONS_BY_INSTITUTION_CACHE_ID = 'publications.institution';
25
	const CACHE_GROUP = 'openaire.statistics';
26
	const LOG = 'openaire';
27
	
28
	private $transport;
29
	private $client;
30
	private $cache;
31

  
32
	// Construct a new OpenAireModelStatistics.
33
	// $configuration the configuration to use
34
	public function __construct($configuration) {
35
		parent :: __construct($configuration);
36
		$parameters = JComponentHelper :: getParams('com_openaire');
37
		$socket = new TSocket($parameters -> get('thriftHost'), intval($parameters -> get('thriftPort')));
38
		$socket -> setRecvTimeout(intval($parameters -> get('thriftTimeout')));
39
		$this -> transport = new TBufferedTransport($socket);
40
		$this -> client = new OpenAIREConnectorClient(new TBinaryProtocol($this -> transport));
41
		$this -> cache = JCache :: getInstance();
42
		$this -> transport -> open();
43
	}
44
	
45
	// Close Thrift transport.
46
	public function __destruct() {
47
		$this -> transport -> close();
48
	}
49

  
50
	// Retrieve statistics using cache if enabled.
51
	// return statistics (object)
52
	public function getStatistics() {
53
/*
54
		if ($this -> cache -> getCaching()) {
55
			$statistics = $this -> cache -> get(self :: STATISTICS_CACHE_ID, self :: CACHE_GROUP);
56
			if ($statistics === NULL) {
57
				$statistics = $this -> _getStatistics();
58
				$this -> cache -> store($statistics, self :: STATISTICS_CACHE_ID, self :: CACHE_GROUP);
59
			}
60
		} else
61
*/
62
			$statistics = $this -> _getStatistics();
63
		return $statistics;
64
	}
65
	
66
	// Retrieve publications by access mode using cache if enabled.
67
	// return publications by access mode (array)
68
	public function getPublicationsByAccessMode() {
69
/*
70
		if ($this -> cache -> getCaching()) {
71
			$publicationsByAccessMode = $this -> cache -> get(self :: PUBLICATIONS_BY_ACCESS_MODE_CACHE_ID, self :: CACHE_GROUP);
72
			if ($publications === NULL) {
73
				$publicationsByAccessMode = $this -> _getPublicationsByAccessMode();
74
				$this -> cache -> store($publicationsByAccessMode, self :: PUBLICATIONS_BY_ACCESS_MODE_CACHE_ID, self :: CACHE_GROUP);
75
			}
76
		} else
77
*/
78
			$publicationsByAccessMode = $this -> _getPublicationsByAccessMode();
79
		return $publicationsByAccessMode;
80
	}
81
	
82
	// Retrieve publications by programme using cache if enabled.
83
	// limit the maximum number of programmes to retrieve
84
	// return publications by programme (array)
85
	public function getPublicationsByProgramme($limit) {
86
/*
87
		if ($this -> cache -> getCaching()) {
88
			$id = self :: PUBLICATIONS_BY_PROGRAMME_CACHE_ID . '.' . $limit;
89
			$publicationsByProgramme = $this -> cache -> get($id, self :: CACHE_GROUP);
90
			if ($publicationsByProgramme === NULL) {
91
				$publicationsByProgramme = $this -> _getPublicationsByProgramme($limit);
92
				$this -> cache -> store($publicationsByProgramme, $id, self :: CACHE_GROUP);
93
			}
94
		} else
95
*/
96
			$publicationsByProgramme = $this -> _getPublicationsByProgramme($limit);
97
		return $publicationsByProgramme;
98
	}
99
		
100
	// Retrieve publications by scientific area using cache if enabled.
101
	// limit the maximum number of scientific areas to retrieve
102
	// return publications by scientific area (array)
103
	public function getPublicationsByScientificArea($limit) {
104
/*
105
		if ($this -> cache -> getCaching()) {
106
			$id = self :: PUBLICATIONS_BY_SCIENTIFIC_AREA_CACHE_ID . '.' . $limit;
107
			$publicationsByScientificArea = $this -> cache -> get($id, self :: CACHE_GROUP);
108
			if ($publicationsByScientificArea === NULL) {
109
				$publicationsByScientificArea = $this -> _getPublicationsByScientificArea($limit);
110
				$this -> cache -> store($publicationsByScientificArea, $limit, self :: CACHE_GROUP);
111
			}
112
		} else
113
*/
114
			$publicationsByScientificArea = $this -> _getPublicationsByScientificArea($limit);
115
		return $publicationsByScientificArea;
116
	}
117
		
118
	// Retrieve publications by country using cache if enabled.
119
	// limit the maximum number of countries to retrieve
120
	// return publications by country (array)
121
	public function getPublicationsByCountry($limit) {
122
/*
123
		if ($this -> cache -> getCaching()) {
124
			$id = self :: PUBLICATIONS_BY_COUNTRY_CACHE_ID . '.' . $limit;
125
			$publicationsByCountry = $this -> cache -> get($id, self :: CACHE_GROUP);
126
			if ($publicationsByCountry === NULL) {
127
				$publicationsByCountry = $this -> _getPublicationsByCountry($limit);
128
				$this -> cache -> store($publicationsByCountry, $id, self :: CACHE_GROUP);
129
			}
130
		} else
131
*/
132
			$publicationsByCountry = $this -> _getPublicationsByCountry($limit);
133
		return $publicationsByCountry;
134
	}
135
		
136
	// Retrieve publications by institution using cache if enabled.
137
	// limit the maximum number of institutions to retrieve
138
	// return publications by institution (array)
139
	public function getPublicationsByInstitution($limit) {
140
/*
141
		if ($this -> cache -> getCaching()) {
142
			$id = self :: PUBLICATIONS_BY_INSTITUTION_CACHE_ID . '.' . $limit;
143
			$publicationsByInstitution = $this -> cache -> get($id, self :: CACHE_GROUP);
144
			if ($publicationsByInstitution === NULL) {
145
				$publicationsByInstitution = $this -> _getPublicationsByInstitution($limit);
146
				$this -> cache -> store($publicationsByInstitution, $id, self :: CACHE_GROUP);
147
			}
148
		} else
149
*/
150
			$publicationsByInstitution = $this -> _getPublicationsByInstitution($limit);
151
		return $publicationsByInstitution;
152
	}
153
	
154
	// Retrieve statistics.
155
	// return the statistics (object) or NULL if any errors occur
156
	private function _getStatistics() {
157
		try {
158
			$time = microtime(TRUE);
159
			$statistics = $this -> client -> getStatistics();
160
			JLog :: add('Retrieved statistics in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
161
			return $statistics;
162
		} catch (Exception $e) {
163
			JLog :: add('Error retrieving statistics: ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
164
			return NULL;
165
		}
166
	}
167
	
168
	// Retrieve publications by access mode.
169
	// return publications by access mode (array) or NULL if any errors occur
170
	private function _getPublicationsByAccessMode() {
171
		try {
172
			$time = microtime(TRUE);
173
			$publicationsByAccessMode = $this -> client -> getPublicationsByAccessMode();
174
			JLog :: add('Retrieved ' . count($publicationsByAccessMode) . ' publications by access mode entries in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
175
			return $publicationsByAccessMode;
176
		} catch (Exception $e) {
177
			JLog :: add('Error retrieving publications by acces mode: ' . $e -> getMessage());
178
			return NULL;
179
		}
180
	}
181
	
182
	// Retrieve publications by programme.
183
	// limit the maximum number of programmes to retrieve
184
	// return publications by programme (array) or NULL if any errors occur
185
	private function _getPublicationsByProgramme($limit) {
186
		try {
187
			$time = microtime(TRUE);
188
			$publicationsByProgramme = $this -> client -> getPublicationsByProgramme($limit);
189
			JLog :: add('Retrieved ' . count($publicationsByProgramme) . ' publications by programme entries in ' . (microtime(TRUE) - $time) . ' s (limit: ' . $limit . ')', JLog :: INFO, self :: LOG);
190
			return $publicationsByProgramme;
191
		} catch (Exception $e) {
192
			JLog :: add('Error retrieving publications by programme (limit: ' . $limit . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
193
			return NULL;
194
		}
195
	}
196
	
197
	// Retrieve publications by scientific area.
198
	// limit the maximum number of scientific areas to retrieve
199
	// return publications by scientific area (array) or NULL if any errors occur
200
	private function _getPublicationsByScientificArea($limit) {
201
		try {
202
			$time = microtime(TRUE);
203
			$publicationsByScientificArea = $this -> client -> getPublicationsByScientificArea($limit);
204
			JLog :: add('Retrieved ' . count($publicationsByScientificArea) . ' publications by scientific area entries in ' . (microtime(TRUE) - $time) . ' s (limit: ' . $limit . ')', JLog :: INFO, self :: LOG);
205
			return $publicationsByScientificArea;
206
		} catch (Exception $e) {
207
			JLog :: add('Error retrieving publications by scientific area (limit: ' . $limit . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
208
			return NULL;
209
		}
210
	}
211

  
212
	// Retrieve publications by country.
213
	// limit the maximum number of countries to retrieve
214
	// return publications by country (array) or NULL if any errors occur
215
	private function _getPublicationsByCountry($limit) {
216
		try {
217
			$time = microtime(TRUE);
218
			$publicationsByCountry = $this -> client -> getPublicationsByCountry($limit);
219
			JLog :: add('Retrieved ' . count($publicationsByCountry) . ' publications by country entries in ' . (microtime(TRUE) - $time) . ' s (limit: ' . $limit . ')', JLog :: INFO, self :: LOG);
220
			return $publicationsByCountry;
221
		} catch (Exception $e) {
222
			JLog :: add('Error retrieving publications by country (limit: ' . $limit . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
223
			return NULL;
224
		}
225
	}
226

  
227
	// Retrieve publications by institution.
228
	// limit the maximum number of institutions to retrieve
229
	// return publications by institution (array) or NULL if any errors occur
230
	private function _getPublicationsByInstitution($limit) {
231
		try {
232
			$time = microtime(TRUE);
233
			$publicationsByInstitution = $this -> client -> getPublicationsByInstitution($limit);
234
			JLog :: add('Retrieved ' . count($publicationsByInstitution) . ' publications by institution entries in ' . (microtime(TRUE) - $time) . ' s (limit: ' . $limit . ')', JLog :: INFO, self :: LOG);
235
			return $publicationsByInstitution;
236
		} catch (Exception $e) {
237
			JLog :: add('Error retrieving publications by institution (limit: ' . $limit . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
238
			return NULL;
239
		}
240
	}
241
}
242

  
modules/uoa-joomla/trunk/joomla-3.4/com_openaire_beta/site/models/thrift
1
link ../../../thrift/
2 0

  
modules/uoa-joomla/trunk/joomla-3.4/com_openaire_beta/site/models/claimsearch.php
1
<?php
2

  
3
defined('_JEXEC') or die('Access denied');
4

  
5
jimport('joomla.application.component.model');
6
jimport('joomla.http.http');
7
jimport('joomla.log.log');
8
 
9
// This model manages claims.
10
class OpenAireModelClaimSearch extends JModelItem {
11
    const SELECTED_PROJECTS = 'selectedProjects';
12
	const SELECTED_CONCEPTS = 'selectedConcepts';
13
	const SELECTED_PUBLICATIONS = 'selectedPublications';
14
	const SEARCH_DOI_CACHE_ID = 'search.doi';
15
	const SEARCH_DATASET_CACHE_ID = 'search.datacite';
16
	const SEARCH_ORCID_CACHE_ID = 'search.orcid';
17
	const CLAIMED_PUBLICATIONS_CACHE_ID = 'claimed.publications';
18
	const CACHE_GROUP = 'openaire.claim';
19
	const CROSSREF_URL = 'http://www.crossref.org/openurl?noredirect=true&pid=antleb%40di.uoa.gr&format=unixref&id=';
20
	const CROSSREF_API_DOI = 'http://api.crossref.org/works/';
21
	const CROSSREF_API_KEYWORD = 'http://api.crossref.org/works?query=';
22
	const DOI_SCHEME = 'doi:';
23
	const DATACITE_URL = 'http://data.datacite.org/application/rdf+xml/';
24
	const DATACITE_URL_KEYWORD = 'http://search.datacite.org/api?q=';
25
	const DATACITE_URL_KEYWORD_REST = '&fl=doi,title,creator,publisher,created&wt=xml';
26
	const DOI_URL = 'http://dx.doi.org/';
27
	const ORCID_URL_PREFIX = 'http://pub.orcid.org/';
28
	const ORCID_URL_PUBLICATIONS_SUFFIX = '/orcid-works';
29
	const ORCID_URL_AUTHOR_SUFFIX = '/orcid-bio';
30
	const HTTP_OK = 200;
31
	const HTTP_NOT_FOUND = 404;
32
	const DOI = 'doi';
33
	const ORCID = 'orcid';
34
	const DATACITE = 'datacite';
35
	const RELATION = 'rels2actions';
36
	const DMF = 'dmf2actions';
37
	const UNDETERMINED = 'Undetermined';
38
	const LOG = 'openaire';
39
	//claim modes
40
	const CLAIM = 'claim';
41
	const CLAIMINLINE = 'claiminline';
42
	const CLAIMINLINE2 = 'claiminline2';
43

  
44
	private $cache;
45
	private $http;
46
        // Construct a new OpenAireModelClaimSearch.
47
	// $configuration the configuration to use
48
	public function __construct($configuration) {
49
		parent :: __construct($configuration);
50
		$this -> cache = JCache :: getInstance();
51
		$this -> http = new JHttp();
52
	}
53
        private function _parseMultipleJsonDOIs($message){
54
            $publications=array();
55
            if(isset($message -> items)){
56
	 		foreach ($message -> items as $item) {
57
                            $publication= $this ->_parseJsonDOI($item);
58
                            if($publication!==null){
59
                             $publications[]=$publication;   
60
                            }
61
                        }
62
            }
63
            return $publications;
64
        }
65
	private function _parseJsonDOI($message) {
66
		$publication = new JObject();
67
		$publication -> id = isset($message -> DOI)?$message -> DOI:NULL;
68
		$publication -> source = self :: DOI;
69
		$publication -> url = isset($message -> URL)?$message -> URL:NULL;
70
		$publication -> accessMode = NULL;
71
		$publication -> datasources = array();
72
		$publication -> title = (isset($message -> title) && isset($message -> title[0]))?$message -> title[0]:NULL;
73
		$publication -> authors =  array();	
74
		if(isset($message -> author)){
75
	 		foreach ($message -> author as $author_item) {
76
	 				$author = new JObject();
77
					$author -> id = NULL;
78
					$author -> lastName = isset($author_item-> family) ?   trim($author_item -> family):NULL;
79
					$author -> firstName = isset($author_item  -> given) ?  trim($author_item -> given):NULL;
80
					$author -> fullName = NULL;
81
					if (($author -> id != NULL) || ($author -> lastName != NULL) || ($author-> firstName != NULL) || ($author -> fullName != NULL))
82
						$publication -> authors[] = $author;
83
			}
84
		}
85
		$publication -> publisher =isset($message -> publisher)?$message -> publisher:NULL;
86
		$publication -> year = (isset($message -> issued )&&isset($message -> issued -> date_parts[0]))?
87
		((isset($message -> issued -> date_parts[0][0]))?$message -> issued -> date_parts[0][0]:NULL):NULL;	
88
 		$publication -> language = NULL;
89
		$publication -> projects = array();
90
		$publication -> embargoEndDate = NULL;
91
		$publication -> description = NULL;
92
		if (($publication -> id != NULL)&&( ($publication -> url != NULL) || ($publication -> title != NULL) || ($publication -> authors != NULL) || ($publication -> year != NULL))) {
93
			return $publication; 
94
		}
95
		return NULL; 
96
		
97
	}
98
                
99
	// Search for a dataset DOI using caching if enabled.
100
	// $doi the dataset DOI to search for
101
	// return a result (object) containing datasets and total
102
	private function _searchDataCiteWithDoi($doi) {
103
		try {
104
			$request = self :: DATACITE_URL . urlencode(trim($doi));
105
			JLog :: add('Requesting ' . $request, JLog :: INFO, self :: LOG);
106
			$time = microtime(TRUE);
107
			$response = $this -> http -> get($request);
108
			JLog :: add('Received response in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
109
			if ($response== NULL)
110
				throw new Exception('no HTTP response');
111
			/*if ($response -> code == self :: HTTP_NOT_FOUND) { // no dataset found; just return empty result
112
				$result = new JObject();
113
				$result -> datasets = array();
114
				$result -> totalDatasets = 0;
115
				JLog :: add('Retrieved 0 DataCite records in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
116
				return $result;
117
			}*/
118
			if ($response -> code != self :: HTTP_OK)
119
				throw new Exception('HTTP response code ' . $response -> code);
120
			$document = new DOMDocument();
121
			$document -> recover = TRUE;
122
			if ($document -> loadXML(trim($response -> body)) == FALSE)
123
				throw new Exception('invalid XML response');
124
			$xpath = new DOMXPath($document);
125
			if ((($descriptionNodes = $xpath -> query('/rdf:RDF/rdf:Description')) == FALSE) || (($descriptionNode = $descriptionNodes -> item(0)) == NULL))
126
				throw new Exception('error parsing DataCite record');
127
			if (($idNodes = $xpath -> query('./j.0:identifier', $descriptionNode)) == FALSE)
128
				throw new Exception('error parsing DataCite record');
129
			if (($titleNodes = $xpath -> query('./j.0:title', $descriptionNode)) == FALSE)
130
				throw new Exception('error parsing DataCite record');
131
			if (($authorNodes = $xpath -> query('./j.0:creator', $descriptionNode)) == FALSE)
132
				throw new Exception('error parsing DataCite record');
133
			if (($yearNodes = $xpath -> query('./j.0:date', $descriptionNode)) == FALSE)
134
				throw new Exception('error parsing DataCite record');
135
			if (($publisherNodes = $xpath -> query('./j.0:publisher', $descriptionNode)) == FALSE)
136
				throw new Exception('error parsing DataCite record');
137
			$dataset = new JObject();
138
			$dataset -> id = (($idNode = $idNodes -> item(0)) == NULL) ? NULL : trim($idNode -> nodeValue);
139
			$dataset -> source = self :: DATACITE;
140
			$dataset -> url = self :: DOI_URL . urlencode(trim($doi));
141
			$dataset -> accessMode = NULL;
142
			$dataset -> datasources = array();
143
			$dataset -> title = (($titleNode = $titleNodes -> item(0)) == NULL) ? NULL : trim($titleNode -> nodeValue);
144
			$dataset -> authors = array();
145
			$dataset -> publisher = (($publisherNode = $publisherNodes -> item(0)) == NULL) ? NULL : trim($publisherNode -> nodeValue);
146
			$dataset -> year = (($yearNode = $yearNodes -> item(0)) == NULL) ? NULL : intval(trim($yearNode -> nodeValue));
147
			$dataset -> language = NULL;
148
			$dataset -> projects = array();
149
			$dataset -> embargoEndDate = NULL;
150
			$dataset -> description = NULL;
151
			foreach ($authorNodes as $authorNode) {
152
				$author = new JObject();
153
				$author -> id = NULL;
154
				$author -> lastName = NULL;
155
				$author -> firstName = NULL;
156
				$author -> fullName = trim($authorNode -> nodeValue);
157
				if ($author -> fullName != NULL)
158
					$dataset -> authors[] = $author;
159
			}
160
			/*$result = new JObject();
161
			$result -> datasets = array();
162
			$result -> totalDatasets = 0;
163
			if (($dataset -> id != NULL) || ($dataset -> url != NULL) || ($dataset -> title != NULL) || ($dataset -> authors != NULL) || ($dataset -> year != NULL)) {
164
				$result -> datasets[] = $dataset;
165
				$result -> totalDatasets = 1;
166
			}*/
167
			JLog :: add('Retrieved DataCite record in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
168
			return $dataset;
169
		} catch (Exception $e) {
170
			JLog :: add('Error performing DataCite search (doi: ' . $doi . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
171
			return NULL;
172
		}
173
	}
174
	private function _searchDataCite($doi, $page, $size) {
175
            $result = new JObject();
176
            $result->datasets = array();
177
            $result->totalPublications = 0;
178
            $result->totalDatasets = 0;
179
            try {
180
                $dois = explode(" ", preg_replace('/\s+/', ' ',$doi));   
181
               
182
                $unique_dois =array_slice( array_unique($dois),0,10);
183
                $pattern1 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b#';
184
                $pattern2 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b#';
185
                if (preg_match($pattern1, $unique_dois[0]) || preg_match($pattern2, $unique_dois[0])) {
186
                    if(count($dois)>10){
187
                       $result = new JObject();
188
                       $result->datasets = array();
189
                       $result->totalPublications = 0;
190
                       $result->totalDatasets = '-';
191
                       $result->maxDoisExceeded = true;
192
                       return $result;
193
                    }
194
                    JLog :: add('It;s a dataset  DOI!!!!!!!!! ' . $dois[0], JLog :: INFO, self :: LOG);
195
                    JLog :: add('Searching for DOIs in Datacite', JLog :: INFO, self :: LOG);
196
                    foreach ($unique_dois as $doi_) {
197
                        JLog :: add('DOI::: ' . $doi_, JLog :: INFO, self :: LOG);
198
                        $dataset = $this->_searchDataCiteWithDoi($doi_);
199
                        if ($dataset != null) {
200
                            $result->datasets[] = $dataset;
201
                        }
202
                    }
203
                }else{
204
                    
205
                    JLog :: add('It;sNOOOOOOOT a dataset  DOI!!!!!!!!! ' . $dois[0], JLog :: INFO, self :: LOG);
206
                }
207
                $result->totalDatasets = count($result->datasets);
208
                if($result->totalDatasets!==0){
209
                    return $result;
210
                }
211
			$request = self :: DATACITE_URL_KEYWORD. urlencode(trim($doi)).self :: DATACITE_URL_KEYWORD_REST."&rows=".$size."&start=".($page-1)*$size;
212
			JLog :: add('Requesting ' . $request, JLog :: INFO, self :: LOG);
213
			$time = microtime(TRUE);
214
			$response = $this -> http -> get($request);
215
			JLog :: add('Received response in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
216
			if ($response== NULL)
217
				throw new Exception('no HTTP response');
218
			if ($response -> code == self :: HTTP_NOT_FOUND) { // no dataset found; just return empty result
219
				$result = new JObject();
220
				//$result -> datasets = array();
221
				$result -> totalDatasets = 0;
222
				$result -> totalPublications = 0;
223
				JLog :: add('Retrieved 0 DataCite records in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
224
				return $result;
225
			}
226
			if ($response -> code != self :: HTTP_OK)
227
				throw new Exception('HTTP response code ' . $response -> code);
228
			$document = new DOMDocument();
229
			$document -> recover = TRUE;
230
			if ($document -> loadXML(trim($response -> body)) == FALSE)
231
				throw new Exception('invalid XML response');
232
			$xpath = new DOMXPath($document);
233
  			if ((($numFoundNodes = $xpath -> query('/response/result[@name = "response"]/@numFound')) == FALSE) || (($numFoundNode = $numFoundNodes -> item(0)) == NULL))
234
				throw new Exception('error parsing DataCite record');
235
			$numFound=((($numFoundNode)) == NULL) ? NULL : trim($numFoundNode -> nodeValue);
236
  			if ((($resultNodes = $xpath -> query('/response/result/doc')) == FALSE) || (($resultNode = $resultNodes -> item(0)) == NULL))
237
				throw new Exception('error parsing DataCite record');                
238
			foreach ($resultNodes as $resultNode) {				 
239
				if (($idNodes = $xpath -> query('./str[@name = "doi"]/text()', $resultNode)) == FALSE)
240
					throw new Exception('error parsing DataCite record');
241
				if (($titleNodes = $xpath -> query('./arr[@name="title"]/str/text()', $resultNode)) == FALSE)
242
					throw new Exception('error parsing DataCite record');
243
				if (($authorNodes = $xpath -> query('./arr[@name = "creator"]/str/text()', $resultNode)) == FALSE)
244
					throw new Exception('error parsing DataCite record');
245
				if (($publisherNodes = $xpath -> query('./str[@name = "publisher"]/text()', $resultNode)) == FALSE)
246
					throw new Exception('error parsing DataCite record');  
247
				if (($yearNodes = $xpath -> query('./date[@name = "created"]/text()', $resultNode)) == FALSE)
248
					throw new Exception('error parsing DataCite record');  
249
				$dataset = new JObject();
250
				$dataset -> id = (($idNode = $idNodes -> item(0)) == NULL) ? NULL : trim($idNode -> nodeValue);
251
				$dataset -> source = self :: DATACITE;
252
				$dataset -> url = self :: DOI_URL . urlencode(trim($dataset -> id));
253
				$dataset -> accessMode = NULL;
254
				$dataset -> datasources = array();
255
				$dataset -> title = (($titleNode = $titleNodes -> item(0)) == NULL) ? NULL : trim($titleNode -> nodeValue);
256
				$dataset -> authors = array();
257
				$dataset -> publisher = (($publisherNode = $publisherNodes -> item(0)) == NULL) ? NULL : trim($publisherNode -> nodeValue);
258
				$dataset -> year = (($yearNode = $yearNodes -> item(0)) == NULL) ? NULL : substr(trim($yearNode -> nodeValue),0,4);
259
				$dataset -> language = NULL;
260
				$dataset -> projects = array();
261
				$dataset -> embargoEndDate = NULL;
262
				$dataset -> description = NULL;				
263
				foreach ($authorNodes as $authorNode) {
264
					$authorName= $authorNode -> nodeValue;	
265
					$author = new JObject();
266
					$author -> id = NULL;
267
					$author -> lastName = NULL;
268
					$author -> firstName = NULL;
269
					$author -> fullName = trim($authorName );
270
					if ($author -> fullName != NULL)
271
						$dataset -> authors[] = $author;
272
				}
273
		
274
				if (($dataset -> id != NULL) || ($dataset -> url != NULL) || ($dataset -> title != NULL) || ($dataset -> authors != NULL) || ($dataset -> year != NULL)) {
275
					$result -> datasets[] = $dataset;
276
					
277
				}
278
			}
279
			//
280
			$result -> totalDatasets =$numFound ;
281
		/*	if(isset($size)&&isset($page)){
282
				$result -> datasets = array_slice($result -> datasets, ($page - 1) * $size, $size);
283
			}*/
284
			JLog :: add('Retrieved DataCite '.count($result -> datasets).' records in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
285
			$result -> totalPublications = 0;
286
			return $result;
287
		} catch (Exception $e) {
288
			JLog :: add('Error performing DataCite search (doi: ' . $doi . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
289
			$result = new JObject();
290
			//$result -> datasets = array();
291
			$result -> totalPublications = 0;
292
			$result -> totalDatasets = 0;
293
			return $result;
294
		}
295
	}
296
	
297
	// Parse a journal out of a DOI record.
298
	// $doi the DOI of the record
299
	// $xpath the DOMXPath to parse
300
	// $journalNode the journal node to start from
301
	// return a result (object) containing publications and total
302
	private function parseJournal($doi, $xpath, $journalNode) {
303
		if (($resourceNodes = $xpath -> query('./journal_article/doi_data/resource', $journalNode)) == FALSE)
304
			throw new Exception('error parsing DOI record');
305
		if (($titleNodes = $xpath -> query('./journal_article/titles/title', $journalNode)) == FALSE)
306
			throw new Exception('error parsing DOI record');
307
		if (($contributorNodes = $xpath -> query('./journal_article/contributors', $journalNode)) == FALSE)
308
			throw new Exception('error parsing DOI record');
309
		if (($yearNodes = $xpath -> query('./journal_article/publication_date/year', $journalNode)) == FALSE)
310
			throw new Exception('error parsing DOI record');
311
		$publication = new JObject();
312
		$publication -> id = $doi;
313
		$publication -> source = self :: DOI;
314
		$publication -> url = (($resourceNode = $resourceNodes -> item(0)) == NULL) ? NULL : trim($resourceNode -> nodeValue);
315
		$publication -> accessMode = NULL;
316
		$publication -> datasources = array();
317
		$publication -> title = (($titleNode = $titleNodes -> item(0)) == NULL) ? NULL : trim($titleNode -> nodeValue);
318
		$publication -> authors = $this -> parseContributors($xpath, $contributorNodes);
319
		$publication -> publisher = NULL;
320
		$publication -> year = (($yearNode = $yearNodes -> item(0)) == NULL) ? NULL : intval(trim($yearNode -> nodeValue));
321
		$publication -> language = NULL;
322
		$publication -> projects = array();
323
		$publication -> embargoEndDate = NULL;
324
		$publication -> description = NULL;
325
		$result = new JObject();
326
		$result -> publications = array();
327
		$result -> totalPublications = 0;
328
		if (($publication -> id != NULL) || ($publication -> url != NULL) || ($publication -> title != NULL) || ($publication -> authors != NULL) || ($publication -> year != NULL)) {
329
			$result -> publications[] = $publication;
330
			$result -> totalPublications = 1;
331
		}
332
		return $result;
333
	}
334

  
335
	// Parse a book out of a DOI record.
336
	// $doi the DOI of the record
337
	// $xpath the DOMXPath to parse
338
	// $bookNode the book node to start from
339
	// return a result (object) containing publications and total	
340
	private function parseBook($doi, $xpath, $bookNode) {
341
		if (($bookMetadataNodes = $xpath -> query('./book_metadata', $bookNode)) == FALSE)
342
			throw new Exception('error parsing DOI record');
343
		if (($bookSeriesMetadataNodes = $xpath -> query('./book_series_metadata', $bookNode)) == FALSE)
344
			throw new Exception('error parsing DOI record');
345
		if (($bookSetMetadataNodes = $xpath -> query('./book_set_metadata', $bookNode)) == FALSE)
346
			throw new Exception('error parsing DOI record');
347
		if ((($metadataNode = $bookMetadataNodes -> item(0)) == NULL) && (($metadataNode = $bookSeriesMetadataNodes -> item(0)) == NULL) && (($metadataNode = $bookSetMetadataNodes -> item(0)) == NULL))
348
			throw new Exception('error parsing DOI record');
349
		if (($resourceNodes = $xpath -> query('./doi_data/resource', $metadataNode)) == FALSE)
350
			throw new Exception('error parsing DOI record');
351
		if (($titleNodes = $xpath -> query('./titles/title', $metadataNode)) == FALSE)
352
			throw new Exception('error parsing DOI record');
353
		if (($contributorNodes = $xpath -> query('./contributors', $metadataNode)) == FALSE)
354
			throw new Exception('error parsing DOI record');
355
		if (($yearNodes = $xpath -> query('./publication_date/year', $metadataNode)) == FALSE)
356
			throw new Exception('error parsing DOI record');
357
		$publication = new JObject();
358
		$publication -> id = $doi;
359
		$publication -> source = self :: DOI;
360
		$publication -> url = (($resourceNode = $resourceNodes -> item(0)) == NULL) ? NULL : trim($resourceNode -> nodeValue);
361
		$publication -> accessMode = NULL;
362
		$publication -> datasources = array();
363
		$publication -> title = (($titleNode = $titleNodes -> item(0)) == NULL) ? NULL : trim($titleNode -> nodeValue);
364
		$publication -> authors = $this -> parseContributors($xpath, $contributorNodes);
365
		$publication -> publisher = NULL;
366
		$publication -> year = (($yearNode = $yearNodes -> item(0)) == NULL) ? NULL : intval(trim($yearNode -> nodeValue));
367
		$publication -> language = NULL;
368
		$publication -> projects = array();
369
		$publication -> embargoEndDate = NULL;
370
		$publication -> description = NULL;
371
		$result = new JObject();
372
		$result -> publications = array();
373
		$result -> totalPublications = 0;
374
		if (($publication -> id != NULL) || ($publication -> url != NULL) || ($publication -> title != NULL) || ($publication -> authors != NULL) || ($publication -> year != NULL)) {
375
			$result -> publications[] = $publication;
376
			$result -> totalPublications = 1;
377
		}
378
		return $result;
379
	}
380
	// Parse a Conference out of a DOI record.
381
	// $doi the DOI of the record
382
	// $xpath the DOMXPath to parse
383
	// $conferenceNode the book node to start from
384
	// return a result (object) containing publications and total	
385
	private function parseConference($doi, $xpath, $conferenceNode) {
386
		 
387
		if (($eventMetadata = $xpath -> query('./event_metadata', $conferenceNode)) == FALSE)
388
			throw new Exception('error parsing DOI record');
389
		if (($proceedingsMetadata = $xpath -> query('./proceedings_metadata', $conferenceNode)) == FALSE)
390
			throw new Exception('error parsing DOI record');	
391
		if (($conferencePaperNodes = $xpath -> query('./conference_paper', $conferenceNode)) == FALSE)
392
			throw new Exception('error parsing DOI record');
393
		if (($resourceNodes = $xpath -> query('./conference_paper/doi_data/resource', $conferenceNode)) == FALSE)
394
			throw new Exception('error parsing DOI record');
395
		if (($titleNodes = $xpath -> query('./conference_paper/titles/title', $conferenceNode)) == FALSE)
396
			throw new Exception('error parsing DOI record');
397
		if (($contributorNodes = $xpath -> query('./conference_paper/contributors', $conferenceNode)) == FALSE)
398
			throw new Exception('error parsing DOI record');
399
		if (($yearNodes = $xpath -> query('./conference_paper/publication_date/year', $conferenceNode)) == FALSE)
400
			throw new Exception('error parsing DOI record');
401
		$publication = new JObject();
402
		$publication -> id = $doi;
403
		$publication -> source = self :: DOI;
404
		$publication -> url = (($resourceNode = $resourceNodes -> item(0)) == NULL) ? NULL : trim($resourceNode -> nodeValue);
405
		$publication -> accessMode = NULL;
406
		$publication -> datasources = array();
407
		$publication -> title = (($titleNode = $titleNodes -> item(0)) == NULL) ? NULL : trim($titleNode -> nodeValue);
408
		$publication -> authors = $this -> parseContributors($xpath, $contributorNodes);
409
		$publication -> publisher = NULL;
410
		$publication -> year = (($yearNode = $yearNodes -> item(0)) == NULL) ? NULL : intval(trim($yearNode -> nodeValue));
411
		$publication -> language = NULL;
412
		$publication -> projects = array();
413
		$publication -> embargoEndDate = NULL;
414
		$publication -> description = NULL;
415
		$result = new JObject();
416
		$result -> publications = array();
417
		$result -> totalPublications = 0;
418
		if (($publication -> id != NULL) || ($publication -> url != NULL) || ($publication -> title != NULL) || ($publication -> authors != NULL) || ($publication -> year != NULL)) {
419
			$result -> publications[] = $publication;
420
			$result -> totalPublications = 1;
421
		}
422
		return $result;
423
	}
424
	// Parse contributor metadata out of a DOI record.
425
	// $doi the DOI of the record
426
	// $xpath the DOMXPath to parse
427
	// $contributorNodes the contributor nodes to start from
428
	// return authors (array)
429
	private function parseContributors($xpath, $contributorNodes) {
430
		$authors = array();
431
		foreach ($contributorNodes as $contributorNode) {
432
			if (($personNameNodes = $xpath -> query('./person_name', $contributorNode)) == FALSE)
433
				throw new Exception('error parsing DOI record');
434
			if (($organizationNodes = $xpath -> query('./organization', $contributorNode)) == FALSE)
435
				throw new Exception('error parsing DOI record');
436
			foreach ($personNameNodes as $personNameNode) {
437
				if (($surnameNodes = $xpath -> query('./surname', $personNameNode)) == FALSE)
438
					throw new Exception('error parsing DOI record');
439
				if (($givenNameNodes = $xpath -> query('./given_name', $personNameNode)) == FALSE)
440
					throw new Exception('error parsing DOI record');
441
				$author = new JObject();
442
				$author -> id = NULL;
443
				$author -> lastName = (($surnameNode = $surnameNodes -> item(0)) == NULL) ? NULL : trim($surnameNode -> nodeValue);
444
				$author -> firstName = (($givenNameNode = $givenNameNodes -> item(0)) == NULL) ? NULL : trim($givenNameNode -> nodeValue);
445
				$author -> fullName = NULL;
446
				if (($author -> id != NULL) || ($author -> lastName != NULL) || ($author -> firstName != NULL) || ($author -> fullName != NULL))
447
					$authors[] = $author;
448
			}
449
			foreach ($organizationNodes as $organizationNode) {
450
				$author = new JObject();
451
				$author -> id = NULL;
452
				$author -> lastName = NULL;
453
				$author -> firstName = NULL;
454
				$author -> fullName = trim($organizationNode -> nodeValue);
455
				if (($author -> id != NULL) || ($author -> lastName != NULL) || ($author -> firstName != NULL) || ($author -> fullName != NULL))
456
					$authors[] = $author;
457
			}
458
		}
459
		return $authors;
460
	}    
461
	private function _searchORCID($orcid, $page, $size) {
462
		try {
463
			$time = microtime(TRUE);
464
			$authorRequest = self :: ORCID_URL_PREFIX . trim($orcid) . self :: ORCID_URL_AUTHOR_SUFFIX;
465
			JLog :: add('Requesting ' . $authorRequest, JLog :: INFO, self :: LOG);
466
			$authorResponse = $this -> http -> get($authorRequest);
467
			JLog :: add('Received response in ' . (microtime(TRUE) - $time) . ' s');
468
			$author = new JObject();	
469
			$result = new JObject();
470
			if ($authorResponse != NULL&&$authorResponse -> code===self :: HTTP_OK){				
471
				/*if ($authorResponse -> code != self :: HTTP_OK)
472
					throw new Exception('HTTP response code ' . $authorResponse -> code);*/					
473
				$authorDocument = new DOMDocument();
474
				$authorDocument -> recover = TRUE;
475
				if ($authorDocument -> loadXML(trim($authorResponse -> body)) == FALSE)
476
					throw new Exception('invalid XML response');
477
				$authorXpath = new DOMXPath($authorDocument);
478
				if ($authorXpath -> registerNamespace('orcid', $authorDocument -> lookupNamespaceUri(NULL)) == FALSE)
479
					throw new Exception('error parsing ORCID bio record');
480
				if (($familyNameNodes = $authorXpath -> query('/orcid:orcid-message/orcid:orcid-profile/orcid:orcid-bio/orcid:personal-details/orcid:family-name')) == FALSE)
481
					throw new Exception('error parsing ORCID bio record');				
482
				if (($givenNamesNodes = $authorXpath -> query('/orcid:orcid-message/orcid:orcid-profile/orcid:orcid-bio/orcid:personal-details/orcid:given-names')) == FALSE)
483
					throw new Exception('error parsing ORCID bio record');
484
				$author -> id = $orcid;
485
				$author -> lastName = (($familyNameNode = $familyNameNodes -> item(0)) == NULL) ? NULL : trim($familyNameNode -> nodeValue);
486
				$author -> firstName = (($givenNamesNode = $givenNamesNodes ->item(0)) == NULL) ? NULL : trim($givenNamesNode -> nodeValue);
487
				$author -> fullName = NULL;
488
			}else{
489
				$time = microtime(TRUE);
490
				$orcid=str_replace(" ","+",$orcid);
491
				//$authorRequest = 'http://pub.orcid.org/search/orcid-bio?q='. trim($orcid);                                
492
                                $authorRequest = 'http://pub.orcid.org/search/orcid-bio?defType=edismax&q='. trim($orcid)."&qf=given-name^1.0+family-name^2.0+other-names^1.0+credit-name^1.0&start=0&rows=10";
493
				JLog :: add('Requesting ' . $authorRequest, JLog :: INFO, self :: LOG);
494
				$authorResponse = $this -> http -> get($authorRequest);
495
				JLog :: add('Received response in ' . (microtime(TRUE) - $time) . ' s');
496
				if ($authorResponse -> code != self :: HTTP_OK)
497
					throw new Exception('HTTP response code ' . $authorResponse -> code);
498
				$authorDocument = new DOMDocument();
499
				$authorDocument -> recover = TRUE;
500
				if ($authorDocument -> loadXML(trim($authorResponse -> body)) == FALSE)
501
					throw new Exception('invalid XML response');
502
				$authorXpath = new DOMXPath($authorDocument);
503

  
504
						
505

  
506
				if ($authorXpath -> registerNamespace('orcid', $authorDocument -> lookupNamespaceUri(NULL)) == FALSE)
507
					throw new Exception('error parsing ORCID bio record');
508
				if (($resultNodes = $authorXpath -> query('/orcid:orcid-message/orcid:orcid-search-results/orcid:orcid-search-result')) == FALSE)
509
					throw new Exception('error parsing ORCID bio record');		
510
				$authors = array();		
511
				foreach ($resultNodes as $resultNode) {					
512
					if (($familyNameNodes = $authorXpath -> query('./orcid:orcid-profile/orcid:orcid-bio/orcid:personal-details/orcid:family-name',$resultNode)) == FALSE)
513
						throw new Exception('error parsing ORCID bio record');				
514
					if (($givenNamesNodes = $authorXpath -> query('./orcid:orcid-profile/orcid:orcid-bio/orcid:personal-details/orcid:given-names',$resultNode)) == FALSE)
515
						throw new Exception('error parsing ORCID bio record');
516
					if (($idNodes = $authorXpath -> query('./orcid:orcid-profile/orcid:orcid-identifier/orcid:path',$resultNode)) == FALSE)
517
						throw new Exception('error parsing ORCID bio record');
518
					if (($relevanceNodes = $authorXpath -> query('./orcid:relevancy-score',$resultNode)) == FALSE)
519
						throw new Exception('error parsing ORCID bio record');
520
					$tempAuthor = new JObject();
521
					$tempAuthor -> id = (($idNode = $idNodes -> item(0)) == NULL) ? NULL : trim($idNode -> nodeValue);
522
					$tempAuthor -> lastName = (($familyNameNode = $familyNameNodes -> item(0)) == NULL) ? NULL : trim($familyNameNode -> nodeValue);
523
					$tempAuthor -> firstName = (($givenNamesNode = $givenNamesNodes ->item(0)) == NULL) ? NULL : trim($givenNamesNode -> nodeValue);
524
					$tempAuthor -> fullName = NULL;
525
					$relevance = (($relevanceNode = $relevanceNodes ->item(0)) == NULL) ? NULL : trim($relevanceNode -> nodeValue);
526
					$authors[] = $tempAuthor;
527
				}
528
				$author= $authors[0];
529
				$authors = array_slice($authors, 0, 10);
530
                                $result ->alternativeAuthors =NULL;
531
                                if($page===1){
532
                                    $result ->alternativeAuthors =$authors;
533
                                }
534
			}
535
			$publicationsRequest = self :: ORCID_URL_PREFIX . trim(((isset($author -> id)&&$author -> id!=null)?$author -> id:$orcid)) . self :: ORCID_URL_PUBLICATIONS_SUFFIX;
536
			JLog :: add('Requesting ' . $publicationsRequest, JLog :: INFO, self :: LOG);
537
			if (($publicationsResponse = $this -> http -> get($publicationsRequest)) == NULL)
538
				throw new Exception('no HTTP response');
539
			if ($publicationsResponse -> code != self :: HTTP_OK)
540
				throw new Exception('HTTP response code ' . $publicationsResponse -> code);
541
			$publicationsDocument = new DOMDocument();
542
			$publicationsDocument -> recover = TRUE;
543
			if ($publicationsDocument -> loadXML(trim($publicationsResponse -> body)) == FALSE)
544
				throw new Exception('invalid XML response');
545
			$publicationsXpath = new DOMXPath($publicationsDocument);
546
			if ($publicationsXpath -> registerNamespace('orcid', $publicationsDocument -> lookupNamespaceUri(NULL)) == FALSE)
547
				throw new Exception('error parsing ORCID works record');
548
			if (($orcidWorkNodes = $publicationsXpath -> query('/orcid:orcid-message/orcid:orcid-profile/orcid:orcid-activities/orcid:orcid-works/orcid:orcid-work')) == FALSE)
549
				throw new Exception('error ORCID works record');
550
		
551
			$result -> publications = array();      
552
                        $dois = array();      
553
                        $i=0;
554
			foreach ($orcidWorkNodes as $orcidWorkNode) { 
555
                            $i++;
556
                            if($i>=($page-1)*$size +1 && $i<=$page*$size ){
557
				if (($putCodeNodes = $publicationsXpath -> query('./@put-code', $orcidWorkNode)) == FALSE)
558
					throw new Exception('error ORCID works record');
559
				if (($urlNodes = $publicationsXpath -> query('./orcid:url', $orcidWorkNode)) == FALSE)
560
					throw new Exception('error ORCID works record');
561
				if (($titleNodes = $publicationsXpath -> query('./orcid:work-title/orcid:title', $orcidWorkNode)) == FALSE)
562
					throw new Exception('error ORCID works record');
563
				if (($yearNodes = $publicationsXpath -> query('./orcid:publication-date/orcid:year', $orcidWorkNode)) == FALSE)
564
					throw new Exception('error ORCID works record');
565
				if (($shortDescriptionNodes = $publicationsXpath -> query('./orcid:short-description', $orcidWorkNode)) == FALSE)
566
					throw new Exception('error ORCID works record');
567
				if (($doiNodes = $publicationsXpath -> query('./orcid:work-external-identifiers/orcid:work-external-identifier[orcid:work-external-identifier-type = "doi"]/orcid:work-external-identifier-id', $orcidWorkNode)) == FALSE)
568
					throw new Exception('error ORCID works record');
569
				$publication = new JObject();
570
				$publication -> id = (($putCodeNode = $putCodeNodes -> item(0)) == NULL) ? NULL : ($author -> id . '-' . trim($putCodeNode -> nodeValue));
571
				$publication -> source = self :: ORCID;
572
				$publication -> url = (($urlNode = $urlNodes -> item(0)) == NULL) ? NULL : trim($urlNode -> nodeValue);
573
				$publication -> accessMode = NULL;
574
				$publication -> datasources = array();
575
				$publication -> title = (($titleNode = $titleNodes -> item(0)) == NULL) ? NULL : trim($titleNode -> nodeValue);
576
				$publication -> authors = array();
577
				$publication -> publisher = NULL;
578
				$publication -> year = (($yearNode = $yearNodes -> item(0)) == NULL) ? NULL : intval(trim($yearNode -> nodeValue));
579
				$publication -> language = NULL;
580
				$publication -> projects = array();
581
				$publication -> embargoEndDate = NULL;
582
				$publication -> description = (($shortDescriptionNode = $shortDescriptionNodes -> item(0)) == NULL) ? NULL : trim($shortDescriptionNode -> nodeValue);
583
				if (($author -> lastName != NULL) || ($author -> firstName != NULL))
584
					$publication -> authors[] = $author;
585
				if ((($doiNode = $doiNodes -> item(0)) != NULL) && (($doiResult = $this -> searchSingleDOI(trim($doiNode -> nodeValue))) != NULL)) { // resolve via DOI
586
					if ($publication -> url == NULL) // set URL if missing
587
						$publication -> url = $doiResult -> url;
588
					if ($publication -> title == NULL) // set title if missing
589
						$publication -> title = $doiResult -> title;
590
					
591
					foreach ($doiResult -> authors as $doiAuthor) { // merge authors
592
						if ((count($publication -> authors) == 0) || ($doiAuthor -> id != $publication -> authors[0] -> id) || ($doiAuthor -> lastName != $publication -> authors[0] -> lastName) || ($doiAuthor -> firstName != $publication -> authors[0] -> firstName) || ($doiAuthor -> fullName != $publication -> authors[0] -> fullName))
593
							$publication -> authors[] = $doiAuthor;
594
					}
595
					if ($publication -> year == NULL) // set year if missing
596
						$publication -> year = $doiResult  -> year;
597
				}				
598
				if (($publication -> id != NULL) || ($publication -> title != NULL) || ($publication -> authors != NULL) || ($publication -> year != NULL) || ($publication -> description != NULL)){
599
                                    if ((($doiNode = $doiNodes -> item(0)) != NULL)) { // resolve via DOI
600
                                        $doi=trim($doiNode -> nodeValue);
601
                                         if((strpos($doi,"DOI: ") !== false)){
602
                                             $doi=explode("DOI: ", $doi)[1];                                        
603
                                         }
604
                                        $dois[$publication -> id]=$doi;                                        
605
                                    }
606
                                    $result -> publications[$publication -> id] = $publication;
607
                                }
608
                            }
609
			}
610
                        // request to crossref via DOI
611
                        $resultsFromDois=$this->_searchMultipleDOIs($dois);
612
                        foreach ($result -> publications as $publication){
613
                            $doi=$dois[$publication -> id];
614
                            if($doi!=null&&$resultsFromDois[$doi]!=null){
615
                                $doiResult=$resultsFromDois[$doi];
616
                            
617
                                    if ($publication -> url == NULL) // set URL if missing                                    
618
                                        $publication -> url = $doiResult -> url;
619
                                    if ($publication -> title == NULL) // set title if missing
620
					$publication -> title = $doiResult -> title;					
621
                                    foreach ($doiResult -> authors as $doiAuthor) { // merge authors
622
					if ((count($publication -> authors) == 0) || ($doiAuthor -> id != $publication -> authors[0] -> id) || ($doiAuthor -> lastName != $publication -> authors[0] -> lastName) || ($doiAuthor -> firstName != $publication -> authors[0] -> firstName) || ($doiAuthor -> fullName != $publication -> authors[0] -> fullName))
623
						$publication -> authors[] = $doiAuthor;
624
                                    }
625
                                    if ($publication -> year == NULL) // set year if missing
626
                        		$publication -> year = $doiResult  -> year;
627
                            }
628
                            
629
                        }
630
                        $result -> totalPublications = $i; 
631
			$result -> totalDatasets = 0;
632
			$result -> author = $author;
633
			JLog :: add('ORCID search retrieved ' . count($result -> publications) . ' publications in ' . (microtime(TRUE) - $time) . ' s (ORCID: ' . $orcid . ', page: ' . $page . ', size: ' . $size . ')', JLog :: INFO, self :: LOG);
634
			return $result;
635
		} catch (Exception $e) {
636
			JLog :: add('Error performing ORCID search (ORCID: ' . $orcid . ', page: ' . $page . ', size: ' . $size . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
637
			$result = new JObject();
638
			$result -> totalPublications = 0;
639
			$result -> totalDatasets = 0;
640
			$result -> author = $author;
641
			return $result;
642
		}
643
	}    
644
	private function _searchDOI($doi, $page, $size) {
645
		try {
646
                        $result = new JObject();
647
                        $result -> publications = array();
648
                        $result -> totalPublications = 0;
649
                        $result -> totalDatasets = 0;	
650
                        $dois = explode(" ", preg_replace('/\s+/', ' ',$doi));                  
651
                        $unique_dois =array_slice( array_unique($dois),0,10);
652
                        $pattern1 ='#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b#';
653
                        $pattern2 ='#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b#';                        
654
                         if (preg_match($pattern1,$unique_dois[0])||preg_match($pattern2,$unique_dois[0])){
655
                              if(count($dois)>10){
656
                                $result = new JObject();
657
                                $result->publications = array();
658
                                $result->totalPublications = '-';
659
                                $result->totalDatasets = 0;
660
                                $result->maxDoisExceeded = true;
661
                                return $result;
662
                             }
663
                            JLog :: add('Searching for DOIs ' , JLog :: INFO, self :: LOG);                                              
664
                            /*foreach($unique_dois as $doi_){
665
                                JLog :: add('DOI::: '.$doi_ , JLog :: INFO, self :: LOG);
666
                                $publication = $this->_searchSingleDOI($doi_);
667
                                if ($publication != null) {
668
                                    $result->publications[] = $publication;
669
                                }
670
                            }*/
671
                            $result->publications= $this->_searchMultipleDOIs($unique_dois);
672
                         }
673
                      
674
                        $result -> totalPublications = count( $result -> publications);
675
			if($result -> totalPublications ===0){
676
				//.'&rows='.$size.'&offset='.$page
677
				$request = "http://api.crossref.org/works?query=" . urlencode( trim($doi))."&rows=".$size."&offset=".($page-1)*$size;
678
				JLog :: add('Requesting ' . $request, JLog :: INFO, self :: LOG);
679
				$time = microtime(TRUE);
680
				$response = $this -> http -> get($request);
681
				JLog :: add('Received response in ' . (microtime(TRUE)  - $time) . ' s', JLog :: INFO, self :: LOG);
682
				if ($response == NULL)
683
					throw new Exception('no HTTP response');
684
				if ($response -> code != self :: HTTP_OK)
685
					throw new Exception('HTTP response code ' . $response -> code);
686
				$res = array();
687
                                $response= $response -> body;
688
                                $response=str_replace("date-parts", "date_parts",$response-> body);
689
                                $response=str_replace("total-results", "total_results",$response);
690
				//$res = json_decode(str_replace("-", "_", $response -> body));
691
                                $res = json_decode($response);
692
				if(isset($res -> status)&&$res -> status === "ok" && isset($res -> message)){
693
					foreach($res ->message -> items as $item){
694
						$publication = $this -> _parseJsonDOI($item);
695
						if($publication!=null){
696
							$result -> publications[] = $publication;
697
						}	
698
					}
699
					$result -> totalPublications = $res -> message ->total_results;
700
					/*if(isset($size)&&isset($page)){
701
						$result -> publications = array_slice($result -> publications, ($page - 1) * $size, $size);
702
					}*/
703
			}
704
		}
705
 				return $result;
706
		} catch (Exception $e) {
707
			JLog :: add('Error performing DOI search (doi: ' . $doi . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
708
			$result = new JObject();
709
				$result -> publications = array();
710
				$result -> totalPublications = 0;
711
				$result -> totalDatasets = 0;
712
				JLog :: add('error parsing DOI record', JLog :: INFO, self :: LOG);
713
				return $result;
714
		}
715
	}
716
        public function searchSingleDOI($doi) {
717
		if ($this -> cache -> getCaching()) {
718
			$cacheId = self :: SEARCH_DOI_CACHE_ID . '.' . $doi;
719
			$results = $this -> cache -> get($cacheId, self :: CACHE_GROUP);
720
			if ($results === FALSE) {
721
				$results = $this -> _searchSingleDOI($doi);
722
				if ($results !== NULL)
723
					$this -> cache -> store($results, $cacheId, self :: CACHE_GROUP);
724
			}
725
		} else
726
			$results = $this -> _searchSingleDOI($doi);
727
		return $results;
728
	}
729
        private function _searchSingleDOI($doi) {
730
		try {                           
731
			$request = self :: CROSSREF_API_DOI . urlencode( trim($doi));
732
			JLog :: add('Requesting ' . $request, JLog :: INFO, self :: LOG);
733
			$time = microtime(TRUE);
734
			$response = $this -> http -> get($request);
735
			JLog :: add('Received response in ' . (microtime(TRUE)  - $time) . ' s', JLog :: INFO, self :: LOG);
736
			if ($response == NULL)
737
				throw new Exception('no HTTP response');
738
			if ($response -> code != self :: HTTP_OK)
739
				throw new Exception('HTTP response code ' . $response -> code);
740
			$res = array();
741
                        $response= $response -> body;
742
                        $response=str_replace("date-parts", "date_parts",$response-> body);
743
                        $response=str_replace("total-results", "total_results",$response);
744
			//$res = json_decode(str_replace("-", "_", $response -> body));
745
                        $res = json_decode($response);				
746
			if(isset($res -> status) && $res -> status === "ok" && isset($res -> message)){				
747
                            $publication = $this -> _parseJsonDOI($res -> message);
748
                            return $publication;					 
749
			}
750
                
751
		} catch (Exception $e) {
752
			JLog :: add('Error performing DOI search (doi: ' . $doi . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
753
			$result = new JObject();
754
				$result -> publications = array();
755
				$result -> totalPublications = 0;
756
				$result -> totalDatasets = 0;
757
				JLog :: add('error parsing DOI record', JLog :: INFO, self :: LOG);
758
				return null;
759
		}
760
	}
761
	private function _searchMultipleDOIs($dois){
762
            try {                           
763
			$request ="http://api.crossref.org/works"."?filter=";
764
                        foreach($dois as $doi){
765
                            $request.="doi:".urlencode( trim($doi)).",";
766
                        }
767
			JLog :: add('Requesting ' . $request, JLog :: INFO, self :: LOG);
768
			$time = microtime(TRUE);
769
			$response = $this -> http -> get($request);
770
			JLog :: add('Received response in ' . (microtime(TRUE)  - $time) . ' s', JLog :: INFO, self :: LOG);
771
			if ($response == NULL)
772
				throw new Exception('no HTTP response');
773
			if ($response -> code != self :: HTTP_OK)
774
				throw new Exception('HTTP response code ' . $response -> code);
775
			$res = array();
776
                        $response=str_replace("date-parts", "date_parts",$response-> body);
777
                        $response=str_replace("total-results", "total_results",$response);
778
                        $res = json_decode($response);	
779
			//$res = json_decode(str_replace("-", "_", $response -> body));				
780
			if(isset($res -> status) && $res -> status === "ok" && isset($res -> message)){				
781
                            $publications = $this ->_parseMultipleJsonDOIs($res -> message);
782
                            return $publications;					 
783
			}
784
                
785
		} catch (Exception $e) {
786
			JLog :: add('Error performing DOI search (doi: ' . $doi . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
787
			$result = new JObject();
788
				$result -> publications = array();
789
				$result -> totalPublications = 0;
790
				$result -> totalDatasets = 0;
791
				JLog :: add('error parsing DOI record', JLog :: INFO, self :: LOG);
792
				return null;
793
		}
794
        }
795
	// Search for a publication DOI using caching if enabled.
796
	// $doi the publication DOI to search for
797
	// return an array of results
798
	public function searchDOI($doi, $page, $size) {
799
		if ($this -> cache -> getCaching()) {
800
			$cacheId = self :: SEARCH_DOI_CACHE_ID . '.' . $doi;
801
			$results = $this -> cache -> get($cacheId, self :: CACHE_GROUP);
802
			if ($results === FALSE) {
803
				$results = $this -> _searchDOI($doi, $page, $size);
804
				if ($results !== NULL)
805
					$this -> cache -> store($results, $cacheId, self :: CACHE_GROUP);
806
			}
807
		} else
808
			$results = $this -> _searchDOI($doi, $page, $size);
809
		return $results;
810
	}
811
	
812
	// Search for a dataset DOI using caching if enabled.
813
	// $doi the dataset DOI to search for
814
	// return a result (object) containing publications and total
815
	public function searchDataCite($doi, $page, $size) {
816
		if ($this -> cache -> getCaching()) {
817
			$cacheId = self :: SEARCH_DATASET_CACHE_ID . '.' . $doi;
818
			$results = $this -> cache -> get($cacheId, self :: CACHE_GROUP);
819
			if ($results === FALSE) {
820
				$results = $this -> _searchDataCite($doi, $page, $size);
821
				if ($results !== NULL)
822
					$this -> cache -> store($results, $cacheId, self :: CACHE_GROUP);
823
			}
824
		} else
825
			$results = $this -> _searchDataCite($doi, $page, $size);
826
		return $results;
827
	}
828
	
829
	// Search for publications in ORCID using caching if enabled.
830
	// $doi the ORCID id to search for
831
	// $page the result page to retrieve
832
	// $size the result page size to use
833
	// return a result (object) containing datasets and total
834
	public function searchORCID($orcid, $page, $size) {
835
		if ($this -> cache -> getCaching()) {
836
			$cacheId = self :: SEARCH_ORCID_CACHE_ID . '.' . $orcid . '.' . $page . '.' . $size;
837
			$results = $this -> cache -> get($cacheId, self :: CACHE_GROUP);
838
			if ($results === FALSE) {
839
				$results = $this -> _searchORCID($orcid, $page, $size);
840
				if ($results !== NULL)
841
					$this -> cache -> store($results, $cacheId, self :: CACHE_GROUP);
842
			}
843
		} else
844
			$results = $this -> _searchORCID($orcid, $page, $size);
845
			
846
		return $results;
847
	}
848
}
849
?>
modules/uoa-joomla/trunk/joomla-3.4/com_openaire_beta/site/models/piwik/PiwikDownload.php
1
<?php
2
/**
3
 * Script for tracking direct downloads with Piwik-powered web analytics.
4
 * 2013-02-27, by Amenel VOGLOZIN @ khalemy.com
5
 * All (my) rights abandoned: my work is public domain and this entire script package comes with absolutely NO WARRANTY.
6
 *
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff