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 = 'instancetypename';
62
    const PUBLICATION_LANGUAGE = 'resultlanguagename';
63
    const PUBLICATION_CONTEXT = 'community';
64
    const PUBLICATION_FUNDER = 'relfunder';
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 RESULT_HOSTING_DATASOURCE = 'resulthostingdatasource';
71
    const RESULT_HOSTING_DATASOURCE_ID = 'resulthostingdatasourceid';
72
    const RESULT_COLLECTED_FROM_DATASOURCE = 'collectedfrom';
73
    const RESULT_COLLECTED_FROM_DATASOURCE_ID = 'collectedfromdatasourceid';
74
    const PUBLICATION_PROJECT = 'relproject';
75
    const PUBLICATION_PROJECT_ID = 'relprojectid';
76
    const PUBLICATION_AUTHOR_ID = 'relpersonid';
77
    const PUBLICATION_ARTICLE = '0001';
78
    const PUBLICATION_PREPRINT = '0016';
79
    const PUBLICATION_BOOK = '0002';
80
    const PUBLICATION_BOOK_PART = '0013';
81
    const PUBLICATION_PHD_THESIS = '0006';
82
    const PUBLICATION_MASTER_THESIS = '0007';
83
    const PUBLICATION_BACHELOR_THESIS = '0008';
84
    const PUBLICATION_REPORT = '0017';
85
    const PUBLICATION_INTERNAL_REPORT = '0011';
86
    const PUBLICATION_EXTERNAL_REPORT = '0009';
87
    const PUBLICATION_TITLE = 'resulttitle';
88
    const PUBLICATION_AUTHOR = 'relperson';
89
    const PUBLICATION_PUBLISHER = 'resultpublisher';
90
    const PUBLICATION_SUBJECT = 'resultsubject';
91
    const PUBLICATION_DATE = 'resultdateofacceptance';
92
    const PUBLICATION_ID = 'objIdentifier';
93
    const DATASET_QUERY = '(oaftype exact result) and (resulttypeid exact dataset)';
94
    const DATASET_TYPE = 'instancetypename';
95
    const DATASET_LANGUAGE = 'resultlanguagename';
96
    const DATASET_FUNDER = 'relfunder';
97
    const DATASET_FUNDING_STREAM = 'relfundinglevel0_id';
98
    const DATASET_SCIENTIFIC_AREA = 'relfundinglevel1_id';
99
    const DATASET_FUNDING_STREAM_LEVEL2 = 'relfundinglevel2_id';
100
    const DATASET_YEAR = 'resultacceptanceyear';
101
    const DATASET_ACCESS_MODE = 'resultbestlicense';
102
    const DATASET_PROJECT = 'relproject';
103
    const DATASET_PROJECT_ID = 'relprojectid';
104
    const DATASET_AUTHOR_ID = 'relpersonid';
105
    const DATASET_ID = 'objIdentifier';
106
    const PROJECT_QUERY = '(oaftype exact project)';
107
    const PROJECT = 'project';
108
    const PROJECT_FUNDER = 'funder';
109
    const PROJECT_FUNDING_STREAM = 'fundinglevel0_id';
110
    const PROJECT_SCIENTIFIC_AREA = 'fundinglevel1_id';
111
    const PROJECT_FUNDING_STREAM_LEVEL2 = 'fundinglevel2_id';
112
    const PROJECT_START_YEAR = 'projectstartyear';
113
    const PROJECT_END_YEAR = 'projectendyear';
114
    const PROJECT_SC39 = 'projectecsc39';
115
    const PROJECT_ACRONYM = 'projectacronym';
116
    const PROJECT_TITLE = 'projecttitle';
117
    const PROJECT_KEYWORDS = 'projectkeywords';
118
    const PROJECT_START_DATE = 'projectstartdate';
119
    const PROJECT_END_DATE = 'projectenddate';
120
    const PROJECT_ID = 'objIdentifier';
121
    const PROJECT_CODE = 'projectcode';
122
    const PERSON_QUERY = '(oaftype exact person)';
123
    // const PERSON_COUNTRY = 'personcountryid';
124
    const PERSON_LAST_NAME = 'personsecondnames';
125
    const PERSON_FIRST_NAME = 'personfirstname';
126
    const PERSON_FULL_NAME = 'personfullname';
127
    const PERSON_ID = 'objIdentifier';
128
    const ORGANIZATION_QUERY = '(oaftype exact organization)';
129
    const ORGANIZATION_QUERY_COMPATIBILITY = 'oaftype exact organization and
130
(reldatasourcecompatibilityid=driver or reldatasourcecompatibilityid=driver-openaire2.0 or
131
reldatasourcecompatibilityid=openaire2.0 or reldatasourcecompatibilityid=openaire3.0 or
132
reldatasourcecompatibilityid=openaire2.0_data or reldatasourcecompatibilityid=hostedBy
133
or relproject=*)';
134
    const ORGANIZATION_COUNTRY = 'organizationcountryname';
135
    const ORGANIZATION_LEGAL_BODY = 'organizationeclegalbody';
136
    const ORGANIZATION_LEGAL_PERSON = 'organizationeclegalperson';
137
    const ORGANIZATION_NON_PROFIT = 'organizationecnonprofit';
138
    const ORGANIZATION_RESEARCH = 'organizationecresearchorganization';
139
    const ORGANIZATION_EU_INTERESTS = 'organizationecinternationalorganizationeurinterests';
140
    const ORGANIZATION_INTERNATIONAL = 'organizationecinternationalorganization';
141
    const ORGANIZATION_ENTERPRISE = 'organizationecenterprise';
142
    const ORGANIZATION_SMALL_MEDIUM_ENTERPRISE = 'organizationecsmevalidated';
143
    const ORGANIZATION_NAME = 'organizationlegalname';
144
    const ORGANIZATION_SHORT_NAME = 'organizationlegalshortname';
145
    const ORGANIZATION_ID = 'objIdentifier';
146
//    const DATASOURCE_QUERY = '(oaftype exact datasource) and (datasourcecompatibilityid <> "UNKNOWN") and (datasourcecompatibilityid <> "hostedBy")';
147
    const DATASOURCE_QUERY = '(oaftype exact datasource) and (datasourcecompatibilityid <> "UNKNOWN")';
148
    const DATASOURCE_QUERY_COMPATIBILITY = '(oaftype exact datasource)';
149
    const DATASOURCE_TYPE = 'datasourcetypeuiname';
150
    const DATASOURCE_LANGUAGE = 'datasourceodlanguages';
151
    const DATASOURCE_CONTENT = 'datasourceodcontenttypes';
152
    const DATASOURCE_COMPATIBILITY = 'datasourcecompatibilityname';
153
    const DATASOURCE_NAME = 'datasourceofficialname';
154
    const DATASOURCE_ENGLISH_NAME = 'datasourceenglishname';
155
    const DATASOURCE_SUBJECT = 'datasourceodsubjects';
156
    const DATASOURCE_ORGANIZATION = 'relorganizationid';
157
    const DATASOURCE_ID = 'objIdentifier';
158
    const DATASOURCE_COMPATIBILITY_NOT_COMPATIBLE = 'notCompatible';
159
    const DATASOURCE_ACCESS_OPEN = 'OPEN';
160
    const DATASOURCE_ACCESS_EMBARGO = 'EMBARGO';
161
    const DATASOURCE_ACCESS_RESTRICTED = 'RESTRICTED';
162
    const DATASOURCE_ACCESS_CLOSED = 'CLOSED';
163
    const UNKNOWN = 'UNKNOWN';
164
    const UNDETERMINED = 'Undetermined';
165
    const PUBLICATION = 'publication';
166
    const DATASET = 'dataset';
167
    const HTTP_OK = 200;
168

    
169
    private $searchService;
170
    private $publicationStatisticsExistUrl;
171
    private $publicationStatisticsChartUrl;
172
    private $datasourceStatisticsExistUrl;
173
    private $datasourceStatisticsChartUrl;
174
    private $projectStatisticsChartUrl;
175
    private $cache;
176
    private $http;
177

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1047
    // Perform a quick search for organizations, searching only by name or short name and using cache if enabled.
1048
    // $keyword the keyword to search for
1049
    // $limit the maximum number of results to retrieve
1050
    // $locale the locale to use
1051
    // return organizations (array) or NULL if any errors occur
1052
    public function quickSearchOrganizations($keyword, $limit, $locale) {
1053
        JLog :: add('Keyword \'' . $keyword . '\'', JLog :: INFO, self :: LOG);
1054
        if ($this->cache->getCaching()) {
1055
            $cacheId = self :: QUICK_SEARCH_ORGANIZATIONS_CACHE_ID . '.' . $keyword . '.' . $limit . '.' . $locale;
1056
            $organizations = $this->cache->get($cacheId, self :: CACHE_GROUP);
1057
            if ($organizations === FALSE) {
1058
                $organizations = $this->_quickSearchOrganizations($keyword, $limit, $locale);
1059
                if ($organizations !== NULL)
1060
                    $this->cache->store($organizations, $cacheId, self :: CACHE_GROUP);
1061
            }
1062
        } else
1063
            $organizations = $this->_quickSearchOrganizations($keyword, $limit, $locale);
1064
        return $organizations;
1065
    }
1066

    
1067
    // Retrieve publication statistics.
1068
    // $locale the locale to use
1069
    // $allFunders get all fields for funders
1070
    // return statistics (object)
1071
    private function _getPublicationStatistics($locale, $allFunders=false) {
1072
    try {
1073
            $time = microtime(TRUE);
1074
            $query = self :: PUBLICATION_QUERY;
1075
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1076
            /* 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 :: RESULT_HOSTING_DATASOURCE . '&fields=' . self :: PUBLICATION_CONTEXT . '&fields=' . self :: PUBLICATION_PROJECT . '&query=' . urlencode($query) . '&locale=' . c('-', '_', $locale))) == NULL)
1077
             */
1078
            if (($response = $this->performGet('search?action=refine&rTransformer=results_openaire_browse&fields='. self :: RESULT_COLLECTED_FROM_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 :: RESULT_HOSTING_DATASOURCE . '&fields=' . self :: PUBLICATION_CONTEXT .  '&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
1079
                throw new Exception('no HTTP response');
1080
            if ($response->code != self :: HTTP_OK)
1081
                throw new Exception('HTTP response code ' . $response->code);
1082
            $document = new DOMDocument();
1083
            $document->recover = TRUE;
1084
            if ($document->loadXML($response->body) == FALSE)
1085
                throw new Exception('invalid XML response');
1086
            $xpath = new DOMXPath($document);
1087
            $statistics=null;
1088
            if($allFunders){
1089
                $statistics = $this->createStatistics($xpath,
1090
                    array('type', 'language', 'funder', 'fundingStream', 'scientificArea', 'fundingStreamLevel2', 'year', 'accessMode', 'datasource', 'community'),
1091
                    array('DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'FUNDING_STREAM_LEVEL_2', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE', 'COMMUNITIES'),
1092
                    array('NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND',
1093
                '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'),
1094
                    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_COLLECTED_FROM_DATASOURCE , self :: PUBLICATION_CONTEXT));
1095
            }else{
1096
                $statistics = $this->createStatistics($xpath,
1097
                    array('type', 'language', 'funder',  'year', 'accessMode', 'datasource', 'community'),
1098
                    array('DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'FUNDER',  'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE', 'COMMUNITIES'),
1099
                    array('NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND',
1100
                'NO_FUNDER_STATISTICS_FOUND',   'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND', 'NO_COMMUNITY_STATISTICS_FOUND'),
1101
                    array(self :: PUBLICATION_TYPE, self :: PUBLICATION_LANGUAGE, self :: PUBLICATION_FUNDER, self :: PUBLICATION_YEAR, self :: PUBLICATION_ACCESS_MODE, self :: RESULT_COLLECTED_FROM_DATASOURCE , self :: PUBLICATION_CONTEXT));
1102

    
1103
            }
1104
            JLog :: add('Retrieved publication statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1105
            return $statistics;
1106
        } catch (Exception $e) {
1107
            JLog :: add('Error retrieving publication statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1108
            return NULL;
1109
        }
1110
    }
1111

    
1112

    
1113
    // Retrieve dataset statistics.
1114
    // $locale the locale to use
1115
    // return statistics (object)
1116
    private function _getDatasetStatistics($locale, $allFunders=false) {
1117
        try {
1118
            $time = microtime(TRUE);
1119
            $query = self :: DATASET_QUERY;
1120
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1121
            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 :: RESULT_HOSTING_DATASOURCE . '&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
1122
                throw new Exception('no HTTP response');
1123
            if ($response->code != self :: HTTP_OK)
1124
                throw new Exception('HTTP response code ' . $response->code);
1125
            $document = new DOMDocument();
1126
            $document->recover = TRUE;
1127
            if ($document->loadXML($response->body) == FALSE)
1128
                throw new Exception('invalid XML response');
1129
            $xpath = new DOMXPath($document);
1130
            $statistics=null;
1131
            if($allFunders){
1132
                $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 :: RESULT_HOSTING_DATASOURCE));
1133
            }else{
1134
                $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 :: RESULT_HOSTING_DATASOURCE));
1135
            }
1136
            JLog :: add('Retrieved dataset statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1137
            return $statistics;
1138
        } catch (Exception $e) {
1139
            JLog :: add('Error retrieving dataset statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1140
            return NULL;
1141
        }
1142
    }
1143

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

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

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

    
1303
    // Retrieve datasource statistics.
1304
    // $locale the locale to use
1305
    // return statistics (object)
1306
    private function _getDatasourceStatistics($locale) {
1307
        try {
1308
            $time = microtime(TRUE);
1309
            $query = self :: DATASOURCE_QUERY;
1310
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1311
            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)
1312
                throw new Exception('no HTTP response');
1313
            if ($response->code != self :: HTTP_OK)
1314
                throw new Exception('HTTP response code ' . $response->code);
1315
            $document = new DOMDocument();
1316
            $document->recover = TRUE;
1317
            if ($document->loadXML($response->body) == FALSE)
1318
                throw new Exception('invalid XML response');
1319
            $xpath = new DOMXPath($document);
1320
            $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));
1321
            JLog :: add('Retrieved datasource statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1322
            return $statistics;
1323
        } catch (Exception $e) {
1324
            JLog :: add('Error retrieving datasource statistics locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1325
            return NULL;
1326
        }
1327
    }
1328

    
1329
    // Perform a simple search for publications.
1330
    // $keyword the keyword to search for
1331
    // $articles flag to limit searching on articles; if all flags are FALSE no limits apply
1332
    // $books flag to limit searching on books; if all flags are FALSE no limits apply
1333
    // $theses flag to limit searching on books; if all flags are FALSE no limits apply
1334
    // $reports flag to limit searching on reports; if all flags are FALSE no limits apply
1335
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
1336
    // $language the ID of the language to use as filter or NULL for no language filtering
1337
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1338
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
1339
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1340
    // $year the year of publication to use as filter or NULL for no year filtering
1341
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1342
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1343
    // $page the page of results to retrieve
1344
    // $size the size of the page of results to retrieve
1345
    // $locale the locale to use
1346
    // return a result (object) containing publications and statistics
1347
    private function _searchPublications($keyword, $articles, $books, $theses, $reports, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project,$isRefine) {
1348
        try {
1349
                $dois = explode(" ", preg_replace('/\s+/', ' ',$keyword));
1350
                $unique_dois =array_unique($dois);
1351
                $pattern1 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b#';
1352
                $pattern2 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b#';
1353
                if (preg_match($pattern1, $unique_dois[0]) || preg_match($pattern2, $unique_dois[0])) {
1354
                   $result= $this->_searchPublicationsWithDois($unique_dois,$page, $size, $locale,$isRefine);
1355
                    return $result;
1356
                }
1357
            $time = microtime(TRUE);
1358
            $query = self :: PUBLICATION_QUERY;
1359
            $query .= ($keyword == NULL) ? '' : ' and "' . str_replace('"', '\\"', $keyword) . '"';
1360
            $types = array();
1361
            if ($articles) {
1362
                $types[] = self :: PUBLICATION_ARTICLE;
1363
                $types[] = self :: PUBLICATION_PREPRINT;
1364
            }
1365
            if ($books) {
1366
                $types[] = self :: PUBLICATION_BOOK;
1367
                $types[] = self :: PUBLICATION_BOOK_PART;
1368
            }
1369
            if ($theses) {
1370
                $types[] = self :: PUBLICATION_PHD_THESIS;
1371
                $types[] = self :: PUBLICATION_MASTER_THESIS;
1372
                $types[] = self :: PUBLICATION_BACHELOR_THESIS;
1373
            }
1374
            if ($reports) {
1375
                $types[] = self :: PUBLICATION_REPORT;
1376
                $types[] = self :: PUBLICATION_INTERNAL_REPORT;
1377
                $types[] = self :: PUBLICATION_EXTERNAL_REPORT;
1378
            }
1379
            $publicationType = self :: PUBLICATION_TYPE;
1380
            $types = implode(' or ', array_map(function($type) use ($publicationType) {
1381
                        return '(' . $publicationType . ' exact "' . $type . '")';
1382
                    }, $types));
1383
            $query .= ($types == NULL) ? '' : (' and (' . $types . ')');
1384
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
1385
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
1386
             if($funder != NULL && (strpos($funder, ',') !== FALSE)){
1387
                $temp='';
1388
                foreach(explode(',',$funder) as $id){
1389
                    if(!empty($id)){
1390
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
1391
                    }
1392

    
1393
                }
1394
                $query .=  (' and (' . substr($temp, 0, -3). ')');
1395
            }else{
1396
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
1397
            }
1398
            //$query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
1399
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1400
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1401
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1402
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact ' . $year . ')');
1403
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
1404
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '")');
1405
            $query .= ($community == NULL) ? '' : (' and (' . self :: PUBLICATION_CONTEXT . ' exact "' . $community . '")');
1406
            $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT . ' exact "' . $project . '")');
1407
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1408
            $completeQuery='search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size .  '&locale=' . str_replace('-', '_', $locale);
1409
            if($isRefine){
1410
                $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 :: RESULT_HOSTING_DATASOURCE . '&fields=' . self :: PUBLICATION_PROJECT . '&locale=' . str_replace('-', '_', $locale);
1411
            }
1412
            //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 :: RESULT_HOSTING_DATASOURCE . '&fields=' . self :: PUBLICATION_PROJECT . '&locale=' . str_replace('-', '_', $locale))) == NULL)
1413
            if (($response = $this->performGet($completeQuery)) == NULL)
1414
                throw new Exception('no HTTP response');
1415
            if ($response->code != self :: HTTP_OK)
1416
                throw new Exception('HTTP response code ' . $response->code);
1417
            $document = new DOMDocument();
1418
            $document->recover = TRUE;
1419
            if ($document->loadXML($response->body) == FALSE)
1420
                throw new Exception('invalid XML response');
1421
            $xpath = new DOMXPath($document);
1422
            $result = new JObject();
1423
            $result->totalPublications = $this->parseTotalResults($xpath);
1424
            $result->totalDatasets = 0;
1425
            $result->publications = $this->parsePublications($xpath);
1426
            $result->statistics = $isRefine? $this->createStatisticsForPublications($xpath):NULL;
1427
            $result->statistics = self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1428
                    //$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 :: RESULT_HOSTING_DATASOURCE));
1429
            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);
