Project

General

Profile

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
$GLOBALS['THRIFT_ROOT'] = dirname(__FILE__) . DS . 'thrift';
10
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'Thrift.php');
11
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'protocol' . DS . 'TBinaryProtocol.php');
12
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'transport' . DS . 'TSocket.php');
13
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'transport' . DS . 'TBufferedTransport.php');
14
require_once($GLOBALS['THRIFT_ROOT'] . DS . 'packages' . DS . 'OpenAIREConnector' . DS . 'OpenAIREConnector.php');
15

    
16

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

    
53
	private $cache;
54
	private $http;
55
	private $transport;
56
	private $client;
57

    
58
	// Construct a new OpenAireModelClaim.
59
	// $configuration the configuration to use
60
	public function __construct($configuration) {
61
		parent :: __construct($configuration);
62
		$this -> cache = JCache :: getInstance();
63
		$this -> http = new JHttp();
64
		$parameters = JComponentHelper :: getParams('com_openaire');
65
		$socket = new TSocket($parameters -> get('thriftHost'), intval($parameters -> get('thriftPort')));
66
		$socket -> setRecvTimeout(intval($parameters -> get('thriftTimeout')));
67
		$this -> transport = new TBufferedTransport($socket);
68
		$this -> client = new OpenAIREConnectorClient(new TBinaryProtocol($this -> transport));
69
		$this -> transport -> open();
70
	}
71
	
72
	// Close Thrift transport
73
	public function __destruct() {
74
		$this -> transport -> close();
75
	}
76
	
77
	// Get the selected projects stored in session.
78
	// return the selected projects (array) or NULL if any errors occur
