Project

General

Profile

1
<?php
2

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

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

    
11
// This model implements document searching using web search.
12
class OpenAireModelSearch extends JModelItem {
13

    
14
    const LOG = 'openaire';
15
    const CACHE_GROUP = 'openaire.search';
16
    const PUBLICATION_STATISTICS_CACHE_ID = 'statistics.publications';
17
    const DATASET_STATISTICS_CACHE_ID = 'statistics.datasets';
18
    const PROJECT_STATISTICS_CACHE_ID = 'statistics.projects';
19
    const PEOPLE_STATISTICS_CACHE_ID = 'statistics.people';
20
    const ORGANIZATION_STATISTICS_CACHE_ID = 'statistics.organizations';
21
    const DATASOURCE_STATISTICS_CACHE_ID = 'statistics.datasource';
22
    const SEARCH_PUBLICATIONS_CACHE_ID = 'search.publications';
23
    const SEARCH_DATASETS_CACHE_ID = 'search.datasets';
24
    const SEARCH_PROJECTS_CACHE_ID = 'search.projects';
25
    const SEARCH_PEOPLE_CACHE_ID = 'search.people';
26
    const SEARCH_ORGANIZATIONS_CACHE_ID = 'search.organizations';
27
    const SEARCH_DATASOURCES_CACHE_ID = 'search.datasources';
28
    const BROWSE_PUBLICATIONS_CACHE_ID = 'browse.publications';
29
    const BROWSE_DATASETS_CACHE_ID = 'browse.datasets';
30
    const BROWSE_PROJECTS_CACHE_ID = 'browse.projects';
31
    const BROWSE_PEOPLE_CACHE_ID = 'browse.people';
32
    const BROWSE_ORGANIZATIONS_CACHE_ID = 'browse.organizations';
33
    const BROWSE_DATASOURCES_CACHE_ID = 'browse.datasources';
34
    const ADVANCED_SEARCH_PUBLICATIONS_CACHE_ID = 'advanced.publications';
35
    const ADVANCED_SEARCH_PROJECTS_CACHE_ID = 'advanced.projects';
36
    const ADVANCED_SEARCH_PEOPLE_CACHE_ID = 'advanced.people';
37
    const ADVANCED_SEARCH_ORGANIZATIONS_CACHE_ID = 'advanced.organizations';
38
    const ADVANCED_SEARCH_DATASOURCES_CACHE_ID = 'advanced.datasources';
39
    const RESULT_CACHE_ID = 'result';
40
    const RESULT_DUP_ID = 'resultdupid';
41
    const PUBLICATION_CACHE_ID = 'publication';
42
    const DATASET_CACHE_ID = 'dataset';
43
    const PROJECT_CACHE_ID = 'project';
44
    const PUBLICATIONS_CACHE_ID = 'publications';
45
    const DATASETS_CACHE_ID = 'datasets';
46
    const PROJECTS_CACHE_ID = 'projects';
47
    const PROJECT_PUBLICATIONS_CACHE_ID = 'project.publications';
48
    const PERSON_CACHE_ID = 'person';
49
    const PERSON_PUBLICATIONS_CACHE_ID = 'person.publications';
50
    const ORGANIZATION_CACHE_ID = 'organization';
51
    const ORGANIZATION_DATASOURCES_CACHE_ID = 'organization.datasources';
52
    const DATASOURCE_CACHE_ID = 'datasource';
53
    const DATASOURCE_PUBLICATIONS_CACHE_ID = 'datasource.publications';
54
    const DATASOURCE_ORGANIZATIONS_CACHE_ID = 'datasource.organizations';
55
    const COMPATIBLE_DATASOURCES_CACHE_ID = 'compatible.datasources';
56
    const QUICK_SEARCH_PROJECTS_CACHE_ID = 'quick.search.projects';
57
    const QUICK_SEARCH_ORGANIZATIONS_CACHE_ID = 'quick.search.organizations';
58
    const RESULT_QUERY = '(oaftype exact result)';
59
    const RESULT_ID = 'objIdentifier';
60
    const PUBLICATION_QUERY = '(oaftype exact result) and (resulttypeid exact publication)';
61
    const PUBLICATION_TYPE = 'instancetypenameid';
62
    const PUBLICATION_LANGUAGE = 'resultlanguageid';
63
    const PUBLICATION_CONTEXT = 'communityid';
64
    const PUBLICATION_FUNDER = 'relfunderid';
65
    const PUBLICATION_FUNDING_STREAM = 'relfundinglevel0_id';
66
    const PUBLICATION_SCIENTIFIC_AREA = 'relfundinglevel1_id';
67
    const PUBLICATION_FUNDING_STREAM_LEVEL2 = 'relfundinglevel2_id';
68
    const PUBLICATION_YEAR = 'resultacceptanceyear';
69
    const PUBLICATION_ACCESS_MODE = 'resultbestlicense';
70
    const PUBLICATION_DATASOURCE = 'resulthostingdatasourceid';
71
    const RESULT_DATASOURCE = 'collectedfromdatasourceid';
72
    const PUBLICATION_PROJECT = 'relprojectid';
73
    const PUBLICATION_AUTHOR_ID = 'relpersonid';
74
    const PUBLICATION_ARTICLE = '0001';
75
    const PUBLICATION_PREPRINT = '0016';
76
    const PUBLICATION_BOOK = '0002';
77
    const PUBLICATION_BOOK_PART = '0013';
78
    const PUBLICATION_PHD_THESIS = '0006';
79
    const PUBLICATION_MASTER_THESIS = '0007';
80
    const PUBLICATION_BACHELOR_THESIS = '0008';
81
    const PUBLICATION_REPORT = '0017';
82
    const PUBLICATION_INTERNAL_REPORT = '0011';
83
    const PUBLICATION_EXTERNAL_REPORT = '0009';
84
    const PUBLICATION_TITLE = 'resulttitle';
85
    const PUBLICATION_AUTHOR = 'relperson';
86
    const PUBLICATION_PUBLISHER = 'resultpublisher';
87
    const PUBLICATION_SUBJECT = 'resultsubject';
88
    const PUBLICATION_DATE = 'resultdateofacceptance';
89
    const PUBLICATION_ID = 'objIdentifier';
90
    const DATASET_QUERY = '(oaftype exact result) and (resulttypeid exact dataset)';
91
    const DATASET_TYPE = 'instancetypenameid';
92
    const DATASET_LANGUAGE = 'resultlanguageid';
93
    const DATASET_FUNDER = 'relfunderid';
94
    const DATASET_FUNDING_STREAM = 'relfundinglevel0_id';
95
    const DATASET_SCIENTIFIC_AREA = 'relfundinglevel1_id';
96
    const DATASET_FUNDING_STREAM_LEVEL2 = 'relfundinglevel2_id';
97
    const DATASET_YEAR = 'resultacceptanceyear';
98
    const DATASET_ACCESS_MODE = 'resultbestlicense';
99
    const DATASET_DATASOURCE = 'resulthostingdatasourceid';
100
    const DATASET_PROJECT = 'relprojectid';
101
    const DATASET_AUTHOR_ID = 'relpersonid';
102
    const DATASET_ID = 'objIdentifier';
103
    const PROJECT_QUERY = '(oaftype exact project)';
104
    const PROJECT = 'project';
105
    const PROJECT_FUNDER = 'funderid';
106
    const PROJECT_FUNDING_STREAM = 'fundinglevel0_id';
107
    const PROJECT_SCIENTIFIC_AREA = 'fundinglevel1_id';
108
    const PROJECT_FUNDING_STREAM_LEVEL2 = 'fundinglevel2_id';
109
    const PROJECT_START_YEAR = 'projectstartyear';
110
    const PROJECT_END_YEAR = 'projectendyear';
111
    const PROJECT_SC39 = 'projectecsc39';
112
    const PROJECT_ACRONYM = 'projectacronym';
113
    const PROJECT_TITLE = 'projecttitle';
114
    const PROJECT_KEYWORDS = 'projectkeywords';
115
    const PROJECT_START_DATE = 'projectstartdate';
116
    const PROJECT_END_DATE = 'projectenddate';
117
    const PROJECT_ID = 'objIdentifier';
118
    const PROJECT_CODE = 'projectcode';
119
    const PERSON_QUERY = '(oaftype exact person)';
120
    const PERSON_COUNTRY = 'personcountryid';
121
    const PERSON_LAST_NAME = 'personsecondnames';
122
    const PERSON_FIRST_NAME = 'personfirstname';
123
    const PERSON_FULL_NAME = 'personfullname';
124
    const PERSON_ID = 'objIdentifier';
125
    const ORGANIZATION_QUERY = '(oaftype exact organization)';
126
    const ORGANIZATION_QUERY_COMPATIBILITY = 'oaftype exact organization and
127
(reldatasourcecompatibilityid=driver or reldatasourcecompatibilityid=driver-openaire2.0 or 
128
reldatasourcecompatibilityid=openaire2.0 or reldatasourcecompatibilityid=openaire3.0 or 
129
reldatasourcecompatibilityid=openaire2.0_data or reldatasourcecompatibilityid=hostedBy 
130
or relprojectid=*)';
131
    const ORGANIZATION_COUNTRY = 'organizationcountryid';
132
    const ORGANIZATION_LEGAL_BODY = 'organizationeclegalbody';
133
    const ORGANIZATION_LEGAL_PERSON = 'organizationeclegalperson';
134
    const ORGANIZATION_NON_PROFIT = 'organizationecnonprofit';
135
    const ORGANIZATION_RESEARCH = 'organizationecresearchorganization';
136
    const ORGANIZATION_EU_INTERESTS = 'organizationecinternationalorganizationeurinterests';
137
    const ORGANIZATION_INTERNATIONAL = 'organizationecinternationalorganization';
138
    const ORGANIZATION_ENTERPRISE = 'organizationecenterprise';
139
    const ORGANIZATION_SMALL_MEDIUM_ENTERPRISE = 'organizationecsmevalidated';
140
    const ORGANIZATION_NAME = 'organizationlegalname';
141
    const ORGANIZATION_SHORT_NAME = 'organizationlegalshortname';
142
    const ORGANIZATION_ID = 'objIdentifier';
143
//    const DATASOURCE_QUERY = '(oaftype exact datasource) and (datasourcecompatibilityid <> "UNKNOWN") and (datasourcecompatibilityid <> "hostedBy")';
144
    const DATASOURCE_QUERY = '(oaftype exact datasource) and (datasourcecompatibilityid <> "UNKNOWN")';
145
    const DATASOURCE_QUERY_COMPATIBILITY = '(oaftype exact datasource)';
146
    const DATASOURCE_TYPE = 'datasourcetypeuiid';
147
    const DATASOURCE_LANGUAGE = 'datasourceodlanguages';
148
    const DATASOURCE_CONTENT = 'datasourceodcontenttypes';
149
    const DATASOURCE_COMPATIBILITY = 'datasourcecompatibilityid';
150
    const DATASOURCE_NAME = 'datasourceofficialname';
151
    const DATASOURCE_ENGLISH_NAME = 'datasourceenglishname';
152
    const DATASOURCE_SUBJECT = 'datasourceodsubjects';
153
    const DATASOURCE_ORGANIZATION = 'relorganizationid';
154
    const DATASOURCE_ID = 'objIdentifier';
155
    const DATASOURCE_COMPATIBILITY_NOT_COMPATIBLE = 'notCompatible';
156
    const DATASOURCE_ACCESS_OPEN = 'OPEN';
157
    const DATASOURCE_ACCESS_EMBARGO = 'EMBARGO';
158
    const DATASOURCE_ACCESS_RESTRICTED = 'RESTRICTED';
159
    const DATASOURCE_ACCESS_CLOSED = 'CLOSED';
160
    const UNKNOWN = 'UNKNOWN';
161
    const UNDETERMINED = 'Undetermined';
162
    const PUBLICATION = 'publication';
163
    const DATASET = 'dataset';
164
    const HTTP_OK = 200;
165

    
166
    private $searchService;
167
    private $publicationStatisticsExistUrl;
168
    private $publicationStatisticsChartUrl;
169
    private $datasourceStatisticsExistUrl;
170
    private $datasourceStatisticsChartUrl;
171
    private $projectStatisticsChartUrl;
172
    private $cache;
173
    private $http;
174

    
175
    // Construct a new OpenAireModelSearch.
176
    // $configuration the configuration to use		
177
    public function __construct($configuration = array()) {
178
        parent :: __construct($configuration);
179
        $parameters = JComponentHelper :: getParams('com_openaire');
180
        $this->searchService = $parameters->get('searchServiceUrl');
181
        $this->publicationStatisticsExistUrl = $parameters->get('statisticsDocumentExistUrl');
182
        $this->publicationStatisticsChartUrl = $parameters->get('statisticsDocumentChartUrl');
183
        $this->datasourceStatisticsExistUrl = $parameters->get('statisticsRepositoryExistUrl');
184
        $this->datasourceStatisticsChartUrl = $parameters->get('statisticsRepositoryChartUrl');
185
        $this->projectStatisticsChartUrl = $parameters->get('statisticsProjectChartUrl');
186
        $this->cache = JCache :: getInstance();
187
        $this->http = new JHttp();
188
    }
189

    
190
    // Retrieve the statistics exist URL for a publication.
191
    // return the URL to use in order to check whether statistics exist for a publication
192
    public function getPublicationStatisticsExistUrl() {
193
        return $this->publicationStatisticsExistUrl;
194
    }
195

    
196
    // Retrieve the statistics chart URL for a publication.
197
    // return the URL to use in order to retrieve statistics chart for a publication
198
    public function getPublicationStatisticsChartUrl() {
199
        return $this->publicationStatisticsChartUrl;
200
    }
201

    
202
    // Retrieve the statistics exist URL for a datasource.
203
    // return the URL to use in order to check whether statistics exist for a datasource
204
    public function getDatasourceStatisticsExistUrl() {
205
        return $this->datasourceStatisticsExistUrl;
206
    }
207

    
208
    // Retrieve the statistics chart URL for a datasource.
209
    // return the URL to use in order to retrieve statistics chart for a datasource
210
    public function getDatasourceStatisticsChartUrl() {
211
        return $this->datasourceStatisticsChartUrl;
212
    }
213

    
214
    // Retrieve the statistics chart URL for a project.
215
    // return the URL to use in order to retrieve statistics chart for a project
216
    public function getProjectStatisticsChartUrl() {
217
        return $this->projectStatisticsChartUrl;
218
    }
219

    
220
    // Retrieve publication statistics using cache if enabled.
221
    // $locale the locale to use
222
    // return statistics (object)
223
    public function getPublicationStatistics($locale,$allFunders) {
224
        if ($this->cache->getCaching()) {
225
            $cacheId = self :: PUBLICATION_STATISTICS_CACHE_ID . '.' . $locale.'.'.$allFunders;
226
            $statistics = $this->cache->get($cacheId, self :: CACHE_GROUP);
227
            if ($statistics === FALSE) {
228
                $statistics = $this->_getPublicationStatistics($locale,$allFunders);
229
                if ($statistics !== NULL)
230
                    $this->cache->store($statistics, $cacheId, self :: CACHE_GROUP);
231
            }
232
        } else
233
            $statistics = $this->_getPublicationStatistics($locale,$allFunders);
234
        return $statistics;
235
    }
236

    
237
    // Retrieve dataset statistics using cache if enabled.
238
    // $locale the locale to use
239
    // return statistics (object)
240
    public function getDatasetStatistics($locale) {
241
        if ($this->cache->getCaching()) {
242
            $cacheId = self :: DATASET_STATISTICS_CACHE_ID . '.' . $locale.'.'. $allFunders;
243
            $statistics = $this->cache->get($cacheId, self :: CACHE_GROUP);
244
            if ($statistics === FALSE) {
245
                $statistics = $this->_getDatasetStatistics($locale,  $allFunders);
246
                if ($statistics !== NULL)
247
                    $this->cache->store($statistics, $cacheId, self :: CACHE_GROUP);
248
            }
249
        } else
250
            $statistics = $this->_getDatasetStatistics($locale, $allFunders);
251
        return $statistics;
252
    }
253

    
254
    // Retrieve project statistics using cache if enabled.
255
    // $locale the locale to use
256
    // return statistics (object)
257
    public function getProjectStatistics($locale,  $allFunders) {
258
        if ($this->cache->getCaching()) {
259
            $cacheId = self :: PROJECT_STATISTICS_CACHE_ID . '.' . $locale.'.'. $allFunders;
260
            $statistics = $this->cache->get($cacheId, self :: CACHE_GROUP);
261
            if ($statistics === FALSE) {
262
                $statistics = $this->_getProjectStatistics($locale,  $allFunders);
263
                if ($statistics !== NULL)
264
                    $this->cache->store($statistics, $cacheId, self :: CACHE_GROUP);
265
            }
266
        } else
267
            $statistics = $this->_getProjectStatistics($locale, $allFunders);
268
        return $statistics;
269
    }
270

    
271
    // Retrieve people statistics using cache if enabled.
272
    // $locale the locale to use
273
    // return statistics (object)
274
    public function getPeopleStatistics($locale) {
275
        if ($this->cache->getCaching()) {
276
            $cacheId = self :: PEOPLE_STATISTICS_CACHE_ID . '.' . $locale;
277
            $statistics = $this->cache->get($cacheId, self :: CACHE_GROUP);
278
            if ($statistics === FALSE) {
279
                $statistics = $this->_getPeopleStatistics($locale);
280
                if ($statistics !== NULL)
281
                    $this->cache->store($statistics, $cacheId, self :: CACHE_GROUP);
282
            }
283
        } else
284
            $statistics = $this->_getPeopleStatistics($locale);
285
        return $statistics;
286
    }
287

    
288
    // Retrieve organization statistics using cache if enabled.
289
    // $locale the locale to use
290
    // return statistics (object)
291
    public function getOrganizationStatistics($locale) {
292
        if ($this->cache->getCaching()) {
293
            $cacheId = self :: ORGANIZATION_STATISTICS_CACHE_ID . '.' . $locale;
294
            $statistics = $this->cache->get($cacheId, self :: CACHE_GROUP);
295
            if ($statistics === FALSE) {
296
                $statistics = $this->_getOrganizationStatistics($locale);
297
                if ($statistics !== NULL)
298
                    $this->cache->store($statistics, $cacheId, self :: CACHE_GROUP);
299
            }
300
        } else
301
            $statistics = $this->_getOrganizationStatistics($locale);
302
        return $statistics;
303
    }
304

    
305
    // Retrieve datasource statistics using cache if enabled.
306
    // $locale the locale to use
307
    // return statistics (object)
308
    public function getDatasourceStatistics($locale) {
309
        if ($this->cache->getCaching()) {
310
            $cacheId = self :: DATASOURCE_STATISTICS_CACHE_ID . '.' . $locale;
311
            $statistics = $this->cache->get($cacheId, self :: CACHE_GROUP);
312
            if ($statistics === FALSE) {
313
                $statistics = $this->_getDatasourceStatistics($locale);
314
                if ($statistics !== NULL)
315
                    $this->cache->store($statistics, $cacheId, self :: CACHE_GROUP);
316
            }
317
        } else
318
            $statistics = $this->_getDatasourceStatistics($locale);
319
        return $statistics;
320
    }
321

    
322
    // Perform a simple search for publications using cache if enabled.
323
    // $keyword the keyword to search for
324
    // $articles flag to limit searching on articles; if all flags are FALSE no limits apply
325
    // $books flag to limit searching on books; if all flags are FALSE no limits apply
326
    // $theses flag to limit searching on books; if all flags are FALSE no limits apply
327
    // $reports flag to limit searching on reports; if all flags are FALSE no limits apply
328
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
329
    // $language the ID of the language to use as filter or NULL for no language filtering
330
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
331
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
332
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
333
    // $year the year of publication to use as filter or NULL for no year filtering
334
    // $accessMode the ID of the access mode to use as a filter or NULL for no access mode filtering
335
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
336
    // $community the ID of the community to use as filter or NULL for no community filtering
337
    // $page the page of results to retrieve
338
    // $size the size of the page of results to retrieve
339
    // $locale the locale to use
340
    // return a result (object) containing publications and statistics
341
    public function searchPublications($keyword, $articles, $books, $theses, $reports, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $isRefine) {
342
        if ($this->cache->getCaching()) {
343
            $cacheId = self :: SEARCH_PUBLICATIONS_CACHE_ID . '.' . $keyword . '.' . $articles . '.' . $books . '.' . $theses . '.' . $reports . '.' . $type . '.' . $language . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.' . $fundingStreamLevel2 . '.' . $year . '.' . $accessMode . '.' . $datasource . '.' . $community . '.' . $page . '.' . $size . '.' . $locale . '.' . $project.'.'.$isRefine;
344
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
345
            if ($result === FALSE) {
346
                $result = $this->_searchPublications($keyword, $articles, $books, $theses, $reports, $type, $language, $funder, $fundingStream, $scientificArea,$fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $isRefine);
347
                if ($result !== NULL)
348
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
349
            }
350
        } else {
351
            $result = $this->_searchPublications($keyword, $articles, $books, $theses, $reports, $type, $language, $funder, $fundingStream, $scientificArea,$fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $isRefine);
352
        }
353
        return $result;
354
    }
355

    
356
    // Perform a simple search for datasets using cache if enabled.
357
    // $keyword the keyword to search for
358
    // $type the ID of the dataset type to use as filter or NULL for no dataset type filtering
359
    // $language the ID of the language to use as filter or NULL for no language filtering
360
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
361
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
362
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
363
    // $year the year of publication to use as filter or NULL for no year filtering
364
    // $accessMode the ID of the access mode to use as a filter or NULL for no access mode filtering
365
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
366
    // $page the page of results to retrieve
367
    // $size the size of the page of results to retrieve
368
    // $locale the locale to use
369
    // return a result (object) containing datasets and statistics
370
    public function searchDatasets($keyword, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale,$isRefine) {
371
        if ($this->cache->getCaching()) {
372
            $cacheId = self :: SEARCH_DATASETS_CACHE_ID . '.' . $keyword . '.' . $type . '.' . $language . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea .  '.' . $fundingStreamLevel2 . '.' . $year . '.' . $accessMode . '.' . $datasource . '.' . $page . '.' . $size . '.' . $locale.'.'.$isRefine;
373
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
374
            if ($result === FALSE) {
375
                $result = $this->_searchDatasets($keyword, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $isRefine);
376
                if ($result !== NULL)
377
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
378
            }
379
        } else
380
            $result = $this->_searchDatasets($keyword, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $isRefine);
381
        return $result;
382
    }
383

    
384
    // Perform a simple search for projects using cache if enabled.
385
    // $keyword the keyword to search for
386
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
387
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
388
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
389
    // $startYear the start year to use as filter or NULL for no start year filtering
390
    // $endYear the end year to suse as filter or NULL for no end year filtering
391
    // $sc39 the SC-39 status to use as filter or NULL for no SC-39 status filtering
392
    // $page the page of results to retrieve
393
    // $size the size of the page of results to retrieve
394
    // $locale the locale to use
395
    // return a result (object) containing projects and statistics
396
    public function searchProjects($keyword, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine) {
397
        if ($this->cache->getCaching()) {
398
            $cacheId = self :: SEARCH_PROJECTS_CACHE_ID . '.' . $keyword . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea .  '.' . $fundingStreamLevel2 .'.' . $startYear . '.' . $endYear . '.' . (($sc39 === NULL) ? '' : (($sc39) ? 'true' : 'false')) . '.' . $page . '.' . $size . '.' . $locale . '.' .$isRefine;
399
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
400
            if ($result === FALSE) {
401
                $result = $this->_searchProjects($keyword, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2 ,$startYear, $endYear, $sc39, $page, $size, $locale, $isRefine);
402
                if ($result !== NULL)
403
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
404
            }
405
        } else
406
            $result = $this->_searchProjects($keyword, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine);
407
        return $result;
408
    }
409

    
410
    // Perform a simple search for people using cache if enabled.
411
    // $keyword the keyword to search for
412
    // $country the ID of the country to use as filter or NULL for no country filtering
413
    // $page the page of results to retrieve
414
    // $size the size of the page of results to retrieve
415
    // $locale the locale to use
416
    // return a result (object) containing people and statistics
417
    public function searchPeople($keyword, $country, $page, $size, $locale, $isRefine) {
418
        if ($this->cache->getCaching()) {
419
            $cacheId = self :: SEARCH_PEOPLE_CACHE_ID . '.' . $keyword . '.' . $country . '.' . $page . '.' . $size . '.' . $locale . '.' . $isRefine;
420
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
421
            if ($result === FALSE) {
422
                $result = $this->_searchPeople($keyword, $country, $page, $size, $locale, $isRefine);
423
                if ($result !== NULL)
424
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
425
            }
426
        } else
427
            $result = $this->_searchPeople($keyword, $country, $page, $size, $locale, $isRefine);
428
        return $result;
429
    }
430

    
431
    // Perform a simple search for organizations using cache if enabled.
432
    // $keyword the keyword to search for
433
    // $country the ID of the country to use as filter or NULL for no country filtering
434
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
435
    // $page the page of results to retrieve
436
    // $size the size of the page of results to retrieve
437
    // $locale the locale to use
438
    // return a result (object) containing organizations and statistics
439
    public function searchOrganizations($keyword, $country, $type, $page, $size, $locale, $isRefine) {
440
        if ($this->cache->getCaching()) {
441
            $cacheId = self :: SEARCH_ORGANIZATIONS_CACHE_ID . '.' . $keyword . '.' . $country . '.' . $type . '.' . $page . '.' . $size . '.' . $locale . '.' .$isRefine;
442
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
443
            if ($result === FALSE) {
444
                $result = $this->_searchOrganizations($keyword, $country, $type, $page, $size, $locale, $isRefine);
445
                if ($result !== NULL)
446
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
447
            }
448
        } else
449
            $result = $this->_searchOrganizations($keyword, $country, $type, $page, $size, $locale, $isRefine);
450
        return $result;
451
    }
452

    
453
    // Perform a simple search for datasources using cache if enabled.
454
    // $keyword the keyword to search for
455
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
456
    // $language ID of the datasource language to use as filter or NULL for no datasource language filtering
457
    // $content the ID of the content to use as filter or NULL for no project filtering
458
    // $compatibility the ID of the compatibility level to use as filter or NULL for no compatibility level filtering
459
    // $page the page of results to retrieve
460
    // $size the size of the page of results to retrieve
461
    // $locale the locale to use
462
    // return a result (object) containing datasources and statistics
463
    public function searchDatasources($keyword, $type, $language, $content, $compatibility, $page, $size, $locale, $isRefine) {
464
        if ($this->cache->getCaching()) {
465
            $cacheId = self :: SEARCH_DATASOURCES_CACHE_ID . '.' . $keyword . '.' . $type . '.' . $language . '.' . $content . '.' . $compatibility . '.' . $page . '.' . $size . '.' . $locale . '.' .$isRefine;
466
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
467
            if ($result === FALSE) {
468
                $result = $this->_searchDatasources($keyword, $type, $language, $content, $compatibility, $page, $size, $locale, $isRefine);
469
                if ($result !== NULL)
470
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
471
            }
472
        } else
473
            $result = $this->_searchDatasources($keyword, $type, $language, $content, $compatibility, $page, $size, $locale, $isRefine);
474
        return $result;
475
    }
476

    
477
    // Perform a browse for publications using cache if enabled.
478
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
479
    // $language the ID of the language to use as filter or NULL for no language filtering
480
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
481
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
482
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
483
    // $year the year of publication to use as filter or NULL for no year filtering
484
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
485
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
486
    // $community the ID of the community to use as filter or NULL for no datasource filtering
487
    // $page the page of results to retrieve
488
    // $size the size of the page of results to retrieve
489
    // $locale the locale to use
490
    // $project the ID of the project to use as filter or NULL for no project filtering
491
    // $author the ID of the author to use as filter or NULL for no author filtering
492
    // return a result (object) containing publications and statistics
493
    public function browsePublications($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $author, $isRefine,$refineFields = NULL) {
494
         if ($this->cache->getCaching()) {
495
             $cacheId = self :: BROWSE_PUBLICATIONS_CACHE_ID . '.' . $type . '.' . $language . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.' . $fundingStreamLevel2. '.' . $year . '.' . $accessMode . '.' . $datasource . '.' . $community . '.' . $page . '.' . $size . '.' . $locale . '.' . $project . '.' . $author.'.'.$isRefine.'.'.$refineFields;
496
             $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
497
             if ($result === FALSE) {
498
                 $result = $this->_browsePublications($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $author,$isRefine,$refineFields);
499
                 if ($result !== NULL)
500
                     $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
501
            }
502
          } else
503
          $result = $this->_browsePublications($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $author,$isRefine,$refineFields);
504
        return $result;
505
    }
506

    
507
    // Perform a browse for datasets using cache if enabled.
508
    // $type the ID of the dataset type to use as filter or NULL for no dataset type filtering
509
    // $language the ID of the language to use as filter or NULL for no language filtering
510
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
511
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
512
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
513
    // $year the year of publication to use as filter or NULL for no year filtering
514
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
515
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
516
    // $page the page of results to retrieve
517
    // $size the size of the page of results to retrieve
518
    // $locale the locale to use
519
    // $project the ID of the project to use as filter or NULL for no project filtering
520
    // $author the ID of the author to use as filter or NULL for no author filtering
521
    // return a result (object) containing datasets and statistics
522
    public function browseDatasets($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine, $refineFields = NULL) {
523
        if ($this->cache->getCaching()) {
524
            $cacheId = self :: BROWSE_DATASETS_CACHE_ID . '.' . $type . '.' . $language . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.' . $fundingStreamLevel2 . '.' . $year . '.' . $accessMode . '.' . $datasource . '.' . $page . '.' . $size . '.' . $locale . '.' . $project . '.' . $author.'.'.$isRefine.'.'.$refineFields;
525
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
526
            if ($result === FALSE) {
527
                $result = $this->_browseDatasets($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine,$refineFields);
528
                if ($result !== NULL)
529
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
530
            }
531
        } else
532
            $result = $this->_browseDatasets($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine,$refineFields);
533
        return $result;
534
    }
535

    
536
    // Perform a browse for projects using cache if enabled.
537
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
538
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
539
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
540
    // $startYear the start year to use as filter or NULL for no start year filtering
541
    // $endYear the end year to use as filter or NULL for no end year filtering
542
    // $sc39 the SC-39 status to use as filter or NULL for no SC-39 status filtering
543
    // $page the page of results to retrieve
544
    // $size the size of the page of results to retrieve
545
    // $locale the locale to use
546
    // return a result (object) containing projects and statistics
547
    public function browseProjects($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine) {
548
        if ($this->cache->getCaching()) {
549
            $cacheId = self :: BROWSE_PROJECTS_CACHE_ID . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.' . $fundingStreamLevel2 . '.' . $startYear . '.' . '.' . $endYear . '.' . $sc39 . '.' . $page . '.' . $size . '.' . $locale. '.' . $isRefine;
550
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
551
            if ($result === FALSE) {
552
                $result = $this->_browseProjects($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine);
553
                if ($result !== NULL)
554
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
555
            }
556
        } else
557
            $result = $this->_browseProjects($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine);
558
        return $result;
559
    }
560

    
561
    // Perform a browse for people using cache if enabled.
562
    // $country the ID of the country to use as filter or NULL for no country filtering
563
    // $page the page of results to retrieve
564
    // $size the size of the page of results to retrieve
565
    // $locale the locale to use
566
    // return a result (object) containing people and statistics
567
    public function browsePeople($country, $page, $size, $locale, $isRefine) {
568
        if ($this->cache->getCaching()) {
569
            $cacheId = self :: BROWSE_PEOPLE_CACHE_ID . '.' . $country . '.' . $page . '.' . $size . '.' . $locale .'.'. $isRefine;
570
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
571
            if ($result === FALSE) {
572
                $result = $this->_browsePeople($country, $page, $size, $locale, $isRefine);
573
                if ($result !== NULL)
574
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
575
            }
576
        } else
577
            $result = $this->_browsePeople($country, $page, $size, $locale, $isRefine);
578
        return $result;
579
    }
580

    
581
    // Perform a browse for organizations using cache if enabled.
582
    // $country the ID of the country to use as filter or NULL for no country filtering
583
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
584
    // $page the page of results to retrieve
585
    // $size the size of the page of results to retrieve
586
    // $locale the locale to use
587
    // return a result (object) containing organizations and statistics
588
    public function browseOrganizations($country, $type, $page, $size, $locale, $isRefine) {
589
        if ($this->cache->getCaching()) {
590
            $cacheId = self :: BROWSE_ORGANIZATIONS_CACHE_ID . '.' . $country . '.' . $type . '.' . $page . '.' . $size . '.' . $locale.'.'.$isRefine;
591
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
592
            if ($result === FALSE) {
593
                $result = $this->_browseOrganizations($country, $type, $page, $size, $locale, $isRefine);
594
                if ($result !== NULL)
595
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
596
            }
597
        } else
598
            $result = $this->_browseOrganizations($country, $type, $page, $size, $locale, $isRefine);
599
        return $result;
600
    }
601

    
602
    // Perform a browse for datasources using cache if enabled.
603
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
604
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
605
    // $content the ID of the content to use as filter or NULL for no content filtering
606
    // $compatibility the ID of the compatibility level to use as filter or NULL for no compatibility status filtering
607
    // $page the page of results to retrieve
608
    // $size the size of the page of results to retrieve
609
    // $locale the locale to use
610
    // return a result (object) containing datasources and statistics
611
    public function browseDatasources($type, $language, $content, $compatibility, $page, $size, $locale, $isRefine) {
612
        if ($this->cache->getCaching()) {
613
            $cacheId = self :: BROWSE_DATASOURCES_CACHE_ID . '.' . $type . '.' . $language . '.' . $content . '.' . $compatibility . '.' . $page . '.' . $size . '.' . $locale.'.'.$isRefine;
614
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
615
            if ($result === FALSE) {
616
                $result = $this->_browseDatasources($type, $language, $content, $compatibility, $page, $size, $locale,$isRefine);
617
                if ($result !== NULL)
618
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
619
            }
620
        } else
621
            $result = $this->_browseDatasources($type, $language, $content, $compatibility, $page, $size, $locale, $isRefine);
622
        return $result;
623
    }
624

    
625
    // Perform an advanced search for publications using cache if enabled.
626
    // $keywords the keywords to search for (array)
627
    // $fields the fields to match keywords with (array - possible values are TITLE, AUTHOR, PUBLISHER and SUBJECT)
628
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
629
    // $types the IDs of the publication types to search for
630
    // $languages the IDs of the publication languages to search for
631
    // $funders the IDs of the funders to search for
632
    // $fundingStreams the IDs of the funding streams to search for
633
    // $scientificAreas the IDs of the scientific areas to search for
634
    // $date the publication date range to search for expressed in months before current date (if -1 search for any publication date, if 0 search explicitly using $fromMonth, $fromYear, $toMonth and $toYear)
635
    // $fromMonth start month of the publication date range to search for if $date has value 0
636
    // $fromYear start year of the publication date range to search for if $date has value 0
637
    // $toMonth end month of the publication date range to search for if $date has value 0
638
    // $toYear end year of the publication date range to search for if $date has value 0
639
    // $accessModes the IDs of the access modes to search for
640
    // $datasources the IDs of the datasources to search for
641
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
642
    // $language the ID of the publication language to use as filter or NULL for no publication language filtering
643
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
644
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
645
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
646
    // $year the publication year to use as filter or NULL for no publication year filtering
647
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
648
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
649
    // $page the page of results to retrieve
650
    // $size the size of the page of results to retrieve
651
    // $locale the locale to use
652
    // return a result (object) containing publications and statistics
653
    public function advancedSearchPublications($keywords, $fields, $constraints, $types, $languages, $funders, $fundingStreams, $scientificAreas, $fundingStreamsLevel2, $date, $fromMonth, $fromYear, $toMonth, $toYear, $accessModes, $datasources, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale) {
654
        if ($this->cache->getCaching()) {
655
            $cacheId = self :: ADVANCED_SEARCH_PUBLICATIONS_CACHE_ID . '.' . implode('.', $keywords) . '.' . implode('.', $fields) . '.' . implode('.', $constraints) . '.' . implode('.', $types) . '.' . implode('.', $languages) . '.' . implode('.', $funders) . '.' . implode('.', $fundingStreams) . '.' . implode('.', $scientificAreas) .'.' . implode('.', $fundingStreamsLevel2) . '.' . $date . '.' . $fromMonth . '.' . $fromYear . '.' . $toMonth . '.' . $toYear . '.' . implode('.', $accessModes) . '.' . implode('.', $datasources) . '.' . $type . '.' . $language . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.'.$fundingStreamLevel2.'.' . $year . '.' . $accessMode . '.' . $datasource . '.' . $page . '.' . $size . '.' . $locale;
656
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
657
            if ($result === FALSE) {
658
                $result = $this->_advancedSearchPublications($keywords, $fields, $constraints, $types, $languages, $funders, $fundingStreams, $scientificAreas, $fundingStreamsLevel2, $date, $fromMonth, $fromYear, $toMonth, $toYear, $accessModes, $datasources, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2,  $year, $accessMode, $datasource, $page, $size, $locale);
659
                if ($result !== NULL)
660
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
661
            }
662
        } else
663
            $result = $this->_advancedSearchPublications($keywords, $fields, $constraints, $types, $languages, $funders, $fundingStreams, $scientificAreas, $fundingStreamsLevel2, $date, $fromMonth, $fromYear, $toMonth, $toYear, $accessModes, $datasources, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale);
664
        return $result;
665
    }
666

    
667
    // Perform an advanced search for projects using cache if enabled.
668
    // $keywords the keywords to search for (array)
669
    // $fields the fields to match keywords with (array - possible values are ACRONYM, TITLE and KEYWORDS)
670
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
671
    // $funders the IDs of the funders to search for
672
    // $fundingStreams the IDs of the funding streams to search for
673
    // $scientificAreas the IDs of the scientific areas to search for
674
    // $startDate the start date range to search for expressed in months before current date (if -1 search for any start date, if 0 search explicitly using $startFromMonth, $startFromYear, $startToMonth and $startToYear)
675
    // $startFromMonth start month of the start date range to search for if $startDate has value 0
676
    // $startFromYear start year of the start date range to search for if $startDate has value 0
677
    // $startToMonth end month of the start date range to search for if $startDate has value 0
678
    // $startToYear end year of the start date range to search for if $startDate has value 0
679
    // $endDate the end date range to search for expressed in months before current date (if -1 search for any end date, if 0 search explicitly using $endFromMonth, $endFromYear, $endToMonth and $endToYear)
680
    // $endFromMonth start month of the end date range to search for if $endDate has value 0
681
    // $endFromYear start year of the end date range to search for if $endDate has value 0
682
    // $endToMonth end month of the end date range to search for if $endDate has value 0
683
    // $endToYear end year of the end date range to search for if $endDate has value 0
684
    // $sc39 the SC-39 statuses to search for
685
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
686
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
687
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
688
    // $startYear the start year to use as filter or NULL for no start year filtering
689
    // $endYear the end year to use as filter or NULL for no end year filtering	
690
    // $accessMode the ID of the SC-39 status to use as filter or NULL for no SC-39 status filtering
691
    // $page the page of results to retrieve
692
    // $size the size of the page of results to retrieve
693
    // $locale the locale to use
694
    // return a result (object) containing projects and statistics
695
    public function advancedSearchProjects($keywords, $fields, $constraints, $funders, $fundingStreams, $scientificAreas, $fundingStreamsLevel2, $startDate, $startFromMonth, $startFromYear, $startToMonth, $startToYear, $endDate, $endFromMonth, $endFromYear, $endToMonth, $endToYear, $sc39s, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale) {
696
        if ($this->cache->getCaching()) {
697
            $cacheId = self :: ADVANCED_SEARCH_PROJECTS_CACHE_ID . '.' . implode('.', $keywords) . '.' . implode('.', $fields) . '.' . implode('.', $constraints) . '.' . implode('.', $funders) . '.' . implode('.', $fundingStreams) . '.' . implode('.', $scientificAreas) . '.'. implode('.', $fundingStreamLevel2) . '.' . $startDate . '.' . $startFromMonth . '.' . $startFromYear . '.' . $startToMonth . '.' . $startToYear . '.' . $endDate . '.' . $endFromMonth . '.' . $endFromYear . '.' . $endToMonth . '.' . $endToYear . '.' . implode('.', array_map(function ($sc39) {
698
                                return $sc39 ? 'true' : 'false';
699
                            }, $sc39s)) . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.' . $fundingStreamLevel2 . '.' . $startYear . '.' . $endYear . '.' . (($sc39 === NULL) ? '' : ($sc39 ? 'true' : 'false')) . '.' . $page . '.' . $size . '.' . $locale;
700
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
701
            if ($result === FALSE) {
702
                $result = $this->_advancedSearchProjects($keywords, $fields, $constraints, $funders, $fundingStreams, $scientificAreas, $fundingStreamsLevel2, $startDate, $startFromMonth, $startFromYear, $startToMonth, $startToYear, $endDate, $endFromMonth, $endFromYear, $endToMonth, $endToYear, $sc39s, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale);
703
                if ($result !== NULL)
704
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
705
            }
706
        } else
707
            $result = $this->_advancedSearchProjects($keywords, $fields, $constraints, $funders, $fundingStreams, $scientificAreas,  $fundingStreamsLevel2, $startDate, $startFromMonth, $startFromYear, $startToMonth, $startToYear, $endDate, $endFromMonth, $endFromYear, $endToMonth, $endToYear, $sc39s, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale);
708
        return $result;
709
    }
710

    
711
    // Perform an advanced search for people using cache if enabled.
712
    // $keywords the keywords to search for (array)
713
    // $fields the fields to match keywords with (array - possible values are LAST_NAME, FIRST_NAME and FULL_NAME) 
714
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
715
    // $countries the IDs of the countries to search for
716
    // $country the ID of the coutnry to use as filter or NULL for no country filtering
717
    // $page the page of results to retrieve
718
    // $size the size of the page of results to retrieve
719
    // $locale the locale to use
720
    // return a result (object) containing people and statistics
721
    public function advancedSearchPeople($keywords, $fields, $constraints, $countries, $country, $page, $size, $locale) {
722
        if ($this->cache->getCaching()) {
723
            $cacheId = self :: ADVANCED_SEARCH_PEOPLE_CACHE_ID . '.' . implode('.', $keywords) . '.' . implode('.', $fields) . '.' . implode('.', $constraints) . '.' . implode('.', $countries) . '.' . $country . '.' . $page . '.' . $size . '.' . $locale;
724
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
725
            if ($result === FALSE) {
726
                $result = $this->_advancedSearchPeople($keywords, $fields, $constraints, $countries, $country, $page, $size, $locale);
727
                if ($result !== NULL)
728
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
729
            }
730
        } else
731
            $result = $this->_advancedSearchPeople($keywords, $fields, $constraints, $countries, $country, $page, $size, $locale);
732
        return $result;
733
    }
734

    
735
    // Perform an advanced search for organizations using cache if enabled.
736
    // $keywords the keywords to search for (array)
737
    // $fields the fields to match keywords with (array - possible values are NAME and SHORT_NAME)
738
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
739
    // $countries the IDs of the countries to search for
740
    // $types the IDs of the organization types to search for
741
    // $country the ID of the country to use as filter or NULL for no country filtering
742
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
743
    // $page the page of results to retrieve
744
    // $size the size of the page of results to retrieve
745
    // $locale the locale to use
746
    // return a result (object) containing people and statistics	
747
    public function advancedSearchOrganizations($keywords, $fields, $constraints, $countries, $types, $country, $type, $page, $size, $locale) {
748
        if ($this->cache->getCaching()) {
749
            $cacheId = self :: ADVANCED_SEARCH_ORGANIZATIONS_CACHE_ID . '.' . implode('.', $keywords) . '.' . implode('.', $fields) . '.' . implode('.', $constraints) . '.' . implode('.', $countries) . '.' . implode('.', $types) . $country . '.' . $type . '.' . $page . '.' . $size . '.' . $locale;
750
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
751
            if ($result === FALSE) {
752
                $result = $this->_advancedSearchOrganizations($keywords, $fields, $constraints, $countries, $types, $country, $type, $page, $size, $locale);
753
                if ($result !== NULL)
754
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
755
            }
756
        } else
757
            $result = $this->_advancedSearchOrganizations($keywords, $fields, $constraints, $countries, $types, $country, $type, $page, $size, $locale);
758
        return $result;
759
    }
760

    
761
    // Perform an advanced search for datasources using cache if enabled.
762
    // $keywords the keywords to search for (array)
763
    // $fields the fields to match keywords with (array - possible values are NAME, ENGLISH_NAME and SUBJECT)
764
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
765
    // $types the IDs of the datasource types to search for
766
    // $languages the IDs of the datasource languages to search for
767
    // $contents the IDs of the contents to search for
768
    // $compatibilities the IDs of the compatibilities to search for
769
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
770
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
771
    // $content the ID of the content to use as filter or NULL for no content filtering
772
    // $compatibility the ID of the compatibility to use as filter or NULL for no compatibility filtering
773
    // $page the page of results to retrieve
774
    // $size the size of the page of results to retrieve
775
    // $locale the locale to use
776
    // return a result (object) containing datasources and statistics
777
    public function advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale) {
778
        if ($this->cache->getCaching()) {
779
            $cacheId = self :: ADVANCED_SEARCH_DATASOURCES_CACHE_ID . '.' . implode('.', $keywords) . '.' . implode('.', $fields) . '.' . implode('.', $constraints) . '.' . implode('.', $types) . '.' . implode('.', $languages) . '.' . implode('.', $contents) . '.' . implode('.', $compatibilities) . '.' . $type . '.' . $language . '.' . $content . '.' . $compatibility . '.' . $page . '.' . $size . '.' . $locale;
780
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
781
            if ($result === FALSE) {
782
                $result = $this->_advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale);
783
                if ($result !== NULL)
784
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
785
            }
786
        } else
787
            $result = $this->_advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale);
788
        return $result;
789
    }
790

    
791
    // Retrieve a single publication by identifier using caching if enabled.
792
    // $id the publication identifier
793
    // $locale the locale to use
794
    // return a publication (object) or NULL if no such publication exists
795
    public function getPublication($id, $locale) {
796
        if ($this->cache->getCaching()) {
797
            $cacheId = self :: PUBLICATION_CACHE_ID . '.' . $id . '.' . $locale;
798
            $publication = $this->cache->get($cacheId, self :: CACHE_GROUP);
799
            if ($publication === FALSE) {
800
                $publication = $this->_getPublication($id, $locale);
801
                if ($publication !== NULL)
802
                    $this->cache->store($publication, $cacheId, self :: CACHE_GROUP);
803
            }
804
        } else
805
            $publication = $this->_getPublication($id, $locale);
806
        return $publication;
807
    }
808

    
809
    // Retrieve a single publication by identifier using caching if enabled.
810
    // $ids the publication identifiers
811
    // $locale the locale to use
812
    // return a publication (object) or NULL if no such publication exists
813
    public function getResults($ids, $locale) {
814
        /*if ($this->cache->getCaching()) {
815
            $cacheId = self :: RESULT_CACHE_ID . '.' . join(",", $ids) . '.' . $locale;
816
            $results = $this->cache->get($cacheId, self :: CACHE_GROUP);
817
            if ($results === FALSE) {
818
                $results = $this->_getResults($ids, $locale);
819
                if ($results !== NULL)
820
                    $this->cache->store($results, $cacheId, self :: CACHE_GROUP);
821
            }
822
        } else
823
          */  $results = $this->_getResults($ids, $locale);
824
        return $results;
825
    }
826

    
827
    // Retrieve a single publication by identifier using caching if enabled.
828
    // $ids the publication identifiers
829
    // $locale the locale to use
830
    // return a publication (object) or NULL if no such publication exists
831
    public function getPublications($ids, $locale) {
832
        if ($this->cache->getCaching()) {
833
            $cacheId = self :: PUBLICATIONS_CACHE_ID . '.' . join(",", $ids) . '.' . $locale;
834
            $publications = $this->cache->get($cacheId, self :: CACHE_GROUP);
835
            if ($publications === FALSE) {
836
                $publications = $this->_getPublications($ids, $locale);
837
                if ($publications !== NULL)
838
                    $this->cache->store($publications, $cacheId, self :: CACHE_GROUP);
839
            }
840
        } else
841
            $publications = $this->_getPublications($ids, $locale);
842
        return $publications;
843
    }
844

    
845
    // Retrieve a single dataset by identifier using caching if enabled.
846
    // $ids the dataset identifiers
847
    // $locale the locale to use
848
    // return a publication (object) or NULL if no such publication exists
849
    public function getDatasets($ids, $locale) {
850
        if ($this->cache->getCaching()) {
851
            $cacheId = self :: DATASETS_CACHE_ID . '.' . join(",", $ids) . '.' . $locale;
852
            $datasets = $this->cache->get($cacheId, self :: CACHE_GROUP);
853
            if ($datasets === FALSE) {
854
                $datasets = $this->_getDatasets($ids, $locale);
855
                if ($datasets !== NULL)
856
                    $this->cache->store($datasets, $cacheId, self :: CACHE_GROUP);
857
            }
858
        } else
859
            $publications = $this->_getDatasets($ids, $locale);
860
        return $publications;
861
    }
862

    
863
    // Retrieve projects by identifier using caching if enabled.
864
    // $ids the project identifiers
865
    // $locale the locale to use
866
    // return an array of project (object) or NULL if no such projects exists
867
    public function getProjects($ids, $locale) {
868
         if ($this->cache->getCaching()) {
869
            $cacheId = self :: PROJECTS_CACHE_ID . '.' . join(",", $ids) . '.' . $locale;
870
            $projects = $this->cache->get($cacheId, self :: CACHE_GROUP);
871
            if ($projects === FALSE) {
872
                $projects = $this->_getProjects($ids, $locale);
873
                if ($projects !== NULL)
874
                    $this->cache->store($projects, $cacheId, self :: CACHE_GROUP);
875
            }
876
        } else
877
            $projects = $this->_getProjects($ids, $locale);
878
        return $projects;
879
    }
880
    // Retrieve projects by identifier using caching if enabled.
881
    // $ids the project identifiers
882
    // $locale the locale to use
883
    // return an array of project (object) or NULL if no such projects exists
884
    public function getProjectByCodeId($id, $funder, $locale) {
885
         if ($this->cache->getCaching()) {
886
            $cacheId = self :: PROJECT_CACHE_ID . '.' . $id . '.' . $funder . '.' . $locale;
887
            $projects = $this->cache->get($cacheId, self :: CACHE_GROUP);
888
            if ($projects === FALSE) {
889
                $projects = $this->_getProjectByCodeId($id, $funder, $locale);
890
                if ($projects !== NULL)
891
                    $this->cache->store($projects, $cacheId, self :: CACHE_GROUP);
892
            }
893
        } else
894
            $projects = $this->_getProjectByCodeId($id, $funder, $locale);
895
        return $projects;
896
    }
897

    
898
    // Retrieve a single dataset by identifier using caching if enabled.
899
    // $id the dataset identifier
900
    // $locale the locale to use
901
    // return a dataset (object) or NULL if no such dataset exists
902
    public function getDataset($id, $locale) {
903
        if ($this->cache->getCaching()) {
904
            $cacheId = self :: DATASET_CACHE_ID . '.' . $id . '.' . $locale;
905
            $dataset = $this->cache->get($cacheId, self :: CACHE_GROUP);
906
            if ($dataset === FALSE) {
907
                $dataset = $this->_getDataset($id, $locale);
908
                if ($dataset !== NULL)
909
                    $this->cache->store($dataset, $cacheId, self :: CACHE_GROUP);
910
            }
911
        } else
912
            $dataset = $this->_getDataset($id, $locale);
913
        return $dataset;
914
    }
915

    
916
    // Retrieve a single project by identifier using caching if enabled.
917
    // $id the project identifier
918
    // $locale the locale to use
919
    // return a project (object) or NULL if no such project exists
920
    public function getProject($id, $locale) {
921
        if ($this->cache->getCaching()) {
922
            $cacheId = self :: PROJECT_CACHE_ID . '.' . $id . '.' . $locale;
923
            $project = $this->cache->get($cacheId, self :: CACHE_GROUP);
924
            if ($project === FALSE) {
925
                $project = $this->_getProject($id, $locale);
926
                if ($project !== NULL)
927
                    $this->cache->store($project, $cacheId, self :: CACHE_GROUP);
928
            }
929
        } else
930
            $project = $this->_getProject($id, $locale);
931
        return $project;
932
    }
933

    
934
    // Retrieve a single person by identifier using caching if enabled.
935
    // $id the person identifier
936
    // $locale the locale to use
937
    // return a person (object) or NULL if no such person exists
938
    public function getPerson($id, $locale) {
939
        if ($this->cache->getCaching()) {
940
            $cacheId = self :: PERSON_CACHE_ID . '.' . $id . '.' . $locale;
941
            $person = $this->cache->get($cacheId, self :: CACHE_GROUP);
942
            if ($person === FALSE) {
943
                $person = $this->_getPerson($id, $locale);
944
                if ($person !== NULL)
945
                    $this->cache->store($person, $cacheId, self :: CACHE_GROUP);
946
            }
947
        } else
948
            $person = $this->_getPerson($id, $locale);
949
        return $person;
950
    }
951

    
952
    // Retreive a single organization by identifier using cache if enabled.
953
    // $id the organization identifier
954
    // $locale the locale to use
955
    // return an organization (object) or NULL if no such organization exists
956
    public function getOrganization($id, $locale) {
957
        if ($this->cache->getCaching()) {
958
            $cacheId = self :: ORGANIZATION_CACHE_ID . '.' . $id . '.' . $locale;
959
            $organization = $this->cache->get($cacheId, self :: CACHE_GROUP);
960
            if ($organization === FALSE) {
961
                $organization = $this->_getOrganization($id, $locale);
962
                if ($organization !== NULL)
963
                    $this->cache->store($organization, $cacheId, self :: CACHE_GROUP);
964
            }
965
        } else
966
            $organization = $this->_getOrganization($id, $locale);
967
        return $organization;
968
    }
969

    
970
    // Retrieve the datasources of an organization using caching if enabled.
971
    // $id the organization identifier
972
    // $size the maximum number of organizations to retrieve
973
    // $locale the locale to use
974
    // return a result (object) containing datasources and total
975
    public function getOrganizationDatasources($id, $size, $locale) {
976
        if ($this->cache->getCaching()) {
977
            $cacheId = self :: ORGANIZATION_DATASOURCES_CACHE_ID . '.' . $id . '.' . $size . '.' . $locale;
978
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
979
            if ($result === FALSE) {
980
                $result = $this->_getOrganizationDatasources($id, $size, $locale);
981
                if ($result !== NULL)
982
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
983
            }
984
        } else
985
            $result = $this->_getOrganizationDatasources($id, $size, $locale);
986
        return $result;
987
    }
988

    
989
    // Retrieve a single datasource by identifier using cache if enabled.
990
    // $id the datasource identifier
991
    // $locale the locale to use
992
    // return a datasource (object) or NULL if no such datasource exists
993
    public function getDatasource($id, $locale, $compatibility = false) {
994
        if ($this->cache->getCaching()) {
995
            $cacheId = self :: DATASOURCE_CACHE_ID . '.' . $id . '.' . $locale . "." . $compatibility;
996
            $datasource = $this->cache->get($cacheId, self :: CACHE_GROUP);
997
            if ($datasource === FALSE) {
998
                $datasource = $this->_getDatasource($id, $locale, $compatibility);
999
                if ($datasource !== NULL)
1000
                    $this->cache->store($datasource, $cacheId, self :: CACHE_GROUP);
1001
            }
1002
        } else
1003
            $datasource = $this->_getDatasource($id, $locale, $compatibility);
1004
        return $datasource;
1005
    }
1006

    
1007
    // Retrieve all the OpenAIRE compatible datasources using cache if enabled.
1008
    // $locale the locale to use
1009
    // return the datasources (array) or NULL if any errors occur
1010
    public function getCompatibleDatasources($locale) {
1011
        if ($this->cache->getCaching()) {
1012
            $cacheId = self :: COMPATIBLE_DATASOURCES_CACHE_ID . '.' . $locale;
1013
            $datasources = $this->cache->get($cacheId, self :: CACHE_GROUP);
1014
            if ($datasources === FALSE) {
1015
                $datasources = $this->_getCompatibleDatasources($locale);
1016
                if ($datasources !== NULL)
1017
                    $this->cache->store($datasources, $cacheId, self :: CACHE_GROUP);
1018
            }
1019
        } else
1020
            $datasources = $this->_getCompatibleDatasources($locale);
1021
        return $datasources;
1022
    }
1023

    
1024
    // Perform a quick search for projects, searching only by acronym, title or code and funder and using cahce if enabled.
1025
    // $keyword the keyword to search for
1026
    // $funder the funder to search for
1027
    // $limit the maximum number of results to retrieve
1028
    // $locale the locale to use
1029
    // return projects (array) or NULL if any errors occur
1030
    public function quickSearchProjects($keyword, $funder, $limit, $locale) {
1031
        if ($this->cache->getCaching()) {
1032
            $cacheId = self :: QUICK_SEARCH_PROJECTS_CACHE_ID . '.' . $keyword . '.' . $funder . '.' . $limit . '.' . $locale;
1033
            $projects = $this->cache->get($cacheId, self :: CACHE_GROUP);
1034
            if ($projects === FALSE) {
1035
                $projects = $this->_quickSearchProjects($keyword, $funder, $limit, $locale);
1036
                if ($projects !== NULL)
1037
                    $this->cache->store($projects, $cacheId, self :: CACHE_GROUP);
1038
            }
1039
        } else
1040
            $projects = $this->_quickSearchProjects($keyword, $funder, $limit, $locale);
1041
        return $projects;
1042
    }
1043

    
1044
    // Perform a quick search for organizations, searching only by name or short name and using cache if enabled.
1045
    // $keyword the keyword to search for
1046
    // $limit the maximum number of results to retrieve
1047
    // $locale the locale to use
1048
    // return organizations (array) or NULL if any errors occur
1049
    public function quickSearchOrganizations($keyword, $limit, $locale) {
1050
        JLog :: add('Keyword \'' . $keyword . '\'', JLog :: INFO, self :: LOG);
1051
        if ($this->cache->getCaching()) {
1052
            $cacheId = self :: QUICK_SEARCH_ORGANIZATIONS_CACHE_ID . '.' . $keyword . '.' . $limit . '.' . $locale;
1053
            $organizations = $this->cache->get($cacheId, self :: CACHE_GROUP);
1054
            if ($organizations === FALSE) {
1055
                $organizations = $this->_quickSearchOrganizations($keyword, $limit, $locale);
1056
                if ($organizations !== NULL)
1057
                    $this->cache->store($organizations, $cacheId, self :: CACHE_GROUP);
1058
            }
1059
        } else
1060
            $organizations = $this->_quickSearchOrganizations($keyword, $limit, $locale);
1061
        return $organizations;
1062
    }
1063
   
1064
    // Retrieve publication statistics.
1065
    // $locale the locale to use
1066
    // $allFunders get all fields for funders
1067
    // return statistics (object)
1068
    private function _getPublicationStatistics($locale, $allFunders=false) {
1069
    try {
1070
            $time = microtime(TRUE);
1071
            $query = self :: PUBLICATION_QUERY;
1072
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1073
            /* if (($response = $this->performGet('search?action=refine&rTransformer=results_openaire_browse&fields=' . self :: PUBLICATION_TYPE . '&fields=' . self :: PUBLICATION_LANGUAGE . '&fields=' . self :: PUBLICATION_CONTEXT . '&fields=' . self :: PUBLICATION_FUNDER . '&fields=' . self :: PUBLICATION_FUNDING_STREAM . '&fields=' . self :: PUBLICATION_SCIENTIFIC_AREA . '&fields=' . self :: PUBLICATION_YEAR . '&fields=' . self :: PUBLICATION_ACCESS_MODE . '&fields=' . self :: PUBLICATION_DATASOURCE . '&fields=' . self :: PUBLICATION_CONTEXT . '&fields=' . self :: PUBLICATION_PROJECT . '&query=' . urlencode($query) . '&locale=' . c('-', '_', $locale))) == NULL)            
1074
             */         
1075
            if (($response = $this->performGet('search?action=refine&rTransformer=results_openaire_browse&fields='. self :: RESULT_DATASOURCE.'&fields=' . self :: PUBLICATION_TYPE . '&fields=' . self :: PUBLICATION_LANGUAGE . '&fields=' . self :: PUBLICATION_CONTEXT . '&fields=' . self :: PUBLICATION_FUNDER . '&fields=' . self :: PUBLICATION_FUNDING_STREAM . '&fields=' . self :: PUBLICATION_SCIENTIFIC_AREA . '&fields=' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . '&fields=' . self :: PUBLICATION_YEAR . '&fields=' . self :: PUBLICATION_ACCESS_MODE . '&fields=' . self :: PUBLICATION_DATASOURCE . '&fields=' . self :: PUBLICATION_CONTEXT .  '&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)            
1076
                throw new Exception('no HTTP response');
1077
            if ($response->code != self :: HTTP_OK)
1078
                throw new Exception('HTTP response code ' . $response->code);
1079
            $document = new DOMDocument();
1080
            $document->recover = TRUE;
1081
            if ($document->loadXML($response->body) == FALSE)
1082
                throw new Exception('invalid XML response');
1083
            $xpath = new DOMXPath($document);
1084
            $statistics=null;
1085
            if($allFunders){
1086
                $statistics = $this->createStatistics($xpath, 
1087
                    array('type', 'language', 'funder', 'fundingStream', 'scientificArea', 'fundingStreamLevel2', 'year', 'accessMode', 'datasource', 'community'),
1088
                    array('DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'FUNDING_STREAM_LEVEL_2', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE', 'COMMUNITIES'), 
1089
                    array('NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND',
1090
                'NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_FUNDING_STREAM_LEVEL2_STATISTICS_FOUND', 'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND', 'NO_COMMUNITY_STATISTICS_FOUND'), 
1091
                    array(self :: PUBLICATION_TYPE, self :: PUBLICATION_LANGUAGE, self :: PUBLICATION_FUNDER, self :: PUBLICATION_FUNDING_STREAM, self :: PUBLICATION_SCIENTIFIC_AREA, self :: PUBLICATION_FUNDING_STREAM_LEVEL2,  self :: PUBLICATION_YEAR, self :: PUBLICATION_ACCESS_MODE, self :: RESULT_DATASOURCE , self :: PUBLICATION_CONTEXT));
1092
            }else{
1093
                $statistics = $this->createStatistics($xpath, 
1094
                    array('type', 'language', 'funder',  'year', 'accessMode', 'datasource', 'community'),
1095
                    array('DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'FUNDER',  'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE', 'COMMUNITIES'), 
1096
                    array('NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND',
1097
                'NO_FUNDER_STATISTICS_FOUND',   'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND', 'NO_COMMUNITY_STATISTICS_FOUND'), 
1098
                    array(self :: PUBLICATION_TYPE, self :: PUBLICATION_LANGUAGE, self :: PUBLICATION_FUNDER, self :: PUBLICATION_YEAR, self :: PUBLICATION_ACCESS_MODE, self :: RESULT_DATASOURCE , self :: PUBLICATION_CONTEXT));
1099
             
1100
            }                
1101
            JLog :: add('Retrieved publication statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1102
            return $statistics;
1103
        } catch (Exception $e) {
1104
            JLog :: add('Error retrieving publication statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1105
            return NULL;
1106
        }
1107
    }
1108

    
1109
                
1110
    // Retrieve dataset statistics.
1111
    // $locale the locale to use
1112
    // return statistics (object)
1113
    private function _getDatasetStatistics($locale, $allFunders=false) {
1114
        try {
1115
            $time = microtime(TRUE);
1116
            $query = self :: DATASET_QUERY;
1117
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1118
            if (($response = $this->performGet('search?action=refine&rTransformer=results_openaire_browse&fields=' . self :: DATASET_TYPE . '&fields=' . self :: DATASET_LANGUAGE . '&fields=' . self :: DATASET_FUNDER . '&fields=' . self :: DATASET_FUNDING_STREAM . '&fields=' . self :: DATASET_SCIENTIFIC_AREA . '&fields=' . self :: DATASET_YEAR . '&fields=' . self :: DATASET_ACCESS_MODE . '&fields=' . self :: DATASET_DATASOURCE . '&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
1119
                throw new Exception('no HTTP response');
1120
            if ($response->code != self :: HTTP_OK)
1121
                throw new Exception('HTTP response code ' . $response->code);
1122
            $document = new DOMDocument();
1123
            $document->recover = TRUE;
1124
            if ($document->loadXML($response->body) == FALSE)
1125
                throw new Exception('invalid XML response');
1126
            $xpath = new DOMXPath($document);
1127
            $statistics=null;
1128
            if($allFunders){
1129
                $statistics = $this->createStatistics($xpath, array('type', 'language', 'funder', 'fundingStream', 'scientificArea', 'year', 'accessMode', 'datasource'), array('TYPE', 'LANGUAGE', 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE'), array('NO_DATASET_TYPE_STATISTICS_FOUND', 'NO_DATASET_LANGUAGE_STATISTICS_FOUND', 'NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND'), array(self :: DATASET_TYPE, self :: DATASET_LANGUAGE, self :: DATASET_FUNDER, self :: DATASET_FUNDING_STREAM, self :: DATASET_SCIENTIFIC_AREA, self :: DATASET_YEAR, self :: DATASET_ACCESS_MODE, self :: DATASET_DATASOURCE));
1130
            }else{
1131
                $statistics = $this->createStatistics($xpath, array('type', 'language', 'funder', 'year', 'accessMode', 'datasource'), array('TYPE', 'LANGUAGE', 'FUNDER',   'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE'), array('NO_DATASET_TYPE_STATISTICS_FOUND', 'NO_DATASET_LANGUAGE_STATISTICS_FOUND', 'NO_FUNDER_STATISTICS_FOUND',  'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND'), array(self :: DATASET_TYPE, self :: DATASET_LANGUAGE, self :: DATASET_FUNDER,   self :: DATASET_YEAR, self :: DATASET_ACCESS_MODE, self :: DATASET_DATASOURCE));
1132
            }                        
1133
            JLog :: add('Retrieved dataset statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1134
            return $statistics;
1135
        } catch (Exception $e) {
1136
            JLog :: add('Error retrieving dataset statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1137
            return NULL;
1138
        }
1139
    }
1140

    
1141
    // Retrieve project statistics.
1142
    // $locale the locale to use
1143
    // return statistics (object)
1144
    private function _getProjectStatistics($locale, $allFunders) {
1145
        try {
1146
            $time = microtime(TRUE);
1147
            $query = self :: PROJECT_QUERY;
1148
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1149
            if (($response = $this->performGet('search?action=refine&rTransformer=results_openaire_browse&fields=' . self :: PROJECT_FUNDER . '&fields=' . self :: PROJECT_FUNDING_STREAM . '&fields=' . self :: PROJECT_SCIENTIFIC_AREA . '&fields=' . self :: PROJECT_START_YEAR . '&fields=' . self :: PROJECT_END_YEAR . '&fields=' . self :: PROJECT_SC39 . '&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
1150
            //if (($response = $this->performGet('search?action=refine&rTransformer=results_openaire_browse&fields=' . self :: PROJECT_FUNDER . '&fields=' . self :: PROJECT_START_YEAR . '&fields=' . self :: PROJECT_END_YEAR . '&fields=' . self :: PROJECT_SC39 . '&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
1151
                throw new Exception('no HTTP response');
1152
            if ($response->code != self :: HTTP_OK)
1153
                throw new Exception('HTTP response code ' . $response->code);
1154
            $document = new DOMDocument();
1155
            $document->recover = TRUE;
1156
            if ($document->loadXML($response->body) == FALSE)
1157
                throw new Exception('invalid XML response');
1158
            $statistics=null;
1159
            $xpath = new DOMXPath($document);
1160
            if( $allFunders){
1161
                $statistics = $this->createStatistics($xpath, 
1162
                    array('funder', 'fundingStream', 'scientificArea', 'startYear', 'endYear', 'sc39'),
1163
                    array('FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'), 
1164
                    array('NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_START_YEAR_STATISTICS_FOUND', 'NO_END_YEAR_STATISTICS_FOUND', 'NO_SPECIAL_CLAUSE_39_STATISTICS_FOUND'), 
1165
                    array(self :: PROJECT_FUNDER, self :: PROJECT_FUNDING_STREAM, self :: PROJECT_SCIENTIFIC_AREA, self :: PROJECT_START_YEAR, self :: PROJECT_END_YEAR, self :: PROJECT_SC39));
1166
            }else{
1167
                $statistics = $this->createStatistics($xpath, 
1168
                    array('funder',   'startYear', 'endYear', 'sc39'),
1169
                    array('FUNDER',   'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'), 
1170
                    array('NO_FUNDER_STATISTICS_FOUND', 'NO_START_YEAR_STATISTICS_FOUND', 'NO_END_YEAR_STATISTICS_FOUND', 'NO_SPECIAL_CLAUSE_39_STATISTICS_FOUND'), 
1171
                    array(self :: PROJECT_FUNDER,  self :: PROJECT_START_YEAR, self :: PROJECT_END_YEAR, self :: PROJECT_SC39));
1172
            }
1173
            JLog :: add('Retrieved project statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1174
            return $statistics;
1175
        } catch (Exception $e) {
1176
            JLog :: add('Error retrieving project statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1177
            return NULL;
1178
        }
1179
    }
1180

    
1181
    // Retrieve people statistics.
1182
    // $locale the locale to use
1183
    // return statistics (object)
1184
    private function _getPeopleStatistics($locale) {
1185
        try {
1186
            $time = microtime(TRUE);
1187
            $query = self :: PERSON_QUERY;
1188
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1189
            if (($response = $this->performGet('search?action=refine&rTransformer=results_openaire_browse&fields=' . self :: PERSON_COUNTRY . '&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
1190
                throw new Exception('no HTTP response');
1191
            if ($response->code != self :: HTTP_OK)
1192
                throw new Exception('HTTP response code ' . $response->code);
1193
            $document = new DOMDocument();
1194
            $document->recover = TRUE;
1195
            if ($document->loadXML($response->body) == FALSE)
1196
                throw new Exception('invalid XML response');
1197
            $xpath = new DOMXPath($document);
1198
            $statistics = $this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: PERSON_COUNTRY));
1199
            JLog :: add('Retrieved people statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1200
            return $statistics;
1201
        } catch (Exception $e) {
1202
            JLog :: add('Error retrieving people statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1203
            return NULL;
1204
        }
1205
    }
1206

    
1207
    // Retrieve organization statistics.
1208
    // $locale the locale to use
1209
    // return statistics (object)
1210
    private function _getOrganizationStatistics($locale) {
1211
        try {
1212
            $time = microtime(TRUE);
1213
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
1214
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1215
            if (($response = $this->performGet('search?action=refine&rTransformer=results_openaire_browse&fields=' . self :: ORGANIZATION_COUNTRY . '&fields=' . self :: ORGANIZATION_LEGAL_BODY . '&fields=' . self :: ORGANIZATION_LEGAL_PERSON . '&fields=' . self :: ORGANIZATION_NON_PROFIT . '&fields=' . self :: ORGANIZATION_RESEARCH . '&fields=' . self :: ORGANIZATION_EU_INTERESTS . '&fields=' . self :: ORGANIZATION_INTERNATIONAL . '&fields=' . self :: ORGANIZATION_ENTERPRISE . '&fields=' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . '&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
1216
                throw new Exception('no HTTP response');
1217
            if ($response->code != self :: HTTP_OK)
1218
                throw new Exception('HTTP response code ' . $response->code);
1219
            $document = new DOMDocument();
1220
            $document->recover = TRUE;
1221
            if ($document->loadXML($response->body) == FALSE)
1222
                throw new Exception('invalid XML response');
1223
            $xpath = new DOMXPath($document);
1224
            $statistics = $this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
1225
            $statistics['type'] = new JObject();
1226
            $statistics['type']->id = 'type';
1227
            $statistics['type']->title = JText :: _('TYPE');
1228
            $statistics['type']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
1229
            $statistics['type']->data = array();
1230
            $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
1231
            if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
1232
                $statistics['type']->data['legalBody'] = new JObject();
1233
                $statistics['type']->data['legalBody']->id = 'legalBody';
1234
                $statistics['type']->data['legalBody']->name = JText :: _('LEGAL_BODY');
1235
                $statistics['type']->data['legalBody']->count = $legalBody['true']->count;
1236
            }
1237
            $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
1238
            if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
1239
                $statistics['type']->data['legalPerson'] = new JObject();
1240
                $statistics['type']->data['legalPerson']->id = 'legalPerson';
1241
                $statistics['type']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
1242
                $statistics['type']->data['legalPerson']->count = $legalPerson['true']->count;
1243
            }
1244
            $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
1245
            if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
1246
                $statistics['type']->data['nonProfit'] = new JObject();
1247
                $statistics['type']->data['nonProfit']->id = 'nonProfit';
1248
                $statistics['type']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
1249
                $statistics['type']->data['nonProfit']->count = $nonProfit['true']->count;
1250
            }
1251
            $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
1252
            if (($research != NULL) && array_key_exists('true', $research)) {
1253
                $statistics['type']->data['research'] = new JObject();
1254
                $statistics['type']->data['research']->id = 'research';
1255
                $statistics['type']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
1256
                $statistics['type']->data['research']->count = $research['true']->count;
1257
            }
1258
            $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
1259
            if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
1260
                $statistics['type']->data['euInterests'] = new JObject();
1261
                $statistics['type']->data['euInterests']->id = 'euInterests';
1262
                $statistics['type']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
1263
                $statistics['type']->data['euInterests']->count = $euInterests['true']->count;
1264
            }
1265
            $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
1266
            if (($international != NULL) && array_key_exists('true', $international)) {
1267
                $statistics['type']->data['international'] = new JObject();
1268
                $statistics['type']->data['international']->id = 'international';
1269
                $statistics['type']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
1270
                $statistics['type']->data['international']->count = $international['true']->count;
1271
            }
1272
            $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
1273
            if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
1274
                $statistics['type']->data['enterprise'] = new JObject();
1275
                $statistics['type']->data['enterprise']->id = 'enterprise';
1276
                $statistics['type']->data['enterprise']->name = JText :: _('ENTERPRISE');
1277
                $statistics['type']->data['enterprise']->count = $enterprise['true']->count;
1278
            }
1279
            $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
1280
            if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
1281
                $statistics['type']->data['smallMediumEnterprise'] = new JObject();
1282
                $statistics['type']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
1283
                $statistics['type']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
1284
                $statistics['type']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
1285
            }
1286
            uasort($statistics['type']->data, function ($row1, $row2) {
1287
                return $row2->count - $row1->count;
1288
            });
1289
            JLog :: add('Retrieved organization statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1290
            return $statistics;
1291
        } catch (Exception $e) {
1292
            JLog :: add('Error retrieving organization statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1293
            return NULL;
1294
        }
1295
    }
1296

    
1297
    // Retrieve datasource statistics.
1298
    // $locale the locale to use
1299
    // return statistics (object)
1300
    private function _getDatasourceStatistics($locale) {
1301
        try {
1302
            $time = microtime(TRUE);
1303
            $query = self :: DATASOURCE_QUERY;
1304
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1305
            if (($response = $this->performGet('search?action=refine&rTransformer=results_openaire_browse&fields=' . self :: DATASOURCE_TYPE . '&fields=' . self :: DATASOURCE_LANGUAGE . '&fields=' . self :: DATASOURCE_CONTENT . '&fields=' . self :: DATASOURCE_COMPATIBILITY . '&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
1306
                throw new Exception('no HTTP response');
1307
            if ($response->code != self :: HTTP_OK)
1308
                throw new Exception('HTTP response code ' . $response->code);
1309
            $document = new DOMDocument();
1310
            $document->recover = TRUE;
1311
            if ($document->loadXML($response->body) == FALSE)
1312
                throw new Exception('invalid XML response');
1313
            $xpath = new DOMXPath($document);
1314
            $statistics = $this->createStatistics($xpath, array('type', 'language', 'content', 'compatibility'), array('TYPE', 'LANGUAGE', 'CONTENT', 'COMPATIBILITY'), array('NO_TYPE_STATISTICS_FOUND', 'NO_LANGUAGE_STATISTICS_FOUND', 'NO_CONTENT_STATISTICS_FOUND', 'NO_COMPATIBILITY_STATISTICS_FOUND'), array(self :: DATASOURCE_TYPE, self :: DATASOURCE_LANGUAGE, self :: DATASOURCE_CONTENT, self :: DATASOURCE_COMPATIBILITY));
1315
            JLog :: add('Retrieved datasource statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1316
            return $statistics;
1317
        } catch (Exception $e) {
1318
            JLog :: add('Error retrieving datasource statistics locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1319
            return NULL;
1320
        }
1321
    }
1322

    
1323
    // Perform a simple search for publications.
1324
    // $keyword the keyword to search for
1325
    // $articles flag to limit searching on articles; if all flags are FALSE no limits apply
1326
    // $books flag to limit searching on books; if all flags are FALSE no limits apply
1327
    // $theses flag to limit searching on books; if all flags are FALSE no limits apply
1328
    // $reports flag to limit searching on reports; if all flags are FALSE no limits apply
1329
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
1330
    // $language the ID of the language to use as filter or NULL for no language filtering
1331
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1332
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
1333
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1334
    // $year the year of publication to use as filter or NULL for no year filtering
1335
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1336
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1337
    // $page the page of results to retrieve
1338
    // $size the size of the page of results to retrieve
1339
    // $locale the locale to use
1340
    // return a result (object) containing publications and statistics
1341
    private function _searchPublications($keyword, $articles, $books, $theses, $reports, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project,$isRefine) {
1342
        try {
1343
                $dois = explode(" ", preg_replace('/\s+/', ' ',$keyword));                  
1344
                $unique_dois =array_unique($dois);                
1345
                $pattern1 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b#';
1346
                $pattern2 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b#';
1347
                if (preg_match($pattern1, $unique_dois[0]) || preg_match($pattern2, $unique_dois[0])) {
1348
                   $result= $this->_searchPublicationsWithDois($unique_dois,$page, $size, $locale,$isRefine);
1349
                    return $result;
1350
                }             
1351
            $time = microtime(TRUE);
1352
            $query = self :: PUBLICATION_QUERY;
1353
            $query .= ($keyword == NULL) ? '' : ' and "' . str_replace('"', '\\"', $keyword) . '"';
1354
            $types = array();
1355
            if ($articles) {
1356
                $types[] = self :: PUBLICATION_ARTICLE;
1357
                $types[] = self :: PUBLICATION_PREPRINT;
1358
            }
1359
            if ($books) {
1360
                $types[] = self :: PUBLICATION_BOOK;
1361
                $types[] = self :: PUBLICATION_BOOK_PART;
1362
            }
1363
            if ($theses) {
1364
                $types[] = self :: PUBLICATION_PHD_THESIS;
1365
                $types[] = self :: PUBLICATION_MASTER_THESIS;
1366
                $types[] = self :: PUBLICATION_BACHELOR_THESIS;
1367
            }
1368
            if ($reports) {
1369
                $types[] = self :: PUBLICATION_REPORT;
1370
                $types[] = self :: PUBLICATION_INTERNAL_REPORT;
1371
                $types[] = self :: PUBLICATION_EXTERNAL_REPORT;
1372
            }
1373
            $publicationType = self :: PUBLICATION_TYPE;
1374
            $types = implode(' or ', array_map(function($type) use ($publicationType) {
1375
                        return '(' . $publicationType . ' exact "' . $type . '")';
1376
                    }, $types));
1377
            $query .= ($types == NULL) ? '' : (' and (' . $types . ')');
1378
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
1379
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
1380
             if($funder != NULL && (strpos($funder, ',') !== FALSE)){
1381
                $temp='';
1382
                foreach(split(',',$funder) as $id){
1383
                    if(!empty($id)){
1384
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
1385
                    }
1386
                   
1387
                }
1388
                $query .=  (' and (' . substr($temp, 0, -3). ')');
1389
            }else{
1390
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
1391
            }
1392
            //$query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
1393
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1394
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1395
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1396
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact ' . $year . ')');
1397
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
1398
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: PUBLICATION_DATASOURCE . ' exact "' . $datasource . '")');
1399
            $query .= ($community == NULL) ? '' : (' and (' . self :: PUBLICATION_CONTEXT . ' exact "' . $community . '")');
1400
            $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT . ' exact "' . $project . '")');
1401
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1402
            $completeQuery='search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size .  '&locale=' . str_replace('-', '_', $locale);
1403
            if($isRefine){
1404
                $completeQuery='search?action=searchNrefine&sTransformer=results_openaire&rTransformer=results_openaire_browse&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size . '&fields=' . self :: PUBLICATION_TYPE . '&fields=' . self :: PUBLICATION_LANGUAGE . $this->_getFundingFields($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, self::PUBLICATION) . '&fields=' . self :: PUBLICATION_YEAR . '&fields=' . self :: PUBLICATION_ACCESS_MODE . '&fields=' . self :: PUBLICATION_DATASOURCE . '&fields=' . self :: PUBLICATION_PROJECT . '&locale=' . str_replace('-', '_', $locale);
1405
            }
1406
            //if (($response = $this->performGet('search?action=searchNrefine&sTransformer=results_openaire&rTransformer=results_openaire_browse&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size . '&fields=' . self :: PUBLICATION_TYPE . '&fields=' . self :: PUBLICATION_LANGUAGE . '&fields=' . self :: PUBLICATION_FUNDER . '&fields=' . self :: PUBLICATION_FUNDING_STREAM . '&fields=' . self :: PUBLICATION_SCIENTIFIC_AREA . '&fields=' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . '&fields=' . self :: PUBLICATION_YEAR . '&fields=' . self :: PUBLICATION_ACCESS_MODE . '&fields=' . self :: PUBLICATION_DATASOURCE . '&fields=' . self :: PUBLICATION_PROJECT . '&locale=' . str_replace('-', '_', $locale))) == NULL)
1407
            if (($response = $this->performGet($completeQuery)) == NULL)
1408
                throw new Exception('no HTTP response');
1409
            if ($response->code != self :: HTTP_OK)
1410
                throw new Exception('HTTP response code ' . $response->code);
1411
            $document = new DOMDocument();
1412
            $document->recover = TRUE;
1413
            if ($document->loadXML($response->body) == FALSE)
1414
                throw new Exception('invalid XML response');
1415
            $xpath = new DOMXPath($document);
1416
            $result = new JObject();
1417
            $result->totalPublications = $this->parseTotalResults($xpath);
1418
            $result->totalDatasets = 0;
1419
            $result->publications = $this->parsePublications($xpath);
1420
            $result->statistics = $isRefine? $this->createStatisticsForPublications($xpath):NULL;
1421
            $result->statistics = self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1422
                    //$this->createStatistics($xpath, array('type', 'language', 'funder', 'fundingStream', 'scientificArea', 'fundingStreamLevel2', 'project', 'year', 'accessMode', 'datasource'), array('DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA','FUNDING_STREAM_LEVEL2', 'PROJECT', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE'), array('NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND', 'NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND','NO_FUNDING_STREAM_LEVEL2_STATISTICS_FOUND', 'NO_PROJECT_STATISTICS_FOUND', 'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND'), array(self :: PUBLICATION_TYPE, self :: PUBLICATION_LANGUAGE, self :: PUBLICATION_FUNDER, self :: PUBLICATION_FUNDING_STREAM, self :: PUBLICATION_SCIENTIFIC_AREA, self::PUBLICATION_FUNDING_STREAM_LEVEL2, self :: PUBLICATION_FUNDING_STREAM_LEVEL2, self :: PUBLICATION_PROJECT, self :: PUBLICATION_YEAR, self :: PUBLICATION_ACCESS_MODE, self :: PUBLICATION_DATASOURCE));
1423
            JLog :: add('Simple search retrieved ' . count($result->publications) . ' publications in ' . (microtime(TRUE) - $time) . ' s (keyword: ' . $keyword . ', articles: ' . ($articles ? 'true' : 'false') . ', books: ' . ($books ? 'true' : 'false') . ', theses: ' . ($theses ? 'true' : 'false') . ', reports: ' . ($reports ? 'true' : 'false') . ', type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', year: ' . (($year == NULL) ? 'null' : $year) . ', access mode: ' . (($accessMode == NULL) ? 'null' : $accessMode) . ', datasource: ' . (($datasource == NULL) ? 'null' : $datasource) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1424
            return $result;
1425
        } catch (Exception $e) {
1426
            JLog :: add('Error performing publication simple search (keyword: ' . $keyword . ', articles: ' . ($articles ? 'true' : 'false') . ', books: ' . ($books ? 'true' : 'false') . ', theses: ' . ($theses ? 'true' : 'false') . ', reports: ' . ($reports ? 'true' : 'false') . ', type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', year: ' . (($year == NULL) ? 'null' : $year) . ', access mode: ' . (($accessMode == NULL) ? 'null' : $accessMode) . (($datasource == NULL) ? 'null' : $datasource) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1427
            $result->publications = array();
1428
            $result->totalPublications = 0;
1429
            $result->totalDatasets = 0;
1430
            return $result;
1431
        }
1432
    }
1433
 private function _searchPublicationsWithDois($dois, $page, $size, $locale,$isRefine) {
1434
        try {                
1435
            $time = microtime(TRUE);
1436
            $query = self :: PUBLICATION_QUERY;
1437
            $query .= ' and (';
1438
            foreach ($dois as $doi) {
1439
                $query .= ' ((pidclassid exact doi) and (pid exact "'.$doi.'")) ';
1440
                $query .= 'OR';
1441
            }
1442
            if(count($dois)>0){
1443
                $query=substr($query, 0, -2);
1444
            }
1445
            $query .= ')';            
1446
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1447
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=results_openaire&rTransformer=results_openaire_browse&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size . '&fields=' . self :: PUBLICATION_TYPE . '&fields=' . self :: PUBLICATION_LANGUAGE . '&fields=' . self :: PUBLICATION_FUNDER . '&fields=' . self :: PUBLICATION_FUNDING_STREAM . '&fields=' . self :: PUBLICATION_SCIENTIFIC_AREA . '&fields=' . self :: PUBLICATION_YEAR . '&fields=' . self :: PUBLICATION_ACCESS_MODE . '&fields=' . self :: PUBLICATION_DATASOURCE . '&fields=' . self :: PUBLICATION_PROJECT . '&locale=' . str_replace('-', '_', $locale)
1448
                    :'search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size   . '&locale=' . str_replace('-', '_', $locale);                
1449
            if (($response = $this->performGet($completeQuery)) == NULL)
1450
                throw new Exception('no HTTP response');
1451
            if ($response->code != self :: HTTP_OK)
1452
                throw new Exception('HTTP response code ' . $response->code);
1453
            $document = new DOMDocument();
1454
            $document->recover = TRUE;
1455
            if ($document->loadXML($response->body) == FALSE)
1456
                throw new Exception('invalid XML response');
1457
            $xpath = new DOMXPath($document);
1458
            $result = new JObject();
1459
            $result->totalPublications = $this->parseTotalResults($xpath);
1460
            $result->totalDatasets = 0;
1461
            $result->publications = $this->parsePublications($xpath);
1462
            $result->statistics =$isRefine? $this->createStatistics($xpath, array('type', 'language', 'funder', 'fundingStream', 'scientificArea', 'project', 'year', 'accessMode', 'datasource'), array('DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'PROJECT', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE'), array('NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND', 'NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_PROJECT_STATISTICS_FOUND', 'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND'), array(self :: PUBLICATION_TYPE, self :: PUBLICATION_LANGUAGE, self :: PUBLICATION_FUNDER, self :: PUBLICATION_FUNDING_STREAM, self :: PUBLICATION_SCIENTIFIC_AREA, self :: PUBLICATION_PROJECT, self :: PUBLICATION_YEAR, self :: PUBLICATION_ACCESS_MODE, self :: PUBLICATION_DATASOURCE)):NULL;
1463
            JLog :: add('Simple search for DOIs retrieved ' . count($result->publications) . ' publications in ' . (microtime(TRUE) - $time) . ' s (query: ' . $query. ')', JLog :: INFO, self :: LOG);
1464
            return $result;
1465
        } catch (Exception $e) {
1466
            JLog :: add('Error performing publication simple search for DOIs(query: ' . $query  . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1467
            return NULL;
1468
        }
1469
    }
1470
    // Perform a simple search for datasets.
1471
    // $keyword the keyword to search for
1472
    // $type the ID of the dataset type to use as filter or NULL for no dataset type filtering
1473
    // $language the ID of the language to use as filter or NULL for no language filtering
1474
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1475
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
1476
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1477
    // $year the year of publication to use as filter or NULL for no year filtering
1478
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1479
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1480
    // $page the page of results to retrieve
1481
    // $size the size of the page of results to retrieve
1482
    // $locale the locale to use
1483
    // return a result (object) containing datasets and statistics
1484
    private function _searchDatasets($keyword, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $isRefine) {
1485
        try {
1486
                $dois = explode(" ", preg_replace('/\s+/', ' ',$keyword));                  
1487
                $unique_dois =array_unique($dois);                
1488
                $pattern1 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b#';
1489
                $pattern2 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b#';
1490
                if (preg_match($pattern1, $unique_dois[0]) || preg_match($pattern2, $unique_dois[0])) {
1491
                   $result= $this->_searchDatasetsWithDois($unique_dois,$page, $size, $locale,$isRefine);
1492
                    return $result;
1493
                }                         
1494
            $time = microtime(TRUE);
1495
            $query = self :: DATASET_QUERY;
1496
            $query .= ($keyword == NULL) ? '' : ' and "' . str_replace('"', '\\"', $keyword) . '"';
1497
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASET_TYPE . ' exact "' . $type . '")');
1498
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASET_LANGUAGE . ' exact "' . $language . '")');
1499
            $query .= ($funder == NULL) ? '' : (' and (' . self :: DATASET_FUNDER . ' exact "' . $funder . '")');
1500
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1501
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: DATASET_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1502
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1503
            $query .= ($year == NULL) ? '' : (' and (' . self :: DATASET_YEAR . ' exact ' . $year . ')');
1504
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: DATASET_ACCESS_MODE . ' exact "' . $accessMode . '")');
1505
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: DATASET_DATASOURCE . ' exact "' . $datasource . '")');
1506
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1507
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=results_openaire&rTransformer=results_openaire_browse&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size . '&fields=' . self :: DATASET_TYPE . '&fields=' . self :: DATASET_LANGUAGE .  $this->_getFundingFields($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, self::DATASET) . '&fields=' . self :: DATASET_YEAR . '&fields=' . self :: DATASET_ACCESS_MODE . '&fields=' . self :: DATASET_DATASOURCE . '&locale=' . str_replace('-', '_', $locale):
1508
                    'search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size  . '&locale=' . str_replace('-', '_', $locale);
1509
            if (($response = $this->performGet($completeQuery)) == NULL)
1510
                throw new Exception('no HTTP response');
1511
            if ($response->code != self :: HTTP_OK)
1512
                throw new Exception('HTTP response code ' . $response->code);
1513
            $document = new DOMDocument();
1514
            $document->recover = TRUE;
1515
            if ($document->loadXML($response->body) == FALSE)
1516
                throw new Exception('invalid XML response');
1517
            $xpath = new DOMXPath($document);
1518
            $result = new JObject();
1519
            $result->totalDatasets = $this->parseTotalResults($xpath);
1520
            $result->datasets = $this->parseDatasets($xpath);
1521
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
1522
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1523
                    //createStatistics($xpath, array('type', 'language', 'funder', 'fundingStream', 'scientificArea', 'year', 'accessMode', 'datasource'), array('DATASET_TYPE', 'DATASET_LANGUAGE', 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE'), array('NO_DATASET_TYPE_STATISTICS_FOUND', 'NO_DATASET_LANGUAGE_STATISTICS_FOUND', 'NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND'), array(self :: DATASET_TYPE, self :: DATASET_LANGUAGE, self :: DATASET_FUNDER, self :: DATASET_FUNDING_STREAM, self :: DATASET_SCIENTIFIC_AREA, self :: DATASET_YEAR, self :: DATASET_ACCESS_MODE, self :: DATASET_DATASOURCE));
1524
            JLog :: add('Simple search retrieved ' . count($result->datasets) . ' datasets in ' . (microtime(TRUE) - $time) . ' s (keyword: ' . $keyword . ', type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', year: ' . (($year == NULL) ? 'null' : $year) . ', access mode: ' . (($accessMode == NULL) ? 'null' : $accessMode) . ', datasource: ' . (($datasource == NULL) ? 'null' : $datasource) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1525
            return $result;
1526
        } catch (Exception $e) {
1527
            JLog :: add('Error performing dataset simple search (keyword: ' . $keyword . ', type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', year: ' . (($year == NULL) ? 'null' : $year) . ', access mode: ' . (($accessMode == NULL) ? 'null' : $accessMode) . (($datasource == NULL) ? 'null' : $datasource) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1528
            return NULL;
1529
        }
1530
    }
1531

    
1532
 private function _searchDatasetsWithDois($dois, $page, $size, $locale,$isRefine) {
1533
        try {                
1534
            $time = microtime(TRUE);
1535
            $query = self :: DATASET_QUERY;
1536
            $query .= ' and (';
1537
            foreach ($dois as $doi) {
1538
                $query .= ' ((pidclassid exact doi) and (pid exact "'.$doi.'")) ';
1539
                $query .= 'OR';
1540
            }
1541
            if(count($dois)>0){
1542
                $query=substr($query, 0, -2);
1543
            }
1544
            $query .= ')';            
1545
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1546
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=results_openaire&rTransformer=results_openaire_browse&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size . '&fields=' . self :: PUBLICATION_TYPE . '&fields=' . self :: PUBLICATION_LANGUAGE . '&fields=' . self :: PUBLICATION_FUNDER . '&fields=' . self :: PUBLICATION_FUNDING_STREAM . '&fields=' . self :: PUBLICATION_SCIENTIFIC_AREA . '&fields=' . self :: PUBLICATION_YEAR . '&fields=' . self :: PUBLICATION_ACCESS_MODE . '&fields=' . self :: PUBLICATION_DATASOURCE . '&fields=' . self :: PUBLICATION_PROJECT . '&locale=' . str_replace('-', '_', $locale)
1547
                    :'search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size   . '&locale=' . str_replace('-', '_', $locale);                
1548
            if (($response = $this->performGet($completeQuery)) == NULL)
1549
                throw new Exception('no HTTP response');
1550
            if ($response->code != self :: HTTP_OK)
1551
                throw new Exception('HTTP response code ' . $response->code);
1552
            $document = new DOMDocument();
1553
            $document->recover = TRUE;
1554
            if ($document->loadXML($response->body) == FALSE)
1555
                throw new Exception('invalid XML response');
1556
            $xpath = new DOMXPath($document);
1557
            $result = new JObject();
1558
            $result->totalPublications = 0;
1559
            $result->totalDatasets = $this->parseTotalResults($xpath);
1560
            $result->datasets = $this->parsePublications($xpath);
1561
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
1562
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1563
                    //createStatistics($xpath, array('type', 'language', 'funder', 'fundingStream', 'scientificArea', 'year', 'accessMode', 'datasource'), array('DATASET_TYPE', 'DATASET_LANGUAGE', 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE'), array('NO_DATASET_TYPE_STATISTICS_FOUND', 'NO_DATASET_LANGUAGE_STATISTICS_FOUND', 'NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND'), array(self :: DATASET_TYPE, self :: DATASET_LANGUAGE, self :: DATASET_FUNDER, self :: DATASET_FUNDING_STREAM, self :: DATASET_SCIENTIFIC_AREA, self :: DATASET_YEAR, self :: DATASET_ACCESS_MODE, self :: DATASET_DATASOURCE));
1564
            JLog :: add('Simple search for DOIs retrieved ' . count($result->datasets) . ' datasets in ' . (microtime(TRUE) - $time) . ' s (query: ' . $query. ')', JLog :: INFO, self :: LOG);
1565
            return $result;
1566
        } catch (Exception $e) {
1567
            JLog :: add('Error performing dataset simple search for DOIs(query: ' . $query  . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1568
            return NULL;
1569
        }
1570
    }
1571
    // Perform a simple search for projects.
1572
    // $keyword the keyword to search for
1573
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1574
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
1575
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1576
    // $startYear the start year to use as filter or NULL for no start year filtering
1577
    // $endYear the end year to suse as filter or NULL for no end year filtering
1578
    // $sc39 the SC-39 status to use as filter or NULL for no SC-39 status filtering
1579
    // $page the page of results to retrieve
1580
    // $size the size of the page of results to retrieve
1581
    // $locale the locale to use
1582
    // return a result (object) containing projects and statistics
1583
    private function _searchProjects($keyword, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine) {
1584
        try {
1585
            $time = microtime(TRUE);
1586
            $query = self :: PROJECT_QUERY;
1587
            $query .= ($keyword == NULL) ? '' : ' and ((' . self :: PROJECT_ACRONYM . ' = "' . str_replace('"', '\\"', $keyword) . '") or (' . self :: PROJECT_CODE . ' = "' . str_replace('"', '\\"', $keyword) . '") or (' . self :: PROJECT_TITLE . ' = "' . str_replace('"', '\\"', $keyword) . '"))';
1588
            $query .= ($funder == NULL) ? '' : (' and (' . self :: PROJECT_FUNDER . ' exact "' . $funder . '")');
1589
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1590
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PROJECT_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1591
            $query .= ($startYear == NULL) ? '' : (' and (' . self :: PROJECT_START_YEAR . ' exact ' . $startYear . ')');
1592
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM_LEVEL2. ' exact "' . $fundingStreamLevel2 . '")');
1593
            $query .= ($endYear == NULL) ? '' : (' and (' . self :: PROJECT_END_YEAR . ' exact ' . $endYear . ')');
1594
            $query .= ($sc39 === NULL) ? '' : (' and (' . self :: PROJECT_SC39 . ' exact ' . ($sc39 ? 'true' : 'false') . ')');
1595
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1596
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=projects_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size .    $this->_getFundingFields($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, self::PROJECT) . '&fields=' . self :: PROJECT_START_YEAR . '&fields=' . self :: PROJECT_END_YEAR . '&fields=' . self :: PROJECT_SC39 . '&locale=' . str_replace('-', '_', $locale)
1597
                    :'search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
1598
            if (($response = $this->performGet($completeQuery)) == NULL)
1599
                throw new Exception('no HTTP response');
1600
            if ($response->code != self :: HTTP_OK)
1601
                throw new Exception('HTTP response code ' . $response->code);
1602
            $document = new DOMDocument();
1603
            $document->recover = TRUE;
1604
            if ($document->loadXML($response->body) == FALSE)
1605
                throw new Exception('invalid XML response');
1606
            $xpath = new DOMXPath($document);
1607
            $result = new JObject();
1608
            $result->totalProjects = $this->parseTotalResults($xpath);
1609
            $result->projects = $this->parseProjects($xpath);
1610
            $result->statistics = $isRefine?$this->createStatisticsForProjects($xpath,''):NULL;
1611
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1612
                    //createStatistics($xpath, array('funder', 'fundingStream', 'scientificArea', 'startYear', 'endYear', 'sc39'), array('FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'), array('NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_START_YEAR_STATISTICS_FOUND', 'NO_END_YEAR_STATISTICS_FOUND', 'NO_SPECIAL_CLAUSE_39_STATISTICS_FOUND'), array(self :: PROJECT_FUNDER, self :: PROJECT_FUNDING_STREAM, self :: PROJECT_SCIENTIFIC_AREA, self :: PROJECT_START_YEAR, self :: PROJECT_END_YEAR, self :: PROJECT_SC39));
1613
            JLog :: add('Simple search retrieved ' . count($result->projects) . ' projects in ' . (microtime(TRUE) - $time) . ' s (keyword: ' . $keyword . ', funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', start year: ' . (($startYear == NULL) ? 'null' : $startYear) . ', end year: ' . (($endYear == NULL) ? 'null' : $endYear) . ', SC-39: ' . (($sc39 === NULL) ? 'null' : ($sc39 ? 'true' : 'false')) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1614
            return $result;
1615
        } catch (Exception $e) {
1616
            JLog :: add('Error performing project simple search (keyword: ' . $keyword . ', funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', start year: ' . (($startYear == NULL) ? 'null' : $startYear) . ', end year: ' . (($endYear == NULL) ? 'null' : $endYear) . ', SC-39: ' . (($sc39 === NULL) ? 'null' : ($sc39 ? 'true' : 'false')) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1617
            return NULL;
1618
        }
1619
    }
1620

    
1621
    // Perform a simple search for people.
1622
    // $keyword the keyword to search for
1623
    // $country the country to use as filter or NULL for no country filtering
1624
    // $page the page of results to retrieve
1625
    // $size the size of the page of results to retrieve
1626
    // $locale the locale to use
1627
    // return a result (object) containing people and statistics
1628
    private function _searchPeople($keyword, $country, $page, $size, $locale, $isRefine) {
1629
        try {
1630
            $time = microtime(TRUE);
1631
            $query = self :: PERSON_QUERY;
1632
            $query .= ($keyword == NULL) ? '' : ' and "' . str_replace('"', '\\"', $keyword) . '"';
1633
            $query .= ($country == NULL) ? '' : (' and (' . self :: PERSON_COUNTRY . ' exact "' . $country . '")');
1634
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1635
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=persons_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&fields=' . self :: PERSON_COUNTRY . '&locale=' . str_replace('-', '_', $locale)
1636
                    :'search?action=search&sTransformer=persons_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
1637
            if (($response = $this->performGet($completeQuery)) == NULL)
1638
                throw new Exception('no HTTP response');
1639
            if ($response->code != self :: HTTP_OK)
1640
                throw new Exception('HTTP response code ' . $response->code);
1641
            $document = new DOMDocument();
1642
            $document->recover = TRUE;
1643
            if ($document->loadXML($response->body) == FALSE)
1644
                throw new Exception('invalid XML response');
1645
            $xpath = new DOMXPath($document);
1646
            $result = new JObject();
1647
            $result->totalPeople = $this->parseTotalResults($xpath);
1648
            $result->people = $this->parsePeople($xpath);
1649
            $result->statistics = $isRefine?$this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: PERSON_COUNTRY)):NULL;
1650
            JLog :: add('Simple search retrieved ' . count($result->people) . ' people in ' . (microtime(TRUE) - $time) . ' s (keyword: ' . $keyword . ', country: ' . (($country == NULL) ? 'null' : $country) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1651
            return $result;
1652
        } catch (Exception $e) {
1653
            JLog :: add('Error performing people simple search (keyword: ' . $keyword . ', country: ' . (($country == NULL) ? 'null' : $country) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1654
            return NULL;
1655
        }
1656
    }
1657

    
1658
    // Perform a simple search for organizations.
1659
    // $keyword the keyword to search for
1660
    // $country the ID of the country to use as filter or NULL for no country filtering
1661
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
1662
    // $page the page of results to retrieve
1663
    // $size the size of the page of results to retrieve
1664
    // $locale the locale to use
1665
    // return a result (object) containing people and statistics
1666
    private function _searchOrganizations($keyword, $country, $type, $page, $size, $locale, $isRefine) {
1667
        try {
1668
            $time = microtime(TRUE);
1669
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
1670
            $query .= ($keyword == NULL) ? '' : (' and "' . str_replace('"', '\\"', $keyword) . '"');
1671
            $query .= ($country == NULL) ? '' : (' and (' . self :: ORGANIZATION_COUNTRY . ' exact "' . $country . '")');
1672
            switch ($type) {
1673
                case 'legalBody':
1674
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_BODY . ' exact true)';
1675
                    break;
1676
                case 'legalPerson':
1677
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_PERSON . ' exact true)';
1678
                    break;
1679
                case 'nonProfit':
1680
                    $query .= ' and (' . self :: ORGANIZATION_NON_PROFIT . ' exact true)';
1681
                    break;
1682
                case 'research':
1683
                    $query .= ' and (' . self :: ORGANIZATION_RESEARCH . ' exact true)';
1684
                    break;
1685
                case 'euInterests':
1686
                    $query .= ' and (' . self :: ORGANIZATION_EU_INTERESTS . ' exact true)';
1687
                    break;
1688
                case 'international':
1689
                    $query .= ' and (' . self :: ORGANIZATION_INTERNATIONAL . ' exact true)';
1690
                    break;
1691
                case 'enterprise':
1692
                    $query .= ' and (' . self :: ORGANIZATION_ENTERPRISE . ' exact true)';
1693
                    break;
1694
                case 'smallMediumEnterprise':
1695
                    $query .= ' and (' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . ' exact true)';
1696
            }
1697
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1698
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=organizations_openaire&rTransformer=results_openaire_browse&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size . '&fields=' . self :: ORGANIZATION_COUNTRY . '&fields=' . self :: ORGANIZATION_LEGAL_BODY . '&fields=' . self :: ORGANIZATION_LEGAL_PERSON . '&fields=' . self :: ORGANIZATION_NON_PROFIT . '&fields=' . self :: ORGANIZATION_RESEARCH . '&fields=' . self :: ORGANIZATION_EU_INTERESTS . '&fields=' . self :: ORGANIZATION_INTERNATIONAL . '&fields=' . self :: ORGANIZATION_ENTERPRISE . '&fields=' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . '&locale=' . str_replace('-', '_', $locale)
1699
                    :'search?action=search&sTransformer=organizations_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size .  '&locale=' . str_replace('-', '_', $locale);
1700
            if (($response = $this->performGet($completeQuery)) == NULL)
1701
                throw new Exception('no HTTP response');
1702
            if ($response->code != self :: HTTP_OK)
1703
                throw new Exception('HTTP response code ' . $response->code);
1704
            $document = new DOMDocument();
1705
            $document->recover = TRUE;
1706
            if ($document->loadXML($response->body) == FALSE)
1707
                throw new Exception('invalid XML response');
1708
            $xpath = new DOMXPath($document);
1709
            $result = new JObject();
1710
            $result->totalOrganizations = $this->parseTotalResults($xpath);
1711
            $result->organizations = $this->parseOrganizations($xpath);
1712
            if($isRefine){
1713
                $result->statistics = $this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
1714
                $result->statistics['type'] = new JObject();
1715
                $result->statistics['type']->id = 'type';
1716
                $result->statistics['type']->title = JText :: _('TYPE');
1717
                $result->statistics['type']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
1718
                $result->statistics['type']->data = array();
1719
                $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
1720
                if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
1721
                    $result->statistics['type']->data['legalBody'] = new JObject();
1722
                    $result->statistics['type']->data['legalBody']->id = 'legalBody';
1723
                    $result->statistics['type']->data['legalBody']->name = JText :: _('LEGAL_BODY');
1724
                    $result->statistics['type']->data['legalBody']->count = $legalBody['true']->count;
1725
                }
1726
                $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
1727
                if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
1728
                    $result->statistics['type']->data['legalPerson'] = new JObject();
1729
                    $result->statistics['type']->data['legalPerson']->id = 'legalPerson';
1730
                    $result->statistics['type']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
1731
                    $result->statistics['type']->data['legalPerson']->count = $legalPerson['true']->count;
1732
                }
1733
                $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
1734
                if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
1735
                    $result->statistics['type']->data['nonProfit'] = new JObject();
1736
                    $result->statistics['type']->data['nonProfit']->id = 'nonProfit';
1737
                    $result->statistics['type']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
1738
                    $result->statistics['type']->data['nonProfit']->count = $nonProfit['true']->count;
1739
                }
1740
                $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
1741
                if (($research != NULL) && array_key_exists('true', $research)) {
1742
                    $result->statistics['type']->data['research'] = new JObject();
1743
                    $result->statistics['type']->data['research']->id = 'research';
1744
                    $result->statistics['type']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
1745
                    $result->statistics['type']->data['research']->count = $research['true']->count;
1746
                }
1747
                $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
1748
                if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
1749
                    $result->statistics['type']->data['euInterests'] = new JObject();
1750
                    $result->statistics['type']->data['euInterests']->id = 'euInterests';
1751
                    $result->statistics['type']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
1752
                    $result->statistics['type']->data['euInterests']->count = $euInterests['true']->count;
1753
                }
1754
                $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
1755
                if (($international != NULL) && array_key_exists('true', $international)) {
1756
                    $result->statistics['type']->data['international'] = new JObject();
1757
                    $result->statistics['type']->data['international']->id = 'international';
1758
                    $result->statistics['type']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
1759
                    $result->statistics['type']->data['international']->count = $international['true']->count;
1760
                }
1761
                $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
1762
                if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
1763
                    $result->statistics['type']->data['enterprise'] = new JObject();
1764
                    $result->statistics['type']->data['enterprise']->id = 'enterprise';
1765
                    $result->statistics['type']->data['enterprise']->name = JText :: _('ENTERPRISE');
1766
                    $result->statistics['type']->data['enterprise']->count = $enterprise['true']->count;
1767
                }
1768
                $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
1769
                if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
1770
                    $result->statistics['type']->data['smallMediumEnterprise'] = new JObject();
1771
                    $result->statistics['type']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
1772
                    $result->statistics['type']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
1773
                    $result->statistics['type']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
1774
                }
1775
                uasort($result->statistics['type']->data, function ($row1, $row2) {
1776
                    return $row2->count - $row1->count;
1777
                });
1778
            }
1779
            JLog :: add('Simple search retrieved ' . count($result->organizations) . ' organizations in ' . (microtime(TRUE) - $time) . ' s (keyword: ' . $keyword . ', country: ' . (($country == NULL) ? 'null' : $country) . ', type: ' . (($type == NULL) ? 'null' : $type) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1780
            return $result;
1781
        } catch (Exception $e) {
1782
            JLog :: add('Error performing organization simple search (keyword: ' . $keyword . ', country: ' . (($country == NULL) ? 'null' : $country) . ', type: ' . (($type == NULL) ? 'null' : $type) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1783
            return NULL;
1784
        }
1785
    }
1786

    
1787
    // Perform a simple search for datasources.
1788
    // $keyword the keyword to search for
1789
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
1790
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
1791
    // $content the ID of the content to use as filter or NULL for no project filtering
1792
    // $compatibility the ID of the compatibility level to use as filter or NULL for no compatibility level filtering
1793
    // $page the page of results to retrieve
1794
    // $size the size of the page of results to retrieve
1795
    // $locale the locale to use
1796
    // return a result (object) containing datasources and statistics
1797
    private function _searchDatasources($keyword, $type, $language, $content, $compatibility, $page, $size, $locale, $isRefine) {
1798
        try {
1799
            $time = microtime(TRUE);
1800
            $query = self :: DATASOURCE_QUERY;
1801
            $query .= ($keyword == NULL) ? '' : (' and "' . str_replace('"', '\\"', $keyword) . '"');
1802
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASOURCE_TYPE . ' exact "' . $type . '")');
1803
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASOURCE_LANGUAGE . ' exact "' . $language . '")');
1804
            $query .= ($content == NULL) ? '' : (' and (' . self :: DATASOURCE_CONTENT . ' exact "' . $content . '")');
1805
            $query .= ($compatibility == NULL) ? '' : (' and (' . self :: DATASOURCE_COMPATIBILITY . ' exact "' . $compatibility . '")');
1806
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1807
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=datasources_openaire&rTransformer=results_openaire_browse&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size . '&fields=' . self :: DATASOURCE_TYPE . '&fields=' . self :: DATASOURCE_LANGUAGE . '&fields=' . self :: DATASOURCE_CONTENT . '&fields=' . self :: DATASOURCE_COMPATIBILITY . '&locale=' . str_replace('-', '_', $locale)
1808
                    :'search?action=search&sTransformer=datasources_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
1809
            if (($response = $this->performGet($completeQuery)) == NULL)
1810
                throw new Exception('no HTTP response');
1811
            if ($response->code != self :: HTTP_OK)
1812
                throw new Exception('HTTP response code ' . $response->code);
1813
            $document = new DOMDocument();
1814
            $document->recover = TRUE;
1815
            if ($document->loadXML($response->body) == FALSE)
1816
                throw new Exception('invalid XML response');
1817
            $xpath = new DOMXPath($document);
1818
            $result = new JObject();
1819
            $result->totalDatasources = $this->parseTotalResults($xpath);
1820
            $result->datasources = $this->parseDatasources($xpath);
1821
            $result->statistics = $isRefine ? $this->createStatistics($xpath, array('type', 'language', 'content', 'compatibility'), array('TYPE', 'LANGUAGE', 'CONTENT', 'COMPATIBILITY'), array('NO_TYPE_STATISTICS_FOUND', 'NO_LANGUAGE_STATISTICS_FOUND', 'NO_CONTENT_STATISTICS_FOUND', 'NO_COMPATIBILITY_STATISTICS_FOUND'), array(self :: DATASOURCE_TYPE, self :: DATASOURCE_LANGUAGE, self :: DATASOURCE_CONTENT, self :: DATASOURCE_COMPATIBILITY)):NULL;
1822
            JLog :: add('Simple search retrieved ' . count($result->datasources) . ' datasources in ' . (microtime(TRUE) - $time) . ' s (keyword: ' . $keyword . ', type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', content: ' . (($content == NULL) ? 'null' : $content) . ', compatibility: ' . (($compatibility == NULL) ? 'null' : $compatibility) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1823
            return $result;
1824
        } catch (Exception $e) {
1825
            JLog :: add('Error performing datasource simple search (keyword: ' . $keyword . ', type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', content: ' . (($content == NULL) ? 'null' : $content) . ', compatibility: ' . (($compatibility == NULL) ? 'null' : $compatibility) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1826
            return NULL;
1827
        }
1828
    }
1829

    
1830
    // Perform a browse for publications.
1831
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
1832
    // $language the ID of the language to use as filter or NULL for no language filtering
1833
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1834
    // $fundingStream the ID of the fundingStream to use as filter or NULL for no funding stream filtering
1835
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1836
    // $year the year of publication to use as filter or NULL for no year filtering
1837
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1838
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1839
    // $community the ID of the community to use as filter or NULL for no datasource filtering
1840
    // $page the page of results to retrieve
1841
    // $size the size of the page of results to retrieve
1842
    // $locale the locale to use
1843
    // $project the ID of the project to use as filter or NULL for no project filtering
1844
    // $author the ID of the author to use as filter or NULL for no author filtering
1845
    // return a result (object) containing publications and statistics
1846
    private function _browsePublications($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $author,$isRefine,$refineFields) {
1847
        try {
1848
            $time = microtime(TRUE);
1849
            $query = self :: PUBLICATION_QUERY;
1850
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
1851
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
1852
            if($funder != NULL && (strpos($funder, ',') !== FALSE)){
1853
                $temp='';
1854
                foreach(split(',',$funder) as $id){
1855
                    if(!empty($id)){
1856
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
1857
                    }
1858
                   
1859
                }
1860
                $query .=  (' and (' . substr($temp, 0, -3). ')');
1861
            }else{
1862
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
1863
            }
1864
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1865
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1866
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1867
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact ' . $year . ')');
1868
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
1869
            $query .= ($datasource == NULL) ? '' : (' and ((' . self :: PUBLICATION_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_DATASOURCE . ' exact "' . $datasource . '") )');
1870
            $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT . ' exact "' . $project . '")');
1871
            $query .= ($author == NULL) ? '' : (' and (' . self :: PUBLICATION_AUTHOR_ID . ' exact "' . $author . '")');
1872
            $query .= ($community == NULL) ? '' : (' and (' . self :: PUBLICATION_CONTEXT . ' exact "' . $community . '")');
1873
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1874
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=results_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . ($refineFields!=null?$refineFields:'&fields=' . self :: PUBLICATION_TYPE . '&fields=' . self :: PUBLICATION_LANGUAGE .  $this->_getFundingFields($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, self::PUBLICATION).'&fields=' . self :: PUBLICATION_PROJECT . '&fields=' . self :: PUBLICATION_YEAR . '&fields=' . self :: PUBLICATION_ACCESS_MODE . '&fields=' . self :: PUBLICATION_DATASOURCE . '&fields=' . self :: PUBLICATION_CONTEXT ). '&locale=' . str_replace('-', '_', $locale):
1875
                'search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size  . '&locale=' . str_replace('-', '_', $locale);
1876
            if (($response = $this->performGet($completeQuery)) == NULL)
1877
                throw new Exception('no HTTP response');
1878
            if ($response->code != self :: HTTP_OK)
1879
                throw new Exception('HTTP response code ' . $response->code);
1880
            $document = new DOMDocument();
1881
            $document->recover = TRUE;
1882
            if ($document->loadXML($response->body) == FALSE)
1883
                throw new Exception('invalid XML response');
1884
            $xpath = new DOMXPath($document);
1885
            $result = new JObject();
1886
            $result->totalPublications = $this->parseTotalResults($xpath);
1887
            $result->publications = $this->parsePublications($xpath);
1888
            $result->statistics = $isRefine?$this->createStatisticsForPublications($xpath):NULL;
1889
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1890
                    //$this->createStatistics($xpath, array('type', 'language', 'funder', 'fundingStream', 'scientificArea', 'fundingStreamLevel2', 'project', 'year', 'accessMode', 'datasource', 'community'), array('DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA','FUNDING_STREAM_LEVEL_2', 'PROJECT', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE', 'COMMUNITY'), array('NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND', 'NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_FUNDING_STREAM_LEVEL_2_STATISTICS_FOUND', 'NO_PROJECT_STATISTICS_FOUND', 'NO_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_CONTEXT_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND'), array(self :: PUBLICATION_TYPE, self :: PUBLICATION_LANGUAGE, self :: PUBLICATION_FUNDER, self :: PUBLICATION_FUNDING_STREAM, self :: PUBLICATION_SCIENTIFIC_AREA, self::PUBLICATION_FUNDING_STREAM_LEVEL2, self :: PUBLICATION_PROJECT, self :: PUBLICATION_YEAR, self :: PUBLICATION_ACCESS_MODE, self :: PUBLICATION_DATASOURCE, self :: PUBLICATION_CONTEXT));
1891
            $result->totalDatasets = 0;
1892
            JLog :: add('Browse retrieved ' . count($result->publications) . ' publications in ' . (microtime(TRUE) - $time) . ' s (type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', year: ' . (($year == NULL) ? 'null' : $year) . ', access mode: ' . (($accessMode == NULL) ? 'null' : $accessMode) . ', datasource: ' . (($datasource == NULL) ? 'null' : $datasource) . ', community: ' . (($community == NULL) ? 'null' : $community) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ', project: ' . (($project == NULL) ? 'null' : $project) . ', author: ' . (($author == NULL) ? 'null' : $author) . ')', JLog :: INFO, self :: LOG);
1893
            return $result;
1894
        } catch (Exception $e) {
1895
            JLog :: add('Error performing publication browse (type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', year: ' . (($year == NULL) ? 'null' : $year) . ', access mode: ' . (($accessMode == NULL) ? 'null' : $accessMode) . ', datasource: ' . (($datasource == NULL) ? 'null' : $datasource) . ', community: ' . (($community == NULL) ? 'null' : $community) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ', project: ' . (($project == NULL) ? 'null' : $project) . ', author: ' . (($author == NULL) ? 'null' : $author) . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1896
            return NULL;
1897
        }
1898
    }
1899
    public static function pruningStatisticsForFunders($statistics, $funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2,$filter){
1900
        return self::_pruningStatisticsForFunders($statistics, $funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2,$filter);
1901
    }
1902
    private static function _pruningStatisticsForFunders($statistics, $funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2,$filter=''){
1903
        if($statistics==NULL){
1904
            return NULL;
1905
        }
1906
        if($fundingStreamLevel1!=NULL){
1907
           $newData= array(); 
1908
           foreach ($statistics["fundingStreamLevel2".$filter]->data as $data){
1909
               if(strpos($data->id,$fundingStreamLevel1)!==FALSE){
1910
                   $newData[$data->id]=$data;
1911
               }               
1912
           }
1913
           $statistics["fundingStreamLevel2".$filter]->data=$newData;
1914
         }
1915
        if($fundingStream!=NULL){
1916
           $newData= array(); 
1917
           foreach ($statistics["fundingStreamLevel1".$filter]->data as $data){
1918
               if(strpos($data->id,$fundingStream)!==FALSE){
1919
                   $newData[$data->id]=$data;
1920
               }               
1921
           }
1922
           $statistics["fundingStreamLevel1".$filter]->data=$newData;
1923
        }           
1924
        if($funder!=NULL){
1925
           $newData= array(); 
1926
           if(strpos($funder, ',') !== FALSE){
1927
                foreach ($statistics["fundingStream".$filter]->data as $data){                  
1928
                   foreach(split(',',$funder) as $id){               
1929
                       if(!empty($id) && (strpos($data->id,$id)!==FALSE)){
1930
                        $newData[$data->id]=$data;                           
1931
                       }
1932
                   }
1933
               }
1934
           }else{
1935
               foreach ($statistics["fundingStream".$filter]->data as $data){
1936
                    if(strpos($data->id,$funder)!==FALSE){
1937
                        $newData[$data->id]=$data;
1938
                    }               
1939
                }
1940
           }
1941
           $statistics["fundingStream".$filter]->data=$newData;
1942
            
1943
        }
1944
        return $statistics;
1945
    }
1946
    //Reduces the Funding Fields 
1947
    //$funder filter for funder
1948
    //$fundingStream filter for funding stream
1949
    //$fundingStreamLevel1 filter for fundingStreamLevel1
1950
    //$fundingStreamLevel2 filter  for fundingStreamLevel2
1951
    private static function _getFundingFields($funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2, $type){
1952
            $field = self::_getFundingFieldsPerType($type);
1953
            $f = array();
1954
             $f[0]=true;
1955
            for($i=1;$i<4;$i++){
1956
                $f[$i]=false;
1957
            }                
1958
            if($fundingStreamLevel2 !== null && !empty($fundingStreamLevel2)){
1959
                $f[3]=true;
1960
           }if($fundingStreamLevel1 !== NULL && strlen($fundingStreamLevel1)>0){
1961
               $f[2]=true;
1962
               $f[3]=true;             
1963
            } if($fundingStream !== NULL && strlen($fundingStream)>0){
1964
                $f[1]=true;
1965
                $f[2]=true;
1966
            } if($funder !== NULL && strlen($funder)>0){
1967
                $f[0]=true;
1968
                $f[1]=true;
1969
            }
1970
            $returnedFields='';
1971
            $none=true;
1972
            for($i=0;$i<4;$i++){
1973
                if($f[$i]){
1974
                    $returnedFields.=($f[$i])?$field[$i]:'';
1975
                    $none=false;
1976
                }                
1977
            }
1978
            $returnedFields=($none)?$field[0].$field[1]:$returnedFields;                
1979
            return $returnedFields;            
1980
        }
1981

    
1982
        private function _getFundingFieldsPerType($type){
1983
            $field=array();
1984
             switch ($type) {
1985
                case self::PUBLICATION:
1986
                    $field[3]='&fields=' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2;
1987
                    $field[2]='&fields=' . self :: PUBLICATION_SCIENTIFIC_AREA;
1988
                    $field[1]='&fields=' . self :: PUBLICATION_FUNDING_STREAM;
1989
                    $field[0]='&fields=' . self :: PUBLICATION_FUNDER;
1990
                    break;
1991
                case self::DATASET:
1992
                    $field[3]='&fields=' . self :: DATASET_FUNDING_STREAM_LEVEL2;
1993
                    $field[2]='&fields=' . self :: DATASET_SCIENTIFIC_AREA;
1994
                    $field[1]='&fields=' . self :: DATASET_FUNDING_STREAM;
1995
                    $field[0]='&fields=' . self :: DATASET_FUNDER;
1996
                    break;
1997
                case self::PROJECT:
1998
                    $field[3]='&fields=' . self :: PROJECT_FUNDING_STREAM_LEVEL2;
1999
                    $field[2]='&fields=' . self :: PROJECT_SCIENTIFIC_AREA;
2000
                    $field[1]='&fields=' . self :: PROJECT_FUNDING_STREAM;
2001
                    $field[0]='&fields=' . self :: PROJECT_FUNDER;
2002
                    break;
2003
             }
2004
             
2005
             return $field;
2006
        }
2007
    public function browsePublicationsRaw($query) {
2008
        try {
2009
            $time = microtime(TRUE);
2010
            
2011
            if (($response = $this->performGet($query)) == NULL)
2012
                throw new Exception('no HTTP response');
2013
            if ($response->code != self :: HTTP_OK)
2014
                throw new Exception('HTTP response code ' . $response->code);
2015
            JLog :: add('Browse publications raw  for query:'.$query.' in ' . (microtime(TRUE) - $time) , JLog :: INFO, self :: LOG);
2016
            return $response;
2017
        } catch (Exception $e) {
2018
            JLog :: add('Error performing publications browse raw', JLog :: ERROR, self :: LOG);
2019
            return NULL;
2020
        }
2021
    }
2022
     public function browseProjectsRaw($query) {
2023
        try {
2024
            $time = microtime(TRUE);
2025
            
2026
            if (($response = $this->performGet(str_replace(' ', '+', $query))) == NULL)
2027
                throw new Exception('no HTTP response');
2028
            if ($response->code != self :: HTTP_OK)
2029
                throw new Exception('HTTP response code ' . $response->code);            
2030
            JLog :: add('Browse projects raw  for query:'.$query.' in ' . (microtime(TRUE) - $time) , JLog :: INFO, self :: LOG);
2031
            return $response;
2032
        } catch (Exception $e) {
2033
            JLog :: add('Error performing projects browse raw', JLog :: ERROR, self :: LOG);
2034
            return NULL;
2035
        }
2036
    }
2037
    // Perform a browse for datasets.
2038
    // $type the ID of the dataset type to use as filter or NULL for no dataset type filtering
2039
    // $language the ID of the language to use as filter or NULL for no language filtering
2040
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2041
    // $fundingStream the ID of the fundingStream to use as filter or NULL for no funding stream filtering
2042
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2043
    // $year the year of publication to use as filter or NULL for no year filtering
2044
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
2045
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
2046
    // $page the page of results to retrieve
2047
    // $size the size of the page of results to retrieve
2048
    // $locale the locale to use
2049
    // $project the ID of the project to use as filter or NULL for no project filtering
2050
    // $author the ID of the author to use as filter or NULL for no author filtering
2051
    // return a result (object) containing datasets and statistics
2052
    private function _browseDatasets($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine, $refineFields) {
2053
        try {
2054
            $time = microtime(TRUE);
2055
            $query = self :: DATASET_QUERY;
2056
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASET_TYPE . ' exact "' . $type . '")');
2057
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASET_LANGUAGE . ' exact "' . $language . '")');
2058
            $query .= ($funder == NULL) ? '' : (' and (' . self :: DATASET_FUNDER . ' exact "' . $funder . '")');
2059
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2060
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: DATASET_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2061
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2062
            $query .= ($year == NULL) ? '' : (' and (' . self :: DATASET_YEAR . ' exact ' . $year . ')');
2063
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: DATASET_ACCESS_MODE . ' exact "' . $accessMode . '")');
2064
            $query .= ($datasource == NULL) ? '' : (' and ((' . self :: DATASET_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_DATASOURCE . ' exact "' . $datasource . '") )');
2065
            //$query .= ($datasource == NULL) ? '' : (' and (' . self :: DATASET_DATASOURCE . ' exact "' . $datasource . '")');
2066
            $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
2067
            $query .= ($author == NULL) ? '' : (' and (' . self :: DATASET_AUTHOR_ID . ' exact "' . $author . '")');
2068
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2069
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=results_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size .  ($refineFields!=null?$refineFields:'&fields=' . self :: DATASET_TYPE . '&fields=' . self :: DATASET_LANGUAGE . $this->_getFundingFields($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, self::DATASET) .'&fields=' . self :: DATASET_YEAR . '&fields=' . self :: DATASET_ACCESS_MODE . '&fields=' . self :: DATASET_DATASOURCE ). '&locale=' . str_replace('-', '_', $locale):
2070
                    'search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2071
            if (($response = $this->performGet($completeQuery)) == NULL)
2072
                throw new Exception('no HTTP response');
2073
            if ($response->code != self :: HTTP_OK)
2074
                throw new Exception('HTTP response code ' . $response->code);
2075
            $document = new DOMDocument();
2076
            $document->recover = TRUE;
2077
            if ($document->loadXML($response->body) == FALSE)
2078
                throw new Exception('invalid XML response');
2079
            $xpath = new DOMXPath($document);
2080
            $result = new JObject();
2081
            $result->totalDatasets = $this->parseTotalResults($xpath);
2082
            $result->datasets = $this->parseDatasets($xpath);
2083
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
2084
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');          
2085
                    //createStatistics($xpath, array('type', 'language', 'funder', 'fundingStream', 'scientificArea', 'year', 'accessMode', 'datasource'), array('DATASET_TYPE', 'DATASET_LANGUAGE', 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE'), array('NO_DATASET_TYPE_STATISTICS_FOUND', 'NO_DATASET_LANGUAGE_STATISTICS_FOUND', 'NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND'), array(self :: DATASET_TYPE, self :: DATASET_LANGUAGE, self :: DATASET_FUNDER, self :: DATASET_FUNDING_STREAM, self :: DATASET_SCIENTIFIC_AREA, self :: DATASET_YEAR, self :: DATASET_ACCESS_MODE, self :: DATASET_DATASOURCE));
2086
            JLog :: add('Browse retrieved ' . count($result->datasets) . ' datasets in ' . (microtime(TRUE) - $time) . ' s (type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', year: ' . (($year == NULL) ? 'null' : $year) . ', access mode: ' . (($accessMode == NULL) ? 'null' : $accessMode) . ', datasource: ' . (($datasource == NULL) ? 'null' : $datasource) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ', project: ' . (($project == NULL) ? 'null' : $project) . ', author: ' . (($author == NULL) ? 'null' : $author) . ')', JLog :: INFO, self :: LOG);
2087
            return $result;
2088
        } catch (Exception $e) {
2089
            JLog :: add('Error performing dataset browse (type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', year: ' . (($year == NULL) ? 'null' : $year) . ', access mode: ' . (($accessMode == NULL) ? 'null' : $accessMode) . ', datasource: ' . (($datasource == NULL) ? 'null' : $datasource) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ', project: ' . (($project == NULL) ? 'null' : $project) . ', author: ' . (($author == NULL) ? 'null' : $author) . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2090
            return NULL;
2091
        }
2092
    }
2093

    
2094
    // Perform a browse for projects.
2095
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2096
    // $fundingStream the ID of the fundingStream to use as filter or NULL for no funding stream filtering
2097
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2098
    // $startYear the start year to use as filter or NULL for no start year filtering
2099
    // $endYear the end year to use as filter or NULL for no end year filtering
2100
    // $$sc39 the SC-39 status to use as filter or NULL for no SC-39 status filtering
2101
    // $page the page of results to retrieve
2102
    // $size the size of the page of results to retrieve
2103
    // $locale the locale to use
2104
    // return a result (object) containing projects and statistics
2105
    private function _browseProjects($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine) {
2106
        try {
2107
            $time = microtime(TRUE);
2108
            $query = self :: PROJECT_QUERY;
2109
            if($funder != NULL && (strpos($funder, ',') !== FALSE)){
2110
                $temp='';
2111
                foreach(split(',',$funder) as $id){
2112
                    if(!empty($id)){
2113
                        $temp.='(' . self :: PROJECT_FUNDER . ' exact "' . $id . '") and';
2114
                    }
2115
                   
2116
                }
2117
                $query .=  (' and (' . substr($temp, 0, -3). ')');
2118
            }else{
2119
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PROJECT_FUNDER . ' exact "' . $funder . '")');
2120
            }
2121
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2122
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PROJECT_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2123
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2124
            $query .= ($startYear == NULL) ? '' : (' and (' . self :: PROJECT_START_YEAR . ' exact ' . $startYear . ')');
2125
            $query .= ($endYear == NULL) ? '' : (' and (' . self :: PROJECT_END_YEAR . ' exact ' . $endYear . ')');
2126
            $query .= ($sc39 === NULL) ? '' : (' and (' . self :: PROJECT_SC39 . ' exact ' . ($sc39 ? 'true' : 'false') . ')');
2127
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2128
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=projects_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . $this->_getFundingFields($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, self::PROJECT) . '&fields=' . self :: PROJECT_START_YEAR . '&fields=' . self :: PROJECT_END_YEAR . '&fields=' . self :: PROJECT_SC39 . '&locale=' . str_replace('-', '_', $locale)
2129
                    :'search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2130
            if (($response = $this->performGet($completeQuery)) == NULL)
2131
                throw new Exception('no HTTP response');
2132
            if ($response->code != self :: HTTP_OK)
2133
                throw new Exception('HTTP response code ' . $response->code);
2134
            $document = new DOMDocument();
2135
            $document->recover = TRUE;
2136
            if ($document->loadXML($response->body) == FALSE)
2137
                throw new Exception('invalid XML response');
2138
            $xpath = new DOMXPath($document);
2139
            $result = new JObject();
2140
            $result->totalProjects = $this->parseTotalResults($xpath);
2141
            $result->projects = $this->parseProjects($xpath);
2142
            $result->statistics = $isRefine? $this->createStatisticsForProjects($xpath):NULL;
2143
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
2144
                    //createStatistics($xpath, array('funder', 'fundingStream', 'scientificArea', 'startYear', 'endYear', 'sc39'), array('FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'), array('NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_START_YEAR_STATISTICS_FOUND', 'NO_END_YEAR_STATISTICS_FOUND', 'NO_SPECIAL_CLAUSE_39_STATISTICS_FOUND'), array(self :: PROJECT_FUNDER, self :: PROJECT_FUNDING_STREAM, self :: PROJECT_SCIENTIFIC_AREA, self :: PROJECT_START_YEAR, self :: PROJECT_END_YEAR, self :: PROJECT_SC39));
2145
            JLog :: add('Browse retrieved ' . count($result->projects) . ' projects in ' . (microtime(TRUE) - $time) . ' s (funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', start year: ' . (($startYear == NULL) ? 'null' : $startYear) . ', end year: ' . (($endYear == NULL) ? 'null' : $endYear) . ', SC-39: ' . (($sc39 === NULL) ? 'null' : ($sc39 ? 'true' : 'false')) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
2146
            return $result;
2147
        } catch (Exception $e) {
2148
            JLog :: add('Error performing project browse (funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', start year: ' . (($startYear == NULL) ? 'null' : $startYear) . ', end year: ' . (($endYear == NULL) ? 'null' : $endYear) . ', SC-39: ' . (($sc39 === NULL) ? 'null' : ($sc39 ? 'true' : 'false')) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2149
            return NULL;
2150
        }
2151
    }
2152

    
2153
    // Perform a browse for people.
2154
    // $country the ID of the country to use as filter or NULL for no country filtering
2155
    // $page the page of results to retrieve
2156
    // $size the size of the page of results to retrieve
2157
    // $locale the locale to use
2158
    // return a result (object) containing people and statistics
2159
    private function _browsePeople($country, $page, $size, $locale, $isRefine) {
2160
        try {
2161
            $time = microtime(TRUE);
2162
            $query = self :: PERSON_QUERY;
2163
            $query .= ($country == NULL) ? '' : (' and (' . self :: PERSON_COUNTRY . ' exact "' . $country . '")');
2164
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2165
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=persons_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&fields=' . self :: PERSON_COUNTRY . '&locale=' . str_replace('-', '_', $locale)
2166
                    :'search?action=search&sTransformer=persons_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2167
            if (($response = $this->performGet($completeQuery)) == NULL)
2168
                throw new Exception('no HTTP response');
2169
            if ($response->code != self :: HTTP_OK)
2170
                throw new Exception('HTTP response code ' . $response->code);
2171
            $document = new DOMDocument();
2172
            $document->recover = TRUE;
2173
            if ($document->loadXML($response->body) == FALSE)
2174
                throw new Exception('invalid XML response');
2175
            $xpath = new DOMXPath($document);
2176
            $result = new JObject();
2177
            $result->totalPeople = $this->parseTotalResults($xpath);
2178
            $result->people = $this->parsePeople($xpath);
2179
            $result->statistics =$isRefine? $this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: PERSON_COUNTRY)):NULL;
2180
            JLog :: add('Browse retrieved ' . count($result->people) . ' people in ' . (microtime(TRUE) - $time) . ' s (country: ' . (($country == NULL) ? 'null' : $country) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
2181
            return $result;
2182
        } catch (Exception $e) {
2183
            JLog :: add('Error performing people browse (country: ' . (($country == NULL) ? 'null' : $country) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2184
            return NULL;
2185
        }
2186
    }
2187

    
2188
    // Perform a browse for organizations.
2189
    // $country the ID of the country to use as filter or NULL for no country filtering
2190
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
2191
    // $page the page of results to retrieve
2192
    // $size the size of the page of results to retrieve
2193
    // $locale the locale to use
2194
    // return a result (object) containing organizations and statistics
2195
    private function _browseOrganizations($country, $type, $page, $size, $locale, $isRefine) {
2196
        try {
2197
            $time = microtime(TRUE);
2198
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
2199
            $query .= ($country == NULL) ? '' : (' and (' . self :: ORGANIZATION_COUNTRY . ' exact "' . $country . '")');
2200
            switch ($type) {
2201
                case 'legalBody':
2202
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_BODY . ' exact true)';
2203
                    break;
2204
                case 'legalPerson':
2205
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_PERSON . ' exact true)';
2206
                    break;
2207
                case 'nonProfit':
2208
                    $query .= ' and (' . self :: ORGANIZATION_NON_PROFIT . ' exact true)';
2209
                    break;
2210
                case 'research':
2211
                    $query .= ' and (' . self :: ORGANIZATION_RESEARCH . ' exact true)';
2212
                    break;
2213
                case 'euInterests':
2214
                    $query .= ' and (' . self :: ORGANIZATION_EU_INTERESTS . ' exact true)';
2215
                    break;
2216
                case 'international':
2217
                    $query .= ' and (' . self :: ORGANIZATION_INTERNATIONAL . ' exact true)';
2218
                    break;
2219
                case 'enterprise':
2220
                    $query .= ' and (' . self :: ORGANIZATION_ENTERPRISE . ' exact true)';
2221
                    break;
2222
                case 'smallMediumEnterprise':
2223
                    $query .= ' and (' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . ' exact true)';
2224
            }
2225
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2226
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=organizations_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&fields=' . self :: ORGANIZATION_COUNTRY . '&fields=' . self :: ORGANIZATION_LEGAL_BODY . '&fields=' . self :: ORGANIZATION_LEGAL_PERSON . '&fields=' . self :: ORGANIZATION_NON_PROFIT . '&fields=' . self :: ORGANIZATION_RESEARCH . '&fields=' . self :: ORGANIZATION_EU_INTERESTS . '&fields=' . self :: ORGANIZATION_INTERNATIONAL . '&fields=' . self :: ORGANIZATION_ENTERPRISE . '&fields=' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . '&locale=' . str_replace('-', '_', $locale)
2227
                    :'search?action=searchsTransformer=organizations_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2228
            if (($response = $this->performGet($completeQuery)) == NULL)
2229
                throw new Exception('no HTTP response');
2230
            if ($response->code != self :: HTTP_OK)
2231
                throw new Exception('HTTP response code ' . $response->code);
2232
            $document = new DOMDocument();
2233
            $document->recover = TRUE;
2234
            if ($document->loadXML($response->body) == FALSE)
2235
                throw new Exception('invalid XML response');
2236
            $xpath = new DOMXPath($document);
2237
            $result = new JObject();
2238
            $result->totalOrganizations = $this->parseTotalResults($xpath);
2239
            $result->organizations = $this->parseOrganizations($xpath);
2240
            if($isRefine){
2241
                $result->statistics = $this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
2242
                $result->statistics['type'] = new JObject();
2243
                $result->statistics['type']->id = 'type';
2244
                $result->statistics['type']->title = JText :: _('TYPE');
2245
                $result->statistics['type']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
2246
                $result->statistics['type']->data = array();           
2247
                $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
2248
                if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
2249
                    $result->statistics['type']->data['legalBody'] = new JObject();
2250
                    $result->statistics['type']->data['legalBody']->id = 'legalBody';
2251
                    $result->statistics['type']->data['legalBody']->name = JText :: _('LEGAL_BODY');
2252
                    $result->statistics['type']->data['legalBody']->count = $legalBody['true']->count;
2253
                }
2254
                $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
2255
                if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
2256
                    $result->statistics['type']->data['legalPerson'] = new JObject();
2257
                    $result->statistics['type']->data['legalPerson']->id = 'legalPerson';
2258
                    $result->statistics['type']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
2259
                    $result->statistics['type']->data['legalPerson']->count = $legalPerson['true']->count;
2260
                }
2261
                $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
2262
                if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
2263
                    $result->statistics['type']->data['nonProfit'] = new JObject();
2264
                    $result->statistics['type']->data['nonProfit']->id = 'nonProfit';
2265
                    $result->statistics['type']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
2266
                    $result->statistics['type']->data['nonProfit']->count = $nonProfit['true']->count;
2267
                }
2268
                $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
2269
                if (($research != NULL) && array_key_exists('true', $research)) {
2270
                    $result->statistics['type']->data['research'] = new JObject();
2271
                    $result->statistics['type']->data['research']->id = 'research';
2272
                    $result->statistics['type']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
2273
                    $result->statistics['type']->data['research']->count = $research['true']->count;
2274
                }
2275
                $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
2276
                if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
2277
                    $result->statistics['type']->data['euInterests'] = new JObject();
2278
                    $result->statistics['type']->data['euInterests']->id = 'euInterests';
2279
                    $result->statistics['type']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
2280
                    $result->statistics['type']->data['euInterests']->count = $euInterests['true']->count;
2281
                }
2282
                $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
2283
                if (($international != NULL) && array_key_exists('true', $international)) {
2284
                    $result->statistics['type']->data['international'] = new JObject();
2285
                    $result->statistics['type']->data['international']->id = 'international';
2286
                    $result->statistics['type']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
2287
                    $result->statistics['type']->data['international']->count = $international['true']->count;
2288
                }
2289
                $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
2290
                if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
2291
                    $result->statistics['type']->data['enterprise'] = new JObject();
2292
                    $result->statistics['type']->data['enterprise']->id = 'enterprise';
2293
                    $result->statistics['type']->data['enterprise']->name = JText :: _('ENTERPRISE');
2294
                    $result->statistics['type']->data['enterprise']->count = $enterprise['true']->count;
2295
                }
2296
                $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
2297
                if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
2298
                    $result->statistics['type']->data['smallMediumEnterprise'] = new JObject();
2299
                    $result->statistics['type']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
2300
                    $result->statistics['type']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
2301
                    $result->statistics['type']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
2302
                }
2303
                uasort($result->statistics['type']->data, function ($row1, $row2) {
2304
                    return $row2->count - $row1->count;
2305
                });
2306
            }
2307
            JLog :: add('Browse retrieved ' . count($result->organizations) . ' organizations in ' . (microtime(TRUE) - $time) . ' s (country: ' . (($country == NULL) ? 'null' : $country) . ', type: ' . (($type == NULL) ? 'null' : $type) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
2308
            return $result;
2309
        } catch (Exception $e) {
2310
            JLog :: add('Error performing organization browse (country: ' . (($country == NULL) ? 'null' : $country) . ', type: ' . (($type == NULL) ? 'null' : $type) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2311
            return NULL;
2312
        }
2313
    }
2314

    
2315
    // Perform a browse for datasources.
2316
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
2317
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
2318
    // $content the ID of the content to use as filter or NULL for no content filtering
2319
    // $compatibility the ID of the compatibility level to use as filter or NULL for no compatibility status filtering
2320
    // $page the page of results to retrieve
2321
    // $size the size of the page of results to retrieve
2322
    // $locale the locale to use
2323
    // return a result (object) containing datasources and statistics
2324
    private function _browseDatasources($type, $language, $content, $compatibility, $page, $size, $locale, $isRefine) {
2325
        try {
2326
            $time = microtime(TRUE);
2327
            $query = self :: DATASOURCE_QUERY;
2328
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASOURCE_TYPE . ' exact "' . $type . '")');
2329
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASOURCE_LANGUAGE . ' exact "' . $language . '")');
2330
            $query .= ($content == NULL) ? '' : (' and (' . self :: DATASOURCE_CONTENT . ' exact "' . $content . '")');
2331
            $query .= ($compatibility == NULL) ? '' : (' and (' . self :: DATASOURCE_COMPATIBILITY . ' exact "' . $compatibility . '")');
2332
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2333
            $completeQuery=$isRefine?'search?action=searchNrefine&sTransformer=datasources_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&fields=' . self :: DATASOURCE_TYPE . '&fields=' . self :: DATASOURCE_LANGUAGE . '&fields=' . self :: DATASOURCE_CONTENT . '&fields=' . self :: DATASOURCE_COMPATIBILITY . '&locale=' . str_replace('-', '_', $locale):
2334
                'search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2335
            if (($response = $this->performGet($completeQuery)) == NULL)
2336
                throw new Exception('no HTTP response');
2337
            if ($response->code != self :: HTTP_OK)
2338
                throw new Exception('HTTP response code ' . $response->code);
2339
            $document = new DOMDocument();
2340
            $document->recover = TRUE;
2341
            if ($document->loadXML($response->body) == FALSE)
2342
                throw new Exception('invalid XML response');
2343
            $xpath = new DOMXPath($document);
2344
            $result = new JObject();
2345
            $result->totalDatasources = $this->parseTotalResults($xpath);
2346
            $result->datasources = $this->parseDatasources($xpath);
2347
            $result->statistics = $isRefine?$this->createStatistics($xpath, array('type', 'language', 'content', 'compatibility'), array('TYPE', 'LANGUAGE', 'CONTENT', 'COMPATIBILITY'), array('NO_TYPE_STATISTICS_FOUND', 'NO_LANGUAGE_STATISTICS_FOUND', 'NO_CONTENT_STATISTICS_FOUND', 'NO_COMPATIBILITY_STATISTICS_FOUND'), array(self :: DATASOURCE_TYPE, self :: DATASOURCE_LANGUAGE, self :: DATASOURCE_CONTENT, self :: DATASOURCE_COMPATIBILITY)):NULL;
2348
            JLog :: add('Browse retrieved ' . count($result->datasources) . ' datasources in ' . (microtime(TRUE) - $time) . ' s (type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', content: ' . (($content == NULL) ? 'null' : $content) . ', compatibility: ' . (($compatibility == NULL) ? 'null' : $compatibility) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
2349
            return $result;
2350
        } catch (Exception $e) {
2351
            JLog :: add('Error performing datasource browse (type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', content: ' . (($content == NULL) ? 'null' : $content) . ', compatibility: ' . (($compatibility == NULL) ? 'null' : $compatibility) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2352
            return NULL;
2353
        }
2354
    }
2355

    
2356
    // Perform an advanced search for publications.
2357
    // $keywords the keywords to search for (array)
2358
    // $fields the fields to match keywords with (array - possible values are TITLE, AUTHOR, PUBLISHER and SUBJECT)
2359
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2360
    // $types the IDs of the publication types to search for
2361
    // $languages the IDs of the publication languages to search for
2362
    // $funders the IDs of the funders to search for
2363
    // $fundingStreams the IDs of the funding streams to search for
2364
    // $scientificAreas the IDs of the scientific areas to search for
2365
    // $date the publication date range to search for expressed in months before current date (if -1 search for any publication date, if 0 search explicitly using $fromMonth, $fromYear, $toMonth and $toYear)
2366
    // $fromMonth start month of the publication date range to search for if $date has value 0
2367
    // $fromYear start year of the publication date range to search for if $date has value 0
2368
    // $toMonth end month of the publication date range to search for if $date has value 0
2369
    // $toYear end year of the publication date range to search for if $date has value 0
2370
    // $accessModes the IDs of the access modes to search for
2371
    // $datasources the IDs of the datasources to search for
2372
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
2373
    // $language the ID of the publication language to use as filter or NULL for no publication language filtering
2374
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2375
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
2376
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2377
    // $year the publication year to use as filter or NULL for no publication year filtering
2378
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
2379
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
2380
    // $page the page of results to retrieve
2381
    // $size the size of the page of results to retrieve
2382
    // $locale the locale to use
2383
    // return a result (object) containing publications and statistics
2384
    private function _advancedSearchPublications($keywords, $fields, $constraints, $types, $languages, $funders, $fundingStreams, $scientificAreas, $fundingStreamsLevel2, $date, $fromMonth, $fromYear, $toMonth, $toYear, $accessModes, $datasources, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale) {
2385
        try {
2386
            $time = microtime(TRUE);
2387
            $query = self :: PUBLICATION_QUERY;
2388
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2389
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2390
                switch ($constraints[$i]) {
2391
                    case OpenAireViewAdvancedSearchPublications :: ALL:
2392
                        $operator = ' and ';
2393
                        break;
2394
                    case OpenAireViewAdvancedSearchPublications :: ANY:
2395
                        $operator = ' or ';
2396
                        break;
2397
                    default:
2398
                        $operator = NULL;
2399
                }
2400
                switch ($fields[$i]) {
2401
                    case OpenAireViewAdvancedSearchPublications :: TITLE:
2402
                        $field = self :: PUBLICATION_TITLE;
2403
                        break;
2404
                    case OpenAireViewAdvancedSearchPublications :: AUTHOR:
2405
                        $field = self :: PUBLICATION_AUTHOR;
2406
                        break;
2407
                    case OpenAireViewAdvancedSearchPublications :: PUBLISHER:
2408
                        $field = self :: PUBLICATION_PUBLISHER;
2409
                        break;
2410
                    case OpenAireViewAdvancedSearchPublications :: SUBJECT:
2411
                        $field = self :: PUBLICATION_SUBJECT;
2412
                        break;
2413
                    default:
2414
                        $field = NULL;
2415
                }
2416
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2417
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2418
                                }, $tokens)) . ')');
2419
            }
2420
            $field = self :: PUBLICATION_TYPE;
2421
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($field) {
2422
                                return '(' . $field . ' exact "' . $type . '")';
2423
                            }, $types)) . ')');
2424
            $field = self :: PUBLICATION_LANGUAGE;
2425
            $query .= ($languages == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($language) use ($field) {
2426
                                return '(' . $field . ' exact "' . $language . '")';
2427
                            }, $languages)) . ')');
2428
            $field = self :: PUBLICATION_FUNDER;
2429
            $query .= ($funders == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($funder) use ($field) {
2430
                                return '(' . $field . ' exact "' . $funder . '")';
2431
                            }, $funders)) . ')');
2432
            $field = self :: PUBLICATION_FUNDING_STREAM;
2433
            $query .= ($fundingStreams == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStream) use ($field) {
2434
                                return '(' . $field . ' exact "' . $fundingStream . '")';
2435
                            }, $fundingStreams)) . ')');
2436
            $field = self :: PUBLICATION_SCIENTIFIC_AREA;
2437
            $query .= ($scientificAreas == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($scientificArea) use ($field) {
2438
                                return '(' . $field . ' exact "' . $scientificArea . '")';
2439
                            }, $scientificAreas)) . ')');
2440
            $field = self :: PUBLICATION_FUNDING_STREAM_LEVEL2;
2441
            $query .= ($fundingStreamsLevel2 == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStreamsLevel2) use ($field) {
2442
                                return '(' . $field . ' exact "' . $fundingStreamsLevel2 . '")';
2443
                            }, $fundingStreamsLevel2)) . ')');
2444
            $from = new DateTime();
2445
            $to = new DateTime();
2446
            switch ($date) {
2447
                case -1:
2448
                    break;
2449
                case 0:
2450
                    $from->setDate($fromYear, $fromMonth, 1);
2451
                    $to->setDate($toYear, $toMonth, 1);
2452
                    $to->setDate($toYear, $toMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2453
                    $query .= ' and (' . self :: PUBLICATION_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2454
                    break;
2455
                default:
2456
                    $from->sub(new DateInterval('P' . $date . 'M'));
2457
                    $query .= ' and (' . self :: PUBLICATION_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2458
            }
2459
            $field = self :: PUBLICATION_ACCESS_MODE;
2460
            $query .= ($accessModes == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($accessMode) use ($field) {
2461
                                return '(' . $field . ' exact "' . $accessMode . '")';
2462
                            }, $accessModes)) . ')');
2463
            $field = self :: PUBLICATION_DATASOURCE;
2464
            $query .= ($datasources == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($datasource) use ($field) {
2465
                                return '(' . $field . ' exact "' . $datasource . '")';
2466
                            }, $datasources)) . ')');
2467
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
2468
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
2469
            //$query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
2470
              if($funder != NULL && (strpos($funder, ',') !== FALSE)){
2471
                $temp='';
2472
                foreach(split(',',$funder) as $id){
2473
                    if(!empty($id)){
2474
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
2475
                    }
2476
                   
2477
                }
2478
                $query .=  (' and (' . substr($temp, 0, -3). ')');
2479
            }else{
2480
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
2481
            }
2482
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2483
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2484
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2485
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact "' . $year . '")');
2486
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
2487
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: PUBLICATION_DATASOURCE . ' exact "' . $datasource . '")');
2488
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2489
            if (($response = $this->performGet('search?action=searchNrefine&sTransformer=results_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&fields=' . self :: PUBLICATION_TYPE . '&fields=' . self :: PUBLICATION_LANGUAGE .   $this->_getFundingFields($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, self::PUBLICATION). '&fields=' . self :: PUBLICATION_YEAR . '&fields=' . self :: PUBLICATION_ACCESS_MODE . '&fields=' . self :: PUBLICATION_DATASOURCE . '&locale=' . str_replace('-', '_', $locale))) == NULL)
2490
                throw new Exception('no HTTP response');
2491
            if ($response->code != self :: HTTP_OK)
2492
                throw new Exception('HTTP response code ' . $response->code);
2493
            $document = new DOMDocument();
2494
            $document->recover = TRUE;
2495
            if ($document->loadXML($response->body) == FALSE)
2496
                throw new Exception('invalid XML response');
2497
            $xpath = new DOMXPath($document);
2498
            $result = new JObject();
2499
            $result->totalPublications = $this->parseTotalResults($xpath);
2500
            $result->publications = $this->parsePublications($xpath);
2501
            $result->statistics =$this->createStatisticsForPublications($xpath,'Filter');
2502
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,"Filter");
2503
                    //$this->createStatistics($xpath, array('typeFilter', 'language', 'funderFilter', 'fundingStreamFilter', 'scientificAreaFilter', 'yearFilter', 'accessModeFilter', 'datasourceFilter'), array('DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE'), array('NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND', 'NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND'), array(self :: PUBLICATION_TYPE, self :: PUBLICATION_LANGUAGE, self :: PUBLICATION_FUNDER, self :: PUBLICATION_FUNDING_STREAM, self :: PUBLICATION_SCIENTIFIC_AREA, self :: PUBLICATION_YEAR, self :: PUBLICATION_ACCESS_MODE, self :: PUBLICATION_DATASOURCE));
2504
            JLog :: add('Advanced search retrieved ' . count($result->publications) . ' publications in ' . (microtime(TRUE) - $time) . ' s (keywords: [' . implode(', ', $keywords) . '], fields: [' . implode(', ', $fields) . '], constraints: [' . implode(', ', $constraints) . '], types: [' . implode(', ', $types) . '], languages: [' . implode(', ', $languages) . '], funders: [' . implode(', ', $funders) . '], funding streams: [' . implode(', ', $fundingStreams) . '], scientific areas: [' . implode(', ', $scientificAreas) . '], date: ' . $date . ', from month: ' . $fromMonth . ', from year: ' . $fromYear . ', to month: ' . $toMonth . ', to year: ' . $toYear . ', access modes: [' . implode(', ', $accessModes) . '], datasources: [' . implode(', ', $datasources) . '], type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', year: ' . (($year == NULL) ? 'null' : $year) . ', access mode: ' . (($accessMode == NULL) ? 'null' : $accessMode) . ', datasource: ' . (($datasource == NULL) ? 'null' : $datasource) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
2505
            return $result;
2506
        } catch (Exception $e) {
2507
            JLog :: add('Error performing publication advanced search (keywords: [' . implode(', ', $keywords) . '], fields: [' . implode(', ', $fields) . '], constraints: [' . implode(', ', $constraints) . '], types: [' . implode(', ', $types) . '], languages: [' . implode(', ', $languages) . '], funders: [' . implode(', ', $funders) . '], funding streams: [' . implode(', ', $fundingStreams) . '], scientific areas: [' . implode(', ', $scientificAreas) . '], date: ' . $date . ', from month: ' . $fromMonth . ', from year: ' . $fromYear . ', to month: ' . $toMonth . ', to year: ' . $toYear . ', access modes: [' . implode(', ', $accessModes) . '], datasources: [' . implode(', ', $datasources) . '], type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', year: ' . (($year == NULL) ? 'null' : $year) . ', access mode: ' . (($accessMode == NULL) ? 'null' : $accessMode) . ', datasource: ' . (($datasource == NULL) ? 'null' : $datasource) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2508
            return NULL;
2509
        }
2510
    }
2511

    
2512
    // Perform an advanced search for projects.
2513
    // $keywords the keywords to search for (array)
2514
    // $fields the fields to match keywords with (array - possible values are ACRONYM, TITLE and KEYWORDS)
2515
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2516
    // $funders the IDs of the funders to search for
2517
    // $fundingStreams the IDs of the funding streams to search for
2518
    // $scientificAreas the IDs of the scientific areas to search for
2519
    // $startDate the start date range to search for expressed in months before current date (if -1 search for any start date, if 0 search explicitly using $startFromMonth, $startFromYear, $startToMonth and $startToYear)
2520
    // $startFromMonth start month of the start date range to search for if $startDate has value 0
2521
    // $startFromYear start year of the start date range to search for if $startDate has value 0
2522
    // $startToMonth end month of the start date range to search for if $startDate has value 0
2523
    // $startToYear end year of the start date range to search for if $startDate has value 0
2524
    // $endDate the end date range to search for expressed in months brefore current date (if -1 search for any end date, if 0 search explicitly using $endFromMonth, $endFromYear, $endToMonth and $endToYear)
2525
    // $endFromMonth start month of the end date range to search for if $endDate has value 0
2526
    // $endFromYear start year of the end date range to search for if $endDate has value 0
2527
    // $endToMonth end month of the end date range to search for if $endDate has value 0
2528
    // $endToYear end year of the end date range to search for if $endDate has value 0
2529
    // $sc39s the IDs of the SC-39 statuses to search for
2530
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2531
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
2532
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2533
    // $startYear the start year to use as filter or NULL for no start year filtering
2534
    // $endYear the end year to use as filter or NULL for no end year filtering
2535
    // $sc39 the ID of the SC-39 status to use as filter or NULL for no SC-39 status filtering
2536
    // $page the page of results to retrieve
2537
    // $size the size of the page of results to retrieve
2538
    // $locale the locale to use
2539
    // return a result (object) containing projects and statistics
2540
    private function _advancedSearchProjects($keywords, $fields, $constraints, $funders, $fundingStreams, $scientificAreas, $fundingStreamsLevel2, $startDate, $startFromMonth, $startFromYear, $startToMonth, $startToYear, $endDate, $endFromMonth, $endFromYear, $endToMonth, $endToYear, $sc39s, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale) {
2541
        try {
2542
            $time = microtime(TRUE);
2543
            $query = self :: PROJECT_QUERY;
2544
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2545
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2546
                switch ($constraints[$i]) {
2547
                    case OpenAireViewAdvancedSearchProjects :: ALL:
2548
                        $operator = ' and ';
2549
                        break;
2550
                    case OpenAireViewAdvancedSearchProjects :: ANY:
2551
                        $operator = ' or ';
2552
                        break;
2553
                    default:
2554
                        $operator = NULL;
2555
                }
2556
                switch ($fields[$i]) {
2557
                    case OpenAireViewAdvancedSearchProjects :: ACRONYM:
2558
                        $field = self :: PROJECT_ACRONYM;
2559
                        break;
2560
                    case OpenAireViewAdvancedSearchProjects :: TITLE:
2561
                        $field = self :: PROJECT_TITLE;
2562
                        break;
2563
                    case OpenAireViewAdvancedSearchProjects :: KEYWORDS:
2564
                        $field = self :: PROJECT_KEYWORDS;
2565
                        break;
2566
                    default:
2567
                        $field = NULL;
2568
                }
2569
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2570
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2571
                                }, $tokens)) . ')');
2572
            }
2573
            $field = self :: PROJECT_FUNDER;
2574
            $query .= ($funders == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($funder) use ($field) {
2575
                                return '(' . $field . ' exact "' . $funder . '")';
2576
                            }, $funders)) . ')');
2577
            $field = self :: PROJECT_FUNDING_STREAM;
2578
            $query .= ($fundingStreams == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStream) use ($field) {
2579
                                return '(' . $field . ' exact "' . $fundingStream . '")';
2580
                            }, $fundingStreams)) . ')');
2581
            $field = self :: PROJECT_SCIENTIFIC_AREA;
2582
            $query .= ($scientificAreas == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($scientificArea) use ($field) {
2583
                                return '(' . $field . ' exact "' . $scientificArea . '")';
2584
                            }, $scientificAreas)) . ')');
2585
            $field = self :: PROJECT_FUNDING_STREAM_LEVEL2;
2586
            $query .= ($fundingStreamsLevel2 == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStreamsLevel2) use ($field) {
2587
                                return '(' . $field . ' exact "' . $fundingStreamsLevel2 . '")';
2588
                            }, $scientificAreas)) . ')');
2589
            $from = new DateTime();
2590
            $to = new DateTime();
2591
            switch ($startDate) {
2592
                case -1:
2593
                    break;
2594
                case 0:
2595
                    $from->setDate($startFromYear, $startFromMonth, 1);
2596
                    $to->setDate($startToYear, $startToMonth, 1);
2597
                    $to->setDate($startToYear, $startToMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2598
                    $query .= ' and (' . self :: PROJECT_START_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2599
                    break;
2600
                default:
2601
                    $from->sub(new DateInterval('P' . $startDate . 'M'));
2602
                    $query .= ' and (' . self :: PROJECT_START_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2603
            }
2604
            $from = new DateTime();
2605
            $to = new DateTime();
2606
            switch ($endDate) {
2607
                case -1:
2608
                    break;
2609
                case 0:
2610
                    $from->setDate($endFromYear, $endFromMonth, 1);
2611
                    $to->setDate($endToYear, $endToMonth, 1);
2612
                    $to->setDate($endToYear, $endToMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2613
                    $query .= ' and (' . self :: PROJECT_END_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2614
                    break;
2615
                default:
2616
                    $from->sub(new DateInterval('P' . $endDate . 'M'));
2617
                    $query .= ' and (' . self :: PROJECT_END_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2618
            }
2619
            $field = self :: PROJECT_SC39;
2620
            $query .= ($sc39s == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($sc39) use ($field) {
2621
                                return '(' . $field . ' exact "' . ($sc39 ? 'true' : 'false') . '")';
2622
                            }, $sc39s)) . ')');
2623
            $query .= ($funder == NULL) ? '' : (' and (' . self :: PROJECT_FUNDER . ' exact "' . $funder . '")');
2624
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2625
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PROJECT_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2626
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2627
            $query .= ($startYear == NULL) ? '' : (' and (' . self :: PROJECT_START_YEAR . ' exact "' . $startYear . '")');
2628
            $query .= ($endYear == NULL) ? '' : (' and (' . self :: PROJECT_END_YEAR . ' exact "' . $endYear . '")');
2629
            $query .= ($sc39 === NULL) ? '' : (' and (' . self :: PROJECT_SC39 . ' exact "' . ($sc39 ? 'true' : 'false') . '")');
2630
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2631
            if (($response = $this->performGet('search?action=searchNrefine&sTransformer=projects_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&fields=' . self :: PROJECT_FUNDER . '&fields=' . self :: PROJECT_FUNDING_STREAM . '&fields=' . self :: PROJECT_SCIENTIFIC_AREA . '&fields=' . self :: PROJECT_FUNDING_STREAM_LEVEL2. '&fields=' . self :: PROJECT_START_YEAR . '&fields=' . self :: PROJECT_END_YEAR . '&fields=' . self :: PROJECT_SC39 . '&locale=' . str_replace('-', '_', $locale))) == NULL)
2632
                throw new Exception('no HTTP response');
2633
            if ($response->code != self :: HTTP_OK)
2634
                throw new Exception('HTTP response code ' . $response->code);
2635
            $document = new DOMDocument();
2636
            $document->recover = TRUE;
2637
            if ($document->loadXML($response->body) == FALSE)
2638
                throw new Exception('invalid XML response');
2639
            $xpath = new DOMXPath($document);
2640
            $result = new JObject();
2641
            $result->totalProjects = $this->parseTotalResults($xpath);
2642
            $result->projects = $this->parseProjects($xpath);
2643
            $result->statistics = $this->createStatisticsForProjects($xpath,"Filter");
2644
                    //createStatistics($xpath, array('funderFilter', 'fundingStreamFilter', 'scientificAreaFilter', 'startYearFilter', 'endYearFilter', 'sc39Filter'), array('FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'), array('NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_START_YEAR_STATISTICS_FOUND', 'NO_END_YEAR_STATISTICS_FOUND', 'NO_SPECIAL_CLAUSE_39_STATISTICS_FOUND'), array(self :: PROJECT_FUNDER, self :: PROJECT_FUNDING_STREAM, self :: PROJECT_SCIENTIFIC_AREA, self :: PROJECT_START_YEAR, self :: PROJECT_END_YEAR, self :: PROJECT_SC39));
2645
            JLog :: add('Advanced search retrieved ' . count($result->projects) . ' projects in ' . (microtime(TRUE) - $time) . ' s (keywords: [' . implode(', ', $keywords) . '], fields: [' . implode(', ', $fields) . '], constraints: [' . implode(', ', $constraints) . '], funders: [' . implode(', ', $funders) . '], funding streams: [' . implode(', ', $fundingStreams) . '], scientific areas: [' . implode(', ', $scientificAreas) . '], start date: ' . $startDate . ', start from month: ' . $startFromMonth . ', start from year: ' . $startFromYear . ', start to month: ' . $startToMonth . ', start to year: ' . $startToYear . ', end date: ' . $endDate . ', end from month: ' . $endFromMonth . ', end from year: ' . $endFromYear . ', end to month: ' . $endToMonth . ', end to year: ' . $endToYear . ', SC-39s: [' . implode(', ', array_map(function ($sc39) {
2646
                                return $sc39 ? 'true' : 'false';
2647
                            }, $sc39s)) . '], funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', start year: ' . (($startYear == NULL) ? 'null' : $startYear) . ', end year: ' . (($endYear == NULL) ? 'null' : $endYear) . ', SC-39: ' . (($sc39 === NULL) ? 'null' : ($sc39 ? 'true' : 'false')) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
2648
            return $result;
2649
        } catch (Exception $e) {
2650
            JLog :: add('Error performing publication advanced search (keywords: [' . implode(', ', $keywords) . '], fields: [' . implode(', ', $fields) . '], constraints: [' . implode(', ', $constraints) . '], funders: [' . implode(', ', $funders) . '], funding streams: [' . implode(', ', $fundingStreams) . '], scientific areas: [' . implode(', ', $scientificAreas) . '], start date: ' . $startDate . ', start from month: ' . $startFromMonth . ', start from year: ' . $startFromYear . ', start to month: ' . $startToMonth . ', start to year: ' . $startToYear . ', end date: ' . $endDate . ', end from month: ' . $endFromMonth . ', end from year: ' . $endFromYear . ', end to month: ' . $endToMonth . ', end to year: ' . $endToYear . ', SC-39s: [' . implode(', ', array_map(function ($sc39) {
2651
                                return $sc39 ? 'true' : 'false';
2652
                            }, $sc39s)) . '], funder: ' . (($funder == NULL) ? 'null' : $funder) . ', funding stream: ' . (($fundingStream == NULL) ? 'null' : $fundingStream) . ', scientific area: ' . (($scientificArea == NULL) ? 'null' : $scientificArea) . ', start year: ' . (($startYear == NULL) ? 'null' : $startYear) . ', end year: ' . (($endYear == NULL) ? 'null' : $endYear) . ', SC-39: ' . (($sc39 === NULL) ? 'null' : ($sc39 ? 'true' : 'false')) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2653
            return NULL;
2654
        }
2655
    }
2656

    
2657
    // Perform an advanced search for people.
2658
    // $keywords the keywords to search for (array)
2659
    // $fields the fields to match keywords with (array - possible values are LAST_NAME, FIRST_NAME and FULL_NAME)
2660
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2661
    // $countries the IDs of the countries to search for
2662
    // $country the ID of the coutnry to use as filter or NULL for no country filtering
2663
    // $page the page of results to retrieve
2664
    // $size the size of the page of results to retrieve
2665
    // $locale the locale to use
2666
    // return a result (object) containing people and statistics
2667
    private function _advancedSearchPeople($keywords, $fields, $constraints, $countries, $country, $page, $size, $locale) {
2668
        try {
2669
            $time = microtime(TRUE);
2670
            $query = self :: PERSON_QUERY;
2671
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2672
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2673
                switch ($constraints[$i]) {
2674
                    case OpenAireViewAdvancedSearchPeople :: ALL:
2675
                        $operator = ' and ';
2676
                        break;
2677
                    case OpenAireViewAdvancedSearchPeople :: ANY:
2678
                        $operator = ' or ';
2679
                        break;
2680
                    default:
2681
                        $operator = NULL;
2682
                }
2683
                switch ($fields[$i]) {
2684
                    case OpenAireViewAdvancedSearchPeople :: LAST_NAME:
2685
                        $field = self :: PERSON_LAST_NAME;
2686
                        break;
2687
                    case OpenAireViewAdvancedSearchPeople :: FIRST_NAME:
2688
                        $field = self :: PERSON_FIRST_NAME;
2689
                        break;
2690
                    case OpenAireViewAdvancedSearchPeople :: FULL_NAME:
2691
                        $field = self :: PERSON_FULL_NAME;
2692
                        break;
2693
                    default:
2694
                        $field = NULL;
2695
                }
2696
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2697
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2698
                                }, $tokens)) . ')');
2699
            }
2700
            $field = self :: PERSON_COUNTRY;
2701
            $query .= ($countries == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($country) use ($field) {
2702
                                return '(' . $field . ' exact "' . $country . '")';
2703
                            }, $countries)) . ')');
2704
            $query .= ($country == NULL) ? '' : (' and (' . self :: PERSON_COUNTRY . ' exact "' . $country . '")');
2705
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2706
            if (($response = $this->performGet('search?action=searchNrefine&sTransformer=persons_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&fields=' . self :: PERSON_COUNTRY . '&locale=' . str_replace('-', '_', $locale))) == NULL)
2707
                throw new Exception('no HTTP response');
2708
            if ($response->code != self :: HTTP_OK)
2709
                throw new Exception('HTTP response code ' . $response->code);
2710
            $document = new DOMDocument();
2711
            $document->recover = TRUE;
2712
            if ($document->loadXML($response->body) == FALSE)
2713
                throw new Exception('invalid XML response');
2714
            $xpath = new DOMXPath($document);
2715
            $result = new JObject();
2716
            $result->totalPeople = $this->parseTotalResults($xpath);
2717
            $result->people = $this->parsePeople($xpath);
2718
            $result->statistics = $this->createStatistics($xpath, array('countryFilter'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: PERSON_COUNTRY));
2719
            JLog :: add('Advanced search retrieved ' . count($result->people) . ' people in ' . (microtime(TRUE) - $time) . ' s (keywords: [' . implode(', ', $keywords) . '], fields: [' . implode(', ', $fields) . '], constraints: [' . implode(', ', $constraints) . '], countries: [' . implode(', ', $countries) . '], country: ' . (($country == NULL) ? 'null' : $country) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
2720
            return $result;
2721
        } catch (Exception $e) {
2722
            JLog :: add('Error performing datasource advanced search (keywords: [' . implode(', ', $keywords) . '], fields: [' . implode(', ', $fields) . '], constraints: [' . implode(', ', $constraints) . '], countries: [' . implode(', ', $countries) . '], country: ' . (($country == NULL) ? 'null' : $country) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2723
            return NULL;
2724
        }
2725
    }
2726

    
2727
    // Perform an advanced search for organizations.
2728
    // $keywords the keywords to search for (array)
2729
    // $fields the fields to match keywords with (array - possible values are NAME and SHORT_NAME)
2730
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2731
    // $countries the IDs of the countries to search for
2732
    // $types the IDs of the organization types to search for
2733
    // $country the ID of the coutnry to use as filter or NULL for no country filtering
2734
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
2735
    // $page the page of results to retrieve
2736
    // $size the size of the page of results to retrieve
2737
    // $locale the locale to use
2738
    // return a result (object) containing organizations and statistics
2739
    private function _advancedSearchOrganizations($keywords, $fields, $constraints, $countries, $types, $country, $type, $page, $size, $locale) {
2740
        try {
2741
            $time = microtime(TRUE);
2742
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
2743
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2744
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2745
                switch ($constraints[$i]) {
2746
                    case OpenAireViewAdvancedSearchPeople :: ALL:
2747
                        $operator = ' and ';
2748
                        break;
2749
                    case OpenAireViewAdvancedSearchPeople :: ANY:
2750
                        $operator = ' or ';
2751
                        break;
2752
                    default:
2753
                        $operator = NULL;
2754
                }
2755
                switch ($fields[$i]) {
2756
                    case OpenAireViewAdvancedSearchOrganizations :: NAME:
2757
                        $field = self :: ORGANIZATION_NAME;
2758
                        break;
2759
                    case OpenAireViewAdvancedSearchOrganizations :: SHORT_NAME:
2760
                        $field = self :: ORGANIZATION_SHORT_NAME;
2761
                        break;
2762
                    default:
2763
                        $field = NULL;
2764
                }
2765
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2766
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2767
                                }, $tokens)) . ')');
2768
            }
2769
            $field = self :: ORGANIZATION_COUNTRY;
2770
            $query .= ($countries == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($country) use ($field) {
2771
                                return '(' . $field . ' exact "' . $country . '")';
2772
                            }, $countries)) . ')');
2773
            $organizationLegalBody = self :: ORGANIZATION_LEGAL_BODY;
2774
            $organizationLegalPerson = self :: ORGANIZATION_LEGAL_PERSON;
2775
            $organizationNonProfit = self :: ORGANIZATION_NON_PROFIT;
2776
            $organizationResearch = self :: ORGANIZATION_RESEARCH;
2777
            $organizationEuInterests = self :: ORGANIZATION_EU_INTERESTS;
2778
            $organizationInternational = self :: ORGANIZATION_INTERNATIONAL;
2779
            $organizationEnterprise = self :: ORGANIZATION_ENTERPRISE;
2780
            $organizationSmallMediumEnterprise = self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE;
2781
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($organizationLegalBody, $organizationLegalPerson, $organizationNonProfit, $organizationResearch, $organizationEuInterests, $organizationInternational, $organizationEnterprise, $organizationSmallMediumEnterprise) {
2782
                                switch ($type) {
2783
                                    case 'legalBody': return '(' . $organizationLegalBody . ' exact true)';
2784
                                    case 'legalPerson': return '(' . $organizationLegalPerson . ' exact true)';
2785
                                    case 'nonProfit': return '(' . $organizationNonProfit . ' exact true)';
2786
                                    case 'research': return '(' . $organizationResearch . ' exact true)';
2787
                                    case 'euInterests': return '(' . $organizationEuInterests . ' exact true)';
2788
                                    case 'international': return '(' . $organizationInternational . ' exact true)';
2789
                                    case 'enterprise': return '(' . $organizationEnterprise . ' exact true)';
2790
                                    case 'smallMediumEnterprise': return '(' . $organizationSmallMediumEnterprise . ' exact true)';
2791
                                }
2792
                            }, $types)) . ')');
2793
            $query .= ($country == NULL) ? '' : (' and (' . self :: ORGANIZATION_COUNTRY . ' exact "' . $country . '")');
2794
            switch ($type) {
2795
                case 'legalBody':
2796
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_BODY . ' exact true)';
2797
                    break;
2798
                case 'legalPerson':
2799
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_PERSON . ' exact true)';
2800
                    break;
2801
                case 'nonProfit':
2802
                    $query .= ' and (' . self :: ORGANIZATION_NON_PROFIT . ' exact true)';
2803
                    break;
2804
                case 'research':
2805
                    $query .= ' and (' . self :: ORGANIZATION_RESEARCH . ' exact true)';
2806
                    break;
2807
                case 'euInterests':
2808
                    $query .= ' and (' . self :: ORGANIZATION_EU_INTERESTS . ' exact true)';
2809
                    break;
2810
                case 'international':
2811
                    $query .= ' and (' . self :: ORGANIZATION_INTERNATIONAL . ' exact true)';
2812
                    break;
2813
                case 'enterprise':
2814
                    $query .= ' and (' . self :: ORGANIZATION_ENTERPRISE . ' exact true)';
2815
                    break;
2816
                case 'smallMediumEnterprise':
2817
                    $query .= ' and (' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . ' exact true)';
2818
            }
2819
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2820
            if (($response = $this->performGet('search?action=searchNrefine&sTransformer=organizations_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&fields=' . self :: ORGANIZATION_COUNTRY . '&fields=' . self :: ORGANIZATION_LEGAL_BODY . '&fields=' . self :: ORGANIZATION_LEGAL_PERSON . '&fields=' . self :: ORGANIZATION_NON_PROFIT . '&fields=' . self :: ORGANIZATION_RESEARCH . '&fields=' . self :: ORGANIZATION_EU_INTERESTS . '&fields=' . self :: ORGANIZATION_INTERNATIONAL . '&fields=' . self :: ORGANIZATION_ENTERPRISE . '&fields=' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . '&locale=' . str_replace('-', '_', $locale))) == NULL)
2821
                throw new Exception('no HTTP response');
2822
            if ($response->code != self :: HTTP_OK)
2823
                throw new Exception('HTTP response code ' . $response->code);
2824
            $document = new DOMDocument();
2825
            $document->recover = TRUE;
2826
            if ($document->loadXML($response->body) == FALSE)
2827
                throw new Exception('invalid XML response');
2828
            $xpath = new DOMXPath($document);
2829
            $result = new JObject();
2830
            $result->totalOrganizations = $this->parseTotalResults($xpath);
2831
            $result->organizations = $this->parseOrganizations($xpath);
2832
            $result->statistics = $this->createStatistics($xpath, array('countryFilter'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
2833
            $result->statistics['typeFilter'] = new JObject();
2834
            $result->statistics['typeFilter']->id = 'typeFilter';
2835
            $result->statistics['typeFilter']->title = JText :: _('TYPE');
2836
            $result->statistics['typeFilter']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
2837
            $result->statistics['typeFilter']->data = array();
2838
            $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
2839
            if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
2840
                $result->statistics['typeFilter']->data['legalBody'] = new JObject();
2841
                $result->statistics['typeFilter']->data['legalBody']->id = 'legalBody';
2842
                $result->statistics['typeFilter']->data['legalBody']->name = JText :: _('LEGAL_BODY');
2843
                $result->statistics['typeFilter']->data['legalBody']->count = $legalBody['true']->count;
2844
            }
2845
            $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
2846
            if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
2847
                $result->statistics['typeFilter']->data['legalPerson'] = new JObject();
2848
                $result->statistics['typeFilter']->data['legalPerson']->id = 'legalPerson';
2849
                $result->statistics['typeFilter']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
2850
                $result->statistics['typeFilter']->data['legalPerson']->count = $legalPerson['true']->count;
2851
            }
2852
            $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
2853
            if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
2854
                $result->statistics['typeFilter']->data['nonProfit'] = new JObject();
2855
                $result->statistics['typeFilter']->data['nonProfit']->id = 'nonProfit';
2856
                $result->statistics['typeFilter']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
2857
                $result->statistics['typeFilter']->data['nonProfit']->count = $nonProfit['true']->count;
2858
            }
2859
            $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
2860
            if (($research != NULL) && array_key_exists('true', $research)) {
2861
                $result->statistics['typeFilter']->data['research'] = new JObject();
2862
                $result->statistics['typeFilter']->data['research']->id = 'research';
2863
                $result->statistics['typeFilter']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
2864
                $result->statistics['typeFilter']->data['research']->count = $research['true']->count;
2865
            }
2866
            $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
2867
            if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
2868
                $result->statistics['typeFilter']->data['euInterests'] = new JObject();
2869
                $result->statistics['typeFilter']->data['euInterests']->id = 'euInterests';
2870
                $result->statistics['typeFilter']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
2871
                $result->statistics['typeFilter']->data['euInterests']->count = $euInterests['true']->count;
2872
            }
2873
            $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
2874
            if (($international != NULL) && array_key_exists('true', $international)) {
2875
                $result->statistics['typeFilter']->data['international'] = new JObject();
2876
                $result->statistics['typeFilter']->data['international']->id = 'international';
2877
                $result->statistics['typeFilter']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
2878
                $result->statistics['typeFilter']->data['international']->count = $international['true']->count;
2879
            }
2880
            $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
2881
            if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
2882
                $result->statistics['typeFilter']->data['enterprise'] = new JObject();
2883
                $result->statistics['typeFilter']->data['enterprise']->id = 'enterprise';
2884
                $result->statistics['typeFilter']->data['enterprise']->name = JText :: _('ENTERPRISE');
2885
                $result->statistics['typeFilter']->data['enterprise']->count = $enterprise['true']->count;
2886
            }
2887
            $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
2888
            if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
2889
                $result->statistics['typeFilter']->data['smallMediumEnterprise'] = new JObject();
2890
                $result->statistics['typeFilter']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
2891
                $result->statistics['typeFilter']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
2892
                $result->statistics['typeFilter']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
2893
            }
2894
            uasort($result->statistics['typeFilter']->data, function ($row1, $row2) {
2895
                return $row2->count - $row1->count;
2896
            });
2897
            JLog :: add('Advanced search retrieved ' . count($result->organizations) . ' organizations in ' . (microtime(TRUE) - $time) . ' s (keywords: [' . implode(', ', $keywords) . '], fields: [' . implode(', ', $fields) . '], constraints: [' . implode(', ', $constraints) . '], countries: [' . implode(', ', $countries) . '], types: [' . implode(', ', $types) . '], country: ' . (($country == NULL) ? 'null' : $country) . ', type: ' . (($type == NULL) ? 'null' : $type) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
2898
            return $result;
2899
        } catch (Exception $e) {
2900
            JLog :: add('Error performing organization advanced search (keywords: [' . implode(', ', $keywords) . '], fields: [' . implode(', ', $fields) . '], constraints: [' . implode(', ', $constraints) . '], countries: [' . implode(', ', $countries) . '], types: [' . implode(', ', $types) . '], country: ' . (($country == NULL) ? 'null' : $country) . ', type: ' . (($type == NULL) ? 'null' : $type) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2901
            return NULL;
2902
        }
2903
    }
2904

    
2905
    // Perform an advanced search for datasources.
2906
    // $keywords the keywords to search for (array)
2907
    // $fields the fields to match keywords with (array - possible values are NAME, ENGLISH_NAME and SUBJECT)
2908
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2909
    // $types the IDs of the datasource types to search for
2910
    // $languages the IDs of the datasource languages to search for
2911
    // $contents the IDs of the contents to search for
2912
    // $compatibilities the IDs of the compatibilities to search for
2913
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
2914
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
2915
    // $content the ID of the content to use as filter or NULL for no content filtering
2916
    // $compatibility the ID of the compatibility to use as filter or NULL for no compatibility filtering
2917
    // $page the page of results to retrieve
2918
    // $size the size of the page of results to retrieve
2919
    // $locale the locale to use
2920
    // return a result (object) containing datasources and statistics
2921
    private function _advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale) {
2922
        try {
2923
            $time = microtime(TRUE);
2924
            $query = self :: DATASOURCE_QUERY;
2925
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2926
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2927
                switch ($constraints[$i]) {
2928
                    case OpenAireViewAdvancedSearchDatasources :: ALL:
2929
                        $operator = ' and ';
2930
                        break;
2931
                    case OpenAireViewAdvancedSearchDatasources :: ANY:
2932
                        $operator = ' or ';
2933
                        break;
2934
                    default:
2935
                        $operator = NULL;
2936
                }
2937
                switch ($fields[$i]) {
2938
                    case OpenAireViewAdvancedSearchDatasources :: NAME:
2939
                        $field = self :: DATASOURCE_NAME;
2940
                        break;
2941
                    case OpenAireViewAdvancedSearchDatasources :: ENGLISH_NAME:
2942
                        $field = self :: DATASOURCE_ENGLISH_NAME;
2943
                        break;
2944
                    case OpenAireViewAdvancedSearchDatasources :: SUBJECT:
2945
                        $field = self :: DATASOURCE_SUBJECT;
2946
                        break;
2947
                    default:
2948
                        $field = NULL;
2949
                }
2950
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2951
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2952
                                }, $tokens)) . ')');
2953
            }
2954
            $field = self :: DATASOURCE_TYPE;
2955
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($field) {
2956
                                return '(' . $field . ' exact "' . $type . '")';
2957
                            }, $types)) . ')');
2958
            $field = self :: DATASOURCE_LANGUAGE;
2959
            $query .= ($languages == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($language) use ($field) {
2960
                                return '(' . $field . ' exact "' . $language . '")';
2961
                            }, $languages)) . ')');
2962
            $field = self :: DATASOURCE_CONTENT;
2963
            $query .= ($contents == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($content) use ($field) {
2964
                                return '(' . $field . ' exact "' . $content . '")';
2965
                            }, $contents)) . ')');
2966
            $field = self :: DATASOURCE_COMPATIBILITY;
2967
            $query .= ($compatibilities == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($compatibility) use ($field) {
2968
                                return '(' . $field . ' exact "' . $compatibility . '")';
2969
                            }, $compatibilities)) . ')');
2970
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASOURCE_TYPE . ' exact "' . $type . '")');
2971
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASOURCE_LANGUAGE . ' exact "' . $language . '")');
2972
            $query .= ($content == NULL) ? '' : (' and (' . self :: DATASOURCE_CONTENT . ' exact "' . $content . '")');
2973
            $query .= ($compatibility == NULL) ? '' : (' and (' . self :: DATASOURCE_COMPATIBILITY . ' exact "' . $compatibility . '")');
2974
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2975
            if (($response = $this->performGet('search?action=searchNrefine&sTransformer=datasources_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&fields=' . self :: DATASOURCE_TYPE . '&fields=' . self :: DATASOURCE_LANGUAGE . '&fields=' . self :: DATASOURCE_CONTENT . '&fields=' . self :: DATASOURCE_COMPATIBILITY . '&locale=' . str_replace('-', '_', $locale))) == NULL)
2976
                throw new Exception('no HTTP response');
2977
            if ($response->code != self :: HTTP_OK)
2978
                throw new Exception('HTTP response code ' . $response->code);
2979
            $document = new DOMDocument();
2980
            $document->recover = TRUE;
2981
            if ($document->loadXML($response->body) == FALSE)
2982
                throw new Exception('invalid XML response');
2983
            $xpath = new DOMXPath($document);
2984
            $result = new JObject();
2985
            $result->totalDatasources = $this->parseTotalResults($xpath);
2986
            $result->datasources = $this->parseDatasources($xpath);
2987
            $result->statistics = $this->createStatistics($xpath, array('typeFilter', 'languageFilter', 'contentFilter', 'compatibilityFilter'), array('TYPE', 'LANGUAGE', 'CONTENT', 'COMPATIBILITY'), array('NO_TYPE_STATISTICS_FOUND', 'NO_LANGUAGE_STATISTICS_FOUND', 'NO_CONTENT_STATISTICS_FOUND', 'NO_COMPATIBILITY_STATISTICS_FOUND'), array(self :: DATASOURCE_TYPE, self :: DATASOURCE_LANGUAGE, self :: DATASOURCE_CONTENT, self :: DATASOURCE_COMPATIBILITY));
2988
            JLog :: add('Advanced search retrieved ' . count($result->datasources) . ' datasources in ' . (microtime(TRUE) - $time) . ' s (keywords: [' . implode(', ', $keywords) . '], fields: [' . implode(', ', $fields) . '], constraints: [' . implode(', ', $constraints) . '], types: [' . implode(', ', $types) . '], languages: [' . implode(', ', $languages) . '], contents: [' . implode(', ', $contents) . '], compatibilities: [' . implode(', ', $compatibilities) . '], type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', content: ' . (($content == NULL) ? 'null' : $content) . ', compatibility: ' . (($compatibility == NULL) ? 'null' : $compatibility) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
2989
            return $result;
2990
        } catch (Exception $e) {
2991
            JLog :: add('Error performing datasource advanced search (keywords: [' . implode(', ', $keywords) . '], fields: [' . implode(', ', $fields) . '], constraints: [' . implode(', ', $constraints) . '], types: [' . implode(', ', $types) . '], languages: [' . implode(', ', $languages) . '], contents: [' . implode(', ', $contents) . '], compatibilities: [' . implode(', ', $compatibilities) . '], type: ' . (($type == NULL) ? 'null' : $type) . ', language: ' . (($language == NULL) ? 'null' : $language) . ', content: ' . (($content == NULL) ? 'null' : $content) . ', compatibility: ' . (($compatibility == NULL) ? 'null' : $compatibility) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2992
            return NULL;
2993
        }
2994
    }
2995

    
2996
    // Retrieve a single publication by identifier.
2997
    // $id the publication identifier
2998
    // $locale the locale to use
2999
    // return a publication (object) or NULL if no such publication exists
3000
    private function _getPublication($id, $locale) {
3001
        try {
3002
            $time = microtime(TRUE);
3003
            $query = self :: PUBLICATION_QUERY . ' and ( (' . self :: PUBLICATION_ID . ' exact "' . $id . '") or (' . self :: RESULT_DUP_ID . ' exact "' . $id . '" ) )';
3004
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3005
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3006
                throw new Exception('no HTTP response');
3007
            if ($response->code != self :: HTTP_OK)
3008
                throw new Exception('HTTP response code ' . $response->code);
3009
            $document = new DOMDocument();
3010
            $document->recover = TRUE;
3011
            if ($document->loadXML($response->body) == FALSE)
3012
                throw new Exception('invalid XML response');
3013
            $xpath = new DOMXPath($document);
3014
            $publication = $this->parsePublication($xpath, $locale);
3015
            JLog :: add('Retrieved publication in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3016
            return $publication;
3017
        } catch (Exception $e) {
3018
            JLog :: add('Error retrieving publication (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3019
            return NULL;
3020
        }
3021
    }
3022

    
3023
    // Retrieve results by identifier.
3024
    // $ids the result identifiers
3025
    // $locale the locale to use
3026
    // return a result (object) or NULL if no such result exists
3027
    private function _getResults($ids, $locale) {
3028
        try {
3029
            $time = microtime(TRUE);
3030
            $query = self :: RESULT_QUERY . ' and (';
3031
            $parts = array();
3032
            foreach ($ids as $id) {
3033
                $parts[] = ('(' . self :: RESULT_ID . ' exact "' . $id . '") OR (' . self :: RESULT_DUP_ID . ' exact "' . $id . '") ');
3034
               //  $parts[] = ('(' . self :: RESULT_ID . ' exact "' . $id . '") ');
3035
            }
3036
            $query .= join(" OR ", $parts);
3037
            $query .= ')';
3038
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3039
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&size=10000&locale=' . str_replace('-', '_', $locale))) == NULL)
3040
                throw new Exception('no HTTP response');        
3041
            if ($response->code != self :: HTTP_OK)
3042
                throw new Exception('HTTP response code ' . $response->code);
3043
            $document = new DOMDocument();
3044
            $document->recover = TRUE;
3045
            if ($document->loadXML($response->body) == FALSE)
3046
                throw new Exception('invalid XML response');
3047
            $xpath = new DOMXPath($document);
3048
            $results = $this->parseResults($ids,$xpath, $locale);
3049
            JLog :: add('Retrieved results in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3050
            return $results;
3051
        } catch (Exception $e) {
3052
            JLog :: add('Error retrieving results (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3053
            return NULL;
3054
        }
3055
    }
3056

    
3057
    // Retrieve publications by identifier.
3058
    // $ids the publication identifiers
3059
    // $locale the locale to use
3060
    // return a publication (object) or NULL if no such publication exists
3061
    private function _getPublications($ids, $locale) {
3062
        try {
3063
            $time = microtime(TRUE);
3064
            $query = self :: PUBLICATION_QUERY . ' and (';
3065
            $parts = array();
3066
            foreach ($ids as $id) {
3067
                $parts[] = '(' . self :: PUBLICATION_ID . ' exact "' . $id . '")';
3068
            }
3069
            $query .= join(" OR ", $parts);
3070
            $query .= ')';
3071
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3072
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3073
                throw new Exception('no HTTP response');
3074
            if ($response->code != self :: HTTP_OK)
3075
                throw new Exception('HTTP response code ' . $response->code);
3076
            $document = new DOMDocument();
3077
            $document->recover = TRUE;
3078
            if ($document->loadXML($response->body) == FALSE)
3079
                throw new Exception('invalid XML response');
3080
            $xpath = new DOMXPath($document);
3081
            $publications = $this->parsePublications($xpath, $locale);
3082
            JLog :: add('Retrieved publication in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3083
            return $publications;
3084
        } catch (Exception $e) {
3085
            JLog :: add('Error retrieving publication (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3086
            return NULL;
3087
        }
3088
    }
3089

    
3090
    // Retrieve publications by identifier.
3091
    // $ids the publication identifiers
3092
    // $locale the locale to use
3093
    // return a publication (object) or NULL if no such publication exists
3094
    private function _getProjects($ids, $locale) {
3095
        try {
3096
            $time = microtime(TRUE);
3097
            $query = self :: PROJECT_QUERY . ' and (';
3098
            $parts = array();
3099
            foreach ($ids as $id) {
3100
                $parts[] = '(' . self :: PROJECT_ID . ' exact "' . $id . '")';
3101
            }
3102
            $query .= join(" OR ", $parts);
3103
            $query .= ')';
3104
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3105
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3106
                throw new Exception('no HTTP response');
3107
            if ($response->code != self :: HTTP_OK)
3108
                throw new Exception('HTTP response code ' . $response->code);
3109
            $document = new DOMDocument();
3110
            $document->recover = TRUE;
3111
            if ($document->loadXML($response->body) == FALSE)
3112
                throw new Exception('invalid XML response');
3113
            $xpath = new DOMXPath($document);
3114
            $projects = $this->parseProjects($xpath, $locale);
3115
            JLog :: add('Retrieved projects in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3116
            return $projects;
3117
        } catch (Exception $e) {
3118
            JLog :: add('Error retrieving projects (ids: ' . join(",", $ids) . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3119
            return NULL;
3120
        }
3121
    }
3122
// Retrieve projects by code id.
3123
    // $id the project grant agreement code
3124
    // $locale the locale to use
3125
    // return projects or NULL if no such project exists
3126
    private function _getProjectByCodeId($id, $funder, $locale) {
3127
        try {
3128
            $time = microtime(TRUE);
3129
            $query = self :: PROJECT_QUERY . ' and ';
3130
//                    (oaftype=project) and (projectcode_nt exact 731011)
3131
                $query.=' ( projectcode_nt exact "' . $id . '") and ';
3132
                $query.=' ( funderid exact "' . $funder . '")';
3133
            //and (funderid exact "ec__________::EC")'
3134
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3135
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3136
                throw new Exception('no HTTP response');
3137
            if ($response->code != self :: HTTP_OK)
3138
                throw new Exception('HTTP response code ' . $response->code);
3139
            $document = new DOMDocument();
3140
            $document->recover = TRUE;
3141
            if ($document->loadXML($response->body) == FALSE)
3142
                throw new Exception('invalid XML response');
3143
            $xpath = new DOMXPath($document);
3144
            $projects = $this->parseProject($xpath, $locale);
3145
            JLog :: add('Retrieved projects in ' . (microtime(TRUE) - $time) . ' s (id: ' .$id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3146
            return $projects;
3147
        } catch (Exception $e) {
3148
            JLog :: add('Error retrieving projects (id: ' .$id. ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3149
            return NULL;
3150
        }
3151
    }
3152
    // Retrieve datasets by identifier.
3153
    // $ids the datasets identifiers
3154
    // $locale the locale to use
3155
    // return datasets array of (object) or NULL if no such dataset exists
3156
    private function _getDatasets($ids, $locale) {
3157
        try {
3158
            $time = microtime(TRUE);
3159
            $query = self :: DATASET_QUERY . ' and (';
3160
            $parts = array();
3161
            foreach ($ids as $id) {
3162
                $parts[] = '(' . self :: DATASET_ID . ' exact "' . $id . '")';
3163
            }
3164
            $query .= join(" OR ", $parts);
3165
            $query .= ')';
3166
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3167
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3168
                throw new Exception('no HTTP response');
3169
            if ($response->code != self :: HTTP_OK)
3170
                throw new Exception('HTTP response code ' . $response->code);
3171
            $document = new DOMDocument();
3172
            $document->recover = TRUE;
3173
            if ($document->loadXML($response->body) == FALSE)
3174
                throw new Exception('invalid XML response');
3175
            $xpath = new DOMXPath($document);
3176
            $datasets = $this->parseDatasets($xpath, $locale);
3177
            JLog :: add('Retrieved publication in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3178
            return $datasets;
3179
        } catch (Exception $e) {
3180
            JLog :: add('Error retrieving publication (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3181
            return NULL;
3182
        }
3183
    }
3184

    
3185
    // Retrieve a single dataset by identifier.
3186
    // $id the dataset identifier
3187
    // $locale the locale to use
3188
    // return a dataset (object) or NULL if no such dataset exists
3189
    private function _getDataset($id, $locale) {
3190
        try {
3191
            $time = microtime(TRUE);
3192
            $query = self :: DATASET_QUERY . ' and ( (' . self :: DATASET_ID . ' exact "' . $id . '") or (' . self :: RESULT_DUP_ID . ' exact "' . $id . '" ) )';
3193
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3194
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3195
                throw new Exception('no HTTP response');
3196
            if ($response->code != self :: HTTP_OK)
3197
                throw new Exception('HTTP response code ' . $response->code);
3198
            $document = new DOMDocument();
3199
            $document->recover = TRUE;
3200
            if ($document->loadXML($response->body) == FALSE)
3201
                throw new Exception('invalid XML response');
3202
            $xpath = new DOMXPath($document);
3203
            $dataset = $this->parseDataset($xpath, $locale);
3204
            JLog :: add('Retrieved dataset in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3205
            return $dataset;
3206
        } catch (Exception $e) {
3207
            JLog :: add('Error retrieving dataset (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3208
            return NULL;
3209
        }
3210
    }
3211

    
3212
    // Retrieve a single project by identifier.
3213
    // $id the project identifier
3214
    // $locale the locale to use
3215
    // return a project (object) or NULL if no such project exists
3216
    private function _getProject($id, $locale) {
3217
        try {
3218
            $time = microtime(TRUE);
3219
            $query = self :: PROJECT_QUERY . ' and (' . self :: PROJECT_ID . ' exact "' . $id . '")';
3220
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3221
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3222
                throw new Exception('no HTTP response');
3223
            if ($response->code != self :: HTTP_OK)
3224
                throw new Exception('HTTP response code ' . $response->code);
3225
            $document = new DOMDocument();
3226
            $document->recover = TRUE;
3227
            if ($document->loadXML($response->body) == FALSE)
3228
                throw new Exception('invalid XML response');
3229
            $xpath = new DOMXPath($document);
3230
            $project = $this->parseProject($xpath);
3231
            JLog :: add('Retrieved project in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3232
            return $project;
3233
        } catch (Exception $e) {
3234
            JLog :: add('Error retrieving project (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3235
            return NULL;
3236
        }
3237
    }
3238

    
3239
    // Retrieve a single person by identifier.
3240
    // $id the person identifier
3241
    // $locale the locale to use
3242
    // return a person (object) or NULL if no such person exists
3243
    private function _getPerson($id, $locale) {
3244
        try {
3245
            $time = microtime(TRUE);
3246
            $query = self :: PERSON_QUERY . ' and (' . self :: PERSON_ID . ' exact "' . $id . '")';
3247
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3248
            if (($response = $this->performGet('search?action=search&sTransformer=persons_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3249
                throw new Exception('no HTTP response');
3250
            if ($response->code != self :: HTTP_OK)
3251
                throw new Exception('HTTP response code ' . $response->code);
3252
            $document = new DOMDocument();
3253
            $document->recover = TRUE;
3254
            if ($document->loadXML($response->body) == FALSE)
3255
                throw new Exception('invalid XML response');
3256
            $xpath = new DOMXPath($document);
3257
            $person = $this->parsePerson($xpath);
3258
            JLog :: add('Retrieved person in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3259
            return $person;
3260
        } catch (Exception $e) {
3261
            JLog :: add('Error retrieving person (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3262
            return NULL;
3263
        }
3264
    }
3265

    
3266
    // Retrieve a single organization by identifier.
3267
    // $id the organization identifier
3268
    // $locale the locale to use
3269
    // return an organization (object) or NULL if no such organization exists
3270
    private function _getOrganization($id, $locale) {
3271
        try {
3272
            $time = microtime(TRUE);
3273
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY . ' and (' . self :: ORGANIZATION_ID . ' exact "' . $id . '")';
3274
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3275
            if (($response = $this->performGet('search?action=search&sTransformer=organizations_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3276
                throw new Exception('no HTTP response');
3277
            if ($response->code != self :: HTTP_OK)
3278
                throw new Exception('HTTP response code ' . $response->code);
3279
            $document = new DOMDocument();
3280
            $document->recover = TRUE;
3281
            if ($document->loadXML($response->body) == FALSE)
3282
                throw new Exception('invalid XML response');
3283
            $xpath = new DOMXPath($document);
3284
            $organization = $this->parseOrganization($xpath);
3285
            JLog :: add('Retrieved organization in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3286
            return $organization;
3287
        } catch (Exception $e) {
3288
            JLog :: add('Error retrieving organization (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3289
            return NULL;
3290
        }
3291
    }
3292

    
3293
    // Retrieve the datasources of an organization.
3294
    // $id the organization identifier
3295
    // $size the maximum number of datasources to retrieve
3296
    // $locale the locale to use
3297
    // return a result (object) containing datasources and total
3298
    private function _getOrganizationDatasources($id, $size, $locale) {
3299
        try {
3300
            $time = microtime(TRUE);
3301
            $query = self :: DATASOURCE_QUERY . ' and (' . self :: DATASOURCE_ORGANIZATION . ' exact "' . $id . '")';
3302
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3303
            if (($response = $this->performGet('search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3304
                throw new Exception('no HTTP response');
3305
            if ($response->code != self :: HTTP_OK)
3306
                throw new Exception('HTTP response code ' . $response->code);
3307
            $document = new DOMDocument();
3308
            $document->recover = TRUE;
3309
            if ($document->loadXML($response->body) == FALSE)
3310
                throw new Exception('invalid XML response');
3311
            $xpath = new DOMXPath($document);
3312
            $result = new JObject();
3313
            $result->totalDatasources = $this->parseTotalResults($xpath);
3314
            $result->datasources = $this->parseDatasources($xpath);
3315
            JLog :: add('Retrieved ' . count($result->datasources) . ' organization datasources in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3316
            return $result;
3317
        } catch (Exception $e) {
3318
            JLog :: add('Error retrieving organization datasources (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3319
            return NULL;
3320
        }
3321
    }
3322

    
3323
    // Retrieve a single datasource by identifier.
3324
    // $id the datasource identifier
3325
    // $locale the locale to use
3326
    // return a datasource (object) or NULL if no such datasource exists
3327
    private function _getDatasource($id, $locale, $compatibility = false) {
3328
        try {
3329
            $time = microtime(TRUE);
3330
            $datasource_query = $compatibility ? self::DATASOURCE_QUERY_COMPATIBILITY : self::DATASOURCE_QUERY;
3331
            $query = $datasource_query . ' and (' . self :: DATASOURCE_ID . ' exact "' . $id . '")';
3332
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3333
            if (($response = $this->performGet('search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3334
                throw new Exception('no HTTP response');
3335
            if ($response->code != self :: HTTP_OK)
3336
                throw new Exception('HTTP response code ' . $response->code);
3337
            $document = new DOMDocument();
3338
            $document->recover = TRUE;
3339
            if ($document->loadXML($response->body) == FALSE)
3340
                throw new Exception('invalid XML response');
3341
            $xpath = new DOMXPath($document);
3342
            $datasource = $this->parseDatasource($xpath);
3343
            JLog :: add('Retrieved datasource in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3344
            return $datasource;
3345
        } catch (Exception $e) {
3346
            JLog :: add('Error retrieving datasource (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3347
            return NULL;
3348
        }
3349
    }
3350

    
3351
    // Retrieve all the OpenAIRE compatible datasources.
3352
    // $locale the locale to use
3353
    // return the datasources (array) or NULL if any errors occur
3354
    private function _getCompatibleDatasources($locale) {
3355
        try {
3356
            $time = microtime(TRUE);
3357
            $query = self :: DATASOURCE_QUERY .' and (datasourcecompatibilityid <> "hostedBy") '. ' and (' . self :: DATASOURCE_COMPATIBILITY . ' <> "' . self :: DATASOURCE_COMPATIBILITY_NOT_COMPATIBLE . '")';
3358
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3359
            if (($response = $this->performGet('search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&size=1&locale=' . str_replace('-', '_', $locale))) == NULL)
3360
                throw new Exception('no HTTP response');
3361
            if ($response->code != self :: HTTP_OK)
3362
                throw new Exception('HTTP response code ' . $response->code);
3363
            $document = new DOMDocument();
3364
            $document->recover = TRUE;
3365
            if ($document->loadXML($response->body) == FALSE)
3366
                throw new Exception('invalid XML response');
3367
            $xpath = new DOMXPath($document);
3368
            $totalDatasources = $this->parseTotalResults($xpath);
3369
            if ($totalDatasources > 0) {
3370
                if (($response = $this->performGet('search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&size=' . $totalDatasources . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3371
                    throw new Exception('no HTTP response');
3372
                if ($response->code != self :: HTTP_OK)
3373
                    throw new Exception('HTTP response code ' . $response->code);
3374
                $document = new DOMDocument();
3375
                $document->recover = TRUE;
3376
                if ($document->loadXML($response->body) == FALSE)
3377
                    throw new Exception('invalid XML response');
3378
                $xpath = new DOMXPath($document);
3379
                $datasources = $this->parseDatasources($xpath);
3380
            } else
3381
                $datasources = array();
3382
            JLog :: add('Retrieved ' . count($datasources) . ' compatible datasources in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3383
            return $datasources;
3384
        } catch (Exception $e) {
3385
            JLog :: add('Error retrieving compatible datasources (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3386
            return NULL;
3387
        }
3388
    }
3389

    
3390
    // Perform a quick search for projects, searching only by acronym, title or code and funder.
3391
    // $keyword the keyword to search for
3392
    // $funder the funder to search for
3393
    // $limit the maximum number of results to retrieve
3394
    // $locale the locale to use
3395
    // return projects (array) or NULL if any errors occur
3396
    private function _quickSearchProjects($keyword, $funder, $limit, $locale) {
3397
        try {
3398
            $time = microtime(TRUE);
3399
            $query = self :: PROJECT_QUERY . ' and ((' . self :: PROJECT_TITLE . ' = "' . $keyword . '") or (' . self :: PROJECT_ACRONYM . ' = "' . $keyword . '") or (' . self :: PROJECT_CODE . ' = "' . $keyword . '")) and (' . self :: PROJECT_FUNDER . ' exact ' . $funder . ')';
3400
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3401
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&size=' . $limit . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3402
                throw new Exception('no HTTP response');
3403
            if ($response->code != self :: HTTP_OK)
3404
                throw new Exception('HTTP response code ' . $response->code);
3405
            $document = new DOMDocument();
3406
            $document->recover = TRUE;
3407
            if ($document->loadXML($response->body) == FALSE)
3408
                throw new Exception('invalid XML response');
3409
            $xpath = new DOMXPath($document);
3410
            $projects = $this->parseProjects($xpath);
3411
            JLog :: add('Retrieved ' . count($projects) . ' projects in ' . (microtime(TRUE) - $time) . ' s (keyword: ' . $keyword . ', funder: ' . $funder . ', limit: ' . $limit . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3412
            return $projects;
3413
        } catch (Exception $e) {
3414
            JLog :: add('Error retrieving projects (keyword: ' . $keyword . ', funder: ' . $funder . ', limit: ' . $limit . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3415
            return NULL;
3416
        }
3417
    }
3418

    
3419
    // Perform a quick search for organizations, searching only by name or short name.
3420
    // $keyword the keyword to search for
3421
    // $limit the maximum number of results to retrieve
3422
    // $locale the locale to use
3423
    // return organizations (array) or NULL if any errors occur
3424
    private function _quickSearchOrganizations($keyword, $limit, $locale) {
3425
        try {
3426
            $time = microtime(TRUE);
3427
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY . ' and ((' . self :: ORGANIZATION_NAME . ' all "' . $keyword . '") or (' . self :: ORGANIZATION_SHORT_NAME . ' all "' . $keyword . '")) and collectedfromdatasourcename exact "OpenDOAR" ';
3428
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3429
            if (($response = $this->performGet('search?action=search&sTransformer=organizations_openaire&query=' . urlencode($query) . '&size=' . $limit . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3430
                throw new Exception('no HTTP response');
3431
            if ($response->code != self :: HTTP_OK)
3432
                throw new Exception('HTTP response code ' . $response->code);
3433
            $document = new DOMDocument();
3434
            $document->recover = TRUE;
3435
            if ($document->loadXML($response->body) == FALSE)
3436
                throw new Exception('invalid XML response');
3437
            $xpath = new DOMXPath($document);
3438
            $organizations = $this->parseOrganizations($xpath);
3439
            JLog :: add('Retrieved ' . count($organizations) . ' organizations in ' . (microtime(TRUE) - $time) . ' s (keyword: ' . $keyword . ', limit: ' . $limit . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3440
            return $organizations;
3441
        } catch (Exception $e) {
3442
            JLog :: add('Error retrieving organizations (keyword: ' . $keyword . ', limit: ' . $limit . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3443
            return NULL;
3444
        }
3445
    }
3446

    
3447
    // Perform an HTTP GET request.
3448
    // $request the relative URL to connect to
3449
    // return the HTTP response (object)
3450
    private function performGet($request) {
3451
        $request = $this->searchService . $request;
3452
        JLog :: add('Requesting ' . $request, JLog :: INFO, self :: LOG);
3453
        $time = microtime(TRUE);
3454
        $response = $this->http->get($request);
3455
        JLog :: add('Received response in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
3456
        return $response;
3457
    }
3458

    
3459
    // Create statistics based on a search service XML response.
3460
    // $xpath the DOMXPath to parse
3461
    // $ids the identifiers of the statistics to create
3462
    // $titles the titles of the statistics to create
3463
    // $errors the error messages of the statistics to create
3464
    // $data the field names of the statistics to create
3465
    // return statistics (array)
3466
    private function createStatistics($xpath, $ids, $titles, $errors, $data) {
3467
        $statistics = array();
3468
        array_map(function ($id, $title, $error, $data) use ($xpath, &$statistics) {
3469
            $statistics[$id] = new JObject();
3470
            $statistics[$id]->id = $id;
3471
            $statistics[$id]->title = JText :: _($title);
3472
            $statistics[$id]->error = JText :: _($error);
3473
            $statistics[$id]->data = OpenAireModelSearch :: parseStatistics($xpath, $data);
3474
        }
3475
                , $ids, $titles, $errors, $data);
3476
        return $statistics;
3477
    }
3478

    
3479
    // Parse statistics from a search service XML response.
3480
    // $xpath the DOMXPath to parse
3481
    // $category the category to retrieve statistics for
3482
    // return statistics (associative array)
3483
    public function parseStatistics($xpath, $category) {
3484
        if ((($browseResultsNodes = $xpath->query('/response/browseResults')) == FALSE) || (($browseResultsNode = $browseResultsNodes->item(0)) == NULL))
3485
            throw new Exception('error parsing statistics');
3486
        if (($fieldNodes = $xpath->query('./result/field[@name = "' . $category . '"]', $browseResultsNode)) == FALSE)
3487
            throw new Exception('error parsing statistics');
3488
        $statistics = array();
3489
        foreach ($fieldNodes as $fieldNode) {
3490
            if ((($idNodes = $xpath->query('./field[@name = "value"]/@value_original', $fieldNode)) == FALSE) || (($idNode = $idNodes->item(0)) == NULL))
3491
                throw new Exception('error parsing statistics');
3492
            if ((($nameNodes = $xpath->query('./field[@name = "value"]/@value', $fieldNode)) == FALSE) || (($nameNode = $nameNodes->item(0)) == NULL))
3493
                throw new Exception('error parsing statistics');
3494
            if ((($countNodes = $xpath->query('./field[@name = "count"]/@value', $fieldNode)) == FALSE) || (($countNode = $countNodes->item(0)) == NULL))
3495
                throw new Exception('error parsing statistics');
3496
            $statistic = new JObject();
3497
            $statistic->id = trim($idNode->nodeValue);
3498

    
3499
            $statistic->name = trim($nameNode->nodeValue);
3500
             $statistic->name=  str_replace("::", JText :: _('FUNDER_SEPARATOR'), $statistic->name);
3501
            /* if ($category === self :: PUBLICATION_PROJECT) {                
3502
              $project =OpenAireModelSearch :: getProject($statistic->name, 'en-GB');
3503
              if($project!==null){
3504
              $statistic->name =  $project->title;
3505
              }
3506
              } */
3507

    
3508
            $statistic->count = intval(trim($countNode->nodeValue));
3509
            $statistics[$statistic->id] = $statistic;
3510
        }
3511
        return $statistics;
3512
    }
3513

    
3514
    // Parse total results from a search service XML response.
3515
    // xpath the DOMXPath to parse
3516
    // return total results (integer)
3517
    private function parseTotalResults($xpath) {
3518
        if ((($totalNodes = $xpath->query('/response/header/total')) == FALSE) || (($totalNode = $totalNodes->item(0)) == NULL))
3519
            throw new Exception('error parsing total results');
3520
        return intval(trim($totalNode->nodeValue));
3521
    }
3522

    
3523
    // Parse publications from a search service XML response.
3524
    // xpath the DOMXPath to parse
3525
    // return results (array)
3526
    private function parseResults($ids,$xpath) {
3527
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
3528
            throw new Exception('error parsing results');
3529
        $publications = array();
3530
        foreach ($resultNodes as $resultNode) {
3531
            if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
3532
                throw new Exception('error parsing results');
3533
            if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
3534
                throw new Exception('error parsing publications');
3535
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
3536
                throw new Exception('error parsing results');
3537
            if (($subjectNodes = $xpath->query('./field[@name = "subject"]', $resultNode)) == FALSE)
3538
                throw new Exception('error parsing results');
3539
            if (($relatedNodes = $xpath->query('./field[@name = "related"]', $resultNode)) == FALSE)
3540
                throw new Exception('error parsing results');
3541
            if (($authorNodes = $xpath->query('./field[@name = "author"]', $resultNode)) == FALSE)
3542
                throw new Exception('error parsing results');
3543
            if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
3544
                throw new Exception('error parsing results');
3545
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
3546
                throw new Exception('error parsing results');
3547
            if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
3548
                throw new Exception('error parsing results');
3549
            if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
3550
                throw new Exception('error parsing results');
3551
            if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
3552
                throw new Exception('error parsing results');
3553
            if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
3554
                throw new Exception('error parsing results');
3555
            $publication = new JObject();
3556
           // $publication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3557
           // $first=$publication->id;
3558
             foreach($idNodes as $idNode){
3559
                 if (in_array(trim($idNode->nodeValue), $ids)) {
3560
                     $publication->id =trim($idNode->nodeValue);
3561
                }                   
3562
            }
3563
            $publication->source = 'openaire';
3564
            $publication->url = NULL;
3565
            $publication->accessMode = NULL;
3566
            $publication->datasources = array();
3567
            $publication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3568
            $publication->authors = array();
3569
            $publication->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
3570
            $publication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
3571
            $publication->language = (($languageNode = $languageNodes->item(0)) == NULL) ? NULL : trim($languageNode->nodeValue);
3572
            $publication->projects = array();
3573
            $publication->subjects = array();
3574
            $publication->related = array();
3575
            $publication->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
3576
            $publication->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
3577
            foreach ($subjectNodes as $subjectNode) {
3578
                if (($titleNodes = $xpath->query('./@value', $subjectNode)) == FALSE)
3579
                    throw new Exception('error parsing results');
3580
                if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $subjectNode)) == FALSE)
3581
                    throw new Exception('error parsing results');
3582
                if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $subjectNode)) == FALSE)
3583
                    throw new Exception('error parsing results');
3584
                if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $subjectNode)) == FALSE)
3585
                    throw new Exception('error parsing results');
3586
                $subject = new JObject();
3587
                $subject->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3588
                $subject->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
3589
                $subject->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
3590
                $subject->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
3591
                if (($subject->title != NULL) || ($subject->inferred != NULL) || ($subject->trust != NULL) || ($subject->provenance != NULL))
3592
                    $publication->subjects[] = $subject;
3593
            }
3594

    
3595
            foreach ($relatedNodes as $relatedNode) {
3596

    
3597
                if (($titleNodes = $xpath->query('./field[@name= "title"]/@value', $relatedNode)) == FALSE)
3598
                    throw new Exception('error parsing results');
3599
                if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
3600
                    throw new Exception('error parsing results');
3601
                if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
3602
                    throw new Exception('error parsing results');
3603
                if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
3604
                    throw new Exception('error parsing results');
3605
                $related = new JObject();
3606
                $related->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3607
                $related->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
3608
                $related->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
3609
                $related->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
3610
                if (($related->title != NULL) || ($related->inferred != NULL) || ($related->trust != NULL) || ($related->provenance != NULL))
3611
                    $publication->related[] = $related;
3612
            }
3613

    
3614
            foreach ($datasourceNodes as $datasourceNode) {
3615
                if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
3616
                    throw new Exception('error parsing results');
3617
                if (($accessModeNodes = $xpath->query('./field[@name = "licenceid"]/@value_original', $datasourceNode)) == FALSE)
3618
                    throw new Exception('error parsing results');
3619
                $datasource = new JObject();
3620
                $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
3621
                $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
3622
                if (($datasource->url != NULL) && ((($datasource->accessMode == self :: DATASOURCE_ACCESS_OPEN) && (($publication->accessMode == NULL) || ($publication->accessMode == self :: UNKNOWN) || ($publication->accessMode == self :: DATASOURCE_ACCESS_CLOSED) || ($publication->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED) || ($publication->accessMode == self :: DATASOURCE_ACCESS_EMBARGO))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_EMBARGO) && (($publication->accessMode == NULL) || ($publication->accessMode == self :: UNKNOWN) || ($publication->accessMode == self :: DATASOURCE_ACCESS_CLOSED) || ($publication->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED) && (($publication->accessMode == NULL) || ($publication->accessMode == self :: UNKNOWN) || ($publication->accessMode == self :: DATASOURCE_ACCESS_CLOSED))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_CLOSED) && (($publication->accessMode == NULL) || ($publication->accessMode == self :: UNKNOWN))) || (($datasource->accessMode == self :: UNKNOWN) && ($publication->accessMode == NULL)) || ((($datasource->accessMode == NULL) && ($publication->accessMode == NULL) && ($publication->url == NULL))))) {
3623
                    $publication->accessMode = $datasource->accessMode;
3624
                    $publication->url = $datasource->url;
3625
                }
3626
                if (($datasource->url != NULL) || ($datasource->accessMode != NULL))
3627
                    $publication->datasources[] = $datasource;
3628
            }
3629
            foreach ($authorNodes as $authorNode) {
3630
                if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
3631
                    throw new Exception('error parsing results');
3632
                if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
3633
                    throw new Exception('error parsing results');
3634
                if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
3635
                    throw new Exception('error parsing results');
3636
                $author = new JObject();
3637
                $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3638
                $author->lastName = NULL;
3639
                $author->firstName = NULL;
3640
                $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
3641
                $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
3642
                if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
3643
                    $publication->authors[] = $author;
3644
                usort($publication->authors, function ($author1, $author2) {
3645
                    return $author1->ranking - $author2->ranking;
3646
                });
3647
            }
3648
            foreach ($projectNodes as $projectNode) {
3649
                if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
3650
                    throw new Exception('error parsing results');
3651
                if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
3652
                    throw new Exception('error parsing results');
3653
                if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
3654
                    throw new Exception('error parsing results');
3655
                if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
3656
                    throw new Exception('error parsing results');
3657
                $project = new JObject();
3658
                $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3659
                $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
3660
                $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3661
                $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
3662
                if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
3663
                    $publication->projects[] = $project;
3664
            }
3665
            if (($publication->id != NULL) || ($publication->source != NULL) || ($publication->url != NULL) || ($publication->accessMode != NULL) || ($publication->datasources != NULL) || ($publication->title != NULL) || ($publication->authors != NULL) || ($publication->publisher != NULL) || ($publication->year != NULL) || ($publication->language != NULL) || ($publication->projects != NULL) || ($publication->embargoEndDate != NULL) || ($publication->description != NULL))
3666
                $publications[] = $publication;
3667
        }
3668
        return $publications;
3669
    }
3670

    
3671
    // Parse publications from a search service XML response.
3672
    // xpath the DOMXPath to parse
3673
    // return publications (array)
3674
    private function parsePublications($xpath) {        
3675
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
3676
            throw new Exception('error parsing publications');
3677
        $publications = array();
3678
        foreach ($resultNodes as $resultNode) {
3679
            if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
3680
                throw new Exception('error parsing publications');
3681
            if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
3682
                throw new Exception('error parsing publications');
3683
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
3684
                throw new Exception('error parsing publications');
3685
            if (($subjectNodes = $xpath->query('./field[@name = "subject"]', $resultNode)) == FALSE)
3686
                throw new Exception('error parsing publications');
3687
            if (($relatedNodes = $xpath->query('./field[@name = "related"]', $resultNode)) == FALSE)
3688
                throw new Exception('error parsing publications');
3689
            if (($authorNodes = $xpath->query('./field[@name = "hasAuthor"]', $resultNode)) == FALSE)
3690
                throw new Exception('error parsing publications');
3691
            if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
3692
                throw new Exception('error parsing publications');
3693
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
3694
                throw new Exception('error parsing publications');
3695
            if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
3696
                throw new Exception('error parsing publications');
3697
            if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
3698
                throw new Exception('error parsing publications');
3699
            if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
3700
                throw new Exception('error parsing publications');
3701
            if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
3702
                throw new Exception('error parsing publications');
3703
            if (($sourceNodes = $xpath->query('./field[@name = "source"]/@value', $resultNode)) == FALSE)
3704
                throw new Exception('error parsing publication');
3705
            if (($pidNodes = $xpath->query('./field[@name = "pid"]', $resultNode)) == FALSE)
3706
                throw new Exception('error parsing publication');
3707
            if (($accessModeNodes = $xpath->query('./field[@name = "bestlicense"]/@value', $resultNode)) == FALSE)
3708
                throw new Exception('error parsing publication');        
3709
            $publication = new JObject();
3710
            $publication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3711
            $publication->source = 'openaire';
3712
             foreach ($sourceNodes as $sourceNode) {
3713
                if (($source = trim($sourceNode->nodeValue)) != NULL){
3714
                     $publication->source_source = $source;
3715
                }
3716
            }          
3717
            $publication->url = NULL;
3718
            $publication->accessMode =(($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
3719
            $publication->datasources = array();
3720
            $publication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3721
            $publication->authors = array();
3722
            $publication->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
3723
            $publication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
3724
            $publication->language = (($languageNode = $languageNodes->item(0)) == NULL) ? NULL : trim($languageNode->nodeValue);
3725
            $publication->projects = array();
3726
            $publication->subjects = array();
3727
            $publication->related = array();                       
3728
            $publication->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
3729
            $publication->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
3730
            $publication->pids = array();
3731
            foreach ($pidNodes as $pidNode) {
3732
                if (($classNodes = $xpath->query('./field[@name = "classid"]/@value', $pidNode)) == FALSE)
3733
                    throw new Exception('error parsing publication');
3734
                if (($valueNodes = $xpath->query('./field[@name = "value"]/@value', $pidNode)) == FALSE)
3735
                    throw new Exception('error parsing publication');
3736
                $pid = new JObject();
3737
                $pid->clazz = (($classNode = $classNodes->item(0)) == NULL) ? NULL : trim($classNode->nodeValue);
3738
                $pid->value = (($valueNode = $valueNodes->item(0)) == NULL) ? NULL : trim($valueNode->nodeValue);
3739
                if (($pid->clazz != NULL) && ($pid->value != NULL))
3740
                    $publication->pids[] = $pid;
3741
            }
3742
            foreach ($subjectNodes as $subjectNode) {
3743
                if (($titleNodes = $xpath->query('./@value', $subjectNode)) == FALSE)
3744
                    throw new Exception('error parsing publications');
3745
                if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $subjectNode)) == FALSE)
3746
                    throw new Exception('error parsing publications');
3747
                if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $subjectNode)) == FALSE)
3748
                    throw new Exception('error parsing publications');
3749
                if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $subjectNode)) == FALSE)
3750
                    throw new Exception('error parsing publications');
3751
                $subject = new JObject();
3752
                $subject->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3753
                $subject->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
3754
                $subject->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
3755
                $subject->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
3756
                if (($subject->title != NULL) || ($subject->inferred != NULL) || ($subject->trust != NULL) || ($subject->provenance != NULL))
3757
                    $publication->subjects[] = $subject;
3758
            }
3759

    
3760
            foreach ($relatedNodes as $relatedNode) {
3761

    
3762
                if (($titleNodes = $xpath->query('./field[@name= "title"]/@value', $relatedNode)) == FALSE)
3763
                    throw new Exception('error parsing publications');
3764
                if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
3765
                    throw new Exception('error parsing publications');
3766
                if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
3767
                    throw new Exception('error parsing publications');
3768
                if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
3769
                    throw new Exception('error parsing publications');
3770
                $related = new JObject();
3771
                $related->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3772
                $related->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
3773
                $related->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
3774
                $related->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
3775
                if (($related->title != NULL) || ($related->inferred != NULL) || ($related->trust != NULL) || ($related->provenance != NULL))
3776
                    $publication->related[] = $related;
3777
            }
3778

    
3779
            foreach ($datasourceNodes as $datasourceNode) {
3780
                if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
3781
                    throw new Exception('error parsing publications');
3782
                if (($accessModeNodes = $xpath->query('./field[@name = "licenceid"]/@value_original', $datasourceNode)) == FALSE)
3783
                    throw new Exception('error parsing publications');
3784
                $datasource = new JObject();
3785
                $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
3786
                $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
3787
                if (($datasource->url != NULL) && ((($datasource->accessMode == self :: DATASOURCE_ACCESS_OPEN) && (($publication->accessMode == NULL) || ($publication->accessMode == self :: UNKNOWN) || ($publication->accessMode == self :: DATASOURCE_ACCESS_CLOSED) || ($publication->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED) || ($publication->accessMode == self :: DATASOURCE_ACCESS_EMBARGO))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_EMBARGO) && (($publication->accessMode == NULL) || ($publication->accessMode == self :: UNKNOWN) || ($publication->accessMode == self :: DATASOURCE_ACCESS_CLOSED) || ($publication->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED) && (($publication->accessMode == NULL) || ($publication->accessMode == self :: UNKNOWN) || ($publication->accessMode == self :: DATASOURCE_ACCESS_CLOSED))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_CLOSED) && (($publication->accessMode == NULL) || ($publication->accessMode == self :: UNKNOWN))) || (($datasource->accessMode == self :: UNKNOWN) && ($publication->accessMode == NULL)) || ((($datasource->accessMode == NULL) && ($publication->accessMode == NULL) && ($publication->url == NULL))))) {
3788
                    $publication->accessMode = $datasource->accessMode;
3789
                    $publication->url = $datasource->url;
3790
                }
3791
                if (($datasource->url != NULL) || ($datasource->accessMode != NULL))
3792
                    $publication->datasources[] = $datasource;
3793
            }
3794
            foreach ($authorNodes as $authorNode) {
3795
                if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
3796
                    throw new Exception('error parsing publications');
3797
                if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
3798
                    throw new Exception('error parsing publications');
3799
                if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
3800
                    throw new Exception('error parsing publications');
3801
                $author = new JObject();
3802
                $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3803
                $author->lastName = NULL;
3804
                $author->firstName = NULL;
3805
                $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
3806
                $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
3807
                if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
3808
                    $publication->authors[] = $author;
3809
                usort($publication->authors, function ($author1, $author2) {
3810
                    return $author1->ranking - $author2->ranking;
3811
                });
3812
            }
3813
            foreach ($projectNodes as $projectNode) {
3814
                if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
3815
                    throw new Exception('error parsing publications');
3816
                if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
3817
                    throw new Exception('error parsing publications');
3818
                if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
3819
                    throw new Exception('error parsing publications');
3820
                if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
3821
                    throw new Exception('error parsing publications');
3822
                if (($fundingNodes = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
3823
                    throw new Exception('error parsing publications');
3824
                $project = new JObject();
3825
                $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3826
                $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
3827
                $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3828
                $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
3829
                $project -> funder = NULL;                    
3830
                if (($fundingNode = $fundingNodes->item(0)) == NULL)
3831
                    ;
3832
                else {
3833
                    if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
3834
                        throw new Exception('error parsing project');                    
3835
                    $project -> funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
3836
                    if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
3837
                        throw new Exception('error parsing project');                    
3838
                    $project -> funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
3839
                }
3840
                if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
3841
                    $publication->projects[] = $project;
3842
            }
3843
            if (($publication->id != NULL) || ($publication->source != NULL) || ($publication->url != NULL) || ($publication->accessMode != NULL) || ($publication->datasources != NULL) || ($publication->title != NULL) || ($publication->authors != NULL) || ($publication->publisher != NULL) || ($publication->year != NULL) || ($publication->language != NULL) || ($publication->projects != NULL) || ($publication->embargoEndDate != NULL) || ($publication->description != NULL))
3844
                $publications[] = $publication;
3845
        }
3846
        return $publications;
3847
    }
3848

    
3849
    // Parse datasets from a search service XML response.
3850
    // xpath the DOMXPath to parse
3851
    // return datasets (array)
3852
    private function parseDatasets($xpath) {
3853
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
3854
            throw new Exception('error parsing datasets');
3855
        $datasets = array();
3856
        foreach ($resultNodes as $resultNode) {
3857
            if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
3858
                throw new Exception('error parsing datasets');
3859
            if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
3860
                throw new Exception('error parsing datasets');
3861
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
3862
                throw new Exception('error parsing datasets');
3863
            if (($authorNodes = $xpath->query('./field[@name = "hasAuthor"]', $resultNode)) == FALSE)
3864
                throw new Exception('error parsing datasets');
3865
            if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
3866
                throw new Exception('error parsing datasets');
3867
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
3868
                throw new Exception('error parsing datasets');
3869
            if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
3870
                throw new Exception('error parsing datasets');
3871
            if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
3872
                throw new Exception('error parsing datasets');
3873
            if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
3874
                throw new Exception('error parsing datasets');
3875
            if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
3876
                throw new Exception('error parsing datasets');
3877
            $dataset = new JObject();
3878
            $dataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3879
            $dataset->source = 'openaire';
3880
            $dataset->url = NULL;
3881
            $dataset->accessMode = NULL;
3882
            $dataset->datasources = array();
3883
            $dataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3884
            $dataset->authors = array();
3885
            $dataset->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
3886
            $dataset->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
3887
            $dataset->language = (($languageNode = $languageNodes->item(0)) == NULL) ? NULL : trim($languageNode->nodeValue);
3888
            $dataset->projects = array();
3889
            $dataset->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
3890
            $dataset->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
3891
            foreach ($datasourceNodes as $datasourceNode) {
3892
                if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
3893
                    throw new Exception('error parsing datasets');
3894
                if (($accessModeNodes = $xpath->query('./field[@name = "licenceid"]/@value_original', $datasourceNode)) == FALSE)
3895
                    throw new Exception('error parsing datasets');
3896
                $datasource = new JObject();
3897
                $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
3898
                $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
3899
                if (($datasource->url != NULL) && ((($datasource->accessMode == self :: DATASOURCE_ACCESS_OPEN) && (($dataset->accessMode == NULL) || ($dataset->accessMode == self :: UNKNOWN) || ($dataset->accessMode == self :: DATASOURCE_ACCESS_CLOSED) || ($dataset->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED) || ($dataset->accessMode == self :: DATASOURCE_ACCESS_EMBARGO))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_EMBARGO) && (($dataset->accessMode == NULL) || ($dataset->accessMode == self :: UNKNOWN) || ($dataset->accessMode == self :: DATASOURCE_ACCESS_CLOSED) || ($dataset->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED) && (($dataset->accessMode == NULL) || ($dataset->accessMode == self :: UNKNOWN) || ($dataset->accessMode == self :: DATASOURCE_ACCESS_CLOSED))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_CLOSED) && (($dataset->accessMode == NULL) || ($dataset->accessMode == self :: UNKNOWN))) || (($datasource->accessMode == self :: UNKNOWN) && ($dataset->accessMode == NULL)) || ((($datasource->accessMode == NULL) && ($dataset->accessMode == NULL) && ($dataset->url == NULL))))) {
3900
                    $dataset->accessMode = $datasource->accessMode;
3901
                    $dataset->url = $datasource->url;
3902
                }
3903
                if (($datasource->url != NULL) || ($datasource->accessMode != NULL))
3904
                    $dataset->datasources[] = $datasource;
3905
            }
3906
            foreach ($authorNodes as $authorNode) {
3907
                if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
3908
                    throw new Exception('error parsing datasets');
3909
                if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
3910
                    throw new Exception('error parsing datasets');
3911
                if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
3912
                    throw new Exception('error parsing datasets');
3913
                $author = new JObject();
3914
                $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3915
                $author->lastName = NULL;
3916
                $author->firstName = NULL;
3917
                $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
3918
                $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
3919
                if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
3920
                    $dataset->authors[] = $author;
3921
                usort($dataset->authors, function ($author1, $author2) {
3922
                    return $author1->ranking - $author2->ranking;
3923
                });
3924
            }
3925
            foreach ($projectNodes as $projectNode) {
3926
                if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
3927
                    throw new Exception('error parsing datasets');
3928
                if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
3929
                    throw new Exception('error parsing datasets');
3930
                if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
3931
                    throw new Exception('error parsing datasets');
3932
                if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
3933
                    throw new Exception('error parsing datasets');
3934
                 if (($fundingNodes = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
3935
                    throw new Exception('error parsing datasets');
3936
                $project = new JObject();
3937
                $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3938
                $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
3939
                $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3940
                $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
3941
                if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
3942
                    $dataset->projects[] = $project;
3943
                  $project -> funder = NULL;                    
3944
                if (($fundingNode = $fundingNodes->item(0)) == NULL)
3945
                    ;
3946
                else {
3947
                    if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
3948
                        throw new Exception('error parsing datasets');                    
3949
                    $project -> funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
3950
                    if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
3951
                        throw new Exception('error parsing datasets');                    
3952
                    $project -> funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
3953
                }
3954
            }
3955
            if (($dataset->id != NULL) || ($dataset->source != NULL) || ($dataset->url != NULL) || ($dataset->accessMode != NULL) || ($dataset->datasources != NULL) || ($dataset->title != NULL) || ($dataset->authors != NULL) || ($dataset->publisher != NULL) || ($dataset->year != NULL) || ($dataset->language != NULL) || ($dataset->projects != NULL) || ($dataset->embargoEndDate != NULL) || ($dataset->description != NULL))
3956
                $datasets[] = $dataset;
3957
        }
3958
        return $datasets;
3959
    }
3960

    
3961
    // Parse projects from a search service XML response.
3962
    // xpath the DOMXPath to parse
3963
    // return projects (array)
3964
    private function parseProjects($xpath) {
3965
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
3966
            throw new Exception('error parsing projects');
3967
        $projects = array();
3968
        foreach ($resultNodes as $resultNode) {
3969
            if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $resultNode)) == FALSE)
3970
                throw new Exception('error parsing projects');
3971
            if (($acronymNodes = $xpath->query('./field[@name = "name"]/@value', $resultNode)) == FALSE)
3972
                throw new Exception('error parsing projects');
3973
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
3974
                throw new Exception('error parsing projects');
3975
            if (($codeNodes = $xpath->query('./field[@name = "code"]/@value', $resultNode)) == FALSE)
3976
                throw new Exception('error parsing projects');
3977
            if (($sc39Nodes = $xpath->query('./field[@name = "ec_sc39"]/@value', $resultNode)) == FALSE)
3978
                throw new Exception('error parsing projects');
3979
            if (($funderNodes = $xpath->query('./field[@name = "funder"]/field[@name = "fundershortname"]/@value', $resultNode)) == FALSE)            
3980
                throw new Exception('error parsing projects');
3981
            if (($startYearNodes = $xpath->query('./field[@name = "startyear"]/@value', $resultNode)) == FALSE)
3982
                throw new Exception('error parsing projects');
3983
            if (($endYearNodes = $xpath->query('./field[@name = "endyear"]/@value', $resultNode)) == FALSE)
3984
                throw new Exception('error parsing projects');
3985
            if (($organizationNodes = $xpath->query('./field[@name = "organization"]', $resultNode)) == FALSE)
3986
                throw new Exception('error parsing projects');
3987
            $project = new JObject();
3988
            $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3989
            $project->acronym = ((($acronymNode = $acronymNodes->item(0)) == NULL) || (trim($acronymNode->nodeValue) == self :: UNKNOWN)) ? NULL : trim($acronymNode->nodeValue);
3990
            $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3991
            $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
3992
            $project->sc39 = (($sc39Node = $sc39Nodes->item(0)) == NULL) ? NULL : trim($sc39Node->nodeValue);
3993
            switch ($project->sc39) {
3994
                case 'true':
3995
                    $project->sc39 = TRUE;
3996
                    break;
3997
                case 'false':
3998
                    $project->sc39 = FALSE;
3999
                    break;
4000
                default:
4001
                    $project->sc39 = NULL;
4002
            }
4003
            $project->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
4004
            $project->startYear = (($startYearNode = $startYearNodes->item(0)) == NULL) ? NULL : intval(trim($startYearNode->nodeValue));
4005
            $project->endYear = (($endYearNode = $endYearNodes->item(0)) == NULL) ? NULL : intval(trim($endYearNode->nodeValue));
4006
            $project->organizations = array();
4007
            foreach ($organizationNodes as $organizationNode) {
4008
                if (($idNodes = $xpath->query('./field[@name = "organizationid"]/@value', $organizationNode)) == FALSE)
4009
                    throw new Exception('error parsing projects');
4010
                if (($shortNameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $organizationNode)) == FALSE)
4011
                    throw new Exception('error parsing projects');
4012
                if (($nameNodes = $xpath->query('./field[@name = "legalname"]/@value', $organizationNode)) == FALSE)
4013
                    throw new Exception('error parsing projects');
4014
                $organization = new JObject();
4015
                $organization->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4016
                $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
4017
                $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4018
                if (($organization->id != NULL) || ($organization->shortName != NULL) || ($organization->name != NULL))
4019
                    $project->organizations[] = $organization;
4020
            }
4021
            if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL) || ($project->sc39 != NULL) || ($project->funder != NULL) || ($project->startYear != NULL) || ($project->endYear != NULL) || ($project->organizations != NULL))
4022
                $projects[] = $project;
4023
        }
4024
        return $projects;
4025
    }
4026

    
4027
    // Parse people from a search service XML response.
4028
    // xpath the DOMXPath to parse
4029
    // return people (array)
4030
    private function parsePeople($xpath) {
4031
        if (($resultNodes = $xpath->query('/response/results/record')) == FALSE)
4032
            throw new Exception('error parsing people');
4033
        $people = array();
4034
        foreach ($resultNodes as $resultNode) {
4035
            if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $resultNode)) == FALSE)
4036
                throw new Exception('error parsing people');
4037
            if (($lastNameNodes = $xpath->query('./field[@name = "secondnames"]/@value', $resultNode)) == FALSE)
4038
                throw new Exception('error parsing people');
4039
            if (($firstNameNodes = $xpath->query('./field[@name = "firstname"]/@value', $resultNode)) == FALSE)
4040
                throw new Exception('error parsing people');
4041
            if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $resultNode)) == FALSE)
4042
                throw new Exception('error parsing people');
4043
            if (($countryNodes = $xpath->query('./field[@name = "nationalityid"]/@value', $resultNode)) == FALSE)
4044
                throw new Exception('error parsing people');
4045
            $person = new JObject();
4046
            $person->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4047
            $person->lastName = (($lastNameNode = $lastNameNodes->item(0)) == NULL) ? NULL : trim($lastNameNode->nodeValue);
4048
            $person->firstName = (($firstNameNode = $firstNameNodes->item(0)) == NULL) ? NULL : trim($firstNameNode->nodeValue);
4049
            $person->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
4050
            $person->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
4051
            if (($person->id != NULL) || ($person->lastName != NULL) || ($person->firstName != NULL) || ($person->fullName != NULL) || ($person->country != NULL))
4052
                $people[] = $person;
4053
        }
4054
        return $people;
4055
    }
4056

    
4057
    // Parse organizations from a search service XML response.
4058
    // xpath the DOMXPath to parse
4059
    // return organizations (array)
4060
    private function parseOrganizations($xpath) {
4061
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
4062
            throw new Exception('error parsing organizations');
4063
        $organizations = array();
4064
        foreach ($resultNodes as $resultNode) {
4065
            if (($idNodes = $xpath->query('./field[@name = "organizationId"]/@value', $resultNode)) == FALSE)
4066
                throw new Exception('error parsing organizations');
4067
            if (($shortNameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $resultNode)) == FALSE)
4068
                throw new Exception('error parsing organizations');
4069
            if (($nameNodes = $xpath->query('./field[@name = "legalname"]/@value', $resultNode)) == FALSE)
4070
                throw new Exception('error parsing organizations');
4071
            if (($countryNodes = $xpath->query('./field[@name = "countryname"]/@value', $resultNode)) == FALSE)
4072
                throw new Exception('error parsing organizations');
4073
            if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
4074
                throw new Exception('error parsing organizations');
4075
            $organization = new JObject();
4076
            $organization->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4077
            $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
4078
            $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4079
            $organization->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
4080
            $organization->projects = array();
4081
            foreach ($projectNodes as $projectNode) {
4082
                if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
4083
                    throw new Exception('error parsing organizations');
4084
                if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
4085
                    throw new Exception('error parsing organizations');
4086
                if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
4087
                    throw new Exception('error parsing organizations');
4088
                if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
4089
                    throw new Exception('error parsing organizations');
4090
                $project = new JObject();
4091
                $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4092
                $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
4093
                $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4094
                $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
4095
                if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
4096
                    $organization->projects[] = $project;
4097
            }
4098
            if (($organization->id != NULL) || ($organization->shortName != NULL) || ($organization->name != NULL) || ($organization->country != NULL) || ($organization->projects != NULL))
4099
                $organizations[] = $organization;
4100
        }
4101
        return $organizations;
4102
    }
4103

    
4104
    // Parse datasources from a search service XML response.
4105
    // xpath the DOMXPath to parse
4106
    // return datasources (array)
4107
    private function parseDatasources($xpath) {
4108
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
4109
            throw new Exception('error parsing datasources');
4110
        $datasources = array();
4111
        foreach ($resultNodes as $resultNode) {
4112
            if (($idNodes = $xpath->query('./field[@name = "datasourceId"]/@value', $resultNode)) == FALSE)
4113
                throw new Exception('error parsing datasources');
4114
            if (($typeNodes = $xpath->query('./field[@name = "datasourcetypeuiid"]/@value', $resultNode)) == FALSE)
4115
                throw new Exception('error parsing datasources');
4116
            if (($typeIdNodes = $xpath->query('./field[@name = "datasourcetypeuiid"]/@value_original', $resultNode)) == FALSE)
4117
                throw new Exception('error parsing datasources');
4118
            if (($compatibilityNodes = $xpath->query('./field[@name = "openairecompatibilityid"]/@value', $resultNode)) == FALSE)
4119
                throw new Exception('error parsing datasources');
4120
            if (($urlNodes = $xpath->query('./field[@name = "websiteurl"]/@value', $resultNode)) == FALSE)
4121
                throw new Exception('error parsing datasources');
4122
            if (($nameNodes = $xpath->query('./field[@name = "officialname"]/@value', $resultNode)) == FALSE)
4123
                throw new Exception('error parsing datasources');
4124
            if (($englishNameNodes = $xpath->query('./field[@name = "englishname"]/@value', $resultNode)) == FALSE)
4125
                throw new Exception('error parsing datasources');
4126
            if (($itemsNodes = $xpath->query('./field[@name = "odnumberofitems"]/@value', $resultNode)) == FALSE)
4127
                throw new Exception('error parsing datasources');
4128
            if (($dateNodes = $xpath->query('./field[@name = "odnumberofitemsdate"]/@value', $resultNode)) == FALSE)
4129
                throw new Exception('error parsing datasources');
4130
            if (($languageNodes = $xpath->query('./field[@name = "odlanguages"]/@value', $resultNode)) == FALSE)
4131
                throw new Exception('error parsing datasources');
4132
            if (($policyNodes = $xpath->query('./field[@name = "odpolicies"]/@value', $resultNode)) == FALSE)
4133
                throw new Exception('error parsing datasources');
4134
            if (($contentNodes = $xpath->query('./field[@name = "odcontenttypes"]/@value', $resultNode)) == FALSE)
4135
                throw new Exception('error parsing datasources');
4136
            if (($oaiPmhNodes = $xpath->query('./field[@name = "accessinfopackage"]/@value', $resultNode)) == FALSE)
4137
                throw new Exception('error parsing datasources');
4138
            if (($descriptionNodes = $xpath->query('./field[@name = "oddescription"]/@value', $resultNode)) == FALSE)
4139
                throw new Exception('error parsing datasources');
4140
            if (($organizationNodes = $xpath->query('./field[@name = "organization"]', $resultNode)) == FALSE)
4141
                throw new Exception('error parsing datasources');
4142
            $datasource = new JObject();
4143
            $datasource->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4144
            $datasource->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4145
            $datasource->typeId = (($typeIdNode = $typeIdNodes->item(0)) == NULL) ? NULL : trim($typeIdNode->nodeValue);
4146
            $datasource->compatibility = (($compatibilityNode = $compatibilityNodes->item(0)) == NULL) ? NULL : trim($compatibilityNode->nodeValue);
4147
            $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4148
            $datasource->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4149
            $datasource->englishName = (($englishNameNode = $englishNameNodes->item(0)) == NULL) ? NULL : trim($englishNameNode->nodeValue);
4150
            $datasource->items = (($itemsNode = $itemsNodes->item(0)) == NULL) ? NULL : intval(trim($itemsNode->nodeValue));
4151
            $datasource->date = (($dateNode = $dateNodes->item(0)) == NULL) ? NULL : strtotime(trim($dateNode->nodeValue));
4152
            $datasource->languages = array();
4153
            $datasource->policies = array();
4154
            $datasource->contents = array();
4155
            $datasource->oaiPmhUrls = array();
4156
            $datasource->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
4157
            $datasource->organizations = array();
4158
            foreach ($languageNodes as $languageNode) {
4159
                if (trim($languageNode->nodeValue) != NULL)
4160
                    $datasource->languages[] = trim($languageNode->nodeValue);
4161
            }
4162
            foreach ($policyNodes as $policyNode) {
4163
                if (trim($policyNode->nodeValue) != NULL)
4164
                    $datasource->policies[] = trim($policyNode->nodeValue);
4165
            }
4166
            foreach ($contentNodes as $contentNode) {
4167
                if (trim($contentNode->nodeValue) != NULL)
4168
                    $datasource->contents[] = trim($contentNode->nodeValue);
4169
            }
4170
            foreach ($oaiPmhNodes as $oaiPmhNode) {
4171
                if (trim($oaiPmhNode->nodeValue) != NULL)
4172
                    $datasource->oaiPmhUrls[] = trim($oaiPmhNode->nodeValue);
4173
            }
4174
            foreach ($organizationNodes as $organizationNode) {
4175
                if (($idNodes = $xpath->query('./field[@name = "organizationid"]/@value', $organizationNode)) == FALSE)
4176
                    throw new Exception('error parsing datasources');
4177
                if (($shortNameNodes = $xpath->query('./field[@name = "legalname"]/@value', $organizationNode)) == FALSE)
4178
                    throw new Exception('error parsing datasources');
4179
                if (($nameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $organizationNode)) == FALSE)
4180
                    throw new Exception('error parsing datasources');
4181
                if (($countryNodes = $xpath->query('./field[@name = "countryname"]/@value', $organizationNode)) == FALSE)
4182
                    throw new Exception('error parsing datasources');
4183
                $organization = new JObject();
4184
                $organization->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4185
                $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
4186
                $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4187
                $organization->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
4188
                if (($organization->id != NULL) || ($organization->shortName != NULL) || ($organization->name != NULL) || ($organization->country != NULL))
4189
                    $datasource->organizations[] = $organization;
4190
            }
4191
            if (($datasource->id != NULL) || ($datasource->type != NULL) || ($datasource->compatibility != NULL) || ($datasource->url != NULL) || ($datasource->name != NULL) || ($datasource->englishName != NULL) || ($datasource->items != NULL) || ($datasource->date != NULL) || ($datsource->languages != NULL) || ($datasource->policies != NULL) || ($datasource->contents != NULL) || ($datasource->oaiPmhUrls != NULL) || ($datasource->description != NULL) || ($datasource->organizations != NULL))
4192
                $datasources[] = $datasource;
4193
        }
4194
        return $datasources;
4195
    }
4196

    
4197
    // Parse a single publication from a search service XML response.
4198
    // xpath the DOMXPath to parse
4199
    // return publication (object)
4200
    private function parsePublication($xpath, $locale) {
4201
        if ((($resultsNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL)) // result
4202
            throw new Exception('error parsing publication');
4203
        if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
4204
            throw new Exception('error parsing publication');
4205
        if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
4206
            throw new Exception('error parsing publication');
4207
        if (($curationNodes = $xpath->query('./field[@name = "underCuration"]/@value', $resultNode)) == FALSE)
4208
            throw new Exception('error parsing publication');
4209
        if (($authorNodes = $xpath->query('./field[@name = "hasAuthor"]', $resultNode)) == FALSE)
4210
            throw new Exception('error parsing publication');
4211
        if (($dateNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
4212
            throw new Exception('error parsing publication');
4213
        if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
4214
            throw new Exception('error parsing publication');
4215
        if (($journalNodes = $xpath->query('./field[@name = "journal"]/@value', $resultNode)) == FALSE)
4216
            throw new Exception('error parsing publication');
4217
        if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
4218
            throw new Exception('error parsing publication');
4219
        if (($typeNodes = $xpath->query('./field[@name ="resulttypename"]/@value', $resultNode)) == FALSE)
4220
            throw new Exception('error parsing publication');
4221
        if (($subjectNodes = $xpath->query('./field[@name = "subject" and field[@name="inferred" and @value="false"]]', $resultNode)) == FALSE)
4222
            throw new Exception('error parsing publication');
4223
        if (($inferredSubjectNodes = $xpath->query('./field[@name = "subject" and field[@name="inferred" and @value="true"]]', $resultNode)) == FALSE)
4224
            throw new Exception('error parsing publication');
4225
        if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
4226
            throw new Exception('error parsing publication');
4227
        if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
4228
            throw new Exception('error parsing publication');
4229
        if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
4230
            throw new Exception('error parsing publication');
4231
        if (($collectedFromNodes = $xpath->query('./field[@name = "collectedfrom"]', $resultNode)) == FALSE)
4232
            throw new Exception('error parsing publication');
4233
        if (($sourceNodes = $xpath->query('./field[@name = "source"]/@value', $resultNode)) == FALSE)
4234
            throw new Exception('error parsing publication');
4235
        if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
4236
            throw new Exception('error parsing publication');
4237
        if (($pidNodes = $xpath->query('./field[@name = "pid"]', $resultNode)) == FALSE)
4238
            throw new Exception('error parsing publication');
4239
        if (($similarNodes = $xpath->query('./field[@name = "hasAmongTopNSimilarDocuments"]', $resultNode)) == FALSE)
4240
            throw new Exception('error parsing publication');
4241
        if (($relatedNodes = $xpath->query('./field[@name = "isRelatedTo"]', $resultNode)) == FALSE)
4242
            throw new Exception('error parsing publication');
4243
        if (($externalReferenceNodes = $xpath->query('./field[@name = "externalreference"]', $resultNode)) == FALSE)
4244
            throw new Exception('error parsing publication');
4245
        if (($contextNodes = $xpath->query('./field[@name = "context"]', $resultNode)) == FALSE)
4246
            throw new Exception('error parsing publication');
4247
        if (($citationNodes = $xpath->query('./field[@name = "citation"]', $resultNode)) == FALSE)
4248
            throw new Exception('error parsing publication');
4249
         if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
4250
            throw new Exception('error parsing publication');
4251
        $publication = new JObject();
4252
        $publication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4253
        $publication->source = 'openaire';
4254
        $publication->accessMode = NULL;
4255
        $publication->url = NULL;
4256
        $publication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4257
        $publication->underCuration = (($curationNode = $curationNodes->item(0)) == NULL) ? NULL : trim($curationNode->nodeValue);
4258
        $publication->authors = array();
4259
        $publication->year = (($dateNode = $dateNodes->item(0)) == NULL) ? NULL : intval(trim($dateNode->nodeValue));
4260
        $publication->date = ($dateNode == NULL) ? NULL : strtotime(trim($dateNode->nodeValue));
4261
        $publication->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
4262
        $publication->journal = (($journalNode = $journalNodes->item(0)) == NULL) ? NULL : trim($journalNode->nodeValue);
4263
        $publication->languages = array();
4264
        $publication->type = array();
4265
        $publication->subjects = array();
4266
        $publication->categorizedSubjects = array();
4267
        $publication->inferredSubjects = array();
4268
        $publication->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
4269
        $publication->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
4270
        $publication->datasources = array();
4271
        $publication->collectedFrom = array();
4272
        $publication->sources = array();
4273
        $publication->projects = array();
4274
        $publication->pids = array();
4275
        $publication->similarPublications = array();
4276
        $publication->relatedPublications = array();
4277
        $publication->relatedDatasets = array();
4278
        $publication->externalPublications = array();
4279
        $publication->bioentities = array();        
4280
        $publication->externalDatasets = array();
4281
        $publication->contexts = array();
4282
        $publication->citations = array();
4283
        foreach ($authorNodes as $authorNode) {
4284
            if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
4285
                throw new Exception('error parsing publication');
4286
            if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
4287
                throw new Exception('error parsing publication');
4288
            if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
4289
                throw new Exception('error parsing publication');
4290
            $author = new JObject();
4291
            $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4292
            $author->lastName = NULL;
4293
            $author->firstName = NULL;
4294
            $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
4295
            $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
4296
            if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
4297
                $publication->authors[] = $author;
4298
            usort($publication->authors, function ($author1, $author2) {
4299
                return $author1->ranking - $author2->ranking;
4300
            });
4301
        }
4302
        foreach ($languageNodes as $languageNode) {
4303
            if ((($language = trim($languageNode->nodeValue)) != NULL) && ($language != self :: UNDETERMINED))
4304
                $publication->languages[] = $language;
4305
        }
4306
        foreach ($subjectNodes as $subjectNode) {
4307
            if (($titleNodes = $xpath->query('./@value', $subjectNode)) == FALSE)
4308
                throw new Exception('error parsing publications');
4309
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $subjectNode)) == FALSE)
4310
                throw new Exception('error parsing publications');
4311
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $subjectNode)) == FALSE)
4312
                throw new Exception('error parsing publications');
4313
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $subjectNode)) == FALSE)
4314
                throw new Exception('error parsing publications');
4315
            if (($taxonomyNodes = $xpath->query('./field[@name = "taxonomy"]/@value', $subjectNode)) == FALSE)
4316
                throw new Exception('error parsing publications');
4317
            $subject = new JObject();
4318
            $subject->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4319
            $subject->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4320
            $subject->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4321
            $subject->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4322
            $subject->taxonomy = (($taxonomyNode = $taxonomyNodes->item(0)) == NULL) ? NULL : trim($taxonomyNode->nodeValue);
4323
            if (($subject->title != NULL) || ($subject->inferred != NULL) || ($subject->trust != NULL) || ($subject->provenance != NULL)){
4324
                if($subject->taxonomy != NULL && $subject->taxonomy != "keyword"){                    
4325
                    $publication->categorizedSubjects[$subject->taxonomy][] =  $subject;
4326
                }else {
4327
                    $publication->subjects[] = $subject;
4328
                }   
4329
                
4330
                   
4331
            }
4332
                
4333
        }
4334
        $inferredSubjectsTempArray = array();
4335
        foreach ($inferredSubjectNodes as $subjectNode) {
4336
            if (($titleNodes = $xpath->query('./@value', $subjectNode)) == FALSE)
4337
                throw new Exception('error parsing publications');
4338
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $subjectNode)) == FALSE)
4339
                throw new Exception('error parsing publications');
4340
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $subjectNode)) == FALSE)
4341
                throw new Exception('error parsing publications');
4342
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $subjectNode)) == FALSE)
4343
                throw new Exception('error parsing publications');
4344
            if (($taxonomyNodes = $xpath->query('./field[@name = "taxonomy"]/@value', $subjectNode)) == FALSE)
4345
                throw new Exception('error parsing publications');
4346

    
4347
            $subject = new JObject();
4348
            $subject->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4349
            $subject->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4350
            $subject->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4351
            $subject->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4352
            $subject->taxonomy = (($taxonomyNode = $taxonomyNodes->item(0)) == NULL) ? NULL : trim($taxonomyNode->nodeValue);
4353

    
4354
            if (($subject->title != NULL) || ($subject->inferred != NULL) || ($subject->trust != NULL) || ($subject->provenance != NULL) || ($subject->taxonomy != NULL)) {
4355
                $miniSubject = new JObject();
4356
                $miniSubject->title = $subject->title;
4357
                $miniSubject->trust = $subject->trust;
4358
                $inferredSubjectsTempArray[$subject->taxonomy][] = $miniSubject;
4359
            }
4360
        }
4361
        //Sort the subjects on trust
4362
        foreach ($inferredSubjectsTempArray as $taxonomyKey => $subjectsValues) {
4363
            usort($subjectsValues, function ($a, $b) {
4364
                if ($a->trust == $b->trust) {
4365
                    return 0;
4366
                }return ($a->trust > $b->trust) ? -1 : 1;
4367
            });
4368
            $publication->inferredSubjects[$taxonomyKey] = $subjectsValues;
4369
        }
4370

    
4371
        foreach ($datasourceNodes as $datasourceNode) {
4372
            if (($idNodes = $xpath->query('./field[@name = "hostedby"]/@value_original', $datasourceNode)) == FALSE)
4373
                throw new Exception('error parsing publication');
4374
            if (($nameNodes = $xpath->query('./field[@name = "hostedbyname"]/@value', $datasourceNode)) == FALSE)
4375
                throw new Exception('error parsing publication');
4376
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
4377
                throw new Exception('error parsing publication');
4378
            if (($accessModeNodes = $xpath->query('./field[@name = "licenceid"]/@value_original', $datasourceNode)) == FALSE)
4379
                throw new Exception('error parsing publication');
4380
            if (($typeNameNodes = $xpath->query('./field[@name = "typename"]/@value', $datasourceNode)) == FALSE)
4381
                throw new Exception('error parsing publication');
4382
            $datasource = new JObject();
4383
            $datasource->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4384
            $datasource->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4385
            $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4386
            $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
4387
            $datasource->type = (($typeNameNode = $typeNameNodes->item(0)) == NULL) ? NULL : trim($typeNameNode->nodeValue);
4388

    
4389
            if (($datasource->url != NULL) && ((($datasource->accessMode == self :: DATASOURCE_ACCESS_OPEN) && (($publication->accessMode == NULL) || ($publication->accessMode == self :: UNKNOWN) || ($publication->accessMode == self :: DATASOURCE_ACCESS_CLOSED) || ($publication->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED) || ($publication->accessMode == self :: DATASOURCE_ACCESS_EMBARGO))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_EMBARGO) && (($publication->accessMode == NULL) || ($publication->accessMode == self :: UNKNOWN) || ($publication->accessMode == self :: DATASOURCE_ACCESS_CLOSED) || ($publication->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED) && (($publication->accessMode == NULL) || ($publication->accessMode == self :: UNKNOWN) || ($publication->accessMode == self :: DATASOURCE_ACCESS_CLOSED))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_CLOSED) && (($publication->accessMode == NULL) || ($publication->accessMode == self :: UNKNOWN))) || (($datasource->accessMode == self :: UNKNOWN) && ($publication->accessMode == NULL)) || ((($datasource->accessMode == NULL) && ($publication->accessMode == NULL) && ($publication->url == NULL))))) {
4390
                $publication->accessMode = $datasource->accessMode;
4391
                $publication->url = $datasource->url;
4392

    
4393
                if (!in_array($datasource->type, $publication->type)) {
4394
                    array_push($publication->type, $datasource->type);
4395
                }
4396
            }
4397
            if (($datasource->id != NULL) || ($datasource->name != NULL) || ($datasource->url != NULL) || ($datasource->accessMode != NULL))
4398
                $publication->datasources[] = $datasource;
4399
        }
4400
        foreach ($collectedFromNodes as $collectedFromNode) {
4401
            if (($idNodes = $xpath->query('./field[@name = "collectedfromid"]/@value', $collectedFromNode)) == FALSE)
4402
                throw new Exception('error parsing publication');
4403
            if (($nameNodes = $xpath->query('./field[@name = "collectedfromname"]/@value', $collectedFromNode)) == FALSE)
4404
                throw new Exception('error parsing publication');
4405
            $collectedFrom = new JObject();
4406
            $collectedFrom->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4407
            $collectedFrom->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4408
            if (($collectedFrom->id != NULL) || ($collectedFrom->name != NULL))
4409
                $publication->collectedFrom[] = $collectedFrom;
4410
        }
4411
         foreach ($sourceNodes as $sourceNode) {
4412
            if (($source = trim($sourceNode->nodeValue)) != NULL)
4413
                $publication->sources[] = $source;               
4414
        }
4415
        foreach ($projectNodes as $projectNode) {
4416
            if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
4417
                throw new Exception('error parsing publication');
4418
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $projectNode)) == FALSE)
4419
                throw new Exception('error parsing publication');
4420
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $projectNode)) == FALSE)
4421
                throw new Exception('error parsing publication');
4422
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $projectNode)) == FALSE)
4423
                throw new Exception('error parsing publication');
4424
            if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
4425
                throw new Exception('error parsing publication');
4426
            if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
4427
                throw new Exception('error parsing publication');
4428
            if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
4429
                throw new Exception('error parsing publication');
4430
            if (($fundingNodes = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
4431
                throw new Exception('error parsing publication');
4432

    
4433

    
4434
            $project = new JObject();
4435
            $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4436
            $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
4437
            $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4438
            $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
4439
            $project->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4440
            $project->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4441
            $project->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4442
            /*   $project -> funding = new JObject();
4443
              if (($fundingNode = $fundingNodes -> item(0)) == NULL) ;
4444
              else
4445
              {
4446
              if (($funding0Nodes = $xpath -> query('./field[@name = "funding_level_0"]/@value', $fundingNode)) == FALSE)
4447
              throw new Exception('error parsing publication test');
4448
              $project -> funding->funding_level_0 = (($funding0Node = $funding0Nodes -> item(0)) == NULL) ? NULL : trim($funding0Node -> nodeValue);
4449
              } */
4450

    
4451
            $project->funding = new JObject();
4452
            $project->funding->funding_level_0 = NULL;
4453
            $project->funding->funding_level_1 = NULL;
4454
            $project->funding->funding_level_2 = NULL;
4455

    
4456
            if (($fundingNode = $fundingNodes->item(0)) == NULL)
4457
                ;
4458
            else {
4459
                 if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
4460
                    throw new Exception('error parsing project');
4461
                if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
4462
                    throw new Exception('error parsing project');
4463
                if (($funding0Nodes = $xpath->query('./field[@name = "funding_level_0"]', $fundingNode)) == FALSE)
4464
                    throw new Exception('error parsing project');
4465
                if (($funding1Nodes = $xpath->query('./field[@name = "funding_level_1"]', $fundingNode)) == FALSE)
4466
                    throw new Exception('error parsing project');
4467
                if (($funding2Nodes = $xpath->query('./field[@name = "funding_level_2"]', $fundingNode)) == FALSE)
4468
                    throw new Exception('error parsing project');
4469
            
4470
                $project->funding->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
4471
                $project->funding->funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
4472
                
4473
                if (($funding0Node = $funding0Nodes->item(0)) == NULL)
4474
                    ;
4475
                else {
4476
                    if (($funding0NameNodes = $xpath->query('./@value', $funding0Node)) == FALSE)
4477
                        throw new Exception('error parsing publication test');
4478
                    $project->funding->funding_level_0 = (($funding0NameNode = $funding0NameNodes->item(0)) == NULL) ? NULL : trim($funding0NameNode->nodeValue);
4479
                   // $array = explode("::", $project->funding->funding_level_0);
4480
                   // $project->funding->funding_level_0 = $array[sizeof($array) - 1];
4481
                }
4482
                if (($funding1Node = $funding1Nodes->item(0)) == NULL)
4483
                    ;
4484
                else {
4485
                    if (($funding1NameNodes = $xpath->query('./@value', $funding1Node)) == FALSE)
4486
                        throw new Exception('error parsing publication test');
4487
                    $project->funding->funding_level_1 = (($funding1NameNode = $funding1NameNodes->item(0)) == NULL) ? NULL : trim($funding1NameNode->nodeValue);
4488
                   // $array = explode("::", $project->funding->funding_level_1);
4489
                    //$project->funding->funding_level_1 = $array[sizeof($array) - 1];
4490
                }
4491
                if (($funding2Node = $funding2Nodes->item(0)) == NULL)
4492
                    ;
4493
                else {
4494
                    if (($funding2NameNodes = $xpath->query('./@valu', $funding2Node)) == FALSE)
4495
                        throw new Exception('error parsing publication test');
4496
                    $project->funding->funding_level_2 = (($funding2NameNode = $funding2NameNodes->item(0)) == NULL) ? NULL : trim($funding2NameNode->nodeValue);
4497
                   // $array = explode("::", $project->funding->funding_level_2);
4498
                   // $project->funding->funding_level_2 = $array[sizeof($array) - 1];
4499
                }
4500
            }
4501
            //!!!!
4502

    
4503
            if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
4504
                $publication->projects[] = $project;
4505
        }
4506
        foreach ($pidNodes as $pidNode) {
4507
            if (($classNodes = $xpath->query('./field[@name = "classid"]/@value', $pidNode)) == FALSE)
4508
                throw new Exception('error parsing publication');
4509
            if (($valueNodes = $xpath->query('./field[@name = "value"]/@value', $pidNode)) == FALSE)
4510
                throw new Exception('error parsing publication');
4511
            $pid = new JObject();
4512
            $pid->clazz = (($classNode = $classNodes->item(0)) == NULL) ? NULL : trim($classNode->nodeValue);
4513
            $pid->value = (($valueNode = $valueNodes->item(0)) == NULL) ? NULL : trim($valueNode->nodeValue);
4514
            if (($pid->clazz != NULL) && ($pid->value != NULL))
4515
                $publication->pids[] = $pid;
4516
        }
4517
        foreach ($similarNodes as $similarNode) {
4518
            if (($typeNodes = $xpath->query('./field[@name = "resulttypeid"]/@value', $similarNode)) == FALSE)
4519
                throw new Exception('error parsing publication');
4520
            if (($typeNameNodes = $xpath->query('./field[@name = "resulttypename"]/@value', $similarNode)) == FALSE)
4521
                throw new Exception('error parsing publication');
4522
            if (($idNodes = $xpath->query('./field[@name = "resultid"]/@value', $similarNode)) == FALSE)
4523
                throw new Exception('error parsing publication');
4524
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $similarNode)) == FALSE)
4525
                throw new Exception('error parsing publication');
4526
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $similarNode)) == FALSE)
4527
                throw new Exception('error parsing publication');
4528
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $similarNode)) == FALSE)
4529
                throw new Exception('error parsing publication');
4530
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $similarNode)) == FALSE)
4531
                throw new Exception('error parsing publication');
4532
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $similarNode)) == FALSE)
4533
                throw new Exception('error parsing publication');
4534
            if (($similarityNodes = $xpath->query('./field[@name = "similarity"]/@value', $similarNode)) == FALSE)
4535
                throw new Exception('error parsing publication');
4536

    
4537
            $similarPublication = new JObject();
4538
            $similarPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4539
            $similarPublication->source = 'openaire';
4540
            $similarPublication->url = NULL;
4541
            $similarPublication->accessMode = NULL;
4542
            $similarPublication->datasources = array();
4543
            $similarPublication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4544
            $similarPublication->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4545
            $similarPublication->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4546
            $similarPublication->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4547
            $similarPublication->authors = array();
4548
            $similarPublication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4549
            $similarPublication->projects = array();
4550
            $similarPublication->embargoEndDate = NULL;
4551
            $similarPublication->description = NULL;
4552
            $similarPublication->similarity = (($similarityNode = $similarityNodes->item(0)) == NULL) ? NULL : trim($similarityNode->nodeValue);
4553
            $similarPublication->similarity = number_format((float) $similarPublication->similarity, 2);
4554
            if (($similarPublication->id != NULL) || ($similarPublication->title != NULL) || ($similarPublication->year != NULL)) {
4555
                $publication->similarPublications[] = $similarPublication;
4556
            }
4557
        }
4558
        foreach ($relatedNodes as $relatedNode) {
4559
            if (($typeNodes = $xpath->query('./field[@name = "resulttypeid"]/@value', $relatedNode)) == FALSE)
4560
                throw new Exception('error parsing publication');
4561
            if (($idNodes = $xpath->query('./field[@name = "resultid"]/@value', $relatedNode)) == FALSE)
4562
                throw new Exception('error parsing publication');
4563
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
4564
                throw new Exception('error parsing publication');
4565
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
4566
                throw new Exception('error parsing publication');
4567
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
4568
                throw new Exception('error parsing publication');
4569
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $relatedNode)) == FALSE)
4570
                throw new Exception('error parsing publication');
4571
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $relatedNode)) == FALSE)
4572
                throw new Exception('error parsing publication');
4573
            switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
4574
                case self :: PUBLICATION:
4575
                    $relatedPublication = new JObject();
4576
                    $relatedPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4577
                    $relatedPublication->source = 'openaire';
4578
                    $relatedPublication->url = NULL;
4579
                    $relatedPublication->accessMode = NULL;
4580
                    $relatedPublication->datasources = array();
4581
                    $relatedPublication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4582
                    $relatedPublication->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4583
                    $relatedPublication->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4584
                    $relatedPublication->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4585
                    $relatedPublication->authors = array();
4586
                    $relatedPublication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4587
                    $relatedPublication->projects = array();
4588
                    $relatedPublication->embargoEndDate = NULL;
4589
                    $relatedPublication->description = NULL;
4590
                    if (($relatedPublication->id != NULL) || ($relatedPublication->title != NULL) || ($relatedPublication->year != NULL))
4591
                        $publication->relatedPublications[] = $relatedPublication;
4592
                    break;
4593
                case self :: DATASET:
4594
                    $relatedDataset = new JObject();
4595
                    $relatedDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4596
                    $relatedDataset->source = 'openaire';
4597
                    $relatedDataset->url = NULL;
4598
                    $relatedDataset->accessMode = NULL;
4599
                    $relatedDataset->datasources = array();
4600
                    $relatedDataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4601
                    $relatedDataset->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4602
                    $relatedDataset->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4603
                    $relatedDataset->trust = number_format((float) $relatedDataset->trust, 2);
4604
                    $relatedDataset->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4605
                    $relatedDataset->authors = array();
4606
                    $relatedDataset->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4607
                    $relatedDataset->projects = array();
4608
                    $relatedDataset->embargoEndDate = NULL;
4609
                    $relatedDataset->description = NULL;
4610
                    if (($relatedDataset->id != NULL) || ($relatedDataset->title != NULL) || ($relatedDataset->year != NULL))
4611
                        $publication->relatedDatasets[] = $relatedDataset;
4612
                    break;
4613
            }
4614
        }
4615
        foreach ($externalReferenceNodes as $externalReferenceNode) {
4616
            if (($typeNodes = $xpath->query('./field[@name = "typeid"]/@value', $externalReferenceNode)) == FALSE)
4617
                throw new Exception('error parsing publication');
4618
            if (($idNodes = $xpath->query('./field[@name = "refidentifier"]/@value', $externalReferenceNode)) == FALSE)
4619
                throw new Exception('error parsing publication');
4620
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $externalReferenceNode)) == FALSE)
4621
                throw new Exception('error parsing publication');
4622
            if (($labelNodes = $xpath->query('./field[@name = "label"]/@value', $externalReferenceNode)) == FALSE)
4623
                throw new Exception('error parsing publication');
4624
            if (($siteNameNodes = $xpath->query('./field[@name = "sitename"]/@value', $externalReferenceNode)) == FALSE)
4625
                throw new Exception('error parsing publication');
4626
                    $externalEntity = new JObject();
4627
                    //dedup_wf_001::2cd206acf2cfd37f1a7c28823c63112b
4628
                    $externalEntity-> type = (($typeNode =$typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4629
                    $externalEntity-> id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4630
                    $externalEntity-> url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4631
                    $externalEntity-> title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
4632
                    $externalEntity-> sitename = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue); 
4633
                     if (!isset($publication->bioentities[$externalEntity->sitename])){
4634
                        $bioentities = array();  
4635
                        $publication->bioentities[$externalEntity->sitename]=$bioentities;
4636
                     }
4637
                     $publication->bioentities[$externalEntity->sitename] []= $externalEntity;
4638
                    
4639
           /* switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
4640
                case self :: PUBLICATION:
4641
                    $externalPublication = new JObject();
4642
                    $externalPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4643
                    $externalPublication->source = NULL;
4644
                    $externalPublication->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4645
                    $externalPublication->accessMode = NULL;
4646
                    $externalPublication->datasources = array();
4647
                    $externalPublication->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
4648
                    $externalPublication->authors = array();
4649
                    $site = new JObject();
4650
                    $site->id = NULL;
4651
                    $site->lastName = NULL;
4652
                    $site->firstName = NULL;
4653
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
4654
                    if ($site->fullName != NULL)
4655
                        $externalPublication->authors[] = $site;
4656
                    $externalPublication->year = NULL;
4657
                    $externalPublication->projects = array();
4658
                    $externalPublication->embargoEndDate = NULL;
4659
                    $externalPublication->description = NULL;
4660
                    if (($externalPublication->id != NULL) || ($externalPublication->url != NULL) || ($externalPublication->title != NULL))
4661
                        $publication->externalPublications[] = $externalPublication;
4662
                    break;
4663
                case self :: DATASET:
4664
                    $externalDataset = new JObject();
4665
                    $externalDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4666
                    $externalDataset->source = NULL;
4667
                    $externalDataset->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4668
                    $externalDataset->accessMode = NULL;
4669
                    $externalDataset->datasources = array();
4670
                    $externalDataset->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
4671
                    $externalDataset->authors = array();
4672
                    $site = new JObject();
4673
                    $site->id = NULL;
4674
                    $site->lastName = NULL;
4675
                    $site->firstName = NULL;
4676
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
4677
                    if ($site->fullName != NULL)
4678
                        $externalDataset->authors[] = $site;
4679
                    $externalDataset->year = NULL;
4680
                    $externalDataset->projects = array();
4681
                    $externalDataset->embargoEndDate = NULL;
4682
                    $externalDataset->description = NULL;
4683
                    if (($externalDataset->id != NULL) || ($externalDataset->url != NULL) || ($externalDataset->title != NULL))
4684
                        $publication->externalDatasets[] = $externalDataset;
4685
            }*/
4686
        }
4687
        foreach ($contextNodes as $contextNode) {
4688
            if (($idNodes = $xpath->query('./@value', $contextNode)) == FALSE)
4689
                throw new Exception('error parsing publication');
4690
            if (($nameNodes = $xpath->query('./@value_original', $contextNode)) == FALSE)
4691
                throw new Exception('error parsing publication');
4692
            if (($typeNodes = $xpath->query('./field[@name = "contexttype"]/@value', $contextNode)) == FALSE)
4693
                throw new Exception('error parsing publication');
4694
            if (($categoryNodes = $xpath->query('./field[@name = "category"]', $contextNode)) == FALSE)
4695
                throw new Exception('error parsing publication');
4696
            $context = new JObject();
4697
            $context->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4698
            $context->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4699
            $context->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4700
            $context->categories = array();
4701
            foreach ($categoryNodes as $categoryNode) {
4702
                if (($idNodes = $xpath->query('./@value_original', $categoryNode)) == FALSE)
4703
                    throw new Exception('error parsing publication');
4704
                if (($nameNodes = $xpath->query('./@value', $categoryNode)) == FALSE)
4705
                    throw new Exception('error parsing publication');
4706
                if (($conceptNodes = $xpath->query('./field[@name = "concept"]', $categoryNode)) == FALSE)
4707
                    throw new Exception('error parsing publication');
4708
                $category = new JObject();
4709
                $category->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4710
                $category->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4711
                $category->concepts = array();
4712
                foreach ($conceptNodes as $conceptNode) {
4713
                    if (($idNodes = $xpath->query('./@value_original', $conceptNode)) == FALSE)
4714
                        throw new Exception('error parsing publication');
4715
                    if (($nameNodes = $xpath->query('./@value', $conceptNode)) == FALSE)
4716
                        throw new Exception('error parsing publication');
4717
                    $concept = new JObject();
4718
                    $concept->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4719
                    $concept->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4720
                    if (($concept->id != NULL) || ($concept->name != NULL))
4721
                        $category->concepts[] = $concept;
4722
                }
4723
                if (($category->id != NULL) || ($category->name != NULL) || ($category->concepts != NULL))
4724
                    $context->categories[] = $category;
4725
            }
4726
            if (($context->id != NULL) || ($context->name != NULL) || ($context->categories != NULL))
4727
                $publication->contexts[] = $context;
4728
        }
4729
        foreach ($citationNodes as $citationNode) {
4730
            if (($titleNodes = $xpath->query('./field[@name = "rawText"]/@value', $citationNode)) == FALSE)
4731
                throw new Exception('error parsing publications');
4732
            if (($idsNodes = $xpath->query('./field[@name = "citationId"]', $citationNode)) == FALSE)
4733
                throw new Exception('error parsing publications');
4734
            $citation = new JObject();
4735
            $citation->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4736
            $citation->ids = array();
4737
            foreach ($idsNodes as $citationIdNode) {
4738
                if (($idNodes = $xpath->query('./field[@name = "id"]/@value', $citationIdNode)) == FALSE)
4739
                    throw new Exception('error parsing publications');
4740
                if (($typeNodes = $xpath->query('./field[@name = "type"]/@value', $citationIdNode)) == FALSE)
4741
                    throw new Exception('error parsing publications');
4742
                if (($confidenceLevelNodes = $xpath->query('./field[@name = "confidenceLevel"]/@value', $citationIdNode)) == FALSE)
4743
                    throw new Exception('error parsing publications');
4744
                $ids = new JObject();
4745
                $ids->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4746
                $ids->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4747
                $ids->confidenceLevel = (($confidenceLevelNode = $confidenceLevelNodes->item(0)) == NULL) ? NULL : trim($confidenceLevelNode->nodeValue);
4748
                $citation->ids[] = $ids;
4749
            }
4750

    
4751
            $publication->citations[] = $citation;
4752
            /*  $subject -> inferred = (($inferredNode = $inferredNodes -> item(0)) == NULL) ? NULL : trim($inferredNode -> nodeValue)=="true"?true:false;
4753
              $subject -> trust = (($trustNode = $trustNodes -> item(0)) == NULL) ? NULL : trim($trustNode -> nodeValue);
4754
              $subject -> provenance = (($provenanceNode = $provenanceNodes -> item(0)) == NULL) ? NULL : trim($provenanceNode -> nodeValue);
4755
              $subject -> taxonomy = (($taxonomyNode = $taxonomyNodes -> item(0)) == NULL) ? NULL : trim($taxonomyNode -> nodeValue);
4756
             */
4757
        }
4758
        return $publication;
4759
    }
4760

    
4761
    // Parse a single dataset from a search service XML response.
4762
    // xpath the DOMXPath to parse
4763
    // return dataset (object)
4764
    private function parseDataset($xpath, $locale) {
4765
        if ((($resultsNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL)) // result
4766
            throw new Exception('error parsing dataset');
4767
        if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
4768
            throw new Exception('error parsing dataset');
4769
        if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
4770
            throw new Exception('error parsing dataset');
4771
        if (($authorNodes = $xpath->query('./field[@name = "hasAuthor"]', $resultNode)) == FALSE)
4772
            throw new Exception('error parsing dataset');
4773
        if (($dateNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
4774
            throw new Exception('error parsing dataset');
4775
        if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
4776
            throw new Exception('error parsing dataset');
4777
        if (($journalNodes = $xpath->query('./field[@name = "journal"]/@value', $resultNode)) == FALSE)
4778
            throw new Exception('error parsing dataset');
4779
        if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
4780
            throw new Exception('error parsing dataset');
4781
        if (($typeNodes = $xpath->query('./field[@name ="resulttypename"]/@value', $resultNode)) == FALSE)
4782
            throw new Exception('error parsing dataset');
4783
        if (($subjectNodes = $xpath->query('./field[@name = "subject"]/@value', $resultNode)) == FALSE)
4784
            throw new Exception('error parsing dataset');
4785
        if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
4786
            throw new Exception('error parsing dataset');
4787
        if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
4788
            throw new Exception('error parsing dataset');
4789
        if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
4790
            throw new Exception('error parsing dataset');
4791
        if (($collectedFromNodes = $xpath->query('./field[@name = "collectedfrom"]', $resultNode)) == FALSE)
4792
            throw new Exception('error parsing dataset');
4793
        if (($sourceNodes = $xpath->query('./field[@name = "source"]/@value', $resultNode)) == FALSE)
4794
            throw new Exception('error parsing dataset');
4795
        if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
4796
            throw new Exception('error parsing dataset');
4797
        if (($pidNodes = $xpath->query('./field[@name = "pid"]', $resultNode)) == FALSE)
4798
            throw new Exception('error parsing dataset');
4799
        if (($relatedNodes = $xpath->query('./field[@name = "isRelatedTo"]', $resultNode)) == FALSE)
4800
            throw new Exception('error parsing dataset');
4801
        if (($externalReferenceNodes = $xpath->query('./field[@name = "externalreference"]', $resultNode)) == FALSE)
4802
            throw new Exception('error parsing dataset');
4803
        if (($contextNodes = $xpath->query('./field[@name = "context"]', $resultNode)) == FALSE)
4804
            throw new Exception('error parsing dataset');
4805
        $dataset = new JObject();
4806
        $dataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4807
        $dataset->source = 'openaire';
4808
        $dataset->accessMode = NULL;
4809
        $dataset->url = NULL;
4810
        $dataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4811
        $dataset->authors = array();
4812
        $dataset->year = (($dateNode = $dateNodes->item(0)) == NULL) ? NULL : intval(trim($dateNode->nodeValue));
4813
        $dataset->date = ($dateNode == NULL) ? NULL : strtotime(trim($dateNode->nodeValue));
4814
        $dataset->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
4815
        $dataset->journal = (($journalNode = $journalNodes->item(0)) == NULL) ? NULL : trim($journalNode->nodeValue);
4816
        $dataset->languages = array();
4817
        $dataset->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4818
        $dataset->subjects = array();
4819
        $dataset->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
4820
        $dataset->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
4821
        $dataset->datasources = array();
4822
        $dataset->collectedFrom = array();
4823
        $dataset->sources = array();
4824
        $dataset->projects = array();
4825
        $dataset->pids = array();
4826
        $dataset->relatedPublications = array();
4827
        $dataset->relatedDatasets = array();
4828
        $dataset->externalPublications = array();
4829
        $dataset->externalDatasets = array();
4830
        $dataset->contexts = array();
4831
        foreach ($authorNodes as $authorNode) {
4832
            if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
4833
                throw new Exception('error parsing dataset');
4834
            if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
4835
                throw new Exception('error parsing dataset');
4836
            if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
4837
                throw new Exception('error parsing publication');
4838
            $author = new JObject();
4839
            $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4840
            $author->lastName = NULL;
4841
            $author->firstName = NULL;
4842
            $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
4843
            $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
4844
            if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
4845
                $dataset->authors[] = $author;
4846
            usort($dataset->authors, function ($author1, $author2) {
4847
                return $author1->ranking - $author2->ranking;
4848
            });
4849
        }
4850
        foreach ($languageNodes as $languageNode) {
4851
            if ((($language = trim($languageNode->nodeValue)) != NULL) && ($language != self :: UNDETERMINED))
4852
                $dataset->languages[] = $language;
4853
        }
4854
        foreach ($subjectNodes as $subjectNode) {
4855
            if (($subject = trim($subjectNode->nodeValue)) != NULL)
4856
                $dataset->subjects[] = $subject;
4857
        }
4858
        foreach ($datasourceNodes as $datasourceNode) {
4859
            if (($idNodes = $xpath->query('./field[@name = "hostedby"]/@value_original', $datasourceNode)) == FALSE)
4860
                throw new Exception('error parsing dataset');
4861
            if (($nameNodes = $xpath->query('./field[@name = "hostedby"]/@value', $datasourceNode)) == FALSE)
4862
                throw new Exception('error parsing dataset');
4863
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
4864
                throw new Exception('error parsing dataset');
4865
            if (($accessModeNodes = $xpath->query('./field[@name = "licenceid"]/@value_original', $datasourceNode)) == FALSE)
4866
                throw new Exception('error parsing dataset');
4867
            $datasource = new JObject();
4868
            $datasource->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4869
            $datasource->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4870
            $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4871
// TODO
4872
            if (substr($datasource->url, 0, strlen('http://dx.doi.org/http://zenodo.org/record/')) == 'http://dx.doi.org/http://zenodo.org/record/') {
4873
                $url = substr($datasource->url, strlen('http://dx.doi.org/'));
4874
                JLog :: add('Converting datasource URL ' . $datasource->url . ' to ' . $url, JLog :: DEBUG, self :: LOG);
4875
                $datasource->url = $url;
4876
            }
4877
// TODO
4878
            $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
4879
            if (($datasource->url != NULL) && ((($datasource->accessMode == self :: DATASOURCE_ACCESS_OPEN) && (($dataset->accessMode == NULL) || ($dataset->accessMode == self :: UNKNOWN) || ($dataset->accessMode == self :: DATASOURCE_ACCESS_CLOSED) || ($dataset->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED) || ($dataset->accessMode == self :: DATASOURCE_ACCESS_EMBARGO))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_EMBARGO) && (($dataset->accessMode == NULL) || ($dataset->accessMode == self :: UNKNOWN) || ($dataset->accessMode == self :: DATASOURCE_ACCESS_CLOSED) || ($dataset->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_RESTRICTED) && (($dataset->accessMode == NULL) || ($dataset->accessMode == self :: UNKNOWN) || ($dataset->accessMode == self :: DATASOURCE_ACCESS_CLOSED))) || (($datasource->accessMode == self :: DATASOURCE_ACCESS_CLOSED) && (($dataset->accessMode == NULL) || ($dataset->accessMode == self :: UNKNOWN))) || (($datasource->accessMode == self :: UNKNOWN) && ($dataset->accessMode == NULL)) || ((($datasource->accessMode == NULL) && ($dataset->accessMode == NULL) && ($dataset->url == NULL))))) {
4880
                $dataset->accessMode = $datasource->accessMode;
4881
                $dataset->url = $datasource->url;
4882
            }
4883
            if (($datasource->id != NULL) || ($datasource->name != NULL) || ($datasource->url != NULL) || ($datasource->accessMode != NULL))
4884
                $dataset->datasources[] = $datasource;
4885
        }
4886
        foreach ($collectedFromNodes as $collectedFromNode) {
4887
            if (($idNodes = $xpath->query('./field[@name = "collectedfromid"]/@value', $collectedFromNode)) == FALSE)
4888
                throw new Exception('error parsing dataset');
4889
            if (($nameNodes = $xpath->query('./field[@name = "collectedfromname"]/@value', $collectedFromNode)) == FALSE)
4890
                throw new Exception('error parsing dataset');            
4891
            $collectedFrom = new JObject();
4892
            $collectedFrom->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4893
            $collectedFrom->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4894
            if (($collectedFrom->id != NULL) || ($collectedFrom->name != NULL))
4895
                $dataset->collectedFrom[] = $collectedFrom;
4896
        }
4897
        foreach ($sourceNodes as $sourceNode) {
4898
            if (($source = trim($sourceNode->nodeValue)) != NULL)
4899
                $dataset->sources[] = $source;
4900
        }
4901
        foreach ($projectNodes as $projectNode) {
4902
            if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
4903
                throw new Exception('error parsing publication');
4904
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $projectNode)) == FALSE)
4905
                throw new Exception('error parsing publication');
4906
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $projectNode)) == FALSE)
4907
                throw new Exception('error parsing publication');
4908
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $projectNode)) == FALSE)
4909
                throw new Exception('error parsing publication');
4910
            if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
4911
                throw new Exception('error parsing publication');
4912
            if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
4913
                throw new Exception('error parsing publication');
4914
            if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
4915
                throw new Exception('error parsing publication');
4916
            if (($fundingNodes = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
4917
                throw new Exception('error parsing publication');
4918

    
4919

    
4920
            $project = new JObject();
4921
            $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4922
            $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
4923
            $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4924
            $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
4925
            $project->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4926
            $project->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4927
            $project->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4928
            /*   $project -> funding = new JObject();
4929
              if (($fundingNode = $fundingNodes -> item(0)) == NULL) ;
4930
              else
4931
              {
4932
              if (($funding0Nodes = $xpath -> query('./field[@name = "funding_level_0"]/@value', $fundingNode)) == FALSE)
4933
              throw new Exception('error parsing publication test');
4934
              $project -> funding->funding_level_0 = (($funding0Node = $funding0Nodes -> item(0)) == NULL) ? NULL : trim($funding0Node -> nodeValue);
4935
              } */
4936

    
4937
            $project->funding = new JObject();
4938
            $project->funding->funding_level_0 = NULL;
4939
            $project->funding->funding_level_1 = NULL;
4940
            $project->funding->funding_level_2 = NULL;
4941

    
4942
            if (($fundingNode = $fundingNodes->item(0)) == NULL)
4943
                ;
4944
            else {
4945
                if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
4946
                    throw new Exception('error parsing project');
4947
                if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
4948
                    throw new Exception('error parsing project');
4949
                if (($funding0Nodes = $xpath->query('./field[@name = "funding_level_0"]', $fundingNode)) == FALSE)
4950
                    throw new Exception('error parsing project');
4951
                if (($funding1Nodes = $xpath->query('./field[@name = "funding_level_1"]', $fundingNode)) == FALSE)
4952
                    throw new Exception('error parsing project');
4953
                if (($funding2Nodes = $xpath->query('./field[@name = "funding_level_2"]', $fundingNode)) == FALSE)
4954
                    throw new Exception('error parsing project');
4955
                $project->funding->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
4956
                $project->funding->funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
4957
                
4958
                if (($funding0Node = $funding0Nodes->item(0)) == NULL)
4959
                    ;
4960
                else {
4961
                    if (($funding0NameNodes = $xpath->query('./@value', $funding0Node)) == FALSE)
4962
                        throw new Exception('error parsing publication test');
4963
                    $project->funding->funding_level_0 = (($funding0NameNode = $funding0NameNodes->item(0)) == NULL) ? NULL : trim($funding0NameNode->nodeValue);
4964
                    //$array = explode("::", $project->funding->funding_level_0);
4965
                    //$project->funding->funding_level_0 = $array[sizeof($array) - 1];
4966
                }
4967
                if (($funding1Node = $funding1Nodes->item(0)) == NULL)
4968
                    ;
4969
                else {
4970
                    if (($funding1NameNodes = $xpath->query('./@value', $funding1Node)) == FALSE)
4971
                        throw new Exception('error parsing publication test');
4972
                    $project->funding->funding_level_1 = (($funding1NameNode = $funding1NameNodes->item(0)) == NULL) ? NULL : trim($funding1NameNode->nodeValue);
4973
                    //$array = explode("::", $project->funding->funding_level_1);
4974
                    //$project->funding->funding_level_1 = $array[sizeof($array) - 1];
4975
                }
4976
                if (($funding2Node = $funding2Nodes->item(0)) == NULL)
4977
                    ;
4978
                else {
4979
                    if (($funding2NameNodes = $xpath->query('./@value', $funding2Node)) == FALSE)
4980
                        throw new Exception('error parsing publication test');
4981
                    $project->funding->funding_level_2 = (($funding2NameNode = $funding2NameNodes->item(0)) == NULL) ? NULL : trim($funding2NameNode->nodeValue);
4982
                    //$array = explode("::", $project->funding->funding_level_2);
4983
                    //$project->funding->funding_level_2 = $array[sizeof($array) - 1];
4984
                }
4985
                /* 	if (($idNodes = $xpath -> query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
4986
                  throw new Exception('error parsing dataset');
4987
                  if (($acronymNodes = $xpath -> query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
4988
                  throw new Exception('error parsing dataset');
4989
                  if (($titleNodes = $xpath -> query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
4990
                  throw new Exception('error parsing dataset');
4991
                  if (($codeNodes = $xpath -> query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
4992
                  throw new Exception('error parsing dataset');
4993
                  $project = new JObject();
4994
                  $project -> id = (($idNode = $idNodes -> item(0)) == NULL) ? NULL : trim($idNode -> nodeValue);
4995
                  $project -> acronym = (($acronymNode = $acronymNodes -> item(0)) == NULL) ? NULL : ((trim($acronymNode -> nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode -> nodeValue));
4996
                  $project -> title = (($titleNode = $titleNodes -> item(0)) == NULL) ? NULL : trim($titleNode -> nodeValue);
4997
                  $project -> code = (($codeNode = $codeNodes -> item(0)) == NULL) ? NULL : trim($codeNode -> nodeValue);
4998

    
4999
                 */
5000
            }
5001
            if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
5002
                $dataset->projects[] = $project;
5003
        }
5004
        foreach ($pidNodes as $pidNode) {
5005
            if (($classNodes = $xpath->query('./field[@name = "classid"]/@value', $pidNode)) == FALSE)
5006
                throw new Exception('error parsing dataset');
5007
            if (($valueNodes = $xpath->query('./field[@name = "value"]/@value', $pidNode)) == FALSE)
5008
                throw new Exception('error parsing dataset');
5009
            $pid = new JObject();
5010
            $pid->clazz = (($classNode = $classNodes->item(0)) == NULL) ? NULL : trim($classNode->nodeValue);
5011
            $pid->value = (($valueNode = $valueNodes->item(0)) == NULL) ? NULL : trim($valueNode->nodeValue);
5012
            if (($pid->clazz != NULL) && ($pid->value != NULL))
5013
                $dataset->pids[] = $pid;
5014
        }
5015
        foreach ($relatedNodes as $relatedNode) {
5016
            if (($typeNodes = $xpath->query('./field[@name = "resulttypeid"]/@value', $relatedNode)) == FALSE)
5017
                throw new Exception('error parsing publication');
5018
            if (($idNodes = $xpath->query('./field[@name = "resultid"]/@value', $relatedNode)) == FALSE)
5019
                throw new Exception('error parsing publication');
5020
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
5021
                throw new Exception('error parsing publication');
5022
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
5023
                throw new Exception('error parsing publication');
5024
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
5025
                throw new Exception('error parsing publication');
5026
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $relatedNode)) == FALSE)
5027
                throw new Exception('error parsing publication');
5028
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $relatedNode)) == FALSE)
5029
                throw new Exception('error parsing publication');
5030
            switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
5031
                case self :: PUBLICATION:
5032
                    $relatedPublication = new JObject();
5033
                    $relatedPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5034
                    $relatedPublication->source = 'openaire';
5035
                    $relatedPublication->url = NULL;
5036
                    $relatedPublication->accessMode = NULL;
5037
                    $relatedPublication->datasources = array();
5038
                    $relatedPublication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
5039
                    $relatedPublication->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
5040
                    $relatedPublication->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
5041
                    $relatedPublication->trust = ($relatedPublication->trust != null) ? number_format((float) $relatedPublication->trust, 2) : 'NULL';
5042
                    $relatedPublication->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
5043
                    $relatedPublication->authors = array();
5044
                    $relatedPublication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
5045
                    $relatedPublication->projects = array();
5046
                    $relatedPublication->embargoEndDate = NULL;
5047
                    $relatedPublication->description = NULL;
5048
                    if (($relatedPublication->id != NULL) || ($relatedPublication->title != NULL) || ($relatedPublication->year != NULL))
5049
                        $dataset->relatedPublications[] = $relatedPublication;
5050
                    break;
5051
                case self :: DATASET:
5052
                    $relatedDataset = new JObject();
5053
                    $relatedDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5054
                    $relatedDataset->source = 'openaire';
5055
                    $relatedDataset->url = NULL;
5056
                    $relatedDataset->accessMode = NULL;
5057
                    $relatedDataset->datasources = array();
5058
                    $relatedDataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
5059
                    $relatedDataset->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
5060
                    $relatedDataset->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
5061
                    $relatedDataset->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
5062
                    $relatedDataset->authors = array();
5063
                    $relatedDataset->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
5064
                    $relatedDataset->projects = array();
5065
                    $relatedDataset->embargoEndDate = NULL;
5066
                    $relatedDataset->description = NULL;
5067
                    if (($relatedDataset->id != NULL) || ($relatedDataset->title != NULL) || ($relatedDataset->year != NULL))
5068
                        $dataset->relatedDatasets[] = $relatedDataset;
5069
                    break;
5070
            }
5071
        }
5072
        foreach ($externalReferenceNodes as $externalReferenceNode) {
5073
            if (($typeNodes = $xpath->query('./field[@name = "typeid"]/@value', $externalReferenceNode)) == FALSE)
5074
                throw new Exception('error parsing publication');
5075
            if (($idNodes = $xpath->query('./field[@name = "refidentifier"]/@value', $externalReferenceNode)) == FALSE)
5076
                throw new Exception('error parsing publication');
5077
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $externalReferenceNode)) == FALSE)
5078
                throw new Exception('error parsing publication');
5079
            if (($labelNodes = $xpath->query('./field[@name = "label"]/@value', $externalReferenceNode)) == FALSE)
5080
                throw new Exception('error parsing publication');
5081
            if (($siteNameNodes = $xpath->query('./field[@name = "sitename"]/@value', $externalReferenceNode)) == FALSE)
5082
                throw new Exception('error parsing publication');
5083
            switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
5084
                case self :: PUBLICATION:
5085
                    $externalPublication = new JObject();
5086
                    $externalPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5087
                    $externalPublication->source = NULL;
5088
                    $externalPublication->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5089
                    $externalPublication->accessMode = NULL;
5090
                    $externalPublication->datasources = array();
5091
                    $externalPublication->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
5092
                    $externalPublication->authors = array();
5093
                    $site = new JObject();
5094
                    $site->id = NULL;
5095
                    $site->lastName = NULL;
5096
                    $site->firstName = NULL;
5097
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
5098
                    if ($site->fullName != NULL)
5099
                        $externalPublication->authors[] = $site;
5100
                    $externalPublication->year = NULL;
5101
                    $externalPublication->projects = array();
5102
                    $externalPublication->embargoEndDate = NULL;
5103
                    $externalPublication->description = NULL;
5104
                    if (($externalPublication->id != NULL) || ($externalPublication->url != NULL) || ($externalPublication->title != NULL))
5105
                        $dataset->externalPublications[] = $externalPublication;
5106
                    break;
5107
                case self :: DATASET:
5108
                    $externalDataset = new JObject();
5109
                    $externalDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5110
                    $externalDataset->source = NULL;
5111
                    $externalDataset->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5112
                    $externalDataset->accessMode = NULL;
5113
                    $externalDataset->datasources = array();
5114
                    $externalDataset->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
5115
                    $externalDataset->authors = array();
5116
                    $site = new JObject();
5117
                    $site->id = NULL;
5118
                    $site->lastName = NULL;
5119
                    $site->firstName = NULL;
5120
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
5121
                    if ($site->fullName != NULL)
5122
                        $externalDataset->authors[] = $site;
5123
                    $externalDataset->year = NULL;
5124
                    $externalDataset->projects = array();
5125
                    $externalDataset->embargoEndDate = NULL;
5126
                    $externalDataset->description = NULL;
5127
                    if (($externalDataset->id != NULL) || ($externalDataset->url != NULL) || ($externalDataset->title != NULL))
5128
                        $dataset->externalDatasets[] = $externalDataset;
5129
            }
5130
        }
5131
        foreach ($contextNodes as $contextNode) {
5132
            if (($idNodes = $xpath->query('./@value', $contextNode)) == FALSE)
5133
                throw new Exception('error parsing dataset');
5134
            if (($nameNodes = $xpath->query('./@value_original', $contextNode)) == FALSE)
5135
                throw new Exception('error parsing dataset');
5136
            if (($categoryNodes = $xpath->query('./field[@name = "category"]', $contextNode)) == FALSE)
5137
                throw new Exception('error parsing dataset');
5138
            $context = new JObject();
5139
            $context->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5140
            $context->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5141
            $context->categories = array();
5142
            foreach ($categoryNodes as $categoryNode) {
5143
                if (($idNodes = $xpath->query('./@value', $categoryNode)) == FALSE)
5144
                    throw new Exception('error parsing dataset');
5145
                if (($nameNodes = $xpath->query('./@value_original', $categoryNode)) == FALSE)
5146
                    throw new Exception('error parsing dataset');
5147
                if (($conceptNodes = $xpath->query('./field[@name = "concept"]', $categoryNode)) == FALSE)
5148
                    throw new Exception('error parsing dataset');
5149
                $category = new JObject();
5150
                $category->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5151
                $category->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5152
                $category->concepts = array();
5153
                foreach ($conceptNodes as $conceptNode) {
5154
                    if (($idNodes = $xpath->query('./@value', $conceptNode)) == FALSE)
5155
                        throw new Exception('error parsing dataset');
5156
                    if (($nameNodes = $xpath->query('./@value_original', $conceptNode)) == FALSE)
5157
                        throw new Exception('error parsing dataset');
5158
                    $concept = new JObject();
5159
                    $concept->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5160
                    $concept->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5161
                    if (($concept->id != NULL) || ($concept->name != NULL))
5162
                        $category->concepts[] = $concept;
5163
                }
5164
                if (($category->id != NULL) || ($category->name != NULL) || ($category->concepts != NULL))
5165
                    $context->categories[] = $category;
5166
            }
5167
            if (($context->id != NULL) || ($context->name != NULL) || ($context->categories != NULL))
5168
                $dataset->contexts[] = $context;
5169
        }
5170
        return $dataset;
5171
    }
5172

    
5173
    // Parse a single project from a search service XML response.
5174
    // xpath the DOMXPath to parse
5175
    // return project (object)
5176
    private function parseProject($xpath) {
5177
        if ((($resultsNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL))
5178
            throw new Exception('error parsing project');
5179
        if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $resultNode)) == FALSE)
5180
                throw new Exception('error parsing projects');
5181
        if (($acronymNodes = $xpath->query('./field[@name = "name"]/@value', $resultNode)) == FALSE)
5182
            throw new Exception('error parsing project');
5183
        if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
5184
            throw new Exception('error parsing project');
5185
        if (($funderNodes = $xpath->query('./field[@name = "funder"]/field[@name = "fundershortname"]/@value', $resultNode)) == FALSE)
5186
            throw new Exception('error parsing project');
5187
        if (($fundingStreamNodes = $xpath->query('./field[@name = "funding_level_0"]/field[@name = "fundingname"]/@value', $resultNode)) == FALSE)
5188
            throw new Exception('error parsing project');
5189
        if (($scientificAreaNodes = $xpath->query('./field[@name = "funding_level_1"]/field[@name = "fundingname"]/@value', $resultNode)) == FALSE)
5190
            throw new Exception('error parsing project');
5191
         if (($fundingStreamLevel2Nodes = $xpath->query('./field[@name = "funding_level_2"]/field[@name = "fundingname"]/@value', $resultNode)) == FALSE)
5192
            throw new Exception('error parsing project');
5193
        if (($callNodes = $xpath->query('./field[@name = "call_identifier"]/@value', $resultNode)) == FALSE)
5194
            throw new Exception('error parsing project');
5195
        if (($codeNodes = $xpath->query('./field[@name = "code"]/@value', $resultNode)) == FALSE)
5196
            throw new Exception('error parsing project');
5197
        if (($startYearNodes = $xpath->query('./field[@name = "startyear"]/@value', $resultNode)) == FALSE)
5198
            throw new Exception('error parsing project');
5199
        if (($startDateNodes = $xpath->query('./field[@name = "startdate"]/@value', $resultNode)) == FALSE)
5200
            throw new Exception('error parsing project');
5201
        if (($endYearNodes = $xpath->query('./field[@name = "endyear"]/@value', $resultNode)) == FALSE)
5202
            throw new Exception('error parsing project');
5203
        if (($endDateNodes = $xpath->query('./field[@name = "enddate"]/@value', $resultNode)) == FALSE)
5204
            throw new Exception('error parsing project');
5205
        if (($sc39Nodes = $xpath->query('./field[@name = "ec_sc39"]/@value', $resultNode)) == FALSE)
5206
            throw new Exception('error parsing project');
5207
        if (($oaMandateNodes = $xpath->query('./field[@name = "oamandatepublications"]/@value', $resultNode)) == FALSE)
5208
            throw new Exception('error parsing project');
5209
        if (($datapilotNodes = $xpath->query('./field[@name = "ecarticle29_3"]/@value', $resultNode)) == FALSE)
5210
            throw new Exception('error parsing project');
5211
        if (($funding0Nodes = $xpath->query('./field[@name = "funding_level_0"]', $resultNode)) == FALSE)
5212
            throw new Exception('error parsing project');
5213
        if (($funding1Nodes = $xpath->query('./field[@name = "funding_level_1"]', $resultNode)) == FALSE)
5214
            throw new Exception('error parsing project');
5215
        if (($funding2Nodes = $xpath->query('./field[@name = "funding_level_2"]', $resultNode)) == FALSE)
5216
            throw new Exception('error parsing project');
5217
        if (($organizationNodes = $xpath->query('./field[@name = "organization"]', $resultNode)) == FALSE)
5218
            throw new Exception('error parsing project');
5219
        if (($urlNodes = $xpath->query('./field[@name = "websiteurl"]/@value', $resultNode)) == FALSE)
5220
            throw new Exception('error parsing datasources');
5221
        $project = new JObject();
5222
        $project->projectId = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5223
        $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
5224
        $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
5225
        $project->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5226
        $project->fundingStream = (($fundingStreamNode = $fundingStreamNodes->item(0)) == NULL) ? NULL : trim($fundingStreamNode->nodeValue);
5227
        $project->scientificArea = (($scientificAreaNode = $scientificAreaNodes->item(0)) == NULL) ? NULL : trim($scientificAreaNode->nodeValue);
5228
        $project->fundingStreamLevel2 = (($fundingStreamLevel2Node = $fundingStreamLevel2Nodes->item(0)) == NULL) ? NULL : trim($fundingStreamLevel2Node->nodeValue);
5229
        $project->call = (($callNode = $callNodes->item(0)) == NULL) ? NULL : trim($callNode->nodeValue);
5230
        $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
5231
        $project->startYear = (($startYearNode = $startYearNodes->item(0)) == NULL) ? NULL : intval(trim($startYearNode->nodeValue));
5232
        $project->startDate = (($startDateNode = $startDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($startDateNode->nodeValue));
5233
        $project->endYear = (($endYearNode = $endYearNodes->item(0)) == NULL) ? NULL : intval(trim($endYearNode->nodeValue));
5234
        $project->endDate = (($endDateNode = $endDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($endDateNode->nodeValue));
5235
        $project->sc39 = (($sc39Node = $sc39Nodes->item(0)) == NULL) ? NULL : trim($sc39Node->nodeValue);
5236
        switch ($project->sc39) {
5237
            case 'true':
5238
                $project->sc39 = TRUE;
5239
                break;
5240
            case 'false':
5241
                $project->sc39 = FALSE;
5242
                break;
5243
            default:
5244
                $project->sc39 = NULL;
5245
        }
5246
        $project->oaMandate = (($oaMandateNode = $oaMandateNodes->item(0)) == NULL) ? NULL : trim($oaMandateNode->nodeValue);
5247
        switch ($project->oaMandate) {
5248
            case 'true':
5249
                $project->oaMandate = TRUE;
5250
                break;
5251
            case 'false':
5252
                $project->oaMandate = FALSE;
5253
                break;
5254
            default:
5255
                $project->oaMandate = NULL;
5256
        }
5257
        $project->dataPilot = (($datapilotNode = $datapilotNodes->item(0)) == NULL) ? NULL : trim($datapilotNode->nodeValue);
5258
        switch ($project->dataPilot) {
5259
            case 'true':
5260
                $project->dataPilot = TRUE;
5261
                break;
5262
            case 'false':
5263
                $project->dataPilot = FALSE;
5264
                break;
5265
            default:
5266
                $project->dataPilot = NULL;
5267
        }
5268
        $project->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5269
        $project->funding = new JObject();
5270
        $project->funding->funding_level_0 = NULL;
5271
        $project->funding->funding_level_1 = NULL;
5272
        $project->funding->funding_level_2 = NULL;
5273
        if (($funding0Node = $funding0Nodes->item(0)) == NULL)
5274
            ;
5275
        else {
5276
            if (($funding0NameNodes = $xpath->query('./field[@name = "fundingname"]/@value', $funding0Node)) == FALSE)
5277
                throw new Exception('error parsing publication test');
5278
            $project->funding->funding_level_0 = (($funding0NameNode = $funding0NameNodes->item(0)) == NULL) ? NULL : trim($funding0NameNode->nodeValue);
5279
        }
5280
        if (($funding1Node = $funding1Nodes->item(0)) == NULL)
5281
            ;
5282
        else {
5283
            if (($funding1NameNodes = $xpath->query('./field[@name = "fundingname"]/@value', $funding1Node)) == FALSE)
5284
                throw new Exception('error parsing publication test');
5285
            $project->funding->funding_level_1 = (($funding1NameNode = $funding1NameNodes->item(0)) == NULL) ? NULL : trim($funding1NameNode->nodeValue);
5286
        }
5287
        if (($funding2Node = $funding2Nodes->item(0)) == NULL)
5288
            ;
5289
        else {
5290
            if (($funding2NameNodes = $xpath->query('./field[@name = "fundingname"]/@value', $funding2Node)) == FALSE)
5291
                throw new Exception('error parsing publication test');
5292
            $project->funding->funding_level_2 = (($funding2NameNode = $funding2NameNodes->item(0)) == NULL) ? NULL : trim($funding2NameNode->nodeValue);
5293
        }
5294
        $project->organizations = array();
5295
        foreach ($organizationNodes as $organizationNode) {
5296
            if (($idNodes = $xpath->query('./field[@name = "organizationid"]/@value', $organizationNode)) == FALSE)
5297
                throw new Exception('error parsing project');
5298
            if (($shortNameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $organizationNode)) == FALSE)
5299
                throw new Exception('error parsing project');
5300
            if (($nameNodes = $xpath->query('./field[@name = "legalname"]/@value', $organizationNode)) == FALSE)
5301
                throw new Exception('error parsing project');
5302
            $organization = new JObject();
5303
            $organization->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5304
            $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
5305
            $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5306
            if (($organization->id != NULL) || ($organization->shortName != NULL) || ($organization->name != NULL))
5307
                $project->organizations[] = $organization;
5308
        }
5309
        return $project;
5310
    }
5311

    
5312
    // Parse a single person from a search service XML response.
5313
    // xpath the DOMXPath to parse
5314
    // return person (object)
5315
    private function parsePerson($xpath) {
5316
        if ((($resultsNodes = $xpath->query('/response/results/record')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL))
5317
            throw new Exception('error parsing person');
5318
        if (($lastNameNodes = $xpath->query('./field[@name = "secondnames"]/@value', $resultNode)) == FALSE)
5319
            throw new Exception('error parsing person');
5320
        if (($firstNameNodes = $xpath->query('./field[@name = "firstname"]/@value', $resultNode)) == FALSE)
5321
            throw new Exception('error parsing person');
5322
        if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $resultNode)) == FALSE)
5323
            throw new Exception('error parsing person');
5324
        if (($countryNodes = $xpath->query('./field[@name = "nationalityname"]/@value', $resultNode)) == FALSE)
5325
            throw new Exception('error parsing person');
5326
        $person = new JObject();
5327
        $person->lastName = (($lastNameNode = $lastNameNodes->item(0)) == NULL) ? NULL : trim($lastNameNode->nodeValue);
5328
        $person->firstName = (($firstNameNode = $firstNameNodes->item(0)) == NULL) ? NULL : trim($firstNameNode->nodeValue);
5329
        $person->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
5330
        $person->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
5331
        return $person;
5332
    }
5333

    
5334
    // Parse a single organization from a search service XML response.
5335
    // xpath the DOMXPath to parse
5336
    // return organization (object)
5337
    private function parseOrganization($xpath) {
5338
        if ((($resultNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultNodes->item(0)) == NULL))
5339
            throw new Exception('error parsing organization');
5340
        if (($shortNameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $resultNode)) == FALSE)
5341
            throw new Exception('error parsing organization');
5342
        if (($nameNodes = $xpath->query('./field[@name = "legalname"]/@value', $resultNode)) == FALSE)
5343
            throw new Exception('error parsing organization');
5344
        if (($urlNodes = $xpath->query('./field[@name = "websiteurl"]/@value', $resultNode)) == FALSE)
5345
            throw new Exception('error parsing organization');
5346
        if (($countryNodes = $xpath->query('./field[@name = "countryname"]/@value', $resultNode)) == FALSE)
5347
            throw new Exception('error parsing organization');
5348
        if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
5349
            throw new Exception('error parsing organization');
5350
        $organization = new JObject();
5351
        $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
5352
        $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5353
        $organization->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5354
        $organization->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
5355
        $organization->projects = array();
5356
        $organization->allFunders=array();
5357
        foreach ($projectNodes as $projectNode) {
5358
            if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
5359
                throw new Exception('error parsing organization');
5360
            if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
5361
                throw new Exception('error parsing organization');
5362
            if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
5363
                throw new Exception('error parsing organization');
5364
            if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
5365
                throw new Exception('error parsing organization');
5366
            $project = new JObject();
5367
            $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5368
            $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
5369
            $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
5370
            $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
5371
            $project->funders = array();
5372
            if (($projectFunders = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
5373
                throw new Exception('error parsing organization');
5374
            foreach ($projectFunders as $projectFunder) {
5375
                $funder = new JObject();
5376
                if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $projectFunder)) == FALSE)
5377
                    throw new Exception('error parsing organization');
5378
                $funder->name=(($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5379
                if (($funderNodes = $xpath->query('./field[@name = "funderid"]/@value', $projectFunder)) == FALSE)
5380
                    throw new Exception('error parsing organization');
5381
                $funder->id=(($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5382
                if (($funderNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $projectFunder)) == FALSE)
5383
                    throw new Exception('error parsing organization');
5384
                $funder->shortname=(($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5385
                if($funder!=null){
5386
                    $organization->allFunders [$funder->id]=$funder;
5387
                    $project->funders [$funder->id]=$funder;
5388
                    
5389
                }
5390
              
5391
            }
5392
           $project->funders=array_unique($project->funders);
5393
            if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL)){
5394
                $organization->projects[] = $project;
5395
                //$organization->allFunders =array_merge($organization->allFunders,$project->funders);
5396
            }
5397
        }
5398
        //$organization->allFunders=array_unique($organization->allFunders);
5399
        return $organization;
5400
    }
5401

    
5402
    // Parse a single datasource from a search service XML response.
5403
    // xpath the DOMXPath to parse
5404
    // return datasource (object)
5405
    private function parseDatasource($xpath) {
5406
        if ((($resultsNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL))
5407
            throw new Exception('error parsing datasource');
5408
        if (($originalIdNodes = $xpath->query('./field[@name = "originalId"]/@value', $resultNode)) == FALSE)
5409
            throw new Exception('error parsing datasource');
5410
        if (($nameNodes = $xpath->query('./field[@name = "officialname"]/@value', $resultNode)) == FALSE)
5411
            throw new Exception('error parsing datasource');
5412
        if (($englishNameNodes = $xpath->query('./field[@name = "englishname"]/@value', $resultNode)) == FALSE)
5413
            throw new Exception('error parsing datasource');
5414
        if (($urlNodes = $xpath->query('./field[@name = "websiteurl"]/@value', $resultNode)) == FALSE)
5415
            throw new Exception('error parsing datasource');
5416
        if (($logoNodes = $xpath->query('./field[@name = "logourl"]/@value', $resultNode)) == FALSE)
5417
            throw new Exception('error parsing datasource');
5418
        if (($typeNodes = $xpath->query('./field[@name = "datasourcetypeuiid"]/@value', $resultNode)) == FALSE)
5419
            throw new Exception('error pasrsing datasource');
5420
        if (($itemsNodes = $xpath->query('./field[@name = "odnumberofitems"]/@value', $resultNode)) == FALSE)
5421
            throw new Exception('error parsing datasource');
5422
        if (($dateNodes = $xpath->query('./field[@name = "odnumberofitemsdate"]/@value', $resultNode)) == FALSE)
5423
            throw new Exception('error parsing datasource');
5424
        if (($subjectsNodes = $xpath->query('./field[@name = "odsubjects"]/@value', $resultNode)) == FALSE)
5425
            throw new Exception('error parsing datasource');
5426
        if (($languagesNodes = $xpath->query('./field[@name = "odlanguages"]/@value', $resultNode)) == FALSE)
5427
            throw new Exception('error parsing datasource');
5428
        if (($contentsNodes = $xpath->query('./field[@name = "odcontenttypes"]/@value', $resultNode)) == FALSE)
5429
            throw new Exception('error parsing datasource');
5430
        if (($policiesNodes = $xpath->query('./field[@name = "odpolicies"]/@value', $resultNode)) == FALSE)
5431
            throw new Exception('error parsing datasource');
5432
        if (($compatibilityNodes = $xpath->query('./field[@name = "openairecompatibilityid"]/@value', $resultNode)) == FALSE)
5433
            throw new Exception('error parsing datasource');
5434
        if (($oaiPmhNodes = $xpath->query('./field[@name = "accessinfopackage"]/@value', $resultNode)) == FALSE)
5435
            throw new Exception('error parsing datasources');
5436
        if (($descriptionNodes = $xpath->query('./field[@name = "oddescription"]/@value', $resultNode)) == FALSE)
5437
            throw new Exception('error parsing datasource');
5438
        $datasource = new JObject();
5439
        $datasource->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5440
        $datasource->englishName = (($englishNameNode = $englishNameNodes->item(0)) == NULL) ? NULL : trim($englishNameNode->nodeValue);
5441
        $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5442
        $datasource->logo = (($logoNode = $logoNodes->item(0)) == NULL) ? NULL : trim($logoNode->nodeValue);
5443
        $datasource->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
5444
        $datasource->items = (($itemsNode = $itemsNodes->item(0)) == NULL) ? NULL : intval(trim($itemsNode->nodeValue));
5445
        $datasource->date = (($dateNode = $dateNodes->item(0)) == NULL) ? NULL : strtotime(trim($dateNode->nodeValue));
5446
        $datasource->subjects = (($subjectsNode = $subjectsNodes->item(0)) == NULL) ? NULL : trim($subjectsNode->nodeValue);
5447
        $datasource->languages = (($languagesNode = $languagesNodes->item(0)) == NULL) ? NULL : trim($languagesNode->nodeValue);
5448
        $datasource->contents = (($contentsNode = $contentsNodes->item(0)) == NULL) ? NULL : trim($contentsNode->nodeValue);
5449
        $datasource->policies = (($policiesNode = $policiesNodes->item(0)) == NULL) ? NULL : trim($policiesNode->nodeValue);
5450
        $datasource->compatibility = (($compatibilityNode = $compatibilityNodes->item(0)) == NULL) ? NULL : trim($compatibilityNode->nodeValue);
5451
        $datasource->oaiPmh = (($oaiPmhNode = $oaiPmhNodes->item(0)) == NULL) ? NULL : trim($oaiPmhNode->nodeValue);
5452
        $datasource->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
5453
        $datasource->originalId = (($originalIdNode = $originalIdNodes->item(0)) == NULL) ? NULL : trim($originalIdNode->nodeValue);       
5454
        return $datasource;
5455
    }
5456
    private function createStatisticsForPublications($xpath,$filter =''){         
5457
        return $this->createStatistics($xpath, 
5458
                array('funder'.$filter, 'fundingStream'.$filter,  'fundingStreamLevel1'.$filter, 'fundingStreamLevel2'.$filter, 'project'.$filter, 'year'.$filter, 'accessMode'.$filter,  'type'.$filter, 'language'.$filter,'datasource'.$filter, 'community'.$filter), 
5459
                array( 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA','FUNDING_STREAM_LEVEL_2', 'PROJECT', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'DATASOURCE', 'COMMUNITY', 'COMMUNITY'), 
5460
                array( 'NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND','NO_FUNDING_STREAM_LEVEL2_STATISTICS_FOUND', 'NO_PROJECT_STATISTICS_FOUND', 'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND','NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND', 'NO_CONTEXT_STATISTICS_FOUND'), 
5461
                array(self :: PUBLICATION_FUNDER,self :: PUBLICATION_FUNDING_STREAM, self :: PUBLICATION_SCIENTIFIC_AREA, self::PUBLICATION_FUNDING_STREAM_LEVEL2, self :: PUBLICATION_PROJECT,self :: PUBLICATION_YEAR, self :: PUBLICATION_ACCESS_MODE, self :: PUBLICATION_TYPE, self :: PUBLICATION_LANGUAGE,   self :: PUBLICATION_DATASOURCE, self :: PUBLICATION_CONTEXT));        
5462
    }
5463
   private function createStatisticsForDatasets($xpath){     
5464
        return $this->createStatistics($xpath, 
5465
                array('funder', 'fundingStream', 'fundingStreamLevel1', 'fundingStreamLevel2', 'year', 'accessMode','type', 'language',  'datasource'), 
5466
                array( 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'FUNDING_STREAM_LEVEL_2',  'PUBLICATION_YEAR', 'ACCESS_MODE','TYPE', 'LANGUAGE', 'DATASOURCE'), 
5467
                array( 'NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_FUNDING_STREAM_LEVEL2_STATISTICS_FOUND', 'NO_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND','NO_TYPE_STATISTICS_FOUND', 'NO_LANGUAGE_STATISTICS_FOUND', 'NO_STATISTICS_FOUND'),
5468
                array( self :: DATASET_FUNDER, self :: DATASET_FUNDING_STREAM, self :: DATASET_SCIENTIFIC_AREA, self::DATASET_FUNDING_STREAM_LEVEL2, self :: DATASET_YEAR, self :: DATASET_ACCESS_MODE,self :: DATASET_TYPE, self :: DATASET_LANGUAGE, self :: DATASET_DATASOURCE));
5469

    
5470
    }    
5471
    private function createStatisticsForProjects($xpath, $filter =''){     
5472
        return $this->  createStatistics($xpath, 
5473
                array('funder'.$filter, 'fundingStream'.$filter, 'fundingStreamLevel1'.$filter, 'fundingStreamLevel2'.$filter ,  'startYear'.$filter, 'endYear'.$filter, 'sc39'.$filter), 
5474
                array('FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'FUNDING_STREAM_LEVEL_2', 'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'), 
5475
                array('NO_FUNDER_STATISTICS_FOUND', 'NO_FUNDING_STREAM_STATISTICS_FOUND', 'NO_SCIENTIFIC_AREA_STATISTICS_FOUND', 'NO_FUNDING_STREAM_LEVEL2_STATISTICS_FOUND',  'NO_START_YEAR_STATISTICS_FOUND', 'NO_END_YEAR_STATISTICS_FOUND', 'NO_SPECIAL_CLAUSE_39_STATISTICS_FOUND'), 
5476
                array(self :: PROJECT_FUNDER, self :: PROJECT_FUNDING_STREAM, self :: PROJECT_SCIENTIFIC_AREA, self::PROJECT_FUNDING_STREAM_LEVEL2, self :: PROJECT_START_YEAR, self :: PROJECT_END_YEAR, self :: PROJECT_SC39));
5477
            
5478
    }  
5479
    private function _validateResultsSize($size=10){
5480
        if($size > 50){
5481
            $size = 10;
5482
        }
5483
        return $size;
5484
    }
5485
  
5486
}
(7-7/9)