1430
            return $result;
1431
        } catch (Exception $e) {
1432
            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);
1433
            $result->publications = array();
1434
            $result->totalPublications = 0;
1435
            $result->totalDatasets = 0;
1436
            return $result;
1437
        }
1438
    }
1439
 private function _searchPublicationsWithDois($dois, $page, $size, $locale,$isRefine) {
1440
        try {
1441
            $time = microtime(TRUE);
1442
            $query = self :: PUBLICATION_QUERY;
1443
            $query .= ' and (';
1444
            foreach ($dois as $doi) {
1445
                $query .= ' ((pidclassid exact doi) and (pid exact "'.$doi.'")) ';
1446
                $query .= 'OR';
1447
            }
1448
            if(count($dois)>0){
1449
                $query=substr($query, 0, -2);
1450
            }
1451
            $query .= ')';
1452
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1453
            $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 :: RESULT_HOSTING_DATASOURCE . '&fields=' . self :: PUBLICATION_PROJECT . '&locale=' . str_replace('-', '_', $locale)
1454
                    :'search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size   . '&locale=' . str_replace('-', '_', $locale);
1455
            if (($response = $this->performGet($completeQuery)) == NULL)
1456
                throw new Exception('no HTTP response');
1457
            if ($response->code != self :: HTTP_OK)
1458
                throw new Exception('HTTP response code ' . $response->code);
1459
            $document = new DOMDocument();
1460
            $document->recover = TRUE;
1461
            if ($document->loadXML($response->body) == FALSE)
1462
                throw new Exception('invalid XML response');
1463
            $xpath = new DOMXPath($document);
1464
            $result = new JObject();
1465
            $result->totalPublications = $this->parseTotalResults($xpath);
1466
            $result->totalDatasets = 0;
1467
            $result->publications = $this->parsePublications($xpath);
1468
            $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 :: RESULT_HOSTING_DATASOURCE)):NULL;
1469
            JLog :: add('Simple search for DOIs retrieved ' . count($result->publications) . ' publications in ' . (microtime(TRUE) - $time) . ' s (query: ' . $query. ')', JLog :: INFO, self :: LOG);
1470
            return $result;
1471
        } catch (Exception $e) {
1472
            JLog :: add('Error performing publication simple search for DOIs(query: ' . $query  . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1473
            return NULL;
1474
        }
1475
    }
1476
    // Perform a simple search for datasets.
1477
    // $keyword the keyword to search for
1478
    // $type the ID of the dataset type to use as filter or NULL for no dataset type filtering
1479
    // $language the ID of the language to use as filter or NULL for no language filtering
1480
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1481
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
1482
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1483
    // $year the year of publication to use as filter or NULL for no year filtering
1484
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1485
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1486
    // $page the page of results to retrieve
1487
    // $size the size of the page of results to retrieve
1488
    // $locale the locale to use
1489
    // return a result (object) containing datasets and statistics
1490
    private function _searchDatasets($keyword, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $isRefine) {
1491
        try {
1492
                $dois = explode(" ", preg_replace('/\s+/', ' ',$keyword));
1493
                $unique_dois =array_unique($dois);
1494
                $pattern1 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b#';
1495
                $pattern2 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b#';
1496
                if (preg_match($pattern1, $unique_dois[0]) || preg_match($pattern2, $unique_dois[0])) {
1497
                   $result= $this->_searchDatasetsWithDois($unique_dois,$page, $size, $locale,$isRefine);
1498
                    return $result;
1499
                }
1500
            $time = microtime(TRUE);
1501
            $query = self :: DATASET_QUERY;
1502
            $query .= ($keyword == NULL) ? '' : ' and "' . str_replace('"', '\\"', $keyword) . '"';
1503
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASET_TYPE . ' exact "' . $type . '")');
1504
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASET_LANGUAGE . ' exact "' . $language . '")');
1505
            $query .= ($funder == NULL) ? '' : (' and (' . self :: DATASET_FUNDER . ' exact "' . $funder . '")');
1506
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1507
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: DATASET_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1508
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1509
            $query .= ($year == NULL) ? '' : (' and (' . self :: DATASET_YEAR . ' exact ' . $year . ')');
1510
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: DATASET_ACCESS_MODE . ' exact "' . $accessMode . '")');
1511
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '")');
1512
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1513
            $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 :: RESULT_HOSTING_DATASOURCE . '&locale=' . str_replace('-', '_', $locale):
1514
                    'search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size  . '&locale=' . str_replace('-', '_', $locale);
1515
            if (($response = $this->performGet($completeQuery)) == NULL)
1516
                throw new Exception('no HTTP response');
1517
            if ($response->code != self :: HTTP_OK)
1518
                throw new Exception('HTTP response code ' . $response->code);
1519
            $document = new DOMDocument();
1520
            $document->recover = TRUE;
1521
            if ($document->loadXML($response->body) == FALSE)
1522
                throw new Exception('invalid XML response');
1523
            $xpath = new DOMXPath($document);
1524
            $result = new JObject();
1525
            $result->totalDatasets = $this->parseTotalResults($xpath);
1526
            $result->datasets = $this->parseDatasets($xpath);
1527
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
1528
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1529
                    //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 :: RESULT_HOSTING_DATASOURCE));
1530
            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);
1531
            return $result;
1532
        } catch (Exception $e) {
1533
            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);
1534
            return NULL;
1535
        }
1536
    }
1537

    
1538
 private function _searchDatasetsWithDois($dois, $page, $size, $locale,$isRefine) {
1539
        try {
1540
            $time = microtime(TRUE);
1541
            $query = self :: DATASET_QUERY;
1542
            $query .= ' and (';
1543
            foreach ($dois as $doi) {
1544
                $query .= ' ((pidclassid exact doi) and (pid exact "'.$doi.'")) ';
1545
                $query .= 'OR';
1546
            }
1547
            if(count($dois)>0){
1548
                $query=substr($query, 0, -2);
1549
            }
1550
            $query .= ')';
1551
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1552
            $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 :: RESULT_HOSTING_DATASOURCE . '&fields=' . self :: PUBLICATION_PROJECT . '&locale=' . str_replace('-', '_', $locale)
1553
                    :'search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size   . '&locale=' . str_replace('-', '_', $locale);
1554
            if (($response = $this->performGet($completeQuery)) == NULL)
1555
                throw new Exception('no HTTP response');
1556
            if ($response->code != self :: HTTP_OK)
1557
                throw new Exception('HTTP response code ' . $response->code);
1558
            $document = new DOMDocument();
1559
            $document->recover = TRUE;
1560
            if ($document->loadXML($response->body) == FALSE)
1561
                throw new Exception('invalid XML response');
1562
            $xpath = new DOMXPath($document);
1563
            $result = new JObject();
1564
            $result->totalPublications = 0;
1565
            $result->totalDatasets = $this->parseTotalResults($xpath);
1566
            $result->datasets = $this->parsePublications($xpath);
1567
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
1568
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1569
                    //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 :: RESULT_HOSTING_DATASOURCE));
1570
            JLog :: add('Simple search for DOIs retrieved ' . count($result->datasets) . ' datasets in ' . (microtime(TRUE) - $time) . ' s (query: ' . $query. ')', JLog :: INFO, self :: LOG);
1571
            return $result;
1572
        } catch (Exception $e) {
1573
            JLog :: add('Error performing dataset simple search for DOIs(query: ' . $query  . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1574
            return NULL;
1575
        }
1576
    }
1577
    // Perform a simple search for projects.
1578
    // $keyword the keyword to search for
1579
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1580
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
1581
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1582
    // $startYear the start year to use as filter or NULL for no start year filtering
1583
    // $endYear the end year to suse as filter or NULL for no end year filtering
1584
    // $sc39 the SC-39 status to use as filter or NULL for no SC-39 status filtering
1585
    // $page the page of results to retrieve
1586
    // $size the size of the page of results to retrieve
1587
    // $locale the locale to use
1588
    // return a result (object) containing projects and statistics
1589
    private function _searchProjects($keyword, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine) {
1590
        try {
1591
            $time = microtime(TRUE);
1592
            $query = self :: PROJECT_QUERY;
1593
            $query .= ($keyword == NULL) ? '' : ' and ((' . self :: PROJECT_ACRONYM . ' = "' . str_replace('"', '\\"', $keyword) . '") or (' . self :: PROJECT_CODE . ' = "' . str_replace('"', '\\"', $keyword) . '") or (' . self :: PROJECT_TITLE . ' = "' . str_replace('"', '\\"', $keyword) . '"))';
1594
            $query .= ($funder == NULL) ? '' : (' and (' . self :: PROJECT_FUNDER . ' exact "' . $funder . '")');
1595
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1596
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PROJECT_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1597
            $query .= ($startYear == NULL) ? '' : (' and (' . self :: PROJECT_START_YEAR . ' exact ' . $startYear . ')');
1598
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM_LEVEL2. ' exact "' . $fundingStreamLevel2 . '")');
1599
            $query .= ($endYear == NULL) ? '' : (' and (' . self :: PROJECT_END_YEAR . ' exact ' . $endYear . ')');
1600
            $query .= ($sc39 === NULL) ? '' : (' and (' . self :: PROJECT_SC39 . ' exact ' . ($sc39 ? 'true' : 'false') . ')');
1601
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1602
            $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)
1603
                    :'search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
1604
            if (($response = $this->performGet($completeQuery)) == NULL)
1605
                throw new Exception('no HTTP response');
1606
            if ($response->code != self :: HTTP_OK)
1607
                throw new Exception('HTTP response code ' . $response->code);
1608
            $document = new DOMDocument();
1609
            $document->recover = TRUE;
1610
            if ($document->loadXML($response->body) == FALSE)
1611
                throw new Exception('invalid XML response');
1612
            $xpath = new DOMXPath($document);
1613
            $result = new JObject();
1614
            $result->totalProjects = $this->parseTotalResults($xpath);
1615
            $result->projects = $this->parseProjects($xpath);
1616
            $result->statistics = $isRefine?$this->createStatisticsForProjects($xpath,''):NULL;
1617
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1618
                    //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));
1619
            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);