79
	public function getSelectedProjects($suffix = self :: CLAIM) {
80
		try {
81
			$projects = unserialize(JFactory :: getSession() -> get(self :: SELECTED_PROJECTS . $suffix, serialize(array())));
82
			JLog :: add('Retrieved ' . count($projects) . ' selected projects', JLog :: INFO, self :: LOG);
83
			return $projects;
84
		} catch (Exception $e) {
85
			JLog :: add('Error retrieving selected projects: ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
86
			return NULL;
87
		}
88
	}
89
	
90
	// Add a project to the selected projects stored in session.
91
	// $project the project to add
92
	public function addSelectedProject($project, $suffix = self :: CLAIM) {
93
		try {
94
			$session = JFactory :: getSession();
95
			$projects = unserialize($session -> get(self :: SELECTED_PROJECTS . $suffix, serialize(array())));
96
			$projects[$project -> id] = $project;
97
			$session -> set(self :: SELECTED_PROJECTS . $suffix, serialize($projects));
98
			JLog :: add('Added project ' . $project -> id . ' to selected projects', JLog :: INFO, self :: LOG);
99
		} catch (Exception $e) {
100
			JLog :: add('Error adding project ' . $project -> id . ' to selected projects: ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
101
		}
102
	}
103
	
104
	// Remove a project from the selected projects stored in session.
105
	// $projectId the identifier of the project to remove
106
	public function removeSelectedProject($projectId, $suffix = self :: CLAIM) {
107
		try {
108
			$session = JFactory :: getSession();
109
			$projects = unserialize($session -> get(self :: SELECTED_PROJECTS . $suffix, serialize(array())));			
110
			unset($projects[$projectId]);
111
			$session -> set(self :: SELECTED_PROJECTS . $suffix, serialize($projects));
112
			JLog :: add('Removed project ' . $projectId . ' from selected projects', JLog :: INFO, self :: LOG);
113
		} catch (Exception $e) {
114
			JLog :: add('Error removing project ' . $projectId . ' from selected projects: ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
115
		}
116
	}
117
	
118
        //empties selected concepts
119
	public function emptySelectedProjects($suffix = self :: CLAIM) {
120
		try {
121
			$session = JFactory :: getSession();
122
			$session -> set(self :: SELECTED_PROJECTS . $suffix, serialize(array()));
123
		} catch (Exception $e) {
124
                    ;
125
		}
126
	}
127
             //empties selected publications
128
	public function emptySelectedPublications($suffix = self :: CLAIM) {
129
		try {
130
			$session = JFactory :: getSession();
131
			$session -> set(self :: SELECTED_PUBLICATIONS . $suffix, serialize(array()));
132
		} catch (Exception $e) {
133
                    ;
134
		}
135
	}   
136
	//Get concept using id
137
	//returns concept object or error
138
	public function getConcept($conceptId, $withChildren = false){
139
	    $contexts = $this->getContexts();
140

    
141
            $concept = new JObject();
142
	    $concept->context = new JObject();
143
	    $concept->category = new JObject();
144
            $concept->concepts = array();
145
	    $concept->id = $conceptId;
146
	    
147
            $data = explode("::", $conceptId);
148
            if (count($data) > 1){
149
                list ($context, $category) = $data;
150
                $category = $context . "::" . $category;
151
            }
152
            else{
153
                $context = $data[0]; 
154
                $category = null;
155
            }
156
	    if (!isset($contexts[$context]))
157
	        return NULL;
158

    
159
	    $concept->context->id = $context;
160
	    $concept->context->name = $contexts[$context]->name;
161
	    if ($category == null){
162
                $concept->category = null;
163
                $concept->path = $this->getConceptPath($concept);
164
                return $concept;
165
            }
166
	    if (!isset($contexts[$context]->categories[$category]))
167
	        return NULL;
168

    
169
	    $concept->category->id = $category;
170
	    $concept->category->name = $contexts[$context]->categories[$category]->name;
171

    
172
	    $concepts = $contexts[$context]->categories[$category]->concepts;
173
            $conceptId2 = $category;
174
            for ($i = 2; $i < count($data); $i++){
175
                $conceptId2 = $conceptId2 . "::" . $data[$i];
176
                $concept_s = new JObject();
177
                $concept_s -> id = $conceptId2;
178
                $concept_s -> name = $concepts[$conceptId2] -> name;
179
                $concepts = isset($concepts[$conceptId2] -> concepts)?$concepts[$conceptId2] -> concepts:array();
180
                $concept_s -> concepts = $concepts;
181
                $concept -> concepts[] = $concept_s;
182
            }
183
            
184
	    $concept->path = $this->getConceptPath($concept);
185
	    return $concept;
186
	}
187
	
188
	//Get concept using id
189
	//returns concept object or error
190
	public function getConceptPath($concept){
191
	    $path = $concept->context->name . ($concept->category != null?" > " . $concept->category->name:"");
192
            $concept_parts = array();
193
            foreach ($concept -> concepts as $concept_part){
194
                $concept_parts[] = $concept_part -> name;
195
            }
196
            $path = $path . (count($concept_parts)?" > " . implode(" > ", $concept_parts):"");
197
            return $path;
198
	}
199
	
200
	// Get the selected concepts stored in session.
201
	// return the selected concepts (array) or NULL if any errors occur
202
	public function getSelectedConcepts($suffix = self :: CLAIM) {
203
		try {
204
			$concepts = unserialize(JFactory :: getSession() -> get(self :: SELECTED_CONCEPTS . $suffix, serialize(array())));
205
			JLog :: add('Retrieved ' . count($concepts) . ' selected concepts', JLog :: INFO, self :: LOG);
206
			return $concepts;
207
		} catch (Exception $e) {
208
			JLog :: add('Error retrieving selected concepts: ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
209
			return NULL;
210
		}
211
	}
212
	
213
	// Add a project to the selected projects stored in session.
214
	// $project the project to add
215
	public function addSelectedConcept($concept, $suffix = self :: CLAIM) {
216
		try {
217
			$session = JFactory :: getSession();
218
			$concepts = unserialize($session -> get(self :: SELECTED_CONCEPTS . $suffix, serialize(array())));
219
			$concepts[$concept -> id] = $concept;
220
			$session -> set(self :: SELECTED_CONCEPTS . $suffix, serialize($concepts));
221
			JLog :: add('Added project ' . $concept -> id . ' to selected projects', JLog :: INFO, self :: LOG);
222
		} catch (Exception $e) {
223
			JLog :: add('Error adding project ' . $concept -> id . ' to selected projects: ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
224
		}
225
	}
226
	
227
	// Remove a project from the selected projects stored in session.
228
	// $projectId the identifier of the project to remove
229
	public function removeSelectedConcept($conceptId, $suffix = self :: CLAIM) {
230
		try {
231
			$session = JFactory :: getSession();
232
			$concepts = unserialize($session -> get(self :: SELECTED_CONCEPTS . $suffix, serialize(array())));			
233
			unset($concepts[$conceptId]);
234
			$session -> set(self :: SELECTED_CONCEPTS . $suffix, serialize($concepts));
235
			JLog :: add('Removed project ' . $conceptId . ' from selected projects', JLog :: INFO, self :: LOG);
236
		} catch (Exception $e) {
237
			JLog :: add('Error removing project ' . $conceptId . ' from selected projects: ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
238
		}
239
	}
240
	
241
        //empties selected concepts
242
	public function emptySelectedConcepts($suffix = self :: CLAIM) {
243
		try {
244
			$session = JFactory :: getSession();
245
			$session -> set(self :: SELECTED_CONCEPTS . $suffix, serialize(array()));
246
		} catch (Exception $e) {
247
                    ;
248
		}
249
	}
250
	
251
	
252
	// Get the selected publications stored in session.
253
	// return the selected publications (arary) or NULL if any errors occur
254
	public function getSelectedPublications($suffix = self :: CLAIM) {
255
		try {
256
			$publications = unserialize(JFactory :: getSession() -> get(self :: SELECTED_PUBLICATIONS . $suffix, serialize(array())));
257
			JLog :: add('Retrieved ' . count($publications) . ' selected publications', JLog :: INFO, self :: LOG);
258
			return $publications;
259
		} catch (Exception $e) {
260
			JLog :: add('Error retrieving selected publications: ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
261
			return NULL;
262
		}
263
	}
264
	
265
	// Add a publication to the selected publications stored in session.
266
	// $publication the publication to add
267
	public function addSelectedPublication($publication, $suffix = self :: CLAIM) {
268
		try {
269
			$session = JFactory :: getSession();
270
			$publications = unserialize($session -> get(self :: SELECTED_PUBLICATIONS . $suffix, serialize(array())));
271
			$publications[$publication -> source . $publication -> id] = $publication;
272
			$session -> set(self :: SELECTED_PUBLICATIONS . $suffix, serialize($publications));
273
			JLog :: add('Added ' . $publication -> source . ' publication ' . $publication -> id . ' to selected publications', JLog :: INFO, self :: LOG);
274
		} catch (Exception $e) {
275
			JLog :: add('Error adding ' . $publication -> source . ' publication ' . $publication -> id . ' to selected publications: ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
276
		}
277
	}
278
	
279
	// Remove a publication from the selected publications stored in session.
280
	// $source the source of the publication to remove
281
	// $publicationId the identifier of the publication to remove
282
	public function removeSelectedPublication($source, $publicationId, $suffix = self :: CLAIM) {
283
		try {
284
			$session = JFactory :: getSession();
285
			$publications = unserialize($session -> get(self :: SELECTED_PUBLICATIONS . $suffix, serialize(array())));			 
286
			unset($publications[$source . $publicationId]);			
287
			$session -> set(self :: SELECTED_PUBLICATIONS. $suffix, serialize($publications));			
288
			JLog :: add('Removed ' . $source . ' publication ' . $publicationId . ' from selected publications', JLog :: INFO, self :: LOG);
289
		} catch (Exception $e) {
290
			JLog :: add('Error removing ' . $source . ' publication ' . $publicationId . ' from selected publications: ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
291
		}
292
	}	
293

    
294
	// Claim all the selected publications.
295
	// $user the user to claim publications for
296
	public function claimSelectedPublications($user, $mode = self :: CLAIM, $activePublication = NULL, $suffix = "", $activePublicationType = "publication") {
297
		try {
298
                    
299
			$projects = array_map(function ($project) {
300
                            $p = array();
301
                            $p['projectId'] = $project -> id;
302
                            $p['funder'] = $project -> funder;
303
                            $p['fundingStreamLevel0'] = $project -> fundingStream;
304
                            $p['fundingStreamLevel1'] = $project -> scientificArea;
305
                            $p['fundingStreamLevel2'] = $project -> fundingStreamLevel2;
306
                            $p['name'] = $project -> title;                            
307
                            $p['code'] = $project -> code;
308
                            $p['acronym'] = $project -> acronym;
309
                            $p['type'] = NULL;
310
                                return new Project4Index($p);}, $this -> getSelectedProjects($mode.$suffix));  
311
                        $projects_mini = array_map(function ($project) {                            
312
                            $project2  = new Project();
313
                            $project2 -> projectId = $project -> id;                            
314
                            $project2 -> type = NULL;
315
                                return $project2;}, $this -> getSelectedProjects($mode.$suffix));  
316
			$concepts = array_map(function ($concept) {return $concept -> id;}, $this -> getSelectedConcepts($mode.$suffix));
317
			if ($mode != self :: CLAIMINLINE){
318
				$selectedPublications = $this -> getSelectedPublications($mode.$suffix);
319
			}
320
			else {
321
				$selectedPublications = array($activePublication);
322
			}
323
			$dcSource = NULL;
324
			$subjects = array();
325
			$category = NULL;
326
                        
327
			foreach ($selectedPublications as $publication) {
328
				$authors = array_map(function ($author) {
329
					$a = array();
330
					$a['id'] = $author -> id;
331
					$a['firstName'] = $author -> firstName;
332
					$a['lastName'] = $author -> lastName;
333
					if (($author -> lastName == NULL) && ($author -> fullName != NULL))
334
						$a['lastName'] = $author -> fullName;
335
					return new Author($a);
336
				}, $publication -> authors);
337
				$doi = (($publication -> source == self :: DOI) || ($publication -> source == self :: DATACITE)) ? $publication -> id : NULL;
338
				if ($mode != self :: CLAIMINLINE and $publication -> source != "openaire"){                                    
339
                                    JLog :: add("Projects--->". print_r($projects,true), JLog :: DEBUG, self :: LOG);
340
                                    JLog :: add("Concepts--->". print_r($concepts,true), JLog :: DEBUG, self :: LOG);
341
					$docId = $this -> client -> insertDocument($publication -> id, $publication -> source, $publication -> title, $publication -> description, isset($publication -> license)?$publication -> license:"", $publication -> embargoEndDate, $authors, $publication -> url, $dcSource, $user -> email, $subjects, $publication -> year, $publication -> publisher, $publication -> language, $category, $doi, $projects, $concepts);
342
				}else{
343
                                    
344
					$docId = $publication->id;
345
				}
346
                            foreach ($concepts as $concept)
347
                                    $this -> client -> insertConcept($docId, $publication -> source, $concept, $user -> email, $doi );
348
                            foreach ($projects_mini as $project){
349
                                //TODO Check if project is ok after 
350
                                    $this -> client -> insertProjectRelation($docId, $publication -> source, $project, $user -> email);
351
                            } 
352
                            if ($activePublication != NULL && $mode === self::CLAIMINLINE2){
353
                                    $this -> client -> insertResultRelation($activePublication -> id, $activePublicationType, 
354
                            $activePublication -> source, $docId, $publication -> claim_type, $user -> email);
355
                            }
356
               }
357
               if ($this -> cache -> getCaching()){
358
               		$cacheId = self :: CLAIMED_PUBLICATIONS_CACHE_ID . '.' . $user -> username;
359
                    $this -> cache ->remove($cacheId);
360
               }
361
			JLog :: add('Claimed ' . count($selectedPublications) . ' publications (user: ' . $user -> username . ')', JLog :: INFO, self :: LOG);
362
			return true;
363
		} catch (Exception $e) {
364
			JLog :: add('Error claiming selected publications (user: ' . $user -> username . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
365
			return false;
366
		}	
367
	}		
368

    
369
	// Get the publications claimed by a user using caching if enabled.
370
	// $user the user whose claimed publications to retrieve
371
	// return an array of publications
372
	public function getClaimedPublications($user) {
373
	/*	if ($this -> cache -> getCaching()) {
374
			$cacheId = self :: CLAIMED_PUBLICATIONS_CACHE_ID . '.' . $user -> username;
375
			$publications = $this -> cache -> get($cacheId, self :: CACHE_GROUP);
376
			if ($publications === FALSE) {
377
				$publications = $this -> _getClaimedPublications($user);
378
				if ($publications !== NULL)
379
					$this -> cache -> store($publications, $cacheId, self :: CACHE_GROUP);
380
			}
381
		} else
382
		*/	$publications = $this -> _getClaimedPublications($user);
383
		return $publications;
384
	}
385
        
386
        // Get the publications claimed by a user using caching if enabled.
387
	// $user the user whose claimed publications to retrieve
388
	// return an array of publications
389
	public function getAllClaimedPublications($from, $to) {
390
		/*if ($this -> cache -> getCaching()) {
391
			$cacheId = self :: CLAIMED_PUBLICATIONS_CACHE_ID . '.' . $from . "." . $to;
392
			$publications = $this -> cache -> get($cacheId, self :: CACHE_GROUP);
393
			if ($publications === FALSE) {
394
				$publications = $this -> _getAllClaimedPublications($from, $to);
395
				if ($publications !== NULL)
396
					$this -> cache -> store($publications, $cacheId, self :: CACHE_GROUP);
397
			}
398
		} else*/
399
			$publications = $this -> _getAllClaimedPublicationsExtended($from, $to);
400
		return $publications;
401
	}
402
	
403
	// Get the publications claimed by a user.
404
	// $user the user whose claimed publications to retrieve
405
	// return an array of publications or NULL if any errors occur
406
	private function _getClaimedPublications($user) {
407
		try {
408
			$locale = JFactory :: getLanguage()->getTag();
409
			$claimedPublications = array();
410
			$claimedPublicationsGrouped = array();
411
			$time = microtime(TRUE);
412
			$claims = $this -> client -> getClaimedPublications($user -> email);
413
            foreach ($claims as $claim){
414
                $parsedClaim = $this -> parseClaimedPublication($claim);
415
                if ($parsedClaim == null)
416
                    continue;
417
		$claimedPublications[] = $parsedClaim;
418
            }
419
            $resultsToGet = array();
420
            $projectsToGet = array();
421
            $claimedDocuments = array();
422
            foreach ($claimedPublications as $claimedPublication){
423
                if ($claimedPublication -> publication != null and $claimedPublication -> publication -> id != null)
424
                    $claimedDocuments[$claimedPublication->publicationId] = $claimedPublication -> publication;
425
                if ($claimedPublication -> projectId !== null){
426
                    $projectsToGet[] = $claimedPublication -> projectId;
427
                }
428
                if ($claimedPublication -> targetPublicationId !== null){
429
                    $resultsToGet[] = $claimedPublication -> targetPublicationId;
430
                }
431
                if ($claimedPublication -> targetDatasetId !== null){
432
                    $resultsToGet[] = $claimedPublication -> targetDatasetId;
433
                }
434
                if (($claimedPublication -> publication == null || ($claimedPublication -> publication != null and $claimedPublication -> publication -> id == null))){
435
                    $resultsToGet[] = $claimedPublication -> publicationId;   
436
                }
437
                if ($claimedPublication -> publication == null && $claimedPublication -> type == "dataset"){
438
                    $resultsToGet[] = $claimedPublication -> publicationId;   
439
                }
440
            }
441
            $resultsToGet = array_unique($resultsToGet);
442
            $projectsToGet = array_unique($projectsToGet);
443
            $searchModel = new OpenAireModelSearch();
444
            $results = $searchModel->getResults($resultsToGet, $locale);
445
            $projects = $searchModel->getProjects($projectsToGet, $locale);
446
            $keydResults = array();
447
            $keydProjects = array();
448
            foreach ($results as $result)
449
                $keydResults[$result->id] = $result;
450
            foreach ($projects as $project)
451
                $keydProjects[$project->id] = $project;
452
            
453
            foreach ($claimedPublications as $claimedPublication){
454
                if (!isset($claimedPublicationsGrouped[$claimedPublication -> publicationId])){                      
455
                    if ($claimedPublication -> publication == null ||  $claimedPublication -> publication -> id == null){
456
                        $publication = isset($keydResults[$claimedPublication -> publicationId])?$keydResults[$claimedPublication -> publicationId]:null;
457
                    }
458
                    else{
459
                        $publication = $claimedPublication -> publication;
460
                    }
461
                    if ($publication == null || $publication -> id == null)
462
                        continue;
463
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] = new stdClass();
464
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> publicationId = $claimedPublication -> publicationId;
465
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> date = $claimedPublication -> date;
466
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> publication = $publication;
467
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> publications = array();
468
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> datasets = array();
469
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> projects = array();
470
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> concepts = array();
471
                }
472
                if ($claimedPublicationsGrouped[$claimedPublication -> publicationId] -> date < $claimedPublication -> date)
473
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> date = $claimedPublication -> date;
474
                if ($claimedPublication -> publication != null){
475
                    $claimedConcepts = array();
476
                    foreach ($claimedPublication -> publication -> concepts as $concept){
477
                        $concept = $this->getConcept($concept);
478
                        $claimedConcept = new stdClass();
479
                        $claimedConcept->id = $concept->id;
480
                        $claimedConcept->title = $concept->path;
481
                        $claimedConcept->date = $claimedPublication->date;
482
                        $claimedConcepts[] = $claimedConcept;
483
                    }
484
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> concepts = array_merge($claimedPublicationsGrouped[$claimedPublication -> publicationId] -> concepts, $claimedConcepts);
485
                }
486
                if ($claimedPublication -> targetPublicationId !== null){
487
                    $claimedPublication->title = isset($keydResults[$claimedPublication -> targetPublicationId ])?$keydResults[$claimedPublication -> targetPublicationId ]->title:null;
488
                    if ($claimedPublication->title == null){
489
                        $claimedPublication->title = isset($claimedDocuments[$claimedPublication -> targetDatasetId ])?$claimedDocuments[$claimedPublication -> targetDatasetId ]->title:null;
490
                    }
491
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> publications[] = $claimedPublication;
492
                }
493
                if ($claimedPublication -> targetDatasetId !== null){
494
                    $claimedPublication->title = isset($keydResults[$claimedPublication -> targetDatasetId ])?$keydResults[$claimedPublication -> targetDatasetId ]->title:null;
495
                    if ($claimedPublication->title == null){
496
                        $claimedPublication->title = isset($claimedDocuments[$claimedPublication -> targetDatasetId ])?$claimedDocuments[$claimedPublication -> targetDatasetId ]->title:null;
497
                    }
498
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> datasets[] = $claimedPublication;
499
                }
500
                if ($claimedPublication -> projectId !== null){
501
                    $claimedPublication->title = isset($keydProjects[$claimedPublication -> projectId ])?$keydProjects[$claimedPublication -> projectId ]->title:null;
502
                    $claimedPublication->acronym = isset($keydProjects[$claimedPublication -> projectId ])?$keydProjects[$claimedPublication -> projectId ]->acronym:null;
503
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> projects[] = $claimedPublication;
504
                    
505
                    }
506
            }
507
            JLog :: add('Retrieved ' . count($claimedPublications) . ' claimed publications (user: ' . $user -> username . ') in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
508
            return $claimedPublicationsGrouped;
509
		} catch (Exception $e) {
510
			JLog :: add('Error retrieving claimed publications (user: ' . $user -> username . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
511
			return NULL;
512
		}
513
	}
514
	public function _getAllClaimedPublications($from, $to) {
515
                try {
516
		// submit the docs
517
                    $claimedPublications = array();
518
                    $time1 = strtotime(str_replace("/", "-", $from)) * 1000;
519
                    $time2 = strtotime(str_replace("/", "-", $to)) * 1000;
520
		$list = $this->client ->getAllClaimedPublications($time1, $time2);
521
                foreach ($list as $claim){
522
                    $claimedPublications[] = $this -> parseClaimedPublication($claim);
523
                }
524
                }
525
                catch (Exception $e) {
526
			JLog :: add('Error retrieving all claims (from: ' . $from . ', to: '. $to .'): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
527
			return NULL;
528
		}
529
		return $claimedPublications;
530
	}
531
		// Get the publications claimed  
532
 	// return an array of publications or NULL if any errors occur
533
	private function _getAllClaimedPublicationsExtended($from, $to) {
534
		try {
535
			$locale = JFactory :: getLanguage()->getTag();
536
			$claimedPublications = array();
537
			$claimedPublicationsExtended = array();
538
			$time = microtime(TRUE);
539
			$time1 = strtotime(str_replace("/", "-", $from)) * 1000;
540
			$time2 = strtotime(str_replace("/", "-", $to)) * 1000;
541
			$claims = $this->client ->getAllClaimedPublications($time1, $time2);
542
            foreach ($claims as $claim){
543
                $parsedClaim = $this -> parseClaimedPublication($claim);
544
                if ($parsedClaim == null)
545
                    continue;
546
				$claimedPublications[] = $parsedClaim;
547
            }
548
            $resultsToGet = array();
549
            $projectsToGet = array();
550
            $claimedDocuments = array();
551
            foreach ($claimedPublications as $claimedPublication){
552
                if ($claimedPublication -> publication != null and $claimedPublication -> publication -> id != null)
553
                    $claimedDocuments[$claimedPublication->publicationId] = $claimedPublication -> publication;
554
                if ($claimedPublication -> projectId !== null){
555
                    $projectsToGet[] = $claimedPublication -> projectId;
556
                }
557
                if ($claimedPublication -> targetPublicationId !== null){
558
                    $resultsToGet[] = $claimedPublication -> targetPublicationId;
559
                }
560
                if ($claimedPublication -> targetDatasetId !== null){
561
                    $resultsToGet[] = $claimedPublication -> targetDatasetId;
562
                }
563
                if (($claimedPublication -> publication == null || ($claimedPublication -> publication != null and $claimedPublication -> publication -> id == null))){
564
                    $resultsToGet[] = $claimedPublication -> publicationId;   
565
                }
566
                if ($claimedPublication -> publication == null && $claimedPublication -> type == "dataset"){
567
                    $resultsToGet[] = $claimedPublication -> publicationId;   
568
                }
569
            }
570
            $resultsToGet = array_unique($resultsToGet);
571
            $projectsToGet = array_unique($projectsToGet);
572
            $searchModel = new OpenAireModelSearch();
573
            $results = $searchModel->getResults($resultsToGet, $locale);
574
            $projects = $searchModel->getProjects($projectsToGet, $locale);
575
            $keydResults = array();
576
            $keydProjects = array();
577
            foreach ($results as $result)
578
                $keydResults[$result->id] = $result;
579
            foreach ($projects as $project)
580
                $keydProjects[$project->id] = $project;
581
            
582
            foreach ($claimedPublications as $claimedPublication){
583
                        
584
              /*      if ($claimedPublication -> publication == null ||  $claimedPublication -> publication -> id == null){
585
                       //print_r($claimedPublication -> publication -> concepts);
586
                        $claimedPublication -> publication = isset($keydResults[$claimedPublication -> publicationId])?$keydResults[$claimedPublication -> publicationId]:null;                        
587
                    }
588
                */ 
589
            $claimedPublication->targetConceptId=null;
590
                if ($claimedPublication -> publication != null && isset($claimedPublication -> publication -> concepts )){
591
                    $claimedConcepts = array();
592
                    foreach ($claimedPublication -> publication -> concepts as $concept){
593
                        $concept = $this->getConcept($concept);
594
                        $claimedConcept = new stdClass();
595
                        $claimedConcept->id = $concept->id;
596
                        $claimedConcept->title = $concept->path;
597
                        $claimedConcept->date = $claimedPublication->date;
598
                        $claimedConcepts[] = $claimedConcept;
599
                        $claimedPublication->title=$concept->path;
600
                        $claimedPublication->targetConceptId= $concept->id;
601
                    }
602
                    $claimedPublication ->  concepts= $claimedConcepts;
603
                 }
604
                if ($claimedPublication -> targetPublicationId !== null){
605
                    $claimedPublication->title = isset($keydResults[$claimedPublication -> targetPublicationId ])?$keydResults[$claimedPublication -> targetPublicationId ]->title:null;
606
                    if ($claimedPublication->title == null){
607
                        $claimedPublication->title = isset($claimedDocuments[$claimedPublication -> targetDatasetId ])?$claimedDocuments[$claimedPublication -> targetDatasetId ]->title:null;
608
                    }
609
                 }
610
                if ($claimedPublication -> targetDatasetId !== null){
611
                    $claimedPublication->title = isset($keydResults[$claimedPublication -> targetDatasetId ])?$keydResults[$claimedPublication -> targetDatasetId ]->title:null;
612
                    if ($claimedPublication->title == null){
613
                        $claimedPublication->title = isset($claimedDocuments[$claimedPublication -> targetDatasetId ])?$claimedDocuments[$claimedPublication -> targetDatasetId ]->title:null;
614
                    }
615
                 }
616
                if ($claimedPublication -> projectId !== null){
617
                    $claimedPublication->title = isset($keydProjects[$claimedPublication -> projectId ])?$keydProjects[$claimedPublication -> projectId ]->title:null;
618
                    $claimedPublication->acronym = isset($keydProjects[$claimedPublication -> projectId ])?$keydProjects[$claimedPublication -> projectId ]->acronym:null;
619
                  
620
                    }
621
                    if ($claimedPublication -> publication == null ||  $claimedPublication -> publication -> id == null){
622
                       //print_r($claimedPublication -> publication -> concepts);
623
                        $claimedPublication -> publication = isset($keydResults[$claimedPublication -> publicationId])?$keydResults[$claimedPublication -> publicationId]:null;                        
624
                    }
625
            }
626
            JLog :: add('Retrieved ' . count($claimedPublications) . ' claimed publications in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
627
            return $claimedPublications;
628
		} catch (Exception $e) {
629
			JLog :: add('Error retrieving claimed publications (user: ' . $user -> username . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
630
			return NULL;
631
		}
632
	}              
633
	private function parseClaimedPublication($claim) {
634
		$claimedPublication = new JObject();
635
		$claimedPublication -> date = $claim -> date;
636
		$claimedPublication -> claimType=$claim -> type;
637
		$claimedPublication -> claimId=isset($claim -> id)?$claim -> id:'';		 	 
638
		$document = new DOMDocument();
639
		$document -> recover = TRUE;
640
		if ($document -> loadXML(trim($claim -> xml)) == FALSE)
641
			throw new Exception('invalid XML response');
642
		$xPath = new DOMXPath($document);
643
		switch ($claim -> type) {
644
		case self :: RELATION:
645
			if ((($relationNodes = $xPath -> query('/RELATIONS/RELATION')) == FALSE) || (($relationNode = $relationNodes -> item(0)) == NULL))
646
				throw new Exception('error parsing relation');
647
			if ((($sourceNodes = $xPath -> query('./@source', $relationNode)) == FALSE) || (($sourceNode = $sourceNodes -> item(0)) == NULL))
648
				throw new Exception('error parsing relation source');
649
			if ((($targetNodes = $xPath -> query('./@target', $relationNode)) == FALSE) || (($targetNode = $targetNodes -> item(0)) == NULL))
650
				throw new Exception('error parsing relation target');
651
			if ((($relationTypeNodes = $xPath -> query('./@type', $relationNode)) == FALSE) || (($relationTypeNode = $relationTypeNodes -> item(0)) == NULL))
652
				throw new Exception('error parsing relation type');
653

    
654
			$claimedPublication -> projectId = NULL;
655
			$claimedPublication -> targetDatasetId = NULL;
656
			$claimedPublication -> targetPublicationId = NULL;
657
			$claimedPublication -> date = $claim -> date;
658
			$claimedPublication -> type = "publication";
659

    
660
			if ($relationTypeNode -> nodeValue == "resultProject"){
661
				$claimedPublication -> projectId = trim(str_replace("40|", "", $targetNode -> nodeValue));
662
				$claimedPublication -> type = "publication";
663

    
664
			}
665

    
666
			else if ($relationTypeNode -> nodeValue == "resultResult_publicationpublication_isRelatedTo"){
667
				$sourceNode -> nodeValue = str_replace("50|", "", $sourceNode -> nodeValue);
668
				$claimedPublication -> targetPublicationId = trim(str_replace("50|", "", $targetNode -> nodeValue));
669
				$claimedPublication -> type = "publication";
670
			}
671

    
672
			else if ($relationTypeNode -> nodeValue == "resultResult_publicationdataset_isRelatedTo"){
673
				$sourceNode -> nodeValue = str_replace("50|", "", $sourceNode -> nodeValue);
674
				$claimedPublication -> targetDatasetId = trim(str_replace("50|", "", $targetNode -> nodeValue));
675
				$claimedPublication -> type = "publication";
676
			}
677
			else if ($relationTypeNode -> nodeValue == "resultResult_datasetpublication_isRelatedTo"){// openaire dataset me publ
678
				$sourceNode -> nodeValue = str_replace("50|", "", $sourceNode -> nodeValue);
679
				$claimedPublication -> targetPublicationId = trim(str_replace("50|", "", $targetNode -> nodeValue));
680
				$claimedPublication -> type = "dataset";
681
			}
682
			else if ($relationTypeNode -> nodeValue == "resultResult_datasetdataset_isRelatedTo"){// openaire dataset me ext dataset
683
				$sourceNode -> nodeValue = str_replace("50|", "", $sourceNode -> nodeValue);
684
				$claimedPublication -> targetDatasetId = trim(str_replace("50|", "", $targetNode -> nodeValue));
685
				$claimedPublication -> type = "dataset";
686
			}
687
			else {
688
				return null;
689
			}
690
            $claimedPublication -> publication = NULL;
691
			$claimedPublication -> publicationId = str_replace("50|", "",trim($sourceNode -> nodeValue));
692
			$claimedPublication -> userEmail = $claim -> userEmail;
693
			break;
694
		case self :: DMF:
695
                    $claimedPublication -> targetDatasetId = NULL;
696
			$claimedPublication -> targetPublicationId = NULL;
697
			$claimedPublication -> date = $claim -> date;
698
			$claimedPublication -> publication = $this -> parseDMF($xPath);
699
			$claimedPublication -> publicationId = $claim->resultid;
700
			$claimedPublication -> projectId = NULL;
701
			$claimedPublication -> userEmail = $claim -> userEmail;
702
                        break;
703
                case self :: UPDATES2ACTIONS:
704
			$claimedPublication -> targetDatasetId = NULL;
705
			$claimedPublication -> targetPublicationId = NULL;
706
			$claimedPublication -> date = $claim -> date;
707
			$claimedPublication -> publication = $this -> parseDMF($xPath);
708
			$claimedPublication -> publicationId = $claim->resultid;
709
			$claimedPublication -> projectId = NULL;
710
			$claimedPublication -> userEmail = $claim -> userEmail;
711
                        break;
712
		}
713
		return $claimedPublication;
714
	}
715
	
716
	private function parseDMF($xpath) {
717
 		$xpath -> registerNamespace('openaire', 'http://namespace.openaire.eu/');
718
		$xpath -> registerNamespace('dc', 'http://purl.org/dc/elements/1.1/');
719
		$xpath -> registerNamespace('oaf', 'http://namespace.openaire.eu/oaf');
720
		$xpath -> registerNamespace('dr', 'http://www.driver-repository.eu/namespace/dr');
721
		$conceptNodes = $xpath -> query('/record/openaire:metadata/oaf:concept/@id');
722
		$publication = new JObject();
723
		$publication -> id = NULL;
724
		$publication -> source = NULL;
725
		$publication -> languages = array();
726
		$publication -> url = NULL;
727
		$publication -> authors = array();		
728
		$publication -> subjects = array();
729
		$publication -> concepts = array();
730
		$publication -> embargoEndDate = NULL;
731
		$publication -> datasources = array();
732
		$publication -> collectedFrom = array();
733
		$publication -> sources = array();
734
		$publication -> projects = array();
735
		$publication -> pids = array();
736
		$publication -> relatedPublications = array();
737
		$publication -> relatedDatasets = array();
738
		$publication -> externalPublications = array();
739
		$publication -> externalDatasets = array();
740

    
741
		if (($identifierNodes = $xpath -> query('/record/openaire:metadata/dc:identifier|/record/openaire:metadata/oaf:identifier')) == FALSE){
742
			//throw new Exception('error parsing DMF');
743
		}
744
		if (($accessModeNodes = $xpath -> query('/record/openaire:metadata/oaf:accessrights/text()')) == FALSE){
745
			//throw new Exception('error parsing DMF');
746
		}
747
		if (($titleNodes = $xpath -> query('/record/openaire:metadata/dc:title/text()')) == FALSE){
748
			//throw new Exception('error parsing DMF');
749
		}
750
		if (($authorNodes = $xpath -> query('/record/openaire:metadata/dc:creator/text()')) == FALSE){
751
			//throw new Exception('error parsing DMF');
752
		}
753
		if (($dateNodes = $xpath -> query('/record/openaire:metadata/dc:dateAccepted/text()')) == FALSE){
754
			//throw new Exception('error parsing DMF');
755
		}
756
 		if (($publisherNodes = $xpath -> query('/record/openaire:metadata/dc:publisher/text()')) != FALSE){
757
				$publication -> publisher = (($publisherNode = $publisherNodes -> item(0)) == NULL) ? NULL : trim($publisherNode -> nodeValue);
758
			}			
759
		if (($languageNodes = $xpath -> query('/record/openaire:metadata/dc:language/text()')) != FALSE){
760
			foreach ($languageNodes as $languageNode) {
761
				if ((($language = trim($languageNode -> nodeValue)) != NULL) && ($language != self :: UNDETERMINED))
762
					$publication -> languages[] = $language;
763
			}
764
		}
765
 		if (($typeNodes = $xpath -> query('/record/openaire:metadata/dr:CObjCategory/text()')) != FALSE){
766
			$publication -> type = (($typeNode = $typeNodes -> item(0)) == NULL) ? NULL : trim($typeNode -> nodeValue);
767
		}			
768
		if (($descriptionNodes = $xpath -> query('/record/openaire:metadata/dc:description/text()')) != FALSE){
769
			$publication -> description = (($descriptionNode = $descriptionNodes -> item(0)) == NULL) ? NULL : trim($descriptionNode -> nodeValue);
770
		}
771
		if (($datasourceNodes = $xpath -> query('/record/openaire:metadata/oaf:hostedBy')) != FALSE){
772
			foreach ($datasourceNodes as $datasourceNode) {
773
				if (($idNodes = $xpath -> query('./@id', $datasourceNode)) == FALSE){
774
					//throw new Exception('error parsing DMF');
775
				}
776
				if (($nameNodes = $xpath -> query('./@name', $datasourceNode)) == FALSE){
777
					//throw new Exception('error parsing DMF');
778
				}
779
				$datasource = new JObject();
780
				$datasource -> id = (($idNode = $idNodes -> item(0)) == NULL) ? NULL : trim($idNode -> nodeValue);
781
				$datasource -> name = (($nameNode = $nameNodes -> item(0)) == NULL) ? NULL : trim($nameNode -> nodeValue);
782
				$datasource -> url = NULL;
783
				$datasource -> accessMode = NULL;
784
				if (($datasource -> id != NULL) || ($datasource -> name != NULL))
785
					$publication -> datasources[] = $datasource;
786
			}
787
 
788
		}
789
 
790
		if (($collectedFromNodes = $xpath -> query('/record/openaire:metadata/oaf:collectedFrom')) != FALSE){
791
			foreach ($collectedFromNodes as $collectedFromNode) {
792
				if (($idNodes = $xpath -> query('./@id', $collectedFromNode)) == FALSE){
793
					//throw new Exception('error parsing DMF');
794

    
795
				}
796
				if (($nameNodes = $xpath -> query('./@name', $collectedFromNode)) == FALSE){
797
					//throw new Exception('error parsing DMF');
798
				}
799
				$collectedFrom = new JObject();
800
				$collectedFrom -> id = (($idNode = $idNodes -> item(0)) == NULL) ? NULL : trim($idNode -> nodeValue);
801
				$collectedFrom -> name = (($nameNode = $nameNodes -> item(0)) == NULL) ? NULL : trim($nameNode -> nodeValue);
802
				if (($collectedFrom -> id != NULL) || ($collectedFrom -> name != NULL))
803
					$publication -> collectedFrom[] = $collectedFrom;
804
			}
805
		}
806

    
807
		if (($sourceNodes = $xpath -> query('/record/openaire:metadata/dc:source/text()')) != FALSE){
808
			foreach ($sourceNodes as $sourceNode) {
809
				if (($source = trim($sourceNode -> nodeValue)) != NULL)
810
					$publication -> sources[] = $source;
811
			}
812
		}
813

    
814
		if (($projectNodes = $xpath -> query('/record/openaire:metadata/oaf:projectid/text()')) != FALSE){		
815
			foreach ($projectNodes as $projectNode) {
816
			$project = new JObject();
817
			$project -> id = trim($projectNode -> nodeValue);
818
			$project -> acronym = NULL;
819
			$project -> title = NULL;
820
			$project -> code = NULL;
821
			if ($project -> id != NULL)
822
				$publication -> projects[] = $project;
823
			}
824
		}
825
		$publication -> accessMode = (($accessModeNode = $accessModeNodes -> item(0)) == NULL) ? NULL : trim($accessModeNode -> nodeValue);
826
		$publication -> title = (($titleNode = $titleNodes -> item(0)) == NULL) ? NULL : trim($titleNode -> nodeValue);
827
		$publication -> year = (($dateNode = $dateNodes -> item(0)) == NULL) ? NULL : intval(trim($dateNode -> nodeValue));
828
		$publication -> date = ($dateNode == NULL) ? NULL : strtotime(trim($dateNode -> nodeValue));
829
		if ($conceptNodes !== false){
830
			foreach ($conceptNodes as $conceptNode) {
831
				$publication -> concepts[] = trim($conceptNode -> nodeValue);
832
			}
833
		}
834
		foreach ($authorNodes as $authorNode) {
835
			if (($idNodes = $xpath -> query('./field[@name = "personId"]/@value', $authorNode)) == FALSE){
836
		//		throw new Exception('error parsing publication');
837
 			}
838
			if (($fullNameNodes = $xpath -> query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE){
839
				//	throw new Exception('error parsing publication');
840
 			}
841
			if (($rankingNodes = $xpath -> query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE){
842
				//throw new Exception('error parsing publication');
843
 			}
844
			$author = new JObject();
845
			$author -> id = NULL;
846
			$author -> lastName = NULL;
847
			$author -> firstName = NULL;
848
			$author -> fullName = trim($authorNode -> nodeValue);
849
			$author -> ranking = 0;
850
			if ($author -> fullName != NULL)
851
				$publication -> authors[] = $author;
852
			usort($publication -> authors, function ($author1, $author2) {return $author1 -> ranking - $author2 -> ranking;});
853
		}
854
		foreach ($identifierNodes as $identifierNode) {
855

    
856
			$pid = new JObject();
857
			$pid -> clazz=NULL;
858
			$pid -> value=NULL;
859
			if (($typeNodes = $xpath -> query('./@identifierType', $identifierNode)) != FALSE)
860
			$pid -> clazz = (($typeNode = $typeNodes -> item(0)) == NULL) ? NULL : trim($typeNode -> nodeValue);
861
			if (($textNodes = $xpath -> query('./text()', $identifierNode)) != FALSE)
862
			$pid -> value = (($textNode = $textNodes -> item(0)) == NULL) ? NULL : trim($textNode -> nodeValue);
863
			if ($pid -> value != NULL) {
864
				if ($pid -> clazz == NULL && strpos($pid -> value , 'http') !==false){
865
					$publication -> url = $pid -> value;
866
				}else if ($pid -> clazz == NULL && strpos($pid -> value , 'http')===false ){
867
					 $publication -> id = $pid -> value;
868
					$publication -> source = 'other';
869
					$publication -> pids[] = $pid;
870
				}
871
				else if($pid -> clazz != NULL){
872
					$publication -> id = $pid -> value;
873
					$publication -> source = $pid -> clazz;
874
					$publication -> pids[] = $pid;
875
				}
876
			}
877
		}
878
		
879
		return $publication;
880
	}	
881
        
882
    private function _parseContextsConcepts($conceptNodes, &$parent, $xpath){
883
        foreach ($conceptNodes as $conceptNode) {
884
            if (($includeNodes = $xpath -> query('./@claim', $conceptNode)) == FALSE)
885
                                    throw new Exception('error parsing publication');
886
            if (($idNodes = $xpath -> query('./@id', $conceptNode)) == FALSE)
887
                    throw new Exception('error parsing publication');
888
            if (($nameNodes = $xpath -> query('./@label', $conceptNode)) == FALSE)
889
                    throw new Exception('error parsing publication');
890
            if (($subConceptNodes = $xpath -> query('./concept', $conceptNode)) == FALSE)
891
                throw new Exception('error parsing publication');
892
            $concept = new JObject();
893
            $concept -> id = (($idNode = $idNodes -> item(0)) == NULL) ? NULL : trim($idNode -> nodeValue);
894
            $concept -> name = (($nameNode = $nameNodes -> item(0)) == NULL) ? NULL : trim($nameNode -> nodeValue);
895
            $concept -> claim = (($includeNode = $includeNodes -> item(0)) == NULL) ? NULL : trim($includeNode -> nodeValue);
896
            if ($concept -> claim != NULL){
897
                $concept -> claim = ($concept -> claim == "true") ? true : false;
898
            }
899
            $concept -> concepts = array();
900
            $this->_parseContextsConcepts($subConceptNodes, $concept -> concepts, $xpath);
901
            
902
            if (($concept -> id != NULL) || ($concept -> name != NULL))
903
                $parent[$concept -> id] = $concept;
904
        }
905
    }
906
    
907
    public function parseContexts($context_source){
908
         $document = new DOMDocument();
909
		 $document -> recover = TRUE;
910
		 if ($document -> loadXML($context_source) == FALSE)
911
		    throw new Exception('invalid XML response');
912
		$xpath = new DOMXPath($document);
913
        if ((($configurationNodes = $xpath -> query('./BODY/CONFIGURATION')) == FALSE) || (($configurationNode = $configurationNodes -> item(0)) == NULL))
914
			throw new Exception('error parsing contexts');
915

    
916
	    if (($contextNodes = $xpath -> query('./context', $configurationNode)) == FALSE)
917
			throw new Exception('error parsing contexts');
918

    
919
		$contexts = array();	
920
		foreach ($contextNodes as $contextNode) {
921
			if (($includeNodes = $xpath -> query('./@claim', $contextNode)) == FALSE)
922
				throw new Exception('error parsing publication');
923
			if (($idNodes = $xpath -> query('./@id', $contextNode)) == FALSE)
924
				throw new Exception('error parsing publication');
925
			if (($nameNodes = $xpath -> query('./@label', $contextNode)) == FALSE)
926
				throw new Exception('error parsing publication');
927
			if (($categoryNodes = $xpath -> query('./category', $contextNode)) == FALSE)
928
				throw new Exception('error parsing publication');
929
			$context = new JObject();
930
			$context -> id = (($idNode = $idNodes -> item(0)) == NULL) ? NULL : trim($idNode -> nodeValue);
931
			$context -> name = (($nameNode = $nameNodes -> item(0)) == NULL) ? NULL : trim($nameNode -> nodeValue);
932
                        $context -> claim = (($includeNode = $includeNodes -> item(0)) == NULL) ? NULL : trim($includeNode -> nodeValue);
933
                        if ($context -> claim != NULL){
934
                            $context -> claim = ($context -> claim == "true") ? true : false;
935
                        }
936
                        $context -> categories = array();
937
			foreach ($categoryNodes as $categoryNode) {
938
                                if (($includeNodes = $xpath -> query('./@claim', $categoryNode)) == FALSE)
939
                                    throw new Exception('error parsing publication');
940
				if (($idNodes = $xpath -> query('./@id', $categoryNode)) == FALSE)
941
					throw new Exception('error parsing publication');
942
				if (($nameNodes = $xpath -> query('./@label', $categoryNode)) == FALSE)
943
					throw new Exception('error parsing publication');
944
				if (($conceptNodes = $xpath -> query('./concept', $categoryNode)) == FALSE)
945
					throw new Exception('error parsing publication');
946
				$category = new JObject();
947
				$category -> id = (($idNode = $idNodes -> item(0)) == NULL) ? NULL : trim($idNode -> nodeValue);
948
				$category -> name = (($nameNode = $nameNodes -> item(0)) == NULL) ? NULL : trim($nameNode -> nodeValue);
949
                                $category -> claim = (($includeNode = $includeNodes -> item(0)) == NULL) ? NULL : trim($includeNode -> nodeValue);
950
                                if ($category -> claim != NULL){
951
                                    $category -> claim = ($category -> claim == "true") ? true : false;
952
                                }
953
				$category -> concepts = array();
954
                                $this->_parseContextsConcepts($conceptNodes, $category -> concepts, $xpath);
955
				
956
				if ((($category -> id != NULL) || ($category -> name != NULL) || ($category -> concepts != NULL) ) && ( $category -> claim!= null && $category -> claim == true))
957
					$context -> categories[$category -> id] = $category;
958
			}                       
959
			if ((($context -> id != NULL) || ($context -> name != NULL)) && ($context -> categories != NULL && sizeof($context -> categories)>0))
960
				$contexts[$context -> id] = $context;
961
		}
962
		return $contexts;
963
    }
964
    
965
	public function getContexts() {
966
		try {
967
			$time = microtime(TRUE);
968
			$contexts = $this -> client -> getContexts();
969
                        if(!isset($contexts[0])){
970
                            throw new Exception('error retrieving contexts:'.  print_r($contexts,true));
971
                        }
972
                        $parsedContexts = array();	
973
                        foreach($contexts as $context){
974
                            $parsedContexts = array_merge($parsedContexts, $this -> parseContexts($context));                        
975
                        }
976
                        $contexts= $parsedContexts;
977
                        JLog :: add('Retrieved ' . count($contexts) . ' contexts in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);                        
978
			return $contexts;
979
			} catch (Exception $e) {
980
            	JLog :: add('Error retrieving contexts ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
981
                return NULL;
982
			}
983
	}
984
	// Get the publications claimed by a user using caching if enabled.
985
	// $user the user whose claimed publications to retrieve
986
	// return an array of publications
987
	public function getClaimedDocsByUser($user) {
988
	try {
989
		$time = microtime(TRUE);
990
		$claimedDocs = $this -> client -> getClaimedPublications($user -> email);
991
	 	$publications = $this -> parseClaimedDocs($claimedDocs);
992
	 	 JLog :: add('Retrieved ' . count($publications) . ' claimed publications (user: ' . $user -> username . ') in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
993
		return $publications;
994
		} catch (Exception $e) {
995
			JLog :: add('Error retrieving claimed publications (user: ' . $user -> username . '): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
996
			return NULL;
997
		}
998
	}
999
        
1000
        // Get the publications claimed by a user using caching if enabled.
1001
	// $user the user whose claimed publications to retrieve
1002
	// return an array of publications
1003
	public function getClaimedDocsByTime($from, $to) {
1004
	try {
1005
		$time = microtime(TRUE);
1006
 		$time1 = strtotime(str_replace("/", "-", $from)) * 1000;
1007
		$time2 = (strtotime(str_replace("/", "-", $to.' 23:59:59' ))) * 1000;
1008
		$claimedDocs = $this->client ->getAllClaimedPublications($time1, $time2);
1009
		$publications = $this -> parseClaimedDocs($claimedDocs);
1010
		JLog :: add('Retrieved ' . count($claimedDocs) .' Parsed ' . count($publications) . ' claimed publications(from: ' . $from . ', to: '. $to .') in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
1011
		JLog :: add('Time1 : '.strtotime(str_replace("/", "-", $from)).' from: ' . $time1 . ', to :'. strtotime(str_replace("/", "-", $to)).' time2: '. $time2 .')  time: '.$time , JLog :: INFO, self :: LOG);
1012
		return $publications;
1013
		} catch (Exception $e) {
1014
			JLog :: add('Error retrieving all claims (from: ' . $from . ', to: '. $to .'): ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
1015
			return NULL;
1016
		}
1017
	}
1018
	public function deleteClaim($email, $id) {
1019
	try {
1020
		$this->client ->deleteClaim($email, $id);
1021
	 
1022
		JLog :: add('Deleting claim', JLog :: INFO, self :: LOG);
1023
		 
1024
		 
1025
		} catch (Exception $e) {
1026
			JLog :: add('Error deleting claim ' . $e -> getMessage(), JLog :: ERROR, self :: LOG);
1027
		 
1028
		}
1029
	}
1030
	public function parseClaimedDocs($claimedDocs ) {
1031
		$locale = JFactory :: getLanguage()->getTag();
1032
		$claimedPublications = array();
1033
		$claimedPublicationsGrouped = array();
1034
		$time = microtime(TRUE);		 
1035
		foreach ($claimedDocs as $claim){
1036
 			$parsedClaim = $this -> parseClaimedPublication($claim);                                
1037
			if ($parsedClaim == null){
1038
 				continue;
1039
			}
1040
			$claimedPublications[] = $parsedClaim;
1041
		}
1042
		$resultsToGet = array();
1043
		$projectsToGet = array();
1044
		$claimedDocuments = array();
1045
		foreach ($claimedPublications as $claimedPublication){
1046
			if ($claimedPublication -> publication != null and $claimedPublication -> publication -> id != null){
1047
				$claimedDocuments[$claimedPublication->publicationId] = $claimedPublication -> publication;
1048
			}
1049
			if ($claimedPublication -> projectId !== null){
1050
				$projectsToGet[] = $claimedPublication -> projectId;
1051
			}
1052
			if ($claimedPublication -> targetPublicationId !== null){
1053
				$resultsToGet[] = $claimedPublication -> targetPublicationId;
1054
			}
1055
			if ($claimedPublication -> targetDatasetId !== null){
1056
				$resultsToGet[] = $claimedPublication -> targetDatasetId;
1057
			}
1058
			if (($claimedPublication -> publication == null || ($claimedPublication -> publication != null and $claimedPublication -> publication -> id == null))){
1059
				$resultsToGet[] = $claimedPublication -> publicationId;   
1060
			}
1061
			if ($claimedPublication -> publication == null && $claimedPublication -> type == "dataset"){
1062
				$resultsToGet[] = $claimedPublication -> publicationId;   
1063
			}
1064
			
1065
		}                
1066
            $resultsToGet = array_unique($resultsToGet);
1067
            $projectsToGet = array_unique($projectsToGet);            
1068
            $searchModel = new OpenAireModelSearch();
1069
            $results = $searchModel->getResults($resultsToGet, $locale);
1070
            $projects = $searchModel->getProjects($projectsToGet, $locale);
1071
            $keydResults = array();
1072
            $keydProjects = array();
1073
            foreach ($results as $result){
1074
                $keydResults[$result->id] = $result;
1075
            }
1076
            foreach ($projects as $project)
1077
                $keydProjects[$project->id] = $project;
1078
            
1079
            foreach ($claimedPublications as $claimedPublication){
1080
                if (!isset($claimedPublicationsGrouped[$claimedPublication -> publicationId])){   
1081
                     if ($claimedPublication -> publication == null ||  $claimedPublication -> publication -> id == null||isset($keydResults[$claimedPublication -> publicationId])){
1082
			$publication = isset($keydResults[$claimedPublication -> publicationId])?$keydResults[$claimedPublication -> publicationId]:null;
1083
                    }
1084
                    else{
1085
                        $publication = $claimedPublication -> publication;
1086
                    }
1087
                    if ($publication == null )
1088
                        continue;
1089
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] = new stdClass();
1090
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> publicationId = $claimedPublication -> publicationId;
1091
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> date = $claimedPublication -> date;
1092
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> publication = $publication;
1093
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> publications = array();
1094
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> datasets = array();
1095
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> projects = array();
1096
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> concepts = array();
1097
					$claimedPublicationsGrouped[$claimedPublication -> publicationId] -> type = isset($claimedPublication -> type)?$claimedPublication -> type:'Publication';
1098
                    //$claimedPublicationsGrouped[$claimedPublication -> publicationId] -> claimType = $claimedPublication -> claimType;
1099
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> publication -> userEmail = $claimedPublication -> userEmail;
1100
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> publication -> claimId = $claimedPublication -> claimId;                    
1101
                }
1102
                if ($claimedPublicationsGrouped[$claimedPublication -> publicationId] -> date < $claimedPublication -> date)
1103
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> date = $claimedPublication -> date;
1104
                if ($claimedPublication -> publication != null){
1105
                   // $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> publication=(isset($keydResults[$claimedPublication -> publicationId])&&($keydResults[$claimedPublication -> publicationId]!==null))? $keydResults[$claimedPublication -> publicationId]:$claimedPublication -> publication;
1106
                    $claimedConcepts = array();
1107
                    foreach ($claimedPublication -> publication -> concepts as $concept){
1108
                        $concept = $this->getConcept($concept);
1109
                        if(!isset( $concept)){
1110
							$concept  = new stdClass();
1111
						}
1112
                        $claimedConcept = new stdClass();
1113
                        $claimedConcept->id = isset($concept->id)?$concept->id:'';
1114
                        $claimedConcept->title = isset($concept->path)?$concept->path:'';
1115
                        $claimedConcept->date = $claimedPublication->date;
1116
                        $claimedConcept-> userEmail = $claimedPublication -> userEmail;
1117
			$claimedConcept -> claimId = $claimedPublication -> claimId;
1118
                        //$claimedConcepts[] = $claimedConcept;
1119
                        $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> concepts[]=$claimedConcept;
1120
                    }
1121
                    //$claimedPublicationsGrouped[$claimedPublication -> publicationId] -> concepts = array_merge($claimedPublicationsGrouped[$claimedPublication -> publicationId] -> concepts, $claimedConcepts);
1122
                }
1123
                if ($claimedPublication -> targetPublicationId !== null){
1124
                    $claimedPublication->title = isset($keydResults[$claimedPublication -> targetPublicationId ])?$keydResults[$claimedPublication -> targetPublicationId ]->title:null;
1125
                    if ($claimedPublication->title == null){
1126
                        $claimedPublication->title = isset($claimedDocuments[$claimedPublication -> targetPublicationId ])?$claimedDocuments[$claimedPublication -> targetPublicationId ]->title:null;
1127
                    }
1128
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> publications[] = $claimedPublication;
1129
                }
1130
                if ($claimedPublication -> targetDatasetId !== null){
1131
                    $claimedPublication->title = isset($keydResults[$claimedPublication -> targetDatasetId ])?$keydResults[$claimedPublication -> targetDatasetId ]->title:null;
1132
                    if ($claimedPublication->title == null){
1133
                        $claimedPublication->title = isset($claimedDocuments[$claimedPublication -> targetDatasetId ])?$claimedDocuments[$claimedPublication -> targetDatasetId ]->title:null;
1134
                    }
1135
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> datasets[] = $claimedPublication;
1136
                }
1137
                if ($claimedPublication -> projectId !== null){
1138
                    $claimedPublication->title = isset($keydProjects[$claimedPublication -> projectId ])?$keydProjects[$claimedPublication -> projectId ]->title:null;
1139
                    $claimedPublication->acronym = isset($keydProjects[$claimedPublication -> projectId ])?$keydProjects[$claimedPublication -> projectId ]->acronym:null;
1140
                    $claimedPublication->funder = isset($keydProjects[$claimedPublication -> projectId ])?$keydProjects[$claimedPublication -> projectId ]->funder:null;
1141
                    $claimedPublicationsGrouped[$claimedPublication -> publicationId] -> projects[] = $claimedPublication;					                   
1142
		}
1143
            }
1144
             return $claimedPublicationsGrouped;		
1145
	}
1146
}
1147

    
(2-2/9)