1620
            return $result;
1621
        } catch (Exception $e) {
1622
            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);
1623
            return NULL;
1624
        }
1625
    }
1626

    
1627
    // Perform a simple search for people.
1628
    // $keyword the keyword to search for
1629
    // $country the country to use as filter or NULL for no country filtering
1630
    // $page the page of results to retrieve
1631
    // $size the size of the page of results to retrieve
1632
    // $locale the locale to use
1633
    // return a result (object) containing people and statistics
1634
    private function _searchPeople($keyword, $country, $page, $size, $locale, $isRefine) {
1635
        try {
1636
            $time = microtime(TRUE);
1637
            $query = self :: PERSON_QUERY;
1638
            $query .= ($keyword == NULL) ? '' : ' and "' . str_replace('"', '\\"', $keyword) . '"';
1639
            // $query .= ($country == NULL) ? '' : (' and (' . self :: PERSON_COUNTRY . ' exact "' . $country . '")');
1640
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1641
            // $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)
1642
            //         :'search?action=search&sTransformer=persons_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
1643
            $completeQuery='search?action=search&sTransformer=persons_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
1644
            if (($response = $this->performGet($completeQuery)) == NULL)
1645
                throw new Exception('no HTTP response');
1646
            if ($response->code != self :: HTTP_OK)
1647
                throw new Exception('HTTP response code ' . $response->code);
1648
            $document = new DOMDocument();
1649
            $document->recover = TRUE;
1650
            if ($document->loadXML($response->body) == FALSE)
1651
                throw new Exception('invalid XML response');
1652
            $xpath = new DOMXPath($document);
1653
            $result = new JObject();
1654
            $result->totalPeople = $this->parseTotalResults($xpath);
1655
            $result->people = $this->parsePeople($xpath);
1656
            $result->statistics = $isRefine? array():NULL;
1657
            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);
1658
            return $result;
1659
        } catch (Exception $e) {
1660
            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);
1661
            return NULL;
1662
        }
1663
    }
1664

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

    
1794
    // Perform a simple search for datasources.
1795
    // $keyword the keyword to search for
1796
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
1797
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
1798
    // $content the ID of the content to use as filter or NULL for no project filtering
1799
    // $compatibility the ID of the compatibility level to use as filter or NULL for no compatibility level filtering
1800
    // $page the page of results to retrieve
1801
    // $size the size of the page of results to retrieve
1802
    // $locale the locale to use
1803
    // return a result (object) containing datasources and statistics
1804
    private function _searchDatasources($keyword, $type, $language, $content, $compatibility, $page, $size, $locale, $isRefine) {
1805
        try {
1806
            $time = microtime(TRUE);
1807
            $query = self :: DATASOURCE_QUERY;
1808
            $query .= ($keyword == NULL) ? '' : (' and "' . str_replace('"', '\\"', $keyword) . '"');
1809
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASOURCE_TYPE . ' exact "' . $type . '")');
1810
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASOURCE_LANGUAGE . ' exact "' . $language . '")');
1811
            $query .= ($content == NULL) ? '' : (' and (' . self :: DATASOURCE_CONTENT . ' exact "' . $content . '")');
1812
            $query .= ($compatibility == NULL) ? '' : (' and (' . self :: DATASOURCE_COMPATIBILITY . ' exact "' . $compatibility . '")');
1813
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1814
            $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)
1815
                    :'search?action=search&sTransformer=datasources_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
1816
            if (($response = $this->performGet($completeQuery)) == NULL)
1817
                throw new Exception('no HTTP response');
1818
            if ($response->code != self :: HTTP_OK)
1819
                throw new Exception('HTTP response code ' . $response->code);
1820
            $document = new DOMDocument();
1821
            $document->recover = TRUE;
1822
            if ($document->loadXML($response->body) == FALSE)
1823
                throw new Exception('invalid XML response');
1824
            $xpath = new DOMXPath($document);
1825
            $result = new JObject();
1826
            $result->totalDatasources = $this->parseTotalResults($xpath);
1827
            $result->datasources = $this->parseDatasources($xpath);
1828
            $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;
1829
            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);
1830
            return $result;
1831
        } catch (Exception $e) {
1832
            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);
1833
            return NULL;
1834
        }
1835
    }
1836

    
1837
    // Perform a browse for publications.
1838
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
1839
    // $language the ID of the language to use as filter or NULL for no language filtering
1840
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1841
    // $fundingStream the ID of the fundingStream to use as filter or NULL for no funding stream filtering
1842
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1843
    // $year the year of publication to use as filter or NULL for no year filtering
1844
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1845
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1846
    // $community the ID of the community to use as filter or NULL for no datasource filtering
1847
    // $page the page of results to retrieve
1848
    // $size the size of the page of results to retrieve
1849
    // $locale the locale to use
1850
    // $project the ID of the project to use as filter or NULL for no project filtering
1851
    // $author the ID of the author to use as filter or NULL for no author filtering
1852
    // return a result (object) containing publications and statistics
1853
    private function _browsePublications($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $author,$isRefine,$refineFields) {
1854
        try {
1855
            $time = microtime(TRUE);
1856
            $query = self :: PUBLICATION_QUERY;
1857
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
1858
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
1859
            if($funder != NULL && (strpos($funder, '---') !== FALSE)){
1860
                $temp='';
1861
                foreach(explode('---',$funder) as $id){
1862
                    if(!empty($id)){
1863
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
1864
                    }
1865

    
1866
                }
1867
                $query .=  (' and (' . substr($temp, 0, -4). ')');
1868
            }else{
1869
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
1870
            }
1871
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1872
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1873
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1874
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact ' . $year . ')');
1875
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
1876
            // $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
1877
            $datasource_id_array = explode("||", $datasource);
1878
            if(sizeof($datasource_id_array) > 1 ){
1879
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
1880
            }else{
1881
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE_ID . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE_ID . ' exact "' . $datasource . '") )');
1882
            }
1883
            // $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT . ' exact "' . $project . '")');
1884
            $project_id_array = explode("||", $project);
1885
            if(sizeof($project_id_array) > 1 ){
1886
                $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT . ' exact "' . $project . '")');
1887
            }else{
1888
              $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT_ID . ' exact "' . $project . '")');
1889
            }
1890
            $query .= ($author == NULL) ? '' : (' and (' . self :: PUBLICATION_AUTHOR_ID . ' exact "' . $author . '")');
1891
            $query .= ($community == NULL) ? '' : (' and (' . self :: PUBLICATION_CONTEXT . ' exact "' . $community . '")');
1892
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1893
            $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 :: RESULT_HOSTING_DATASOURCE . '&fields=' . self :: PUBLICATION_CONTEXT ). '&locale=' . str_replace('-', '_', $locale):
1894
                'search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size  . '&locale=' . str_replace('-', '_', $locale);
1895
            if (($response = $this->performGet($completeQuery)) == NULL)
1896
                throw new Exception('no HTTP response');
1897
            if ($response->code != self :: HTTP_OK)
1898
                throw new Exception('HTTP response code ' . $response->code);
1899
            $document = new DOMDocument();
1900
            $document->recover = TRUE;
1901
            if ($document->loadXML($response->body) == FALSE)
1902
                throw new Exception('invalid XML response');
1903
            $xpath = new DOMXPath($document);
1904
            $result = new JObject();
1905
            $result->totalPublications = $this->parseTotalResults($xpath);
1906
            $result->publications = $this->parsePublications($xpath);
1907
            $result->statistics = $isRefine?$this->createStatisticsForPublications($xpath):NULL;
1908
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1909
                    //$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 :: RESULT_HOSTING_DATASOURCE, self :: PUBLICATION_CONTEXT));
1910
            $result->totalDatasets = 0;
1911
            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);
1912
            return $result;
1913
        } catch (Exception $e) {
1914
            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);
1915
            return NULL;
1916
        }
1917
    }
1918
    public static function pruningStatisticsForFunders($statistics, $funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2,$filter){
1919
        return self::_pruningStatisticsForFunders($statistics, $funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2,$filter);
1920
    }
1921
    private static function _pruningStatisticsForFunders($statistics, $funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2,$filter=''){
1922
        if($statistics==NULL){
1923
            return NULL;
1924
        }
1925
        if($fundingStreamLevel1!=NULL){
1926
           $newData= array();
1927
           foreach ($statistics["fundingStreamLevel2".$filter]->data as $data){
1928
               if(strpos($data->id,$fundingStreamLevel1)!==FALSE){
1929
                   $newData[$data->id]=$data;
1930
               }
1931
           }
1932
           $statistics["fundingStreamLevel2".$filter]->data=$newData;
1933
         }
1934
        if($fundingStream!=NULL){
1935
           $newData= array();
1936
           foreach ($statistics["fundingStreamLevel1".$filter]->data as $data){
1937
               if(strpos($data->id,$fundingStream)!==FALSE){
1938
                   $newData[$data->id]=$data;
1939
               }
1940
           }
1941
           $statistics["fundingStreamLevel1".$filter]->data=$newData;
1942
        }
1943
        if($funder!=NULL){
1944
           $newData= array();
1945
           if(strpos($funder, '---') !== FALSE){
1946
                foreach ($statistics["fundingStream".$filter]->data as $data){
1947
                   foreach(explode('---',$funder) as $id){                       
1948
                       if(!empty($id) && (strpos($data->id,explode("||",$id)[0])!==FALSE)){
1949
                        $newData[$data->id]=$data;
1950
                       }
1951
                   }
1952
               }
1953
           }else{
1954
               foreach ($statistics["fundingStream".$filter]->data as $data){
1955
                   $funder_id= explode("||",$funder)[0];
1956
                    if(strpos($data->id,$funder_id)!==FALSE){
1957
                        $newData[$data->id]=$data;
1958
                    }
1959
                }
1960
           }
1961
           $statistics["fundingStream".$filter]->data=$newData;
1962

    
1963
        }
1964
        return $statistics;
1965
    }
1966
    //Reduces the Funding Fields
1967
    //$funder filter for funder
1968
    //$fundingStream filter for funding stream
1969
    //$fundingStreamLevel1 filter for fundingStreamLevel1
1970
    //$fundingStreamLevel2 filter  for fundingStreamLevel2
1971
    private static function _getFundingFields($funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2, $type){
1972
            $field = self::_getFundingFieldsPerType($type);
1973
            $f = array();
1974
             $f[0]=true;
1975
            for($i=1;$i<4;$i++){
1976
                $f[$i]=false;
1977
            }
1978
            if($fundingStreamLevel2 !== null && !empty($fundingStreamLevel2)){
1979
                $f[3]=true;
1980
           }if($fundingStreamLevel1 !== NULL && strlen($fundingStreamLevel1)>0){
1981
               $f[2]=true;
1982
               $f[3]=true;
1983
            } if($fundingStream !== NULL && strlen($fundingStream)>0){
1984
                $f[1]=true;
1985
                $f[2]=true;
1986
            } if($funder !== NULL && strlen($funder)>0){
1987
                $f[0]=true;
1988
                $f[1]=true;
1989
            }
1990
            $returnedFields='';
1991
            $none=true;
1992
            for($i=0;$i<4;$i++){
1993
                if($f[$i]){
1994
                    $returnedFields.=($f[$i])?$field[$i]:'';
1995
                    $none=false;
1996
                }
1997
            }
1998
            $returnedFields=($none)?$field[0].$field[1]:$returnedFields;
1999
            return $returnedFields;
2000
        }
2001

    
2002
        private function _getFundingFieldsPerType($type){
2003
            $field=array();
2004
             switch ($type) {
2005
                case self::PUBLICATION:
2006
                    $field[3]='&fields=' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2;
2007
                    $field[2]='&fields=' . self :: PUBLICATION_SCIENTIFIC_AREA;
2008
                    $field[1]='&fields=' . self :: PUBLICATION_FUNDING_STREAM;
2009
                    $field[0]='&fields=' . self :: PUBLICATION_FUNDER;
2010
                    break;
2011
                case self::DATASET:
2012
                    $field[3]='&fields=' . self :: DATASET_FUNDING_STREAM_LEVEL2;
2013
                    $field[2]='&fields=' . self :: DATASET_SCIENTIFIC_AREA;
2014
                    $field[1]='&fields=' . self :: DATASET_FUNDING_STREAM;
2015
                    $field[0]='&fields=' . self :: DATASET_FUNDER;
2016
                    break;
2017
                case self::PROJECT:
2018
                    $field[3]='&fields=' . self :: PROJECT_FUNDING_STREAM_LEVEL2;
2019
                    $field[2]='&fields=' . self :: PROJECT_SCIENTIFIC_AREA;
2020
                    $field[1]='&fields=' . self :: PROJECT_FUNDING_STREAM;
2021
                    $field[0]='&fields=' . self :: PROJECT_FUNDER;
2022
                    break;
2023
             }
2024

    
2025
             return $field;
2026
        }
2027
    public function browsePublicationsRaw($query) {
2028
        try {
2029
            $time = microtime(TRUE);
2030

    
2031
            if (($response = $this->performGet($query)) == NULL)
2032
                throw new Exception('no HTTP response');
2033
            if ($response->code != self :: HTTP_OK)
2034
                throw new Exception('HTTP response code ' . $response->code);
2035
            JLog :: add('Browse publications raw  for query:'.$query.' in ' . (microtime(TRUE) - $time) , JLog :: INFO, self :: LOG);
2036
            return $response;
2037
        } catch (Exception $e) {
2038
            JLog :: add('Error performing publications browse raw', JLog :: ERROR, self :: LOG);
2039
            return NULL;
2040
        }
2041
    }
2042
     public function browseProjectsRaw($query) {
2043
        try {
2044
            $time = microtime(TRUE);
2045

    
2046
            if (($response = $this->performGet(str_replace(' ', '+', $query))) == NULL)
2047
                throw new Exception('no HTTP response');
2048
            if ($response->code != self :: HTTP_OK)
2049
                throw new Exception('HTTP response code ' . $response->code);
2050
            JLog :: add('Browse projects raw  for query:'.$query.' in ' . (microtime(TRUE) - $time) , JLog :: INFO, self :: LOG);
2051
            return $response;
2052
        } catch (Exception $e) {
2053
            JLog :: add('Error performing projects browse raw', JLog :: ERROR, self :: LOG);
2054
            return NULL;
2055
        }
2056
    }
2057
    // Perform a browse for datasets.
2058
    // $type the ID of the dataset type to use as filter or NULL for no dataset type filtering
2059
    // $language the ID of the language to use as filter or NULL for no language filtering
2060
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2061
    // $fundingStream the ID of the fundingStream to use as filter or NULL for no funding stream filtering
2062
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2063
    // $year the year of publication to use as filter or NULL for no year filtering
2064
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
2065
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
2066
    // $page the page of results to retrieve
2067
    // $size the size of the page of results to retrieve
2068
    // $locale the locale to use
2069
    // $project the ID of the project to use as filter or NULL for no project filtering
2070
    // $author the ID of the author to use as filter or NULL for no author filtering
2071
    // return a result (object) containing datasets and statistics
2072
    private function _browseDatasets($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine, $refineFields) {
2073
        try {
2074
            $time = microtime(TRUE);
2075
            $query = self :: DATASET_QUERY;
2076
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASET_TYPE . ' exact "' . $type . '")');
2077
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASET_LANGUAGE . ' exact "' . $language . '")');
2078
            $query .= ($funder == NULL) ? '' : (' and (' . self :: DATASET_FUNDER . ' exact "' . $funder . '")');
2079
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2080
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: DATASET_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2081
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2082
            $query .= ($year == NULL) ? '' : (' and (' . self :: DATASET_YEAR . ' exact ' . $year . ')');
2083
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: DATASET_ACCESS_MODE . ' exact "' . $accessMode . '")');
2084

    
2085
            // $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
2086
            $datasource_id_array = explode("||", $datasource);
2087
            if(sizeof($datasource_id_array) > 1 ){
2088
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
2089
            }else{
2090
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE_ID . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE_ID . ' exact "' . $datasource . '") )');
2091
            }
2092
            // $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
2093
            $project_id_array = explode("||", $project);
2094
            if(sizeof($project_id_array) > 1 ){
2095
                $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
2096
            }else{
2097
              $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT_ID . ' exact "' . $project . '")');
2098
            }
2099
            $query .= ($author == NULL) ? '' : (' and (' . self :: DATASET_AUTHOR_ID . ' exact "' . $author . '")');
2100
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2101
            $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 :: RESULT_HOSTING_DATASOURCE ). '&locale=' . str_replace('-', '_', $locale):
2102
                    'search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2103
            if (($response = $this->performGet($completeQuery)) == NULL)
2104
                throw new Exception('no HTTP response');
2105
            if ($response->code != self :: HTTP_OK)
2106
                throw new Exception('HTTP response code ' . $response->code);
2107
            $document = new DOMDocument();
2108
            $document->recover = TRUE;
2109
            if ($document->loadXML($response->body) == FALSE)
2110
                throw new Exception('invalid XML response');
2111
            $xpath = new DOMXPath($document);
2112
            $result = new JObject();
2113
            $result->totalDatasets = $this->parseTotalResults($xpath);
2114
            $result->datasets = $this->parseDatasets($xpath);
2115
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
2116
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
2117
                    //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 :: RESULT_HOSTING_DATASOURCE));
2118
            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);
2119
            return $result;
2120
        } catch (Exception $e) {
2121
            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);
2122
            return NULL;
2123
        }
2124
    }
2125

    
2126
    // Perform a browse for projects.
2127
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2128
    // $fundingStream the ID of the fundingStream to use as filter or NULL for no funding stream filtering
2129
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2130
    // $startYear the start year to use as filter or NULL for no start year filtering
2131
    // $endYear the end year to use as filter or NULL for no end year filtering
2132
    // $$sc39 the SC-39 status to use as filter or NULL for no SC-39 status filtering
2133
    // $page the page of results to retrieve
2134
    // $size the size of the page of results to retrieve
2135
    // $locale the locale to use
2136
    // return a result (object) containing projects and statistics
2137
    private function _browseProjects($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine) {
2138
        try {
2139
            $time = microtime(TRUE);
2140
            $query = self :: PROJECT_QUERY;
2141
            if($funder != NULL && (strpos($funder, ',') !== FALSE)){
2142
                $temp='';
2143
                foreach(explode(',',$funder) as $id){
2144
                    if(!empty($id)){
2145
                        $temp.='(' . self :: PROJECT_FUNDER . ' exact "' . $id . '") and';
2146
                    }
2147

    
2148
                }
2149
                $query .=  (' and (' . substr($temp, 0, -3). ')');
2150
            }else{
2151
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PROJECT_FUNDER . ' exact "' . $funder . '")');
2152
            }
2153
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2154
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PROJECT_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2155
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2156
            $query .= ($startYear == NULL) ? '' : (' and (' . self :: PROJECT_START_YEAR . ' exact ' . $startYear . ')');
2157
            $query .= ($endYear == NULL) ? '' : (' and (' . self :: PROJECT_END_YEAR . ' exact ' . $endYear . ')');
2158
            $query .= ($sc39 === NULL) ? '' : (' and (' . self :: PROJECT_SC39 . ' exact ' . ($sc39 ? 'true' : 'false') . ')');
2159
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2160
            $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)
2161
                    :'search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2162
            if (($response = $this->performGet($completeQuery)) == NULL)
2163
                throw new Exception('no HTTP response');
2164
            if ($response->code != self :: HTTP_OK)
2165
                throw new Exception('HTTP response code ' . $response->code);
2166
            $document = new DOMDocument();
2167
            $document->recover = TRUE;
2168
            if ($document->loadXML($response->body) == FALSE)
2169
                throw new Exception('invalid XML response');
2170
            $xpath = new DOMXPath($document);
2171
            $result = new JObject();
2172
            $result->totalProjects = $this->parseTotalResults($xpath);
2173
            $result->projects = $this->parseProjects($xpath);
2174
            $result->statistics = $isRefine? $this->createStatisticsForProjects($xpath):NULL;
2175
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
2176
                    //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));
2177
            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);
2178
            return $result;
2179
        } catch (Exception $e) {
2180
            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);
2181
            return NULL;
2182
        }
2183
    }
2184

    
2185
    // Perform a browse for people.
2186
    // $country the ID of the country to use as filter or NULL for no country filtering
2187
    // $page the page of results to retrieve
2188
    // $size the size of the page of results to retrieve
2189
    // $locale the locale to use
2190
    // return a result (object) containing people and statistics
2191
    private function _browsePeople($country, $page, $size, $locale, $isRefine) {
2192
        try {
2193
            $time = microtime(TRUE);
2194
            $query = self :: PERSON_QUERY;
2195
            // $query .= ($country == NULL) ? '' : (' and (' . self :: PERSON_COUNTRY . ' exact "' . $country . '")');
2196
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2197
            // $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)
2198
            //         :'search?action=search&sTransformer=persons_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2199
            $completeQuery='search?action=search&sTransformer=persons_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2200
            if (($response = $this->performGet($completeQuery)) == NULL)
2201
                throw new Exception('no HTTP response');
2202
            if ($response->code != self :: HTTP_OK)
2203
                throw new Exception('HTTP response code ' . $response->code);
2204
            $document = new DOMDocument();
2205
            $document->recover = TRUE;
2206
            if ($document->loadXML($response->body) == FALSE)
2207
                throw new Exception('invalid XML response');
2208
            $xpath = new DOMXPath($document);
2209
            $result = new JObject();
2210
            $result->totalPeople = $this->parseTotalResults($xpath);
2211
            $result->people = $this->parsePeople($xpath);
2212
            $result->statistics =$result->statistics = $isRefine? array():NULL;
2213
            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);
2214
            return $result;
2215
        } catch (Exception $e) {
2216
            JLog :: add('Error performing people browse (country: ' . (($country == NULL) ? 'null' : $country) . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2217
            return NULL;
2218
        }
2219
    }
2220

    
2221
    // Perform a browse for organizations.
2222
    // $country the ID of the country to use as filter or NULL for no country filtering
2223
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
2224
    // $page the page of results to retrieve
2225
    // $size the size of the page of results to retrieve
2226
    // $locale the locale to use
2227
    // return a result (object) containing organizations and statistics
2228
    private function _browseOrganizations($country, $type, $page, $size, $locale, $isRefine) {
2229
        try {
2230
            $time = microtime(TRUE);
2231
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
2232
            $query .= ($country == NULL) ? '' : (' and (' . self :: ORGANIZATION_COUNTRY . ' exact "' . $country . '")');
2233
            switch ($type) {
2234
                case 'legalBody':
2235
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_BODY . ' exact true)';
2236
                    break;
2237
                case 'legalPerson':
2238
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_PERSON . ' exact true)';
2239
                    break;
2240
                case 'nonProfit':
2241
                    $query .= ' and (' . self :: ORGANIZATION_NON_PROFIT . ' exact true)';
2242
                    break;
2243
                case 'research':
2244
                    $query .= ' and (' . self :: ORGANIZATION_RESEARCH . ' exact true)';
2245
                    break;
2246
                case 'euInterests':
2247
                    $query .= ' and (' . self :: ORGANIZATION_EU_INTERESTS . ' exact true)';
2248
                    break;
2249
                case 'international':
2250
                    $query .= ' and (' . self :: ORGANIZATION_INTERNATIONAL . ' exact true)';
2251
                    break;
2252
                case 'enterprise':
2253
                    $query .= ' and (' . self :: ORGANIZATION_ENTERPRISE . ' exact true)';
2254
                    break;
2255
                case 'smallMediumEnterprise':
2256
                    $query .= ' and (' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . ' exact true)';
2257
            }
2258
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2259
            $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)
2260
                    :'search?action=searchsTransformer=organizations_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2261
            if (($response = $this->performGet($completeQuery)) == NULL)
2262
                throw new Exception('no HTTP response');
2263
            if ($response->code != self :: HTTP_OK)
2264
                throw new Exception('HTTP response code ' . $response->code);
2265
            $document = new DOMDocument();
2266
            $document->recover = TRUE;
2267
            if ($document->loadXML($response->body) == FALSE)
2268
                throw new Exception('invalid XML response');
2269
            $xpath = new DOMXPath($document);
2270
            $result = new JObject();
2271
            $result->totalOrganizations = $this->parseTotalResults($xpath);
2272
            $result->organizations = $this->parseOrganizations($xpath);
2273
            if($isRefine){
2274
                $result->statistics = $this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
2275
                $result->statistics['type'] = new JObject();
2276
                $result->statistics['type']->id = 'type';
2277
                $result->statistics['type']->title = JText :: _('TYPE');
2278
                $result->statistics['type']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
2279
                $result->statistics['type']->data = array();
2280
                $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
2281
                if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
2282
                    $result->statistics['type']->data['legalBody'] = new JObject();
2283
                    $result->statistics['type']->data['legalBody']->id = 'legalBody';
2284
                    $result->statistics['type']->data['legalBody']->name = JText :: _('LEGAL_BODY');
2285
                    $result->statistics['type']->data['legalBody']->count = $legalBody['true']->count;
2286
                }
2287
                $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
2288
                if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
2289
                    $result->statistics['type']->data['legalPerson'] = new JObject();
2290
                    $result->statistics['type']->data['legalPerson']->id = 'legalPerson';
2291
                    $result->statistics['type']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
2292
                    $result->statistics['type']->data['legalPerson']->count = $legalPerson['true']->count;
2293
                }
2294
                $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
2295
                if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
2296
                    $result->statistics['type']->data['nonProfit'] = new JObject();
2297
                    $result->statistics['type']->data['nonProfit']->id = 'nonProfit';
2298
                    $result->statistics['type']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
2299
                    $result->statistics['type']->data['nonProfit']->count = $nonProfit['true']->count;
2300
                }
2301
                $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
2302
                if (($research != NULL) && array_key_exists('true', $research)) {
2303
                    $result->statistics['type']->data['research'] = new JObject();
2304
                    $result->statistics['type']->data['research']->id = 'research';
2305
                    $result->statistics['type']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
2306
                    $result->statistics['type']->data['research']->count = $research['true']->count;
2307
                }
2308
                $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
2309
                if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
2310
                    $result->statistics['type']->data['euInterests'] = new JObject();
2311
                    $result->statistics['type']->data['euInterests']->id = 'euInterests';
2312
                    $result->statistics['type']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
2313
                    $result->statistics['type']->data['euInterests']->count = $euInterests['true']->count;
2314
                }
2315
                $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
2316
                if (($international != NULL) && array_key_exists('true', $international)) {
2317
                    $result->statistics['type']->data['international'] = new JObject();
2318
                    $result->statistics['type']->data['international']->id = 'international';
2319
                    $result->statistics['type']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
2320
                    $result->statistics['type']->data['international']->count = $international['true']->count;
2321
                }
2322
                $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
2323
                if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
2324
                    $result->statistics['type']->data['enterprise'] = new JObject();
2325
                    $result->statistics['type']->data['enterprise']->id = 'enterprise';
2326
                    $result->statistics['type']->data['enterprise']->name = JText :: _('ENTERPRISE');
2327
                    $result->statistics['type']->data['enterprise']->count = $enterprise['true']->count;
2328
                }
2329
                $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
2330
                if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
2331
                    $result->statistics['type']->data['smallMediumEnterprise'] = new JObject();
2332
                    $result->statistics['type']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
2333
                    $result->statistics['type']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
2334
                    $result->statistics['type']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
2335
                }
2336
                uasort($result->statistics['type']->data, function ($row1, $row2) {
2337
                    return $row2->count - $row1->count;
2338
                });
2339
            }
2340
            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);
2341
            return $result;
2342
        } catch (Exception $e) {
2343
            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);
2344
            return NULL;
2345
        }
2346
    }
2347

    
2348
    // Perform a browse for datasources.
2349
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
2350
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
2351
    // $content the ID of the content to use as filter or NULL for no content filtering
2352
    // $compatibility the ID of the compatibility level to use as filter or NULL for no compatibility status filtering
2353
    // $page the page of results to retrieve
2354
    // $size the size of the page of results to retrieve
2355
    // $locale the locale to use
2356
    // return a result (object) containing datasources and statistics
2357
    private function _browseDatasources($type, $language, $content, $compatibility, $page, $size, $locale, $isRefine) {
2358
        try {
2359
            $time = microtime(TRUE);
2360
            $query = self :: DATASOURCE_QUERY;
2361
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASOURCE_TYPE . ' exact "' . $type . '")');
2362
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASOURCE_LANGUAGE . ' exact "' . $language . '")');
2363
            $query .= ($content == NULL) ? '' : (' and (' . self :: DATASOURCE_CONTENT . ' exact "' . $content . '")');
2364
            $query .= ($compatibility == NULL) ? '' : (' and (' . self :: DATASOURCE_COMPATIBILITY . ' exact "' . $compatibility . '")');
2365
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2366
            $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):
2367
                'search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2368
            if (($response = $this->performGet($completeQuery)) == NULL)
2369
                throw new Exception('no HTTP response');
2370
            if ($response->code != self :: HTTP_OK)
2371
                throw new Exception('HTTP response code ' . $response->code);
2372
            $document = new DOMDocument();
2373
            $document->recover = TRUE;
2374
            if ($document->loadXML($response->body) == FALSE)
2375
                throw new Exception('invalid XML response');
2376
            $xpath = new DOMXPath($document);
2377
            $result = new JObject();
2378
            $result->totalDatasources = $this->parseTotalResults($xpath);
2379
            $result->datasources = $this->parseDatasources($xpath);
2380
            $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;
2381
            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);
2382
            return $result;
2383
        } catch (Exception $e) {
2384
            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);
2385
            return NULL;
2386
        }
2387
    }
2388

    
2389
    // Perform an advanced search for publications.
2390
    // $keywords the keywords to search for (array)
2391
    // $fields the fields to match keywords with (array - possible values are TITLE, AUTHOR, PUBLISHER and SUBJECT)
2392
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2393
    // $types the IDs of the publication types to search for
2394
    // $languages the IDs of the publication languages to search for
2395
    // $funders the IDs of the funders to search for
2396
    // $fundingStreams the IDs of the funding streams to search for
2397
    // $scientificAreas the IDs of the scientific areas to search for
2398
    // $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)
2399
    // $fromMonth start month of the publication date range to search for if $date has value 0
2400
    // $fromYear start year of the publication date range to search for if $date has value 0
2401
    // $toMonth end month of the publication date range to search for if $date has value 0
2402
    // $toYear end year of the publication date range to search for if $date has value 0
2403
    // $accessModes the IDs of the access modes to search for
2404
    // $datasources the IDs of the datasources to search for
2405
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
2406
    // $language the ID of the publication language to use as filter or NULL for no publication language filtering
2407
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2408
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
2409
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2410
    // $year the publication year to use as filter or NULL for no publication year filtering
2411
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
2412
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
2413
    // $page the page of results to retrieve
2414
    // $size the size of the page of results to retrieve
2415
    // $locale the locale to use
2416
    // return a result (object) containing publications and statistics
2417
    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) {
2418
        try {
2419
            $time = microtime(TRUE);
2420
            $query = self :: PUBLICATION_QUERY;
2421
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2422
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2423
                switch ($constraints[$i]) {
2424
                    case OpenAireViewAdvancedSearchPublications :: ALL:
2425
                        $operator = ' and ';
2426
                        break;
2427
                    case OpenAireViewAdvancedSearchPublications :: ANY:
2428
                        $operator = ' or ';
2429
                        break;
2430
                    default:
2431
                        $operator = NULL;
2432
                }
2433
                switch ($fields[$i]) {
2434
                    case OpenAireViewAdvancedSearchPublications :: TITLE:
2435
                        $field = self :: PUBLICATION_TITLE;
2436
                        break;
2437
                    case OpenAireViewAdvancedSearchPublications :: AUTHOR:
2438
                        $field = self :: PUBLICATION_AUTHOR;
2439
                        break;
2440
                    case OpenAireViewAdvancedSearchPublications :: PUBLISHER:
2441
                        $field = self :: PUBLICATION_PUBLISHER;
2442
                        break;
2443
                    case OpenAireViewAdvancedSearchPublications :: SUBJECT:
2444
                        $field = self :: PUBLICATION_SUBJECT;
2445
                        break;
2446
                    default:
2447
                        $field = NULL;
2448
                }
2449
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2450
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2451
                                }, $tokens)) . ')');
2452
            }
2453
            $field = self :: PUBLICATION_TYPE;
2454
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($field) {
2455
                                return '(' . $field . ' exact "' . $type . '")';
2456
                            }, $types)) . ')');
2457
            $field = self :: PUBLICATION_LANGUAGE;
2458
            $query .= ($languages == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($language) use ($field) {
2459
                                return '(' . $field . ' exact "' . $language . '")';
2460
                            }, $languages)) . ')');
2461
            $field = self :: PUBLICATION_FUNDER;
2462
            $query .= ($funders == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($funder) use ($field) {
2463
                                return '(' . $field . ' exact "' . $funder . '")';
2464
                            }, $funders)) . ')');
2465
            $field = self :: PUBLICATION_FUNDING_STREAM;
2466
            $query .= ($fundingStreams == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStream) use ($field) {
2467
                                return '(' . $field . ' exact "' . $fundingStream . '")';
2468
                            }, $fundingStreams)) . ')');
2469
            $field = self :: PUBLICATION_SCIENTIFIC_AREA;
2470
            $query .= ($scientificAreas == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($scientificArea) use ($field) {
2471
                                return '(' . $field . ' exact "' . $scientificArea . '")';
2472
                            }, $scientificAreas)) . ')');
2473
            $field = self :: PUBLICATION_FUNDING_STREAM_LEVEL2;
2474
            $query .= ($fundingStreamsLevel2 == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStreamsLevel2) use ($field) {
2475
                                return '(' . $field . ' exact "' . $fundingStreamsLevel2 . '")';
2476
                            }, $fundingStreamsLevel2)) . ')');
2477
            $from = new DateTime();
2478
            $to = new DateTime();
2479
            switch ($date) {
2480
                case -1:
2481
                    break;
2482
                case 0:
2483
                    $from->setDate($fromYear, $fromMonth, 1);
2484
                    $to->setDate($toYear, $toMonth, 1);
2485
                    $to->setDate($toYear, $toMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2486
                    $query .= ' and (' . self :: PUBLICATION_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2487
                    break;
2488
                default:
2489
                    $from->sub(new DateInterval('P' . $date . 'M'));
2490
                    $query .= ' and (' . self :: PUBLICATION_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2491
            }
2492
            $field = self :: PUBLICATION_ACCESS_MODE;
2493
            $query .= ($accessModes == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($accessMode) use ($field) {
2494
                                return '(' . $field . ' exact "' . $accessMode . '")';
2495
                            }, $accessModes)) . ')');
2496
            $field = self :: RESULT_HOSTING_DATASOURCE;
2497
            $query .= ($datasources == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($datasource) use ($field) {
2498
                                return '(' . $field . ' exact "' . $datasource . '")';
2499
                            }, $datasources)) . ')');
2500
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
2501
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
2502
            //$query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
2503
              if($funder != NULL && (strpos($funder, ',') !== FALSE)){
2504
                $temp='';
2505
                foreach(explode(',',$funder) as $id){
2506
                    if(!empty($id)){
2507
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
2508
                    }
2509

    
2510
                }
2511
                $query .=  (' and (' . substr($temp, 0, -3). ')');
2512
            }else{
2513
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
2514
            }
2515
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2516
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2517
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2518
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact "' . $year . '")');
2519
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
2520
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '")');
2521
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2522
            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 :: RESULT_HOSTING_DATASOURCE . '&locale=' . str_replace('-', '_', $locale))) == NULL)
2523
                throw new Exception('no HTTP response');
2524
            if ($response->code != self :: HTTP_OK)
2525
                throw new Exception('HTTP response code ' . $response->code);
2526
            $document = new DOMDocument();
2527
            $document->recover = TRUE;
2528
            if ($document->loadXML($response->body) == FALSE)
2529
                throw new Exception('invalid XML response');
2530
            $xpath = new DOMXPath($document);
2531
            $result = new JObject();
2532
            $result->totalPublications = $this->parseTotalResults($xpath);
2533
            $result->publications = $this->parsePublications($xpath);
2534
            $result->statistics =$this->createStatisticsForPublications($xpath,'Filter');
2535
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,"Filter");
2536
                    //$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 :: RESULT_HOSTING_DATASOURCE));
2537
            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);
2538
            return $result;
2539
        } catch (Exception $e) {
2540
            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);
2541
            return NULL;
2542
        }
2543
    }
2544

    
2545
    // Perform an advanced search for projects.
2546
    // $keywords the keywords to search for (array)
2547
    // $fields the fields to match keywords with (array - possible values are ACRONYM, TITLE and KEYWORDS)
2548
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2549
    // $funders the IDs of the funders to search for
2550
    // $fundingStreams the IDs of the funding streams to search for
2551
    // $scientificAreas the IDs of the scientific areas to search for
2552
    // $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)
2553
    // $startFromMonth start month of the start date range to search for if $startDate has value 0
2554
    // $startFromYear start year of the start date range to search for if $startDate has value 0
2555
    // $startToMonth end month of the start date range to search for if $startDate has value 0
2556
    // $startToYear end year of the start date range to search for if $startDate has value 0
2557
    // $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)
2558
    // $endFromMonth start month of the end date range to search for if $endDate has value 0
2559
    // $endFromYear start year of the end date range to search for if $endDate has value 0
2560
    // $endToMonth end month of the end date range to search for if $endDate has value 0
2561
    // $endToYear end year of the end date range to search for if $endDate has value 0
2562
    // $sc39s the IDs of the SC-39 statuses to search for
2563
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2564
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
2565
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2566
    // $startYear the start year to use as filter or NULL for no start year filtering
2567
    // $endYear the end year to use as filter or NULL for no end year filtering
2568
    // $sc39 the ID of the SC-39 status to use as filter or NULL for no SC-39 status filtering
2569
    // $page the page of results to retrieve
2570
    // $size the size of the page of results to retrieve
2571
    // $locale the locale to use
2572
    // return a result (object) containing projects and statistics
2573
    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) {
2574
        try {
2575
            $time = microtime(TRUE);
2576
            $query = self :: PROJECT_QUERY;
2577
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2578
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2579
                switch ($constraints[$i]) {
2580
                    case OpenAireViewAdvancedSearchProjects :: ALL:
2581
                        $operator = ' and ';
2582
                        break;
2583
                    case OpenAireViewAdvancedSearchProjects :: ANY:
2584
                        $operator = ' or ';
2585
                        break;
2586
                    default:
2587
                        $operator = NULL;
2588
                }
2589
                switch ($fields[$i]) {
2590
                    case OpenAireViewAdvancedSearchProjects :: ACRONYM:
2591
                        $field = self :: PROJECT_ACRONYM;
2592
                        break;
2593
                    case OpenAireViewAdvancedSearchProjects :: TITLE:
2594
                        $field = self :: PROJECT_TITLE;
2595
                        break;
2596
                    case OpenAireViewAdvancedSearchProjects :: KEYWORDS:
2597
                        $field = self :: PROJECT_KEYWORDS;
2598
                        break;
2599
                    default:
2600
                        $field = NULL;
2601
                }
2602
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2603
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2604
                                }, $tokens)) . ')');
2605
            }
2606
            $field = self :: PROJECT_FUNDER;
2607
            $query .= ($funders == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($funder) use ($field) {
2608
                                return '(' . $field . ' exact "' . $funder . '")';
2609
                            }, $funders)) . ')');
2610
            $field = self :: PROJECT_FUNDING_STREAM;
2611
            $query .= ($fundingStreams == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStream) use ($field) {
2612
                                return '(' . $field . ' exact "' . $fundingStream . '")';
2613
                            }, $fundingStreams)) . ')');
2614
            $field = self :: PROJECT_SCIENTIFIC_AREA;
2615
            $query .= ($scientificAreas == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($scientificArea) use ($field) {
2616
                                return '(' . $field . ' exact "' . $scientificArea . '")';
2617
                            }, $scientificAreas)) . ')');
2618
            $field = self :: PROJECT_FUNDING_STREAM_LEVEL2;
2619
            $query .= ($fundingStreamsLevel2 == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStreamsLevel2) use ($field) {
2620
                                return '(' . $field . ' exact "' . $fundingStreamsLevel2 . '")';
2621
                            }, $scientificAreas)) . ')');
2622
            $from = new DateTime();
2623
            $to = new DateTime();
2624
            switch ($startDate) {
2625
                case -1:
2626
                    break;
2627
                case 0:
2628
                    $from->setDate($startFromYear, $startFromMonth, 1);
2629
                    $to->setDate($startToYear, $startToMonth, 1);
2630
                    $to->setDate($startToYear, $startToMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2631
                    $query .= ' and (' . self :: PROJECT_START_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2632
                    break;
2633
                default:
2634
                    $from->sub(new DateInterval('P' . $startDate . 'M'));
2635
                    $query .= ' and (' . self :: PROJECT_START_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2636
            }
2637
            $from = new DateTime();
2638
            $to = new DateTime();
2639
            switch ($endDate) {
2640
                case -1:
2641
                    break;
2642
                case 0:
2643
                    $from->setDate($endFromYear, $endFromMonth, 1);
2644
                    $to->setDate($endToYear, $endToMonth, 1);
2645
                    $to->setDate($endToYear, $endToMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2646
                    $query .= ' and (' . self :: PROJECT_END_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2647
                    break;
2648
                default:
2649
                    $from->sub(new DateInterval('P' . $endDate . 'M'));
2650
                    $query .= ' and (' . self :: PROJECT_END_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2651
            }
2652
            $field = self :: PROJECT_SC39;
2653
            $query .= ($sc39s == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($sc39) use ($field) {
2654
                                return '(' . $field . ' exact "' . ($sc39 ? 'true' : 'false') . '")';
2655
                            }, $sc39s)) . ')');
2656
            $query .= ($funder == NULL) ? '' : (' and (' . self :: PROJECT_FUNDER . ' exact "' . $funder . '")');
2657
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2658
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PROJECT_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2659
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2660
            $query .= ($startYear == NULL) ? '' : (' and (' . self :: PROJECT_START_YEAR . ' exact "' . $startYear . '")');
2661
            $query .= ($endYear == NULL) ? '' : (' and (' . self :: PROJECT_END_YEAR . ' exact "' . $endYear . '")');
2662
            $query .= ($sc39 === NULL) ? '' : (' and (' . self :: PROJECT_SC39 . ' exact "' . ($sc39 ? 'true' : 'false') . '")');
2663
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2664
            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)
2665
                throw new Exception('no HTTP response');
2666
            if ($response->code != self :: HTTP_OK)
2667
                throw new Exception('HTTP response code ' . $response->code);
2668
            $document = new DOMDocument();
2669
            $document->recover = TRUE;
2670
            if ($document->loadXML($response->body) == FALSE)
2671
                throw new Exception('invalid XML response');
2672
            $xpath = new DOMXPath($document);
2673
            $result = new JObject();
2674
            $result->totalProjects = $this->parseTotalResults($xpath);
2675
            $result->projects = $this->parseProjects($xpath);
2676
            $result->statistics = $this->createStatisticsForProjects($xpath,"Filter");
2677
                    //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));
2678
            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) {
2679
                                return $sc39 ? 'true' : 'false';
2680
                            }, $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);
2681
            return $result;
2682
        } catch (Exception $e) {
2683
            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) {
2684
                                return $sc39 ? 'true' : 'false';
2685
                            }, $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);
2686
            return NULL;
2687
        }
2688
    }
2689

    
2690
    // Perform an advanced search for people.
2691
    // $keywords the keywords to search for (array)
2692
    // $fields the fields to match keywords with (array - possible values are LAST_NAME, FIRST_NAME and FULL_NAME)
2693
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2694
    // $countries the IDs of the countries to search for
2695
    // $country the ID of the coutnry to use as filter or NULL for no country filtering
2696
    // $page the page of results to retrieve
2697
    // $size the size of the page of results to retrieve
2698
    // $locale the locale to use
2699
    // return a result (object) containing people and statistics
2700
    private function _advancedSearchPeople($keywords, $fields, $constraints, $countries, $country, $page, $size, $locale) {
2701
        try {
2702
            $time = microtime(TRUE);
2703
            $query = self :: PERSON_QUERY;
2704
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2705
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2706
                switch ($constraints[$i]) {
2707
                    case OpenAireViewAdvancedSearchPeople :: ALL:
2708
                        $operator = ' and ';
2709
                        break;
2710
                    case OpenAireViewAdvancedSearchPeople :: ANY:
2711
                        $operator = ' or ';
2712
                        break;
2713
                    default:
2714
                        $operator = NULL;
2715
                }
2716
                switch ($fields[$i]) {
2717
                    case OpenAireViewAdvancedSearchPeople :: LAST_NAME:
2718
                        $field = self :: PERSON_LAST_NAME;
2719
                        break;
2720
                    case OpenAireViewAdvancedSearchPeople :: FIRST_NAME:
2721
                        $field = self :: PERSON_FIRST_NAME;
2722
                        break;
2723
                    case OpenAireViewAdvancedSearchPeople :: FULL_NAME:
2724
                        $field = self :: PERSON_FULL_NAME;
2725
                        break;
2726
                    default:
2727
                        $field = NULL;
2728
                }
2729
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2730
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2731
                                }, $tokens)) . ')');
2732
            }
2733
            // $field = self :: PERSON_COUNTRY;
2734
            // $query .= ($countries == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($country) use ($field) {
2735
            //                     return '(' . $field . ' exact "' . $country . '")';
2736
            //                 }, $countries)) . ')');
2737
            // $query .= ($country == NULL) ? '' : (' and (' . self :: PERSON_COUNTRY . ' exact "' . $country . '")');
2738
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2739
            if (($response = $this->performGet('search?action=searchNrefine&sTransformer=persons_openaire&rTransformer=results_openaire_browse&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale))) == NULL)
2740
                throw new Exception('no HTTP response');
2741
            if ($response->code != self :: HTTP_OK)
2742
                throw new Exception('HTTP response code ' . $response->code);
2743
            $document = new DOMDocument();
2744
            $document->recover = TRUE;
2745
            if ($document->loadXML($response->body) == FALSE)
2746
                throw new Exception('invalid XML response');
2747
            $xpath = new DOMXPath($document);
2748
            $result = new JObject();
2749
            $result->totalPeople = $this->parseTotalResults($xpath);
2750
            $result->people = $this->parsePeople($xpath);
2751
            $result->statistics = NULL; //$this->createStatistics($xpath, array('countryFilter'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: PERSON_COUNTRY));
2752
            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);
2753
            return $result;
2754
        } catch (Exception $e) {
2755
            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);
2756
            return NULL;
2757
        }
2758
    }
2759

    
2760
    // Perform an advanced search for organizations.
2761
    // $keywords the keywords to search for (array)
2762
    // $fields the fields to match keywords with (array - possible values are NAME and SHORT_NAME)
2763
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2764
    // $countries the IDs of the countries to search for
2765
    // $types the IDs of the organization types to search for
2766
    // $country the ID of the coutnry to use as filter or NULL for no country filtering
2767
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
2768
    // $page the page of results to retrieve
2769
    // $size the size of the page of results to retrieve
2770
    // $locale the locale to use
2771
    // return a result (object) containing organizations and statistics
2772
    private function _advancedSearchOrganizations($keywords, $fields, $constraints, $countries, $types, $country, $type, $page, $size, $locale) {
2773
        try {
2774
            $time = microtime(TRUE);
2775
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
2776
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2777
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2778
                switch ($constraints[$i]) {
2779
                    case OpenAireViewAdvancedSearchPeople :: ALL:
2780
                        $operator = ' and ';
2781
                        break;
2782
                    case OpenAireViewAdvancedSearchPeople :: ANY:
2783
                        $operator = ' or ';
2784
                        break;
2785
                    default:
2786
                        $operator = NULL;
2787
                }
2788
                switch ($fields[$i]) {
2789
                    case OpenAireViewAdvancedSearchOrganizations :: NAME:
2790
                        $field = self :: ORGANIZATION_NAME;
2791
                        break;
2792
                    case OpenAireViewAdvancedSearchOrganizations :: SHORT_NAME:
2793
                        $field = self :: ORGANIZATION_SHORT_NAME;
2794
                        break;
2795
                    default:
2796
                        $field = NULL;
2797
                }
2798
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2799
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2800
                                }, $tokens)) . ')');
2801
            }
2802
            $field = self :: ORGANIZATION_COUNTRY;
2803
            $query .= ($countries == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($country) use ($field) {
2804
                                return '(' . $field . ' exact "' . $country . '")';
2805
                            }, $countries)) . ')');
2806
            $organizationLegalBody = self :: ORGANIZATION_LEGAL_BODY;
2807
            $organizationLegalPerson = self :: ORGANIZATION_LEGAL_PERSON;
2808
            $organizationNonProfit = self :: ORGANIZATION_NON_PROFIT;
2809
            $organizationResearch = self :: ORGANIZATION_RESEARCH;
2810
            $organizationEuInterests = self :: ORGANIZATION_EU_INTERESTS;
2811
            $organizationInternational = self :: ORGANIZATION_INTERNATIONAL;
2812
            $organizationEnterprise = self :: ORGANIZATION_ENTERPRISE;
2813
            $organizationSmallMediumEnterprise = self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE;
2814
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($organizationLegalBody, $organizationLegalPerson, $organizationNonProfit, $organizationResearch, $organizationEuInterests, $organizationInternational, $organizationEnterprise, $organizationSmallMediumEnterprise) {
2815
                                switch ($type) {
2816
                                    case 'legalBody': return '(' . $organizationLegalBody . ' exact true)';
2817
                                    case 'legalPerson': return '(' . $organizationLegalPerson . ' exact true)';
2818
                                    case 'nonProfit': return '(' . $organizationNonProfit . ' exact true)';
2819
                                    case 'research': return '(' . $organizationResearch . ' exact true)';
2820
                                    case 'euInterests': return '(' . $organizationEuInterests . ' exact true)';
2821
                                    case 'international': return '(' . $organizationInternational . ' exact true)';
2822
                                    case 'enterprise': return '(' . $organizationEnterprise . ' exact true)';
2823
                                    case 'smallMediumEnterprise': return '(' . $organizationSmallMediumEnterprise . ' exact true)';
2824
                                }
2825
                            }, $types)) . ')');
2826
            $query .= ($country == NULL) ? '' : (' and (' . self :: ORGANIZATION_COUNTRY . ' exact "' . $country . '")');
2827
            switch ($type) {
2828
                case 'legalBody':
2829
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_BODY . ' exact true)';
2830
                    break;
2831
                case 'legalPerson':
2832
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_PERSON . ' exact true)';
2833
                    break;
2834
                case 'nonProfit':
2835
                    $query .= ' and (' . self :: ORGANIZATION_NON_PROFIT . ' exact true)';
2836
                    break;
2837
                case 'research':
2838
                    $query .= ' and (' . self :: ORGANIZATION_RESEARCH . ' exact true)';
2839
                    break;
2840
                case 'euInterests':
2841
                    $query .= ' and (' . self :: ORGANIZATION_EU_INTERESTS . ' exact true)';
2842
                    break;
2843
                case 'international':
2844
                    $query .= ' and (' . self :: ORGANIZATION_INTERNATIONAL . ' exact true)';
2845
                    break;
2846
                case 'enterprise':
2847
                    $query .= ' and (' . self :: ORGANIZATION_ENTERPRISE . ' exact true)';
2848
                    break;
2849
                case 'smallMediumEnterprise':
2850
                    $query .= ' and (' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . ' exact true)';
2851
            }
2852
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2853
            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)
2854
                throw new Exception('no HTTP response');
2855
            if ($response->code != self :: HTTP_OK)
2856
                throw new Exception('HTTP response code ' . $response->code);
2857
            $document = new DOMDocument();
2858
            $document->recover = TRUE;
2859
            if ($document->loadXML($response->body) == FALSE)
2860
                throw new Exception('invalid XML response');
2861
            $xpath = new DOMXPath($document);
2862
            $result = new JObject();
2863
            $result->totalOrganizations = $this->parseTotalResults($xpath);
2864
            $result->organizations = $this->parseOrganizations($xpath);
2865
            $result->statistics = $this->createStatistics($xpath, array('countryFilter'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
2866
            $result->statistics['typeFilter'] = new JObject();
2867
            $result->statistics['typeFilter']->id = 'typeFilter';
2868
            $result->statistics['typeFilter']->title = JText :: _('TYPE');
2869
            $result->statistics['typeFilter']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
2870
            $result->statistics['typeFilter']->data = array();
2871
            $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
2872
            if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
2873
                $result->statistics['typeFilter']->data['legalBody'] = new JObject();
2874
                $result->statistics['typeFilter']->data['legalBody']->id = 'legalBody';
2875
                $result->statistics['typeFilter']->data['legalBody']->name = JText :: _('LEGAL_BODY');
2876
                $result->statistics['typeFilter']->data['legalBody']->count = $legalBody['true']->count;
2877
            }
2878
            $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
2879
            if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
2880
                $result->statistics['typeFilter']->data['legalPerson'] = new JObject();
2881
                $result->statistics['typeFilter']->data['legalPerson']->id = 'legalPerson';
2882
                $result->statistics['typeFilter']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
2883
                $result->statistics['typeFilter']->data['legalPerson']->count = $legalPerson['true']->count;
2884
            }
2885
            $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
2886
            if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
2887
                $result->statistics['typeFilter']->data['nonProfit'] = new JObject();
2888
                $result->statistics['typeFilter']->data['nonProfit']->id = 'nonProfit';
2889
                $result->statistics['typeFilter']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
2890
                $result->statistics['typeFilter']->data['nonProfit']->count = $nonProfit['true']->count;
2891
            }
2892
            $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
2893
            if (($research != NULL) && array_key_exists('true', $research)) {
2894
                $result->statistics['typeFilter']->data['research'] = new JObject();
2895
                $result->statistics['typeFilter']->data['research']->id = 'research';
2896
                $result->statistics['typeFilter']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
2897
                $result->statistics['typeFilter']->data['research']->count = $research['true']->count;
2898
            }
2899
            $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
2900
            if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
2901
                $result->statistics['typeFilter']->data['euInterests'] = new JObject();
2902
                $result->statistics['typeFilter']->data['euInterests']->id = 'euInterests';
2903
                $result->statistics['typeFilter']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
2904
                $result->statistics['typeFilter']->data['euInterests']->count = $euInterests['true']->count;
2905
            }
2906
            $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
2907
            if (($international != NULL) && array_key_exists('true', $international)) {
2908
                $result->statistics['typeFilter']->data['international'] = new JObject();
2909
                $result->statistics['typeFilter']->data['international']->id = 'international';
2910
                $result->statistics['typeFilter']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
2911
                $result->statistics['typeFilter']->data['international']->count = $international['true']->count;
2912
            }
2913
            $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
2914
            if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
2915
                $result->statistics['typeFilter']->data['enterprise'] = new JObject();
2916
                $result->statistics['typeFilter']->data['enterprise']->id = 'enterprise';
2917
                $result->statistics['typeFilter']->data['enterprise']->name = JText :: _('ENTERPRISE');
2918
                $result->statistics['typeFilter']->data['enterprise']->count = $enterprise['true']->count;
2919
            }
2920
            $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
2921
            if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
2922
                $result->statistics['typeFilter']->data['smallMediumEnterprise'] = new JObject();
2923
                $result->statistics['typeFilter']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
2924
                $result->statistics['typeFilter']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
2925
                $result->statistics['typeFilter']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
2926
            }
2927
            uasort($result->statistics['typeFilter']->data, function ($row1, $row2) {
2928
                return $row2->count - $row1->count;
2929
            });
2930
            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);
2931
            return $result;
2932
        } catch (Exception $e) {
2933
            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);
2934
            return NULL;
2935
        }
2936
    }
2937

    
2938
    // Perform an advanced search for datasources.
2939
    // $keywords the keywords to search for (array)
2940
    // $fields the fields to match keywords with (array - possible values are NAME, ENGLISH_NAME and SUBJECT)
2941
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2942
    // $types the IDs of the datasource types to search for
2943
    // $languages the IDs of the datasource languages to search for
2944
    // $contents the IDs of the contents to search for
2945
    // $compatibilities the IDs of the compatibilities to search for
2946
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
2947
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
2948
    // $content the ID of the content to use as filter or NULL for no content filtering
2949
    // $compatibility the ID of the compatibility to use as filter or NULL for no compatibility filtering
2950
    // $page the page of results to retrieve
2951
    // $size the size of the page of results to retrieve
2952
    // $locale the locale to use
2953
    // return a result (object) containing datasources and statistics
2954
    private function _advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale) {
2955
        try {
2956
            $time = microtime(TRUE);
2957
            $query = self :: DATASOURCE_QUERY;
2958
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2959
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2960
                switch ($constraints[$i]) {
2961
                    case OpenAireViewAdvancedSearchDatasources :: ALL:
2962
                        $operator = ' and ';
2963
                        break;
2964
                    case OpenAireViewAdvancedSearchDatasources :: ANY:
2965
                        $operator = ' or ';
2966
                        break;
2967
                    default:
2968
                        $operator = NULL;
2969
                }
2970
                switch ($fields[$i]) {
2971
                    case OpenAireViewAdvancedSearchDatasources :: NAME:
2972
                        $field = self :: DATASOURCE_NAME;
2973
                        break;
2974
                    case OpenAireViewAdvancedSearchDatasources :: ENGLISH_NAME:
2975
                        $field = self :: DATASOURCE_ENGLISH_NAME;
2976
                        break;
2977
                    case OpenAireViewAdvancedSearchDatasources :: SUBJECT:
2978
                        $field = self :: DATASOURCE_SUBJECT;
2979
                        break;
2980
                    default:
2981
                        $field = NULL;
2982
                }
2983
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2984
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2985
                                }, $tokens)) . ')');
2986
            }
2987
            $field = self :: DATASOURCE_TYPE;
2988
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($field) {
2989
                                return '(' . $field . ' exact "' . $type . '")';
2990
                            }, $types)) . ')');
2991
            $field = self :: DATASOURCE_LANGUAGE;
2992
            $query .= ($languages == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($language) use ($field) {
2993
                                return '(' . $field . ' exact "' . $language . '")';
2994
                            }, $languages)) . ')');
2995
            $field = self :: DATASOURCE_CONTENT;
2996
            $query .= ($contents == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($content) use ($field) {
2997
                                return '(' . $field . ' exact "' . $content . '")';
2998
                            }, $contents)) . ')');
2999
            $field = self :: DATASOURCE_COMPATIBILITY;
3000
            $query .= ($compatibilities == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($compatibility) use ($field) {
3001
                                return '(' . $field . ' exact "' . $compatibility . '")';
3002
                            }, $compatibilities)) . ')');
3003
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASOURCE_TYPE . ' exact "' . $type . '")');
3004
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASOURCE_LANGUAGE . ' exact "' . $language . '")');
3005
            $query .= ($content == NULL) ? '' : (' and (' . self :: DATASOURCE_CONTENT . ' exact "' . $content . '")');
3006
            $query .= ($compatibility == NULL) ? '' : (' and (' . self :: DATASOURCE_COMPATIBILITY . ' exact "' . $compatibility . '")');
3007
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3008
            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)
3009
                throw new Exception('no HTTP response');
3010
            if ($response->code != self :: HTTP_OK)
3011
                throw new Exception('HTTP response code ' . $response->code);
3012
            $document = new DOMDocument();
3013
            $document->recover = TRUE;
3014
            if ($document->loadXML($response->body) == FALSE)
3015
                throw new Exception('invalid XML response');
3016
            $xpath = new DOMXPath($document);
3017
            $result = new JObject();
3018
            $result->totalDatasources = $this->parseTotalResults($xpath);
3019
            $result->datasources = $this->parseDatasources($xpath);
3020
            $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));
3021
            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);
3022
            return $result;
3023
        } catch (Exception $e) {
3024
            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);
3025
            return NULL;
3026
        }
3027
    }
3028

    
3029
    // Retrieve a single publication by identifier.
3030
    // $id the publication identifier
3031
    // $locale the locale to use
3032
    // return a publication (object) or NULL if no such publication exists
3033
    private function _getPublication($id, $locale) {
3034
        try {
3035
            $time = microtime(TRUE);
3036
            $query = self :: PUBLICATION_QUERY . ' and ( (' . self :: PUBLICATION_ID . ' exact "' . $id . '") or (' . self :: RESULT_DUP_ID . ' exact "' . $id . '" ) )';
3037
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3038
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3039
                throw new Exception('no HTTP response');
3040
            if ($response->code != self :: HTTP_OK)
3041
                throw new Exception('HTTP response code ' . $response->code);
3042
            $document = new DOMDocument();
3043
            $document->recover = TRUE;
3044
            if ($document->loadXML($response->body) == FALSE)
3045
                throw new Exception('invalid XML response');
3046
            $xpath = new DOMXPath($document);
3047
            $publication = $this->parsePublication($xpath, $locale);
3048
            JLog :: add('Retrieved publication in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3049
            return $publication;
3050
        } catch (Exception $e) {
3051
            JLog :: add('Error retrieving publication (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3052
            return NULL;
3053
        }
3054
    }
3055

    
3056
    // Retrieve results by identifier.
3057
    // $ids the result identifiers
3058
    // $locale the locale to use
3059
    // return a result (object) or NULL if no such result exists
3060
    private function _getResults($ids, $locale) {
3061
        try {
3062
            $time = microtime(TRUE);
3063
            $query = self :: RESULT_QUERY . ' and (';
3064
            $parts = array();
3065
            foreach ($ids as $id) {
3066
                $parts[] = ('(' . self :: RESULT_ID . ' exact "' . $id . '") OR (' . self :: RESULT_DUP_ID . ' exact "' . $id . '") ');
3067
               //  $parts[] = ('(' . self :: RESULT_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) . '&size=10000&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
            $results = $this->parseResults($ids,$xpath, $locale);
3082
            JLog :: add('Retrieved results in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3083
            return $results;
3084
        } catch (Exception $e) {
3085
            JLog :: add('Error retrieving results (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 _getPublications($ids, $locale) {
3095
        try {
3096
            $time = microtime(TRUE);
3097
            $query = self :: PUBLICATION_QUERY . ' and (';
3098
            $parts = array();
3099
            foreach ($ids as $id) {
3100
                $parts[] = '(' . self :: PUBLICATION_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=results_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
            $publications = $this->parsePublications($xpath, $locale);
3115
            JLog :: add('Retrieved publication in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3116
            return $publications;
3117
        } catch (Exception $e) {
3118
            JLog :: add('Error retrieving publication (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3119
            return NULL;
3120
        }
3121
    }
3122

    
3123
    // Retrieve publications by identifier.
3124
    // $ids the publication identifiers
3125
    // $locale the locale to use
3126
    // return a publication (object) or NULL if no such publication exists
3127
    private function _getProjects($ids, $locale) {
3128
        try {
3129
            $time = microtime(TRUE);
3130
            $query = self :: PROJECT_QUERY . ' and (';
3131
            $parts = array();
3132
            foreach ($ids as $id) {
3133
                $parts[] = '(' . self :: PROJECT_ID . ' exact "' . $id . '")';
3134
            }
3135
            $query .= join(" OR ", $parts);
3136
            $query .= ')';
3137
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3138
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3139
                throw new Exception('no HTTP response');
3140
            if ($response->code != self :: HTTP_OK)
3141
                throw new Exception('HTTP response code ' . $response->code);
3142
            $document = new DOMDocument();
3143
            $document->recover = TRUE;
3144
            if ($document->loadXML($response->body) == FALSE)
3145
                throw new Exception('invalid XML response');
3146
            $xpath = new DOMXPath($document);
3147
            $projects = $this->parseProjects($xpath, $locale);
3148
            JLog :: add('Retrieved projects in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3149
            return $projects;
3150
        } catch (Exception $e) {
3151
            JLog :: add('Error retrieving projects (ids: ' . join(",", $ids) . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3152
            return NULL;
3153
        }
3154
    }
3155

    
3156
    // Retrieve datasets by identifier.
3157
    // $ids the datasets identifiers
3158
    // $locale the locale to use
3159
    // return datasets array of (object) or NULL if no such dataset exists
3160
    private function _getDatasets($ids, $locale) {
3161
        try {
3162
            $time = microtime(TRUE);
3163
            $query = self :: DATASET_QUERY . ' and (';
3164
            $parts = array();
3165
            foreach ($ids as $id) {
3166
                $parts[] = '(' . self :: DATASET_ID . ' exact "' . $id . '")';
3167
            }
3168
            $query .= join(" OR ", $parts);
3169
            $query .= ')';
3170
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3171
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3172
                throw new Exception('no HTTP response');
3173
            if ($response->code != self :: HTTP_OK)
3174
                throw new Exception('HTTP response code ' . $response->code);
3175
            $document = new DOMDocument();
3176
            $document->recover = TRUE;
3177
            if ($document->loadXML($response->body) == FALSE)
3178
                throw new Exception('invalid XML response');
3179
            $xpath = new DOMXPath($document);
3180
            $datasets = $this->parseDatasets($xpath, $locale);
3181
            JLog :: add('Retrieved publication in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3182
            return $datasets;
3183
        } catch (Exception $e) {
3184
            JLog :: add('Error retrieving publication (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3185
            return NULL;
3186
        }
3187
    }
3188

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3512
            $statistic->count = intval(trim($countNode->nodeValue));
3513
            $statistics[$statistic->id] = $statistic;
3514
        }
3515
        return $statistics;
3516
    }
3517

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

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

    
3599
            foreach ($relatedNodes as $relatedNode) {
3600

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

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

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

    
3764
            foreach ($relatedNodes as $relatedNode) {
3765

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

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

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

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

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

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

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

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

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

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

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

    
4393
            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))))) {
4394
                $publication->accessMode = $datasource->accessMode;
4395
                $publication->url = $datasource->url;
4396

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

    
4437

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

    
4455
            $project->funding = new JObject();
4456
            $project->funding->funding_level_0 = NULL;
4457
            $project->funding->funding_level_1 = NULL;
4458
            $project->funding->funding_level_2 = NULL;
4459

    
4460
            if (($fundingNode = $fundingNodes->item(0)) == NULL)
4461
                ;
4462
            else {
4463
                 if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
4464
                    throw new Exception('error parsing project');
4465
                if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
4466
                    throw new Exception('error parsing project');
4467
                if (($funding0Nodes = $xpath->query('./field[@name = "funding_level_0"]', $fundingNode)) == FALSE)
4468
                    throw new Exception('error parsing project');
4469
                if (($funding1Nodes = $xpath->query('./field[@name = "funding_level_1"]', $fundingNode)) == FALSE)
4470
                    throw new Exception('error parsing project');
4471
                if (($funding2Nodes = $xpath->query('./field[@name = "funding_level_2"]', $fundingNode)) == FALSE)
4472
                    throw new Exception('error parsing project');
4473

    
4474
                $project->funding->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
4475
                $project->funding->funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
4476

    
4477
                if (($funding0Node = $funding0Nodes->item(0)) == NULL)
4478
                    ;
4479
                else {
4480
                    if (($funding0NameNodes = $xpath->query('./@value', $funding0Node)) == FALSE)
4481
                        throw new Exception('error parsing publication test');
4482
                    $project->funding->funding_level_0 = (($funding0NameNode = $funding0NameNodes->item(0)) == NULL) ? NULL : trim($funding0NameNode->nodeValue);
4483
                   // $array = explode("::", $project->funding->funding_level_0);
4484
                   // $project->funding->funding_level_0 = $array[sizeof($array) - 1];
4485
                }
4486
                if (($funding1Node = $funding1Nodes->item(0)) == NULL)
4487
                    ;
4488
                else {
4489
                    if (($funding1NameNodes = $xpath->query('./@value', $funding1Node)) == FALSE)
4490
                        throw new Exception('error parsing publication test');
4491
                    $project->funding->funding_level_1 = (($funding1NameNode = $funding1NameNodes->item(0)) == NULL) ? NULL : trim($funding1NameNode->nodeValue);
4492
                   // $array = explode("::", $project->funding->funding_level_1);
4493
                    //$project->funding->funding_level_1 = $array[sizeof($array) - 1];
4494
                }
4495
                if (($funding2Node = $funding2Nodes->item(0)) == NULL)
4496
                    ;
4497
                else {
4498
                    if (($funding2NameNodes = $xpath->query('./@valu', $funding2Node)) == FALSE)
4499
                        throw new Exception('error parsing publication test');
4500
                    $project->funding->funding_level_2 = (($funding2NameNode = $funding2NameNodes->item(0)) == NULL) ? NULL : trim($funding2NameNode->nodeValue);
4501
                   // $array = explode("::", $project->funding->funding_level_2);
4502
                   // $project->funding->funding_level_2 = $array[sizeof($array) - 1];
4503
                }
4504
            }
4505
            //!!!!
4506

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

    
4541
            $similarPublication = new JObject();
4542
            $similarPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4543
            $similarPublication->source = 'openaire';
4544
            $similarPublication->url = NULL;
4545
            $similarPublication->accessMode = NULL;
4546
            $similarPublication->datasources = array();
4547
            $similarPublication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4548
            $similarPublication->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4549
            $similarPublication->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4550
            $similarPublication->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4551
            $similarPublication->authors = array();
4552
            $similarPublication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4553
            $similarPublication->projects = array();
4554
            $similarPublication->embargoEndDate = NULL;
4555
            $similarPublication->description = NULL;
4556
            $similarPublication->similarity = (($similarityNode = $similarityNodes->item(0)) == NULL) ? NULL : trim($similarityNode->nodeValue);
4557
            $similarPublication->similarity = number_format((float) $similarPublication->similarity, 2);
4558
            if (($similarPublication->id != NULL) || ($similarPublication->title != NULL) || ($similarPublication->year != NULL)) {
4559
                $publication->similarPublications[] = $similarPublication;
4560
            }
4561
        }
4562
        foreach ($relatedNodes as $relatedNode) {
4563
            if (($typeNodes = $xpath->query('./field[@name = "resulttypename"]/@value', $relatedNode)) == FALSE)
4564
                throw new Exception('error parsing publication');
4565
            if (($idNodes = $xpath->query('./field[@name = "resultid"]/@value', $relatedNode)) == FALSE)
4566
                throw new Exception('error parsing publication');
4567
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
4568
                throw new Exception('error parsing publication');
4569
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
4570
                throw new Exception('error parsing publication');
4571
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
4572
                throw new Exception('error parsing publication');
4573
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $relatedNode)) == FALSE)
4574
                throw new Exception('error parsing publication');
4575
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $relatedNode)) == FALSE)
4576
                throw new Exception('error parsing publication');
4577
            switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
4578
                case self :: PUBLICATION:
4579
                    $relatedPublication = new JObject();
4580
                    $relatedPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4581
                    $relatedPublication->source = 'openaire';
4582
                    $relatedPublication->url = NULL;
4583
                    $relatedPublication->accessMode = NULL;
4584
                    $relatedPublication->datasources = array();
4585
                    $relatedPublication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4586
                    $relatedPublication->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4587
                    $relatedPublication->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4588
                    $relatedPublication->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4589
                    $relatedPublication->authors = array();
4590
                    $relatedPublication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4591
                    $relatedPublication->projects = array();
4592
                    $relatedPublication->embargoEndDate = NULL;
4593
                    $relatedPublication->description = NULL;
4594
                    if (($relatedPublication->id != NULL) || ($relatedPublication->title != NULL) || ($relatedPublication->year != NULL))
4595
                        $publication->relatedPublications[] = $relatedPublication;
4596
                    break;
4597
                case self :: DATASET:
4598
                    $relatedDataset = new JObject();
4599
                    $relatedDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4600
                    $relatedDataset->source = 'openaire';
4601
                    $relatedDataset->url = NULL;
4602
                    $relatedDataset->accessMode = NULL;
4603
                    $relatedDataset->datasources = array();
4604
                    $relatedDataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4605
                    $relatedDataset->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4606
                    $relatedDataset->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4607
                    $relatedDataset->trust = number_format((float) $relatedDataset->trust, 2);
4608
                    $relatedDataset->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4609
                    $relatedDataset->authors = array();
4610
                    $relatedDataset->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4611
                    $relatedDataset->projects = array();
4612
                    $relatedDataset->embargoEndDate = NULL;
4613
                    $relatedDataset->description = NULL;
4614
                    if (($relatedDataset->id != NULL) || ($relatedDataset->title != NULL) || ($relatedDataset->year != NULL))
4615
                        $publication->relatedDatasets[] = $relatedDataset;
4616
                    break;
4617
            }
4618
        }
4619
        foreach ($externalReferenceNodes as $externalReferenceNode) {
4620
            if (($typeNodes = $xpath->query('./field[@name = "typeid"]/@value', $externalReferenceNode)) == FALSE)
4621
                throw new Exception('error parsing publication');
4622
            if (($idNodes = $xpath->query('./field[@name = "refidentifier"]/@value', $externalReferenceNode)) == FALSE)
4623
                throw new Exception('error parsing publication');
4624
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $externalReferenceNode)) == FALSE)
4625
                throw new Exception('error parsing publication');
4626
            if (($labelNodes = $xpath->query('./field[@name = "label"]/@value', $externalReferenceNode)) == FALSE)
4627
                throw new Exception('error parsing publication');
4628
            if (($siteNameNodes = $xpath->query('./field[@name = "sitename"]/@value', $externalReferenceNode)) == FALSE)
4629
                throw new Exception('error parsing publication');
4630
                    $externalEntity = new JObject();
4631
                    //dedup_wf_001::2cd206acf2cfd37f1a7c28823c63112b
4632
                    $externalEntity-> type = (($typeNode =$typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4633
                    $externalEntity-> id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4634
                    $externalEntity-> url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4635
                    $externalEntity-> title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
4636
                    $externalEntity-> sitename = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
4637
                     if (!isset($publication->bioentities[$externalEntity->sitename])){
4638
                        $bioentities = array();
4639
                        $publication->bioentities[$externalEntity->sitename]=$bioentities;
4640
                     }
4641
                     $publication->bioentities[$externalEntity->sitename] []= $externalEntity;
4642

    
4643
           /* switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
4644
                case self :: PUBLICATION:
4645
                    $externalPublication = new JObject();
4646
                    $externalPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4647
                    $externalPublication->source = NULL;
4648
                    $externalPublication->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4649
                    $externalPublication->accessMode = NULL;
4650
                    $externalPublication->datasources = array();
4651
                    $externalPublication->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
4652
                    $externalPublication->authors = array();
4653
                    $site = new JObject();
4654
                    $site->id = NULL;
4655
                    $site->lastName = NULL;
4656
                    $site->firstName = NULL;
4657
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
4658
                    if ($site->fullName != NULL)
4659
                        $externalPublication->authors[] = $site;
4660
                    $externalPublication->year = NULL;
4661
                    $externalPublication->projects = array();
4662
                    $externalPublication->embargoEndDate = NULL;
4663
                    $externalPublication->description = NULL;
4664
                    if (($externalPublication->id != NULL) || ($externalPublication->url != NULL) || ($externalPublication->title != NULL))
4665
                        $publication->externalPublications[] = $externalPublication;
4666
                    break;
4667
                case self :: DATASET:
4668
                    $externalDataset = new JObject();
4669
                    $externalDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4670
                    $externalDataset->source = NULL;
4671
                    $externalDataset->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4672
                    $externalDataset->accessMode = NULL;
4673
                    $externalDataset->datasources = array();
4674
                    $externalDataset->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
4675
                    $externalDataset->authors = array();
4676
                    $site = new JObject();
4677
                    $site->id = NULL;
4678
                    $site->lastName = NULL;
4679
                    $site->firstName = NULL;
4680
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
4681
                    if ($site->fullName != NULL)
4682
                        $externalDataset->authors[] = $site;
4683
                    $externalDataset->year = NULL;
4684
                    $externalDataset->projects = array();
4685
                    $externalDataset->embargoEndDate = NULL;
4686
                    $externalDataset->description = NULL;
4687
                    if (($externalDataset->id != NULL) || ($externalDataset->url != NULL) || ($externalDataset->title != NULL))
4688
                        $publication->externalDatasets[] = $externalDataset;
4689
            }*/
4690
        }
4691
        foreach ($contextNodes as $contextNode) {
4692
            if (($idNodes = $xpath->query('./@value', $contextNode)) == FALSE)
4693
                throw new Exception('error parsing publication');
4694
            if (($nameNodes = $xpath->query('./@value_original', $contextNode)) == FALSE)
4695
                throw new Exception('error parsing publication');
4696
            if (($typeNodes = $xpath->query('./field[@name = "contexttype"]/@value', $contextNode)) == FALSE)
4697
                throw new Exception('error parsing publication');
4698
            if (($categoryNodes = $xpath->query('./field[@name = "category"]', $contextNode)) == FALSE)
4699
                throw new Exception('error parsing publication');
4700
            $context = new JObject();
4701
            $context->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4702
            $context->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4703
            $context->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4704
            $context->categories = array();
4705
            foreach ($categoryNodes as $categoryNode) {
4706
                if (($idNodes = $xpath->query('./@value_original', $categoryNode)) == FALSE)
4707
                    throw new Exception('error parsing publication');
4708
                if (($nameNodes = $xpath->query('./@value', $categoryNode)) == FALSE)
4709
                    throw new Exception('error parsing publication');
4710
                if (($conceptNodes = $xpath->query('./field[@name = "concept"]', $categoryNode)) == FALSE)
4711
                    throw new Exception('error parsing publication');
4712
                $category = new JObject();
4713
                $category->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4714
                $category->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4715
                $category->concepts = array();
4716
                foreach ($conceptNodes as $conceptNode) {
4717
                    if (($idNodes = $xpath->query('./@value_original', $conceptNode)) == FALSE)
4718
                        throw new Exception('error parsing publication');
4719
                    if (($nameNodes = $xpath->query('./@value', $conceptNode)) == FALSE)
4720
                        throw new Exception('error parsing publication');
4721
                    $concept = new JObject();
4722
                    $concept->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4723
                    $concept->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4724
                    if (($concept->id != NULL) || ($concept->name != NULL))
4725
                        $category->concepts[] = $concept;
4726
                }
4727
                if (($category->id != NULL) || ($category->name != NULL) || ($category->concepts != NULL))
4728
                    $context->categories[] = $category;
4729
            }
4730
            if (($context->id != NULL) || ($context->name != NULL) || ($context->categories != NULL))
4731
                $publication->contexts[] = $context;
4732
        }
4733
        foreach ($citationNodes as $citationNode) {
4734
            if (($titleNodes = $xpath->query('./field[@name = "rawText"]/@value', $citationNode)) == FALSE)
4735
                throw new Exception('error parsing publications');
4736
            if (($idsNodes = $xpath->query('./field[@name = "citationId"]', $citationNode)) == FALSE)
4737
                throw new Exception('error parsing publications');
4738
            $citation = new JObject();
4739
            $citation->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4740
            $citation->ids = array();
4741
            foreach ($idsNodes as $citationIdNode) {
4742
                if (($idNodes = $xpath->query('./field[@name = "id"]/@value', $citationIdNode)) == FALSE)
4743
                    throw new Exception('error parsing publications');
4744
                if (($typeNodes = $xpath->query('./field[@name = "type"]/@value', $citationIdNode)) == FALSE)
4745
                    throw new Exception('error parsing publications');
4746
                if (($confidenceLevelNodes = $xpath->query('./field[@name = "confidenceLevel"]/@value', $citationIdNode)) == FALSE)
4747
                    throw new Exception('error parsing publications');
4748
                $ids = new JObject();
4749
                $ids->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4750
                $ids->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4751
                $ids->confidenceLevel = (($confidenceLevelNode = $confidenceLevelNodes->item(0)) == NULL) ? NULL : trim($confidenceLevelNode->nodeValue);
4752
                $citation->ids[] = $ids;
4753
            }
4754

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

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

    
4923

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

    
4941
            $project->funding = new JObject();
4942
            $project->funding->funding_level_0 = NULL;
4943
            $project->funding->funding_level_1 = NULL;
4944
            $project->funding->funding_level_2 = NULL;
4945

    
4946
            if (($fundingNode = $fundingNodes->item(0)) == NULL)
4947
                ;
4948
            else {
4949
                if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
4950
                    throw new Exception('error parsing project');
4951
                if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
4952
                    throw new Exception('error parsing project');
4953
                if (($funding0Nodes = $xpath->query('./field[@name = "funding_level_0"]', $fundingNode)) == FALSE)
4954
                    throw new Exception('error parsing project');
4955
                if (($funding1Nodes = $xpath->query('./field[@name = "funding_level_1"]', $fundingNode)) == FALSE)
4956
                    throw new Exception('error parsing project');
4957
                if (($funding2Nodes = $xpath->query('./field[@name = "funding_level_2"]', $fundingNode)) == FALSE)
4958
                    throw new Exception('error parsing project');
4959
                $project->funding->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
4960
                $project->funding->funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
4961

    
4962
                if (($funding0Node = $funding0Nodes->item(0)) == NULL)
4963
                    ;
4964
                else {
4965
                    if (($funding0NameNodes = $xpath->query('./@value', $funding0Node)) == FALSE)
4966
                        throw new Exception('error parsing publication test');
4967
                    $project->funding->funding_level_0 = (($funding0NameNode = $funding0NameNodes->item(0)) == NULL) ? NULL : trim($funding0NameNode->nodeValue);
4968
                    //$array = explode("::", $project->funding->funding_level_0);
4969
                    //$project->funding->funding_level_0 = $array[sizeof($array) - 1];
4970
                }
4971
                if (($funding1Node = $funding1Nodes->item(0)) == NULL)
4972
                    ;
4973
                else {
4974
                    if (($funding1NameNodes = $xpath->query('./@value', $funding1Node)) == FALSE)
4975
                        throw new Exception('error parsing publication test');
4976
                    $project->funding->funding_level_1 = (($funding1NameNode = $funding1NameNodes->item(0)) == NULL) ? NULL : trim($funding1NameNode->nodeValue);
4977
                    //$array = explode("::", $project->funding->funding_level_1);
4978
                    //$project->funding->funding_level_1 = $array[sizeof($array) - 1];
4979
                }
4980
                if (($funding2Node = $funding2Nodes->item(0)) == NULL)
4981
                    ;
4982
                else {
4983
                    if (($funding2NameNodes = $xpath->query('./@value', $funding2Node)) == FALSE)
4984
                        throw new Exception('error parsing publication test');
4985
                    $project->funding->funding_level_2 = (($funding2NameNode = $funding2NameNodes->item(0)) == NULL) ? NULL : trim($funding2NameNode->nodeValue);
4986
                    //$array = explode("::", $project->funding->funding_level_2);
4987
                    //$project->funding->funding_level_2 = $array[sizeof($array) - 1];
4988
                }
4989
                /* 	if (($idNodes = $xpath -> query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
4990
                  throw new Exception('error parsing dataset');
4991
                  if (($acronymNodes = $xpath -> query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
4992
                  throw new Exception('error parsing dataset');
4993
                  if (($titleNodes = $xpath -> query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
4994
                  throw new Exception('error parsing dataset');
4995
                  if (($codeNodes = $xpath -> query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
4996
                  throw new Exception('error parsing dataset');
4997
                  $project = new JObject();
4998
                  $project -> id = (($idNode = $idNodes -> item(0)) == NULL) ? NULL : trim($idNode -> nodeValue);
4999
                  $project -> acronym = (($acronymNode = $acronymNodes -> item(0)) == NULL) ? NULL : ((trim($acronymNode -> nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode -> nodeValue));
5000
                  $project -> title = (($titleNode = $titleNodes -> item(0)) == NULL) ? NULL : trim($titleNode -> nodeValue);
5001
                  $project -> code = (($codeNode = $codeNodes -> item(0)) == NULL) ? NULL : trim($codeNode -> nodeValue);
5002

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

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

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

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

    
5393
                }
5394

    
5395
            }
5396
           $project->funders=array_unique($project->funders);
5397
            if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL)){
5398
                $organization->projects[] = $project;
5399
                //$organization->allFunders =array_merge($organization->allFunders,$project->funders);
5400
            }
5401
        }
5402
        //$organization->allFunders=array_unique($organization->allFunders);
5403
        return $organization;
5404
    }
5405

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

    
5474
    }
5475
    private function createStatisticsForProjects($xpath, $filter =''){
5476
        return $this->  createStatistics($xpath,
5477
                array('funder'.$filter, 'fundingStream'.$filter, 'fundingStreamLevel1'.$filter, 'fundingStreamLevel2'.$filter ,  'startYear'.$filter, 'endYear'.$filter, 'sc39'.$filter),
5478
                array('FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'FUNDING_STREAM_LEVEL_2', 'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'),
5479
                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'),
5480
                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));
5481

    
5482
    }
5483
    private function _validateResultsSize($size=10){
5484
        if($size > 50){
5485
            $size = 10;
5486
        }
5487
        return $size;
5488
    }
5489

    
5490
}
(7-7/9)