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

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

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

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

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

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

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

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

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

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

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

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

    
306
    // Perform a simple search for publications using cache if enabled.
307
    // $keyword the keyword to search for
308
    // $articles flag to limit searching on articles; if all flags are FALSE no limits apply
309
    // $books flag to limit searching on books; if all flags are FALSE no limits apply
310
    // $theses flag to limit searching on books; if all flags are FALSE no limits apply
311
    // $reports flag to limit searching on reports; if all flags are FALSE no limits apply
312
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
313
    // $language the ID of the language to use as filter or NULL for no language filtering
314
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
315
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
316
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
317
    // $year the year of publication to use as filter or NULL for no year filtering
318
    // $accessMode the ID of the access mode to use as a filter or NULL for no access mode filtering
319
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
320
    // $community the ID of the community to use as filter or NULL for no community filtering
321
    // $page the page of results to retrieve
322
    // $size the size of the page of results to retrieve
323
    // $locale the locale to use
324
    // return a result (object) containing publications and statistics
325
    public function searchPublications($keyword, $articles, $books, $theses, $reports, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $isRefine) {
326
        if ($this->cache->getCaching()) {
327
            $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;
328
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
329
            if ($result === FALSE) {
330
                $result = $this->_searchPublications($keyword, $articles, $books, $theses, $reports, $type, $language, $funder, $fundingStream, $scientificArea,$fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $isRefine);
331
                if ($result !== NULL)
332
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
333
            }
334
        } else {
335
            $result = $this->_searchPublications($keyword, $articles, $books, $theses, $reports, $type, $language, $funder, $fundingStream, $scientificArea,$fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $isRefine);
336
        }
337
        return $result;
338
    }
339

    
340
    // Perform a simple search for datasets using cache if enabled.
341
    // $keyword the keyword to search for
342
    // $type the ID of the dataset type to use as filter or NULL for no dataset type filtering
343
    // $language the ID of the language to use as filter or NULL for no language filtering
344
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
345
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
346
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
347
    // $year the year of publication to use as filter or NULL for no year filtering
348
    // $accessMode the ID of the access mode to use as a filter or NULL for no access mode filtering
349
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
350
    // $page the page of results to retrieve
351
    // $size the size of the page of results to retrieve
352
    // $locale the locale to use
353
    // return a result (object) containing datasets and statistics
354
    public function searchDatasets($keyword, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale,$isRefine) {
355
        if ($this->cache->getCaching()) {
356
            $cacheId = self :: SEARCH_DATASETS_CACHE_ID . '.' . $keyword . '.' . $type . '.' . $language . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea .  '.' . $fundingStreamLevel2 . '.' . $year . '.' . $accessMode . '.' . $datasource . '.' . $page . '.' . $size . '.' . $locale.'.'.$isRefine;
357
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
358
            if ($result === FALSE) {
359
                $result = $this->_searchDatasets($keyword, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $isRefine);
360
                if ($result !== NULL)
361
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
362
            }
363
        } else
364
            $result = $this->_searchDatasets($keyword, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $isRefine);
365
        return $result;
366
    }
367

    
368
    // Perform a simple search for projects using cache if enabled.
369
    // $keyword the keyword to search for
370
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
371
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
372
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
373
    // $startYear the start year to use as filter or NULL for no start year filtering
374
    // $endYear the end year to suse as filter or NULL for no end year filtering
375
    // $sc39 the SC-39 status to use as filter or NULL for no SC-39 status filtering
376
    // $page the page of results to retrieve
377
    // $size the size of the page of results to retrieve
378
    // $locale the locale to use
379
    // return a result (object) containing projects and statistics
380
    public function searchProjects($keyword, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine) {
381
        if ($this->cache->getCaching()) {
382
            $cacheId = self :: SEARCH_PROJECTS_CACHE_ID . '.' . $keyword . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea .  '.' . $fundingStreamLevel2 .'.' . $startYear . '.' . $endYear . '.' . (($sc39 === NULL) ? '' : (($sc39) ? 'true' : 'false')) . '.' . $page . '.' . $size . '.' . $locale . '.' .$isRefine;
383
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
384
            if ($result === FALSE) {
385
                $result = $this->_searchProjects($keyword, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2 ,$startYear, $endYear, $sc39, $page, $size, $locale, $isRefine);
386
                if ($result !== NULL)
387
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
388
            }
389
        } else
390
            $result = $this->_searchProjects($keyword, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine);
391
        return $result;
392
    }
393

    
394
   
395
    // Perform a simple search for organizations using cache if enabled.
396
    // $keyword the keyword to search for
397
    // $country the ID of the country to use as filter or NULL for no country filtering
398
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
399
    // $page the page of results to retrieve
400
    // $size the size of the page of results to retrieve
401
    // $locale the locale to use
402
    // return a result (object) containing organizations and statistics
403
    public function searchOrganizations($keyword, $country, $type, $page, $size, $locale, $isRefine) {
404
        if ($this->cache->getCaching()) {
405
            $cacheId = self :: SEARCH_ORGANIZATIONS_CACHE_ID . '.' . $keyword . '.' . $country . '.' . $type . '.' . $page . '.' . $size . '.' . $locale . '.' .$isRefine;
406
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
407
            if ($result === FALSE) {
408
                $result = $this->_searchOrganizations($keyword, $country, $type, $page, $size, $locale, $isRefine);
409
                if ($result !== NULL)
410
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
411
            }
412
        } else
413
            $result = $this->_searchOrganizations($keyword, $country, $type, $page, $size, $locale, $isRefine);
414
        return $result;
415
    }
416

    
417
    // Perform a simple search for datasources using cache if enabled.
418
    // $keyword the keyword to search for
419
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
420
    // $language ID of the datasource language to use as filter or NULL for no datasource language filtering
421
    // $content the ID of the content to use as filter or NULL for no project filtering
422
    // $compatibility the ID of the compatibility level to use as filter or NULL for no compatibility level filtering
423
    // $page the page of results to retrieve
424
    // $size the size of the page of results to retrieve
425
    // $locale the locale to use
426
    // return a result (object) containing datasources and statistics
427
    public function searchDatasources($keyword, $type, $language, $content, $compatibility, $page, $size, $locale, $isRefine) {
428
        if ($this->cache->getCaching()) {
429
            $cacheId = self :: SEARCH_DATASOURCES_CACHE_ID . '.' . $keyword . '.' . $type . '.' . $language . '.' . $content . '.' . $compatibility . '.' . $page . '.' . $size . '.' . $locale . '.' .$isRefine;
430
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
431
            if ($result === FALSE) {
432
                $result = $this->_searchDatasources($keyword, $type, $language, $content, $compatibility, $page, $size, $locale, $isRefine);
433
                if ($result !== NULL)
434
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
435
            }
436
        } else
437
            $result = $this->_searchDatasources($keyword, $type, $language, $content, $compatibility, $page, $size, $locale, $isRefine);
438
        return $result;
439
    }
440

    
441
    // Perform a browse for publications using cache if enabled.
442
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
443
    // $language the ID of the language to use as filter or NULL for no language filtering
444
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
445
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
446
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
447
    // $year the year of publication to use as filter or NULL for no year filtering
448
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
449
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
450
    // $community the ID of the community to use as filter or NULL for no datasource filtering
451
    // $page the page of results to retrieve
452
    // $size the size of the page of results to retrieve
453
    // $locale the locale to use
454
    // $project the ID of the project to use as filter or NULL for no project filtering
455
    // $author the ID of the author to use as filter or NULL for no author filtering
456
    // return a result (object) containing publications and statistics
457
    public function browsePublications($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $author, $isRefine,$refineFields = NULL) {
458
         if ($this->cache->getCaching()) {
459
             $cacheId = self :: BROWSE_PUBLICATIONS_CACHE_ID . '.' . $type . '.' . $language . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.' . $fundingStreamLevel2. '.' . $year . '.' . $accessMode . '.' . $datasource . '.' . $community . '.' . $page . '.' . $size . '.' . $locale . '.' . $project . '.' . $author.'.'.$isRefine.'.'.$refineFields;
460
             $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
461
             if ($result === FALSE) {
462
                 $result = $this->_browsePublications($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $author,$isRefine,$refineFields);
463
                 if ($result !== NULL)
464
                     $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
465
            }
466
          } else
467
          $result = $this->_browsePublications($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $author,$isRefine,$refineFields);
468
        return $result;
469
    }
470

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

    
500
    // Perform a browse for projects using cache if enabled.
501
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
502
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
503
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
504
    // $startYear the start year to use as filter or NULL for no start year filtering
505
    // $endYear the end year to use as filter or NULL for no end year filtering
506
    // $sc39 the SC-39 status to use as filter or NULL for no SC-39 status filtering
507
    // $page the page of results to retrieve
508
    // $size the size of the page of results to retrieve
509
    // $locale the locale to use
510
    // return a result (object) containing projects and statistics
511
    public function browseProjects($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine) {
512
        if ($this->cache->getCaching()) {
513
            $cacheId = self :: BROWSE_PROJECTS_CACHE_ID . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.' . $fundingStreamLevel2 . '.' . $startYear . '.' . '.' . $endYear . '.' . $sc39 . '.' . $page . '.' . $size . '.' . $locale. '.' . $isRefine;
514
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
515
            if ($result === FALSE) {
516
                $result = $this->_browseProjects($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine);
517
                if ($result !== NULL)
518
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
519
            }
520
        } else
521
            $result = $this->_browseProjects($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine);
522
        return $result;
523
    }
524

    
525

    
526
    // Perform a browse for organizations using cache if enabled.
527
    // $country the ID of the country to use as filter or NULL for no country filtering
528
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
529
    // $page the page of results to retrieve
530
    // $size the size of the page of results to retrieve
531
    // $locale the locale to use
532
    // return a result (object) containing organizations and statistics
533
    public function browseOrganizations($country, $type, $page, $size, $locale, $isRefine) {
534
        if ($this->cache->getCaching()) {
535
            $cacheId = self :: BROWSE_ORGANIZATIONS_CACHE_ID . '.' . $country . '.' . $type . '.' . $page . '.' . $size . '.' . $locale.'.'.$isRefine;
536
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
537
            if ($result === FALSE) {
538
                $result = $this->_browseOrganizations($country, $type, $page, $size, $locale, $isRefine);
539
                if ($result !== NULL)
540
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
541
            }
542
        } else
543
            $result = $this->_browseOrganizations($country, $type, $page, $size, $locale, $isRefine);
544
        return $result;
545
    }
546

    
547
    // Perform a browse for datasources using cache if enabled.
548
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
549
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
550
    // $content the ID of the content to use as filter or NULL for no content filtering
551
    // $compatibility the ID of the compatibility level to use as filter or NULL for no compatibility status filtering
552
    // $page the page of results to retrieve
553
    // $size the size of the page of results to retrieve
554
    // $locale the locale to use
555
    // return a result (object) containing datasources and statistics
556
    public function browseDatasources($type, $language, $content, $compatibility, $page, $size, $locale, $isRefine) {
557
        if ($this->cache->getCaching()) {
558
            $cacheId = self :: BROWSE_DATASOURCES_CACHE_ID . '.' . $type . '.' . $language . '.' . $content . '.' . $compatibility . '.' . $page . '.' . $size . '.' . $locale.'.'.$isRefine;
559
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
560
            if ($result === FALSE) {
561
                $result = $this->_browseDatasources($type, $language, $content, $compatibility, $page, $size, $locale,$isRefine);
562
                if ($result !== NULL)
563
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
564
            }
565
        } else
566
            $result = $this->_browseDatasources($type, $language, $content, $compatibility, $page, $size, $locale, $isRefine);
567
        return $result;
568
    }
569

    
570
    // Perform an advanced search for publications using cache if enabled.
571
    // $keywords the keywords to search for (array)
572
    // $fields the fields to match keywords with (array - possible values are TITLE, AUTHOR, PUBLISHER and SUBJECT)
573
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
574
    // $types the IDs of the publication types to search for
575
    // $languages the IDs of the publication languages to search for
576
    // $funders the IDs of the funders to search for
577
    // $fundingStreams the IDs of the funding streams to search for
578
    // $scientificAreas the IDs of the scientific areas to search for
579
    // $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)
580
    // $fromMonth start month of the publication date range to search for if $date has value 0
581
    // $fromYear start year of the publication date range to search for if $date has value 0
582
    // $toMonth end month of the publication date range to search for if $date has value 0
583
    // $toYear end year of the publication date range to search for if $date has value 0
584
    // $accessModes the IDs of the access modes to search for
585
    // $datasources the IDs of the datasources to search for
586
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
587
    // $language the ID of the publication language to use as filter or NULL for no publication language filtering
588
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
589
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
590
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
591
    // $year the publication year to use as filter or NULL for no publication year filtering
592
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
593
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
594
    // $page the page of results to retrieve
595
    // $size the size of the page of results to retrieve
596
    // $locale the locale to use
597
    // return a result (object) containing publications and statistics
598
    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) {
599
        if ($this->cache->getCaching()) {
600
            $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;
601
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
602
            if ($result === FALSE) {
603
                $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);
604
                if ($result !== NULL)
605
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
606
            }
607
        } else
608
            $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);
609
        return $result;
610
    }
611
        public function advancedSearchDatasets($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) {
612
        if ($this->cache->getCaching()) {
613
            $cacheId = self :: ADVANCED_SEARCH_DATASETS_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;
614
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
615
            if ($result === FALSE) {
616
                $result = $this->_advancedSearchDatasets($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);
617
                if ($result !== NULL)
618
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
619
            }
620
        } else
621
            $result = $this->_advancedSearchDatasets($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);
622
        return $result;
623
    }
624

    
625

    
626
    // Perform an advanced search for projects using cache if enabled.
627
    // $keywords the keywords to search for (array)
628
    // $fields the fields to match keywords with (array - possible values are ACRONYM, TITLE and KEYWORDS)
629
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
630
    // $funders the IDs of the funders to search for
631
    // $fundingStreams the IDs of the funding streams to search for
632
    // $scientificAreas the IDs of the scientific areas to search for
633
    // $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)
634
    // $startFromMonth start month of the start date range to search for if $startDate has value 0
635
    // $startFromYear start year of the start date range to search for if $startDate has value 0
636
    // $startToMonth end month of the start date range to search for if $startDate has value 0
637
    // $startToYear end year of the start date range to search for if $startDate has value 0
638
    // $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)
639
    // $endFromMonth start month of the end date range to search for if $endDate has value 0
640
    // $endFromYear start year of the end date range to search for if $endDate has value 0
641
    // $endToMonth end month of the end date range to search for if $endDate has value 0
642
    // $endToYear end year of the end date range to search for if $endDate has value 0
643
    // $sc39 the SC-39 statuses to search for
644
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
645
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
646
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
647
    // $startYear the start year to use as filter or NULL for no start year filtering
648
    // $endYear the end year to use as filter or NULL for no end year filtering
649
    // $accessMode the ID of the SC-39 status to use as filter or NULL for no SC-39 status filtering
650
    // $page the page of results to retrieve
651
    // $size the size of the page of results to retrieve
652
    // $locale the locale to use
653
    // return a result (object) containing projects and statistics
654
    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) {
655
        if ($this->cache->getCaching()) {
656
            $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) {
657
                                return $sc39 ? 'true' : 'false';
658
                            }, $sc39s)) . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.' . $fundingStreamLevel2 . '.' . $startYear . '.' . $endYear . '.' . (($sc39 === NULL) ? '' : ($sc39 ? 'true' : 'false')) . '.' . $page . '.' . $size . '.' . $locale;
659
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
660
            if ($result === FALSE) {
661
                $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);
662
                if ($result !== NULL)
663
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
664
            }
665
        } else
666
            $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);
667
        return $result;
668
    }
669

    
670
    // Perform an advanced search for organizations using cache if enabled.
671
    // $keywords the keywords to search for (array)
672
    // $fields the fields to match keywords with (array - possible values are NAME and SHORT_NAME)
673
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
674
    // $countries the IDs of the countries to search for
675
    // $types the IDs of the organization types to search for
676
    // $country the ID of the country to use as filter or NULL for no country filtering
677
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
678
    // $page the page of results to retrieve
679
    // $size the size of the page of results to retrieve
680
    // $locale the locale to use
681
    // return a result (object) containing people and statistics
682
    public function advancedSearchOrganizations($keywords, $fields, $constraints, $countries, $types, $country, $type, $page, $size, $locale) {
683
        if ($this->cache->getCaching()) {
684
            $cacheId = self :: ADVANCED_SEARCH_ORGANIZATIONS_CACHE_ID . '.' . implode('.', $keywords) . '.' . implode('.', $fields) . '.' . implode('.', $constraints) . '.' . implode('.', $countries) . '.' . implode('.', $types) . $country . '.' . $type . '.' . $page . '.' . $size . '.' . $locale;
685
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
686
            if ($result === FALSE) {
687
                $result = $this->_advancedSearchOrganizations($keywords, $fields, $constraints, $countries, $types, $country, $type, $page, $size, $locale);
688
                if ($result !== NULL)
689
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
690
            }
691
        } else
692
            $result = $this->_advancedSearchOrganizations($keywords, $fields, $constraints, $countries, $types, $country, $type, $page, $size, $locale);
693
        return $result;
694
    }
695

    
696
    // Perform an advanced search for datasources using cache if enabled.
697
    // $keywords the keywords to search for (array)
698
    // $fields the fields to match keywords with (array - possible values are NAME, ENGLISH_NAME and SUBJECT)
699
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
700
    // $types the IDs of the datasource types to search for
701
    // $languages the IDs of the datasource languages to search for
702
    // $contents the IDs of the contents to search for
703
    // $compatibilities the IDs of the compatibilities to search for
704
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
705
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
706
    // $content the ID of the content to use as filter or NULL for no content filtering
707
    // $compatibility the ID of the compatibility to use as filter or NULL for no compatibility filtering
708
    // $page the page of results to retrieve
709
    // $size the size of the page of results to retrieve
710
    // $locale the locale to use
711
    // return a result (object) containing datasources and statistics
712
    public function advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale) {
713
        if ($this->cache->getCaching()) {
714
            $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;
715
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
716
            if ($result === FALSE) {
717
                $result = $this->_advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale);
718
                if ($result !== NULL)
719
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
720
            }
721
        } else
722
            $result = $this->_advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale);
723
        return $result;
724
    }
725

    
726
    // Retrieve a single publication by identifier using caching if enabled.
727
    // $id the publication identifier
728
    // $locale the locale to use
729
    // return a publication (object) or NULL if no such publication exists
730
    public function getPublication($id, $locale) {
731
        if ($this->cache->getCaching()) {
732
            $cacheId = self :: PUBLICATION_CACHE_ID . '.' . $id . '.' . $locale;
733
            $publication = $this->cache->get($cacheId, self :: CACHE_GROUP);
734
            if ($publication === FALSE) {
735
                $publication = $this->_getPublication($id, $locale);
736
                if ($publication !== NULL)
737
                    $this->cache->store($publication, $cacheId, self :: CACHE_GROUP);
738
            }
739
        } else
740
            $publication = $this->_getPublication($id, $locale);
741
        return $publication;
742
    }
743

    
744
    // Retrieve a single publication by identifier using caching if enabled.
745
    // $ids the publication identifiers
746
    // $locale the locale to use
747
    // return a publication (object) or NULL if no such publication exists
748
    public function getResults($ids, $locale) {
749
        /*if ($this->cache->getCaching()) {
750
            $cacheId = self :: RESULT_CACHE_ID . '.' . join(",", $ids) . '.' . $locale;
751
            $results = $this->cache->get($cacheId, self :: CACHE_GROUP);
752
            if ($results === FALSE) {
753
                $results = $this->_getResults($ids, $locale);
754
                if ($results !== NULL)
755
                    $this->cache->store($results, $cacheId, self :: CACHE_GROUP);
756
            }
757
        } else
758
          */  $results = $this->_getResults($ids, $locale);
759
        return $results;
760
    }
761

    
762
    // Retrieve a single publication by identifier using caching if enabled.
763
    // $ids the publication identifiers
764
    // $locale the locale to use
765
    // return a publication (object) or NULL if no such publication exists
766
    public function getPublications($ids, $locale) {
767
        if ($this->cache->getCaching()) {
768
            $cacheId = self :: PUBLICATIONS_CACHE_ID . '.' . join(",", $ids) . '.' . $locale;
769
            $publications = $this->cache->get($cacheId, self :: CACHE_GROUP);
770
            if ($publications === FALSE) {
771
                $publications = $this->_getPublications($ids, $locale);
772
                if ($publications !== NULL)
773
                    $this->cache->store($publications, $cacheId, self :: CACHE_GROUP);
774
            }
775
        } else
776
            $publications = $this->_getPublications($ids, $locale);
777
        return $publications;
778
    }
779

    
780
    // Retrieve a single dataset by identifier using caching if enabled.
781
    // $ids the dataset identifiers
782
    // $locale the locale to use
783
    // return a publication (object) or NULL if no such publication exists
784
    public function getDatasets($ids, $locale) {
785
        if ($this->cache->getCaching()) {
786
            $cacheId = self :: DATASETS_CACHE_ID . '.' . join(",", $ids) . '.' . $locale;
787
            $datasets = $this->cache->get($cacheId, self :: CACHE_GROUP);
788
            if ($datasets === FALSE) {
789
                $datasets = $this->_getDatasets($ids, $locale);
790
                if ($datasets !== NULL)
791
                    $this->cache->store($datasets, $cacheId, self :: CACHE_GROUP);
792
            }
793
        } else
794
            $publications = $this->_getDatasets($ids, $locale);
795
        return $publications;
796
    }
797

    
798
    // Retrieve projects by identifier using caching if enabled.
799
    // $ids the project identifiers
800
    // $locale the locale to use
801
    // return an array of project (object) or NULL if no such projects exists
802
    public function getProjects($ids, $locale) {
803
         if ($this->cache->getCaching()) {
804
            $cacheId = self :: PROJECTS_CACHE_ID . '.' . join(",", $ids) . '.' . $locale;
805
            $projects = $this->cache->get($cacheId, self :: CACHE_GROUP);
806
            if ($projects === FALSE) {
807
                $projects = $this->_getProjects($ids, $locale);
808
                if ($projects !== NULL)
809
                    $this->cache->store($projects, $cacheId, self :: CACHE_GROUP);
810
            }
811
        } else
812
            $projects = $this->_getProjects($ids, $locale);
813
        return $projects;
814
    }
815
    // Retrieve projects by identifier using caching if enabled.
816
    // $ids the project identifiers
817
    // $locale the locale to use
818
    // return an array of project (object) or NULL if no such projects exists
819
    public function getProjectByCodeId($id, $funder, $locale) {
820
         if ($this->cache->getCaching()) {
821
            $cacheId = self :: PROJECT_CACHE_ID . '.' . $id . '.' . $funder . '.' . $locale;
822
            $projects = $this->cache->get($cacheId, self :: CACHE_GROUP);
823
            if ($projects === FALSE) {
824
                $projects = $this->_getProjectByCodeId($id, $funder, $locale);
825
                if ($projects !== NULL)
826
                    $this->cache->store($projects, $cacheId, self :: CACHE_GROUP);
827
            }
828
        } else
829
            $projects = $this->_getProjectByCodeId($id, $funder, $locale);
830
        return $projects;
831
    }
832

    
833
    // Retrieve a single dataset by identifier using caching if enabled.
834
    // $id the dataset identifier
835
    // $locale the locale to use
836
    // return a dataset (object) or NULL if no such dataset exists
837
    public function getDataset($id, $locale) {
838
        if ($this->cache->getCaching()) {
839
            $cacheId = self :: DATASET_CACHE_ID . '.' . $id . '.' . $locale;
840
            $dataset = $this->cache->get($cacheId, self :: CACHE_GROUP);
841
            if ($dataset === FALSE) {
842
                $dataset = $this->_getDataset($id, $locale);
843
                if ($dataset !== NULL)
844
                    $this->cache->store($dataset, $cacheId, self :: CACHE_GROUP);
845
            }
846
        } else
847
            $dataset = $this->_getDataset($id, $locale);
848
        return $dataset;
849
    }
850

    
851
    // Retrieve a single project by identifier using caching if enabled.
852
    // $id the project identifier
853
    // $locale the locale to use
854
    // return a project (object) or NULL if no such project exists
855
    public function getProject($id, $locale) {
856
        if ($this->cache->getCaching()) {
857
            $cacheId = self :: PROJECT_CACHE_ID . '.' . $id . '.' . $locale;
858
            $project = $this->cache->get($cacheId, self :: CACHE_GROUP);
859
            if ($project === FALSE) {
860
                $project = $this->_getProject($id, $locale);
861
                if ($project !== NULL)
862
                    $this->cache->store($project, $cacheId, self :: CACHE_GROUP);
863
            }
864
        } else
865
            $project = $this->_getProject($id, $locale);
866
        return $project;
867
    }
868

    
869
    // Retrieve a single person by identifier using caching if enabled.
870
    // $id the person identifier
871
    // $locale the locale to use
872
    // return a person (object) or NULL if no such person exists
873
    public function getPerson($id, $locale) {
874
        if ($this->cache->getCaching()) {
875
            $cacheId = self :: PERSON_CACHE_ID . '.' . $id . '.' . $locale;
876
            $person = $this->cache->get($cacheId, self :: CACHE_GROUP);
877
            if ($person === FALSE) {
878
                $person = $this->_getPerson($id, $locale);
879
                if ($person !== NULL)
880
                    $this->cache->store($person, $cacheId, self :: CACHE_GROUP);
881
            }
882
        } else
883
            $person = $this->_getPerson($id, $locale);
884
        return $person;
885
    }
886

    
887
    // Retreive a single organization by identifier using cache if enabled.
888
    // $id the organization identifier
889
    // $locale the locale to use
890
    // return an organization (object) or NULL if no such organization exists
891
    public function getOrganization($id, $locale) {
892
        if ($this->cache->getCaching()) {
893
            $cacheId = self :: ORGANIZATION_CACHE_ID . '.' . $id . '.' . $locale;
894
            $organization = $this->cache->get($cacheId, self :: CACHE_GROUP);
895
            if ($organization === FALSE) {
896
                $organization = $this->_getOrganization($id, $locale);
897
                if ($organization !== NULL)
898
                    $this->cache->store($organization, $cacheId, self :: CACHE_GROUP);
899
            }
900
        } else
901
            $organization = $this->_getOrganization($id, $locale);
902
        return $organization;
903
    }
904

    
905
    // Retrieve the datasources of an organization using caching if enabled.
906
    // $id the organization identifier
907
    // $size the maximum number of organizations to retrieve
908
    // $locale the locale to use
909
    // return a result (object) containing datasources and total
910
    public function getOrganizationDatasources($id, $size, $locale) {
911
        if ($this->cache->getCaching()) {
912
            $cacheId = self :: ORGANIZATION_DATASOURCES_CACHE_ID . '.' . $id . '.' . $size . '.' . $locale;
913
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
914
            if ($result === FALSE) {
915
                $result = $this->_getOrganizationDatasources($id, $size, $locale);
916
                if ($result !== NULL)
917
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
918
            }
919
        } else
920
            $result = $this->_getOrganizationDatasources($id, $size, $locale);
921
        return $result;
922
    }
923

    
924
    // Retrieve a single datasource by identifier using cache if enabled.
925
    // $id the datasource identifier
926
    // $locale the locale to use
927
    // return a datasource (object) or NULL if no such datasource exists
928
    public function getDatasource($id, $locale, $compatibility = false) {
929
        if ($this->cache->getCaching()) {
930
            $cacheId = self :: DATASOURCE_CACHE_ID . '.' . $id . '.' . $locale . "." . $compatibility;
931
            $datasource = $this->cache->get($cacheId, self :: CACHE_GROUP);
932
            if ($datasource === FALSE) {
933
                $datasource = $this->_getDatasource($id, $locale, $compatibility);
934
                if ($datasource !== NULL)
935
                    $this->cache->store($datasource, $cacheId, self :: CACHE_GROUP);
936
            }
937
        } else
938
            $datasource = $this->_getDatasource($id, $locale, $compatibility);
939
        return $datasource;
940
    }
941

    
942
    // Retrieve all the OpenAIRE compatible datasources using cache if enabled.
943
    // $locale the locale to use
944
    // return the datasources (array) or NULL if any errors occur
945
    public function getCompatibleDatasources($locale) {
946
        if ($this->cache->getCaching()) {
947
            $cacheId = self :: COMPATIBLE_DATASOURCES_CACHE_ID . '.' . $locale;
948
            $datasources = $this->cache->get($cacheId, self :: CACHE_GROUP);
949
            if ($datasources === FALSE) {
950
                $datasources = $this->_getCompatibleDatasources($locale);
951
                if ($datasources !== NULL)
952
                    $this->cache->store($datasources, $cacheId, self :: CACHE_GROUP);
953
            }
954
        } else
955
            $datasources = $this->_getCompatibleDatasources($locale);
956
        return $datasources;
957
    }
958

    
959
    // Perform a quick search for projects, searching only by acronym, title or code and funder and using cahce if enabled.
960
    // $keyword the keyword to search for
961
    // $funder the funder to search for
962
    // $limit the maximum number of results to retrieve
963
    // $locale the locale to use
964
    // return projects (array) or NULL if any errors occur
965
    public function quickSearchProjects($keyword, $funder, $limit, $locale) {
966
        if ($this->cache->getCaching()) {
967
            $cacheId = self :: QUICK_SEARCH_PROJECTS_CACHE_ID . '.' . $keyword . '.' . $funder . '.' . $limit . '.' . $locale;
968
            $projects = $this->cache->get($cacheId, self :: CACHE_GROUP);
969
            if ($projects === FALSE) {
970
                $projects = $this->_quickSearchProjects($keyword, $funder, $limit, $locale);
971
                if ($projects !== NULL)
972
                    $this->cache->store($projects, $cacheId, self :: CACHE_GROUP);
973
            }
974
        } else
975
            $projects = $this->_quickSearchProjects($keyword, $funder, $limit, $locale);
976
        return $projects;
977
    }
978

    
979
    // Perform a quick search for organizations, searching only by name or short name and using cache if enabled.
980
    // $keyword the keyword to search for
981
    // $limit the maximum number of results to retrieve
982
    // $locale the locale to use
983
    // return organizations (array) or NULL if any errors occur
984
    public function quickSearchOrganizations($keyword, $limit, $locale) {
985
        JLog :: add('Keyword \'' . $keyword . '\'', JLog :: INFO, self :: LOG);
986
        if ($this->cache->getCaching()) {
987
            $cacheId = self :: QUICK_SEARCH_ORGANIZATIONS_CACHE_ID . '.' . $keyword . '.' . $limit . '.' . $locale;
988
            $organizations = $this->cache->get($cacheId, self :: CACHE_GROUP);
989
            if ($organizations === FALSE) {
990
                $organizations = $this->_quickSearchOrganizations($keyword, $limit, $locale);
991
                if ($organizations !== NULL)
992
                    $this->cache->store($organizations, $cacheId, self :: CACHE_GROUP);
993
            }
994
        } else
995
            $organizations = $this->_quickSearchOrganizations($keyword, $limit, $locale);
996
        return $organizations;
997
    }
998

    
999
    // Retrieve publication statistics.
1000
    // $locale the locale to use
1001
    // $allFunders get all fields for funders
1002
    // return statistics (object)
1003
    private function _getPublicationStatistics($locale, $allFunders=false) {
1004
    try {
1005
            $time = microtime(TRUE);
1006
            $query = self :: PUBLICATION_QUERY;
1007
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1008
            /* if (($response = $this->performGet('search?action=refine&rTransformer=results_openaire_browse&fields=' . self :: PUBLICATION_TYPE . '&fields=' . self :: PUBLICATION_LANGUAGE . '&fields=' . self :: PUBLICATION_CONTEXT . '&fields=' . self :: PUBLICATION_FUNDER . '&fields=' . self :: PUBLICATION_FUNDING_STREAM . '&fields=' . self :: PUBLICATION_SCIENTIFIC_AREA . '&fields=' . self :: PUBLICATION_YEAR . '&fields=' . self :: PUBLICATION_ACCESS_MODE . '&fields=' . self :: PUBLICATION_DATASOURCE . '&fields=' . self :: PUBLICATION_CONTEXT . '&fields=' . self :: PUBLICATION_PROJECT . '&query=' . urlencode($query) . '&locale=' . c('-', '_', $locale))) == NULL)            
1009
             */
1010
            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)
1011
                throw new Exception('no HTTP response');
1012
            if ($response->code != self :: HTTP_OK)
1013
                throw new Exception('HTTP response code ' . $response->code);
1014
            $document = new DOMDocument();
1015
            $document->recover = TRUE;
1016
            if ($document->loadXML($response->body) == FALSE)
1017
                throw new Exception('invalid XML response');
1018
            $xpath = new DOMXPath($document);
1019
            $statistics=null;
1020
            if($allFunders){
1021
                $statistics = $this->createStatistics($xpath,
1022
                    array('type', 'language', 'funder', 'fundingStream', 'scientificArea', 'fundingStreamLevel2', 'year', 'accessMode', 'datasource', 'community'),
1023
                    array('DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'FUNDING_STREAM_LEVEL_2', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE', 'COMMUNITIES'),
1024
                    array('NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND',
1025
                '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'),
1026
                    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));
1027
            }else{
1028
                $statistics = $this->createStatistics($xpath,
1029
                    array('type', 'language', 'funder',  'year', 'accessMode', 'datasource', 'community'),
1030
                    array('DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'FUNDER',  'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE', 'COMMUNITIES'),
1031
                    array('NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND',
1032
                'NO_FUNDER_STATISTICS_FOUND',   'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND', 'NO_COMMUNITY_STATISTICS_FOUND'),
1033
                    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));
1034

    
1035
            }
1036
            JLog :: add('Retrieved publication statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1037
            return $statistics;
1038
        } catch (Exception $e) {
1039
            JLog :: add('Error retrieving publication statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1040
            return NULL;
1041
        }
1042
    }
1043

    
1044

    
1045
    // Retrieve dataset statistics.
1046
    // $locale the locale to use
1047
    // return statistics (object)
1048
    private function _getDatasetStatistics($locale, $allFunders=false) {
1049
        try {
1050
            $time = microtime(TRUE);
1051
            $query = self :: DATASET_QUERY;
1052
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1053
            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)
1054
                throw new Exception('no HTTP response');
1055
            if ($response->code != self :: HTTP_OK)
1056
                throw new Exception('HTTP response code ' . $response->code);
1057
            $document = new DOMDocument();
1058
            $document->recover = TRUE;
1059
            if ($document->loadXML($response->body) == FALSE)
1060
                throw new Exception('invalid XML response');
1061
            $xpath = new DOMXPath($document);
1062
            $statistics=null;
1063
            if($allFunders){
1064
                $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));
1065
            }else{
1066
                $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));
1067
            }
1068
            JLog :: add('Retrieved dataset statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1069
            return $statistics;
1070
        } catch (Exception $e) {
1071
            JLog :: add('Error retrieving dataset statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1072
            return NULL;
1073
        }
1074
    }
1075

    
1076
    // Retrieve project statistics.
1077
    // $locale the locale to use
1078
    // return statistics (object)
1079
    private function _getProjectStatistics($locale, $allFunders) {
1080
        try {
1081
            $time = microtime(TRUE);
1082
            $query = self :: PROJECT_QUERY;
1083
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1084
            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)
1085
            //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)
1086
                throw new Exception('no HTTP response');
1087
            if ($response->code != self :: HTTP_OK)
1088
                throw new Exception('HTTP response code ' . $response->code);
1089
            $document = new DOMDocument();
1090
            $document->recover = TRUE;
1091
            if ($document->loadXML($response->body) == FALSE)
1092
                throw new Exception('invalid XML response');
1093
            $statistics=null;
1094
            $xpath = new DOMXPath($document);
1095
            if( $allFunders){
1096
                $statistics = $this->createStatistics($xpath,
1097
                    array('funder', 'fundingStream', 'scientificArea', 'startYear', 'endYear', 'sc39'),
1098
                    array('FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'),
1099
                    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'),
1100
                    array(self :: PROJECT_FUNDER, self :: PROJECT_FUNDING_STREAM, self :: PROJECT_SCIENTIFIC_AREA, self :: PROJECT_START_YEAR, self :: PROJECT_END_YEAR, self :: PROJECT_SC39));
1101
            }else{
1102
                $statistics = $this->createStatistics($xpath,
1103
                    array('funder',   'startYear', 'endYear', 'sc39'),
1104
                    array('FUNDER',   'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'),
1105
                    array('NO_FUNDER_STATISTICS_FOUND', 'NO_START_YEAR_STATISTICS_FOUND', 'NO_END_YEAR_STATISTICS_FOUND', 'NO_SPECIAL_CLAUSE_39_STATISTICS_FOUND'),
1106
                    array(self :: PROJECT_FUNDER,  self :: PROJECT_START_YEAR, self :: PROJECT_END_YEAR, self :: PROJECT_SC39));
1107
            }
1108
            JLog :: add('Retrieved project statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1109
            return $statistics;
1110
        } catch (Exception $e) {
1111
            JLog :: add('Error retrieving project statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1112
            return NULL;
1113
        }
1114
    }
1115

    
1116

    
1117
    // Retrieve organization statistics.
1118
    // $locale the locale to use
1119
    // return statistics (object)
1120
    private function _getOrganizationStatistics($locale) {
1121
        try {
1122
            $time = microtime(TRUE);
1123
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
1124
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1125
            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)
1126
                throw new Exception('no HTTP response');
1127
            if ($response->code != self :: HTTP_OK)
1128
                throw new Exception('HTTP response code ' . $response->code);
1129
            $document = new DOMDocument();
1130
            $document->recover = TRUE;
1131
            if ($document->loadXML($response->body) == FALSE)
1132
                throw new Exception('invalid XML response');
1133
            $xpath = new DOMXPath($document);
1134
            $statistics = $this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
1135
            $statistics['type'] = new JObject();
1136
            $statistics['type']->id = 'type';
1137
            $statistics['type']->title = JText :: _('TYPE');
1138
            $statistics['type']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
1139
            $statistics['type']->data = array();
1140
            $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
1141
            if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
1142
                $statistics['type']->data['legalBody'] = new JObject();
1143
                $statistics['type']->data['legalBody']->id = 'legalBody';
1144
                $statistics['type']->data['legalBody']->name = JText :: _('LEGAL_BODY');
1145
                $statistics['type']->data['legalBody']->count = $legalBody['true']->count;
1146
            }
1147
            $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
1148
            if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
1149
                $statistics['type']->data['legalPerson'] = new JObject();
1150
                $statistics['type']->data['legalPerson']->id = 'legalPerson';
1151
                $statistics['type']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
1152
                $statistics['type']->data['legalPerson']->count = $legalPerson['true']->count;
1153
            }
1154
            $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
1155
            if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
1156
                $statistics['type']->data['nonProfit'] = new JObject();
1157
                $statistics['type']->data['nonProfit']->id = 'nonProfit';
1158
                $statistics['type']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
1159
                $statistics['type']->data['nonProfit']->count = $nonProfit['true']->count;
1160
            }
1161
            $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
1162
            if (($research != NULL) && array_key_exists('true', $research)) {
1163
                $statistics['type']->data['research'] = new JObject();
1164
                $statistics['type']->data['research']->id = 'research';
1165
                $statistics['type']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
1166
                $statistics['type']->data['research']->count = $research['true']->count;
1167
            }
1168
            $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
1169
            if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
1170
                $statistics['type']->data['euInterests'] = new JObject();
1171
                $statistics['type']->data['euInterests']->id = 'euInterests';
1172
                $statistics['type']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
1173
                $statistics['type']->data['euInterests']->count = $euInterests['true']->count;
1174
            }
1175
            $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
1176
            if (($international != NULL) && array_key_exists('true', $international)) {
1177
                $statistics['type']->data['international'] = new JObject();
1178
                $statistics['type']->data['international']->id = 'international';
1179
                $statistics['type']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
1180
                $statistics['type']->data['international']->count = $international['true']->count;
1181
            }
1182
            $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
1183
            if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
1184
                $statistics['type']->data['enterprise'] = new JObject();
1185
                $statistics['type']->data['enterprise']->id = 'enterprise';
1186
                $statistics['type']->data['enterprise']->name = JText :: _('ENTERPRISE');
1187
                $statistics['type']->data['enterprise']->count = $enterprise['true']->count;
1188
            }
1189
            $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
1190
            if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
1191
                $statistics['type']->data['smallMediumEnterprise'] = new JObject();
1192
                $statistics['type']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
1193
                $statistics['type']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
1194
                $statistics['type']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
1195
            }
1196
            uasort($statistics['type']->data, function ($row1, $row2) {
1197
                return $row2->count - $row1->count;
1198
            });
1199
            JLog :: add('Retrieved organization statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1200
            return $statistics;
1201
        } catch (Exception $e) {
1202
            JLog :: add('Error retrieving organization statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1203
            return NULL;
1204
        }
1205
    }
1206

    
1207
    // Retrieve datasource statistics.
1208
    // $locale the locale to use
1209
    // return statistics (object)
1210
    private function _getDatasourceStatistics($locale) {
1211
        try {
1212
            $time = microtime(TRUE);
1213
            $query = self :: DATASOURCE_QUERY;
1214
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1215
            if (($response = $this->performGet('search?action=refine&rTransformer=results_openaire_browse&fields=' . self :: DATASOURCE_TYPE . '&fields=' . self :: DATASOURCE_LANGUAGE . '&fields=' . self :: DATASOURCE_CONTENT . '&fields=' . self :: DATASOURCE_COMPATIBILITY . '&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
1216
                throw new Exception('no HTTP response');
1217
            if ($response->code != self :: HTTP_OK)
1218
                throw new Exception('HTTP response code ' . $response->code);
1219
            $document = new DOMDocument();
1220
            $document->recover = TRUE;
1221
            if ($document->loadXML($response->body) == FALSE)
1222
                throw new Exception('invalid XML response');
1223
            $xpath = new DOMXPath($document);
1224
            $statistics = $this->createStatistics($xpath, array('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));
1225
            JLog :: add('Retrieved datasource statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1226
            return $statistics;
1227
        } catch (Exception $e) {
1228
            JLog :: add('Error retrieving datasource statistics locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1229
            return NULL;
1230
        }
1231
    }
1232

    
1233
    // Perform a simple search for publications.
1234
    // $keyword the keyword to search for
1235
    // $articles flag to limit searching on articles; if all flags are FALSE no limits apply
1236
    // $books flag to limit searching on books; if all flags are FALSE no limits apply
1237
    // $theses flag to limit searching on books; if all flags are FALSE no limits apply
1238
    // $reports flag to limit searching on reports; if all flags are FALSE no limits apply
1239
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
1240
    // $language the ID of the language to use as filter or NULL for no language filtering
1241
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1242
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
1243
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1244
    // $year the year of publication to use as filter or NULL for no year filtering
1245
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1246
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1247
    // $page the page of results to retrieve
1248
    // $size the size of the page of results to retrieve
1249
    // $locale the locale to use
1250
    // return a result (object) containing publications and statistics
1251
    private function _searchPublications($keyword, $articles, $books, $theses, $reports, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project,$isRefine) {
1252
        try {
1253
                $dois = explode(" ", preg_replace('/\s+/', ' ',$keyword));
1254
                $unique_dois =array_unique($dois);
1255
                $pattern1 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b#';
1256
                $pattern2 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b#';
1257
                if (preg_match($pattern1, $unique_dois[0]) || preg_match($pattern2, $unique_dois[0])) {
1258
                   $result= $this->_searchPublicationsWithDois($unique_dois,$page, $size, $locale,$isRefine);
1259
                    return $result;
1260
                }
1261
            $time = microtime(TRUE);
1262
            $query = self :: PUBLICATION_QUERY;
1263
            $query .= ($keyword == NULL) ? '' : ' and "' . str_replace('"', '\\"', $keyword) . '"';
1264
            $types = array();
1265
            if ($articles) {
1266
                $types[] = self :: PUBLICATION_ARTICLE;
1267
                $types[] = self :: PUBLICATION_PREPRINT;
1268
            }
1269
            if ($books) {
1270
                $types[] = self :: PUBLICATION_BOOK;
1271
                $types[] = self :: PUBLICATION_BOOK_PART;
1272
            }
1273
            if ($theses) {
1274
                $types[] = self :: PUBLICATION_PHD_THESIS;
1275
                $types[] = self :: PUBLICATION_MASTER_THESIS;
1276
                $types[] = self :: PUBLICATION_BACHELOR_THESIS;
1277
            }
1278
            if ($reports) {
1279
                $types[] = self :: PUBLICATION_REPORT;
1280
                $types[] = self :: PUBLICATION_INTERNAL_REPORT;
1281
                $types[] = self :: PUBLICATION_EXTERNAL_REPORT;
1282
            }
1283
            $publicationType = self :: PUBLICATION_TYPE;
1284
            $types = implode(' or ', array_map(function($type) use ($publicationType) {
1285
                        return '(' . $publicationType . ' exact "' . $type . '")';
1286
                    }, $types));
1287
            $query .= ($types == NULL) ? '' : (' and (' . $types . ')');
1288
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
1289
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
1290
             if($funder != NULL && (strpos($funder, ',') !== FALSE)){
1291
                $temp='';
1292
                foreach(explode(',',$funder) as $id){
1293
                    if(!empty($id)){
1294
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
1295
                    }
1296

    
1297
                }
1298
                $query .=  (' and (' . substr($temp, 0, -3). ')');
1299
            }else{
1300
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
1301
            }
1302
            //$query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
1303
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1304
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1305
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1306
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact ' . $year . ')');
1307
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
1308
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '")');
1309
            $query .= ($community == NULL) ? '' : (' and (' . self :: PUBLICATION_CONTEXT . ' exact "' . $community . '")');
1310
            $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT . ' exact "' . $project . '")');
1311
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1312
            $completeQuery='search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size .  '&locale=' . str_replace('-', '_', $locale);
1313
            if($isRefine){
1314
                $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);
1315
            }
1316
            //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)
1317
            if (($response = $this->performGet($completeQuery)) == NULL)
1318
                throw new Exception('no HTTP response');
1319
            if ($response->code != self :: HTTP_OK)
1320
                throw new Exception('HTTP response code ' . $response->code);
1321
            $document = new DOMDocument();
1322
            $document->recover = TRUE;
1323
            if ($document->loadXML($response->body) == FALSE)
1324
                throw new Exception('invalid XML response');
1325
            $xpath = new DOMXPath($document);
1326
            $result = new JObject();
1327
            $result->totalPublications = $this->parseTotalResults($xpath);
1328
            $result->totalDatasets = 0;
1329
            $result->publications = $this->parsePublications($xpath);
1330
            $result->statistics = $isRefine? $this->createStatisticsForPublications($xpath):NULL;
1331
            $result->statistics = self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1332
                    //$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));
1333
            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);
1334
            return $result;
1335
        } catch (Exception $e) {
1336
            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);
1337
            $result->publications = array();
1338
            $result->totalPublications = 0;
1339
            $result->totalDatasets = 0;
1340
            return $result;
1341
        }
1342
    }
1343
 private function _searchPublicationsWithDois($dois, $page, $size, $locale,$isRefine) {
1344
        try {
1345
            $time = microtime(TRUE);
1346
            $query = self :: PUBLICATION_QUERY;
1347
            $query .= ' and (';
1348
            foreach ($dois as $doi) {
1349
                $query .= ' ((pidclassid exact doi) and (pid exact "'.$doi.'")) ';
1350
                $query .= 'OR';
1351
            }
1352
            if(count($dois)>0){
1353
                $query=substr($query, 0, -2);
1354
            }
1355
            $query .= ')';
1356
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1357
            $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)
1358
                    :'search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size   . '&locale=' . str_replace('-', '_', $locale);
1359
            if (($response = $this->performGet($completeQuery)) == NULL)
1360
                throw new Exception('no HTTP response');
1361
            if ($response->code != self :: HTTP_OK)
1362
                throw new Exception('HTTP response code ' . $response->code);
1363
            $document = new DOMDocument();
1364
            $document->recover = TRUE;
1365
            if ($document->loadXML($response->body) == FALSE)
1366
                throw new Exception('invalid XML response');
1367
            $xpath = new DOMXPath($document);
1368
            $result = new JObject();
1369
            $result->totalPublications = $this->parseTotalResults($xpath);
1370
            $result->totalDatasets = 0;
1371
            $result->publications = $this->parsePublications($xpath);
1372
            $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;
1373
            JLog :: add('Simple search for DOIs retrieved ' . count($result->publications) . ' publications in ' . (microtime(TRUE) - $time) . ' s (query: ' . $query. ')', JLog :: INFO, self :: LOG);
1374
            return $result;
1375
        } catch (Exception $e) {
1376
            JLog :: add('Error performing publication simple search for DOIs(query: ' . $query  . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1377
            return NULL;
1378
        }
1379
    }
1380
    // Perform a simple search for datasets.
1381
    // $keyword the keyword to search for
1382
    // $type the ID of the dataset type to use as filter or NULL for no dataset type filtering
1383
    // $language the ID of the language to use as filter or NULL for no language filtering
1384
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1385
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
1386
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1387
    // $year the year of publication to use as filter or NULL for no year filtering
1388
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1389
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1390
    // $page the page of results to retrieve
1391
    // $size the size of the page of results to retrieve
1392
    // $locale the locale to use
1393
    // return a result (object) containing datasets and statistics
1394
    private function _searchDatasets($keyword, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $isRefine) {
1395
        try {
1396
                $dois = explode(" ", preg_replace('/\s+/', ' ',$keyword));
1397
                $unique_dois =array_unique($dois);
1398
                $pattern1 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b#';
1399
                $pattern2 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b#';
1400
                if (preg_match($pattern1, $unique_dois[0]) || preg_match($pattern2, $unique_dois[0])) {
1401
                   $result= $this->_searchDatasetsWithDois($unique_dois,$page, $size, $locale,$isRefine);
1402
                    return $result;
1403
                }
1404
            $time = microtime(TRUE);
1405
            $query = self :: DATASET_QUERY;
1406
            $query .= ($keyword == NULL) ? '' : ' and "' . str_replace('"', '\\"', $keyword) . '"';
1407
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASET_TYPE . ' exact "' . $type . '")');
1408
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASET_LANGUAGE . ' exact "' . $language . '")');
1409
            $query .= ($funder == NULL) ? '' : (' and (' . self :: DATASET_FUNDER . ' exact "' . $funder . '")');
1410
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1411
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: DATASET_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1412
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1413
            $query .= ($year == NULL) ? '' : (' and (' . self :: DATASET_YEAR . ' exact ' . $year . ')');
1414
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: DATASET_ACCESS_MODE . ' exact "' . $accessMode . '")');
1415
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '")');
1416
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1417
            $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):
1418
                    'search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size  . '&locale=' . str_replace('-', '_', $locale);
1419
            if (($response = $this->performGet($completeQuery)) == NULL)
1420
                throw new Exception('no HTTP response');
1421
            if ($response->code != self :: HTTP_OK)
1422
                throw new Exception('HTTP response code ' . $response->code);
1423
            $document = new DOMDocument();
1424
            $document->recover = TRUE;
1425
            if ($document->loadXML($response->body) == FALSE)
1426
                throw new Exception('invalid XML response');
1427
            $xpath = new DOMXPath($document);
1428
            $result = new JObject();
1429
            $result->totalDatasets = $this->parseTotalResults($xpath);
1430
            $result->datasets = $this->parseDatasets($xpath);
1431
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
1432
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1433
                    //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));
1434
            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);
1435
            return $result;
1436
        } catch (Exception $e) {
1437
            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);
1438
            return NULL;
1439
        }
1440
    }
1441

    
1442
 private function _searchDatasetsWithDois($dois, $page, $size, $locale,$isRefine) {
1443
        try {
1444
            $time = microtime(TRUE);
1445
            $query = self :: DATASET_QUERY;
1446
            $query .= ' and (';
1447
            foreach ($dois as $doi) {
1448
                $query .= ' ((pidclassid exact doi) and (pid exact "'.$doi.'")) ';
1449
                $query .= 'OR';
1450
            }
1451
            if(count($dois)>0){
1452
                $query=substr($query, 0, -2);
1453
            }
1454
            $query .= ')';
1455
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1456
            $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)
1457
                    :'search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size   . '&locale=' . str_replace('-', '_', $locale);
1458
            if (($response = $this->performGet($completeQuery)) == NULL)
1459
                throw new Exception('no HTTP response');
1460
            if ($response->code != self :: HTTP_OK)
1461
                throw new Exception('HTTP response code ' . $response->code);
1462
            $document = new DOMDocument();
1463
            $document->recover = TRUE;
1464
            if ($document->loadXML($response->body) == FALSE)
1465
                throw new Exception('invalid XML response');
1466
            $xpath = new DOMXPath($document);
1467
            $result = new JObject();
1468
            $result->totalPublications = 0;
1469
            $result->totalDatasets = $this->parseTotalResults($xpath);
1470
            $result->datasets = $this->parsePublications($xpath);
1471
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
1472
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1473
                    //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));
1474
            JLog :: add('Simple search for DOIs retrieved ' . count($result->datasets) . ' datasets in ' . (microtime(TRUE) - $time) . ' s (query: ' . $query. ')', JLog :: INFO, self :: LOG);
1475
            return $result;
1476
        } catch (Exception $e) {
1477
            JLog :: add('Error performing dataset simple search for DOIs(query: ' . $query  . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1478
            return NULL;
1479
        }
1480
    }
1481
    // Perform a simple search for projects.
1482
    // $keyword the keyword to search for
1483
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1484
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
1485
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1486
    // $startYear the start year to use as filter or NULL for no start year filtering
1487
    // $endYear the end year to suse as filter or NULL for no end year filtering
1488
    // $sc39 the SC-39 status to use as filter or NULL for no SC-39 status filtering
1489
    // $page the page of results to retrieve
1490
    // $size the size of the page of results to retrieve
1491
    // $locale the locale to use
1492
    // return a result (object) containing projects and statistics
1493
    private function _searchProjects($keyword, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine) {
1494
        try {
1495
            $time = microtime(TRUE);
1496
            $query = self :: PROJECT_QUERY;
1497
            $query .= ($keyword == NULL) ? '' : ' and ((' . self :: PROJECT_ACRONYM . ' = "' . str_replace('"', '\\"', $keyword) . '") or (' . self :: PROJECT_CODE . ' = "' . str_replace('"', '\\"', $keyword) . '") or (' . self :: PROJECT_TITLE . ' = "' . str_replace('"', '\\"', $keyword) . '"))';
1498
            $query .= ($funder == NULL) ? '' : (' and (' . self :: PROJECT_FUNDER . ' exact "' . $funder . '")');
1499
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1500
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PROJECT_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1501
            $query .= ($startYear == NULL) ? '' : (' and (' . self :: PROJECT_START_YEAR . ' exact ' . $startYear . ')');
1502
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM_LEVEL2. ' exact "' . $fundingStreamLevel2 . '")');
1503
            $query .= ($endYear == NULL) ? '' : (' and (' . self :: PROJECT_END_YEAR . ' exact ' . $endYear . ')');
1504
            $query .= ($sc39 === NULL) ? '' : (' and (' . self :: PROJECT_SC39 . ' exact ' . ($sc39 ? 'true' : 'false') . ')');
1505
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1506
            $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)
1507
                    :'search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
1508
            if (($response = $this->performGet($completeQuery)) == NULL)
1509
                throw new Exception('no HTTP response');
1510
            if ($response->code != self :: HTTP_OK)
1511
                throw new Exception('HTTP response code ' . $response->code);
1512
            $document = new DOMDocument();
1513
            $document->recover = TRUE;
1514
            if ($document->loadXML($response->body) == FALSE)
1515
                throw new Exception('invalid XML response');
1516
            $xpath = new DOMXPath($document);
1517
            $result = new JObject();
1518
            $result->totalProjects = $this->parseTotalResults($xpath);
1519
            $result->projects = $this->parseProjects($xpath);
1520
            $result->statistics = $isRefine?$this->createStatisticsForProjects($xpath,''):NULL;
1521
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1522
                    //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));
1523
            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);
1524
            return $result;
1525
        } catch (Exception $e) {
1526
            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);
1527
            return NULL;
1528
        }
1529
    }
1530

    
1531

    
1532
    // Perform a simple search for organizations.
1533
    // $keyword the keyword to search for
1534
    // $country the ID of the country to use as filter or NULL for no country filtering
1535
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
1536
    // $page the page of results to retrieve
1537
    // $size the size of the page of results to retrieve
1538
    // $locale the locale to use
1539
    // return a result (object) containing people and statistics
1540
    private function _searchOrganizations($keyword, $country, $type, $page, $size, $locale, $isRefine) {
1541
        try {
1542
            $time = microtime(TRUE);
1543
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
1544
            $query .= ($keyword == NULL) ? '' : (' and "' . str_replace('"', '\\"', $keyword) . '"');
1545
            $query .= ($country == NULL) ? '' : (' and (' . self :: ORGANIZATION_COUNTRY . ' exact "' . $country . '")');
1546
            switch ($type) {
1547
                case 'legalBody':
1548
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_BODY . ' exact true)';
1549
                    break;
1550
                case 'legalPerson':
1551
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_PERSON . ' exact true)';
1552
                    break;
1553
                case 'nonProfit':
1554
                    $query .= ' and (' . self :: ORGANIZATION_NON_PROFIT . ' exact true)';
1555
                    break;
1556
                case 'research':
1557
                    $query .= ' and (' . self :: ORGANIZATION_RESEARCH . ' exact true)';
1558
                    break;
1559
                case 'euInterests':
1560
                    $query .= ' and (' . self :: ORGANIZATION_EU_INTERESTS . ' exact true)';
1561
                    break;
1562
                case 'international':
1563
                    $query .= ' and (' . self :: ORGANIZATION_INTERNATIONAL . ' exact true)';
1564
                    break;
1565
                case 'enterprise':
1566
                    $query .= ' and (' . self :: ORGANIZATION_ENTERPRISE . ' exact true)';
1567
                    break;
1568
                case 'smallMediumEnterprise':
1569
                    $query .= ' and (' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . ' exact true)';
1570
            }
1571
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1572
            $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)
1573
                    :'search?action=search&sTransformer=organizations_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size .  '&locale=' . str_replace('-', '_', $locale);
1574
            if (($response = $this->performGet($completeQuery)) == NULL)
1575
                throw new Exception('no HTTP response');
1576
            if ($response->code != self :: HTTP_OK)
1577
                throw new Exception('HTTP response code ' . $response->code);
1578
            $document = new DOMDocument();
1579
            $document->recover = TRUE;
1580
            if ($document->loadXML($response->body) == FALSE)
1581
                throw new Exception('invalid XML response');
1582
            $xpath = new DOMXPath($document);
1583
            $result = new JObject();
1584
            $result->totalOrganizations = $this->parseTotalResults($xpath);
1585
            $result->organizations = $this->parseOrganizations($xpath);
1586
            if($isRefine){
1587
                $result->statistics = $this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
1588
                $result->statistics['type'] = new JObject();
1589
                $result->statistics['type']->id = 'type';
1590
                $result->statistics['type']->title = JText :: _('TYPE');
1591
                $result->statistics['type']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
1592
                $result->statistics['type']->data = array();
1593
                $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
1594
                if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
1595
                    $result->statistics['type']->data['legalBody'] = new JObject();
1596
                    $result->statistics['type']->data['legalBody']->id = 'legalBody';
1597
                    $result->statistics['type']->data['legalBody']->name = JText :: _('LEGAL_BODY');
1598
                    $result->statistics['type']->data['legalBody']->count = $legalBody['true']->count;
1599
                }
1600
                $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
1601
                if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
1602
                    $result->statistics['type']->data['legalPerson'] = new JObject();
1603
                    $result->statistics['type']->data['legalPerson']->id = 'legalPerson';
1604
                    $result->statistics['type']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
1605
                    $result->statistics['type']->data['legalPerson']->count = $legalPerson['true']->count;
1606
                }
1607
                $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
1608
                if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
1609
                    $result->statistics['type']->data['nonProfit'] = new JObject();
1610
                    $result->statistics['type']->data['nonProfit']->id = 'nonProfit';
1611
                    $result->statistics['type']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
1612
                    $result->statistics['type']->data['nonProfit']->count = $nonProfit['true']->count;
1613
                }
1614
                $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
1615
                if (($research != NULL) && array_key_exists('true', $research)) {
1616
                    $result->statistics['type']->data['research'] = new JObject();
1617
                    $result->statistics['type']->data['research']->id = 'research';
1618
                    $result->statistics['type']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
1619
                    $result->statistics['type']->data['research']->count = $research['true']->count;
1620
                }
1621
                $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
1622
                if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
1623
                    $result->statistics['type']->data['euInterests'] = new JObject();
1624
                    $result->statistics['type']->data['euInterests']->id = 'euInterests';
1625
                    $result->statistics['type']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
1626
                    $result->statistics['type']->data['euInterests']->count = $euInterests['true']->count;
1627
                }
1628
                $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
1629
                if (($international != NULL) && array_key_exists('true', $international)) {
1630
                    $result->statistics['type']->data['international'] = new JObject();
1631
                    $result->statistics['type']->data['international']->id = 'international';
1632
                    $result->statistics['type']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
1633
                    $result->statistics['type']->data['international']->count = $international['true']->count;
1634
                }
1635
                $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
1636
                if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
1637
                    $result->statistics['type']->data['enterprise'] = new JObject();
1638
                    $result->statistics['type']->data['enterprise']->id = 'enterprise';
1639
                    $result->statistics['type']->data['enterprise']->name = JText :: _('ENTERPRISE');
1640
                    $result->statistics['type']->data['enterprise']->count = $enterprise['true']->count;
1641
                }
1642
                $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
1643
                if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
1644
                    $result->statistics['type']->data['smallMediumEnterprise'] = new JObject();
1645
                    $result->statistics['type']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
1646
                    $result->statistics['type']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
1647
                    $result->statistics['type']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
1648
                }
1649
                uasort($result->statistics['type']->data, function ($row1, $row2) {
1650
                    return $row2->count - $row1->count;
1651
                });
1652
            }
1653
            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);
1654
            return $result;
1655
        } catch (Exception $e) {
1656
            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);
1657
            return NULL;
1658
        }
1659
    }
1660

    
1661
    // Perform a simple search for datasources.
1662
    // $keyword the keyword to search for
1663
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
1664
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
1665
    // $content the ID of the content to use as filter or NULL for no project filtering
1666
    // $compatibility the ID of the compatibility level to use as filter or NULL for no compatibility level filtering
1667
    // $page the page of results to retrieve
1668
    // $size the size of the page of results to retrieve
1669
    // $locale the locale to use
1670
    // return a result (object) containing datasources and statistics
1671
    private function _searchDatasources($keyword, $type, $language, $content, $compatibility, $page, $size, $locale, $isRefine) {
1672
        try {
1673
            $time = microtime(TRUE);
1674
            $query = self :: DATASOURCE_QUERY;
1675
            $query .= ($keyword == NULL) ? '' : (' and "' . str_replace('"', '\\"', $keyword) . '"');
1676
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASOURCE_TYPE . ' exact "' . $type . '")');
1677
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASOURCE_LANGUAGE . ' exact "' . $language . '")');
1678
            $query .= ($content == NULL) ? '' : (' and (' . self :: DATASOURCE_CONTENT . ' exact "' . $content . '")');
1679
            $query .= ($compatibility == NULL) ? '' : (' and (' . self :: DATASOURCE_COMPATIBILITY . ' exact "' . $compatibility . '")');
1680
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1681
            $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)
1682
                    :'search?action=search&sTransformer=datasources_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
1683
            if (($response = $this->performGet($completeQuery)) == NULL)
1684
                throw new Exception('no HTTP response');
1685
            if ($response->code != self :: HTTP_OK)
1686
                throw new Exception('HTTP response code ' . $response->code);
1687
            $document = new DOMDocument();
1688
            $document->recover = TRUE;
1689
            if ($document->loadXML($response->body) == FALSE)
1690
                throw new Exception('invalid XML response');
1691
            $xpath = new DOMXPath($document);
1692
            $result = new JObject();
1693
            $result->totalDatasources = $this->parseTotalResults($xpath);
1694
            $result->datasources = $this->parseDatasources($xpath);
1695
            $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;
1696
            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);
1697
            return $result;
1698
        } catch (Exception $e) {
1699
            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);
1700
            return NULL;
1701
        }
1702
    }
1703

    
1704
    // Perform a browse for publications.
1705
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
1706
    // $language the ID of the language to use as filter or NULL for no language filtering
1707
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1708
    // $fundingStream the ID of the fundingStream to use as filter or NULL for no funding stream filtering
1709
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1710
    // $year the year of publication to use as filter or NULL for no year filtering
1711
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1712
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1713
    // $community the ID of the community to use as filter or NULL for no datasource filtering
1714
    // $page the page of results to retrieve
1715
    // $size the size of the page of results to retrieve
1716
    // $locale the locale to use
1717
    // $project the ID of the project to use as filter or NULL for no project filtering
1718
    // $author the ID of the author to use as filter or NULL for no author filtering
1719
    // return a result (object) containing publications and statistics
1720
    private function _browsePublications($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $author,$isRefine,$refineFields) {
1721
        try {
1722
            $time = microtime(TRUE);
1723
            $query = self :: PUBLICATION_QUERY;
1724
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
1725
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
1726
            if($funder != NULL && (strpos($funder, '---') !== FALSE)){
1727
                $temp='';
1728
                foreach(explode('---',$funder) as $id){
1729
                    if(!empty($id)){
1730
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
1731
                    }
1732

    
1733
                }
1734
                $query .=  (' and (' . substr($temp, 0, -4). ')');
1735
            }else{
1736
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
1737
            }
1738
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1739
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1740
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1741
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact ' . $year . ')');
1742
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
1743
            // $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
1744
            $datasource_id_array = explode("||", $datasource);
1745
            if(sizeof($datasource_id_array) > 1 ){
1746
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
1747
            }else{
1748
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE_ID . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE_ID . ' exact "' . $datasource . '") )');
1749
            }
1750
            // $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT . ' exact "' . $project . '")');
1751
            $project_id_array = explode("||", $project);
1752
            if(sizeof($project_id_array) > 1 ){
1753
                $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT . ' exact "' . $project . '")');
1754
            }else{
1755
              $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT_ID . ' exact "' . $project . '")');
1756
            }
1757
            $query .= ($author == NULL) ? '' : (' and (' . self :: PUBLICATION_AUTHOR_ID . ' exact "' . $author . '")');
1758
            $query .= ($community == NULL) ? '' : (' and (' . self :: PUBLICATION_CONTEXT . ' exact "' . $community . '")');
1759
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1760
            $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):
1761
                'search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size  . '&locale=' . str_replace('-', '_', $locale);
1762
            if (($response = $this->performGet($completeQuery)) == NULL)
1763
                throw new Exception('no HTTP response');
1764
            if ($response->code != self :: HTTP_OK)
1765
                throw new Exception('HTTP response code ' . $response->code);
1766
            $document = new DOMDocument();
1767
            $document->recover = TRUE;
1768
            if ($document->loadXML($response->body) == FALSE)
1769
                throw new Exception('invalid XML response');
1770
            $xpath = new DOMXPath($document);
1771
            $result = new JObject();
1772
            $result->totalPublications = $this->parseTotalResults($xpath);
1773
            $result->publications = $this->parsePublications($xpath);
1774
            $result->statistics = $isRefine?$this->createStatisticsForPublications($xpath):NULL;
1775
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1776
                    //$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));
1777
            $result->totalDatasets = 0;
1778
            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);
1779
            return $result;
1780
        } catch (Exception $e) {
1781
            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);
1782
            return NULL;
1783
        }
1784
    }
1785
    public static function pruningStatisticsForFunders($statistics, $funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2,$filter){
1786
        return self::_pruningStatisticsForFunders($statistics, $funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2,$filter);
1787
    }
1788
    private static function _pruningStatisticsForFunders($statistics, $funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2,$filter=''){
1789
        if($statistics==NULL){
1790
            return NULL;
1791
        }
1792
        if($fundingStreamLevel1!=NULL){
1793
           $newData= array();
1794
           foreach ($statistics["fundingStreamLevel2".$filter]->data as $data){
1795
               if(strpos($data->id,$fundingStreamLevel1)!==FALSE){
1796
                   $newData[$data->id]=$data;
1797
               }
1798
           }
1799
           $statistics["fundingStreamLevel2".$filter]->data=$newData;
1800
         }
1801
        if($fundingStream!=NULL){
1802
           $newData= array();
1803
           foreach ($statistics["fundingStreamLevel1".$filter]->data as $data){
1804
               if(strpos($data->id,$fundingStream)!==FALSE){
1805
                   $newData[$data->id]=$data;
1806
               }
1807
           }
1808
           $statistics["fundingStreamLevel1".$filter]->data=$newData;
1809
        }
1810
        if($funder!=NULL){
1811
           $newData= array();
1812
           if(strpos($funder, '---') !== FALSE){
1813
                foreach ($statistics["fundingStream".$filter]->data as $data){
1814
                   foreach(explode('---',$funder) as $id){                       
1815
                       if(!empty($id) && (strpos($data->id,explode("||",$id)[0])!==FALSE)){
1816
                        $newData[$data->id]=$data;
1817
                       }
1818
                   }
1819
               }
1820
           }else{
1821
               foreach ($statistics["fundingStream".$filter]->data as $data){
1822
                   $funder_id= explode("||",$funder)[0];
1823
                    if(strpos($data->id,$funder_id)!==FALSE){
1824
                        $newData[$data->id]=$data;
1825
                    }
1826
                }
1827
           }
1828
           $statistics["fundingStream".$filter]->data=$newData;
1829

    
1830
        }
1831
        return $statistics;
1832
    }
1833
    //Reduces the Funding Fields
1834
    //$funder filter for funder
1835
    //$fundingStream filter for funding stream
1836
    //$fundingStreamLevel1 filter for fundingStreamLevel1
1837
    //$fundingStreamLevel2 filter  for fundingStreamLevel2
1838
    private static function _getFundingFields($funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2, $type){
1839
            $field = self::_getFundingFieldsPerType($type);
1840
            $f = array();
1841
             $f[0]=true;
1842
            for($i=1;$i<4;$i++){
1843
                $f[$i]=false;
1844
            }
1845
            if($fundingStreamLevel2 !== null && !empty($fundingStreamLevel2)){
1846
                $f[3]=true;
1847
           }if($fundingStreamLevel1 !== NULL && strlen($fundingStreamLevel1)>0){
1848
               $f[2]=true;
1849
               $f[3]=true;
1850
            } if($fundingStream !== NULL && strlen($fundingStream)>0){
1851
                $f[1]=true;
1852
                $f[2]=true;
1853
            } if($funder !== NULL && strlen($funder)>0){
1854
                $f[0]=true;
1855
                $f[1]=true;
1856
            }
1857
            $returnedFields='';
1858
            $none=true;
1859
            for($i=0;$i<4;$i++){
1860
                if($f[$i]){
1861
                    $returnedFields.=($f[$i])?$field[$i]:'';
1862
                    $none=false;
1863
                }
1864
            }
1865
            $returnedFields=($none)?$field[0].$field[1]:$returnedFields;
1866
            return $returnedFields;
1867
        }
1868

    
1869
        private function _getFundingFieldsPerType($type){
1870
            $field=array();
1871
             switch ($type) {
1872
                case self::PUBLICATION:
1873
                    $field[3]='&fields=' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2;
1874
                    $field[2]='&fields=' . self :: PUBLICATION_SCIENTIFIC_AREA;
1875
                    $field[1]='&fields=' . self :: PUBLICATION_FUNDING_STREAM;
1876
                    $field[0]='&fields=' . self :: PUBLICATION_FUNDER;
1877
                    break;
1878
                case self::DATASET:
1879
                    $field[3]='&fields=' . self :: DATASET_FUNDING_STREAM_LEVEL2;
1880
                    $field[2]='&fields=' . self :: DATASET_SCIENTIFIC_AREA;
1881
                    $field[1]='&fields=' . self :: DATASET_FUNDING_STREAM;
1882
                    $field[0]='&fields=' . self :: DATASET_FUNDER;
1883
                    break;
1884
                case self::PROJECT:
1885
                    $field[3]='&fields=' . self :: PROJECT_FUNDING_STREAM_LEVEL2;
1886
                    $field[2]='&fields=' . self :: PROJECT_SCIENTIFIC_AREA;
1887
                    $field[1]='&fields=' . self :: PROJECT_FUNDING_STREAM;
1888
                    $field[0]='&fields=' . self :: PROJECT_FUNDER;
1889
                    break;
1890
             }
1891

    
1892
             return $field;
1893
        }
1894
    public function browsePublicationsRaw($query) {
1895
        try {
1896
            $time = microtime(TRUE);
1897

    
1898
            if (($response = $this->performGet($query)) == NULL)
1899
                throw new Exception('no HTTP response');
1900
            if ($response->code != self :: HTTP_OK)
1901
                throw new Exception('HTTP response code ' . $response->code);
1902
            JLog :: add('Browse publications raw  for query:'.$query.' in ' . (microtime(TRUE) - $time) , JLog :: INFO, self :: LOG);
1903
            return $response;
1904
        } catch (Exception $e) {
1905
            JLog :: add('Error performing publications browse raw', JLog :: ERROR, self :: LOG);
1906
            return NULL;
1907
        }
1908
    }
1909
     public function browseProjectsRaw($query) {
1910
        try {
1911
            $time = microtime(TRUE);
1912

    
1913
            if (($response = $this->performGet(str_replace(' ', '+', $query))) == NULL)
1914
                throw new Exception('no HTTP response');
1915
            if ($response->code != self :: HTTP_OK)
1916
                throw new Exception('HTTP response code ' . $response->code);
1917
            JLog :: add('Browse projects raw  for query:'.$query.' in ' . (microtime(TRUE) - $time) , JLog :: INFO, self :: LOG);
1918
            return $response;
1919
        } catch (Exception $e) {
1920
            JLog :: add('Error performing projects browse raw', JLog :: ERROR, self :: LOG);
1921
            return NULL;
1922
        }
1923
    }
1924
    // Perform a browse for datasets.
1925
    // $type the ID of the dataset type to use as filter or NULL for no dataset type filtering
1926
    // $language the ID of the language to use as filter or NULL for no language filtering
1927
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1928
    // $fundingStream the ID of the fundingStream to use as filter or NULL for no funding stream filtering
1929
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1930
    // $year the year of publication to use as filter or NULL for no year filtering
1931
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1932
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1933
    // $page the page of results to retrieve
1934
    // $size the size of the page of results to retrieve
1935
    // $locale the locale to use
1936
    // $project the ID of the project to use as filter or NULL for no project filtering
1937
    // $author the ID of the author to use as filter or NULL for no author filtering
1938
    // return a result (object) containing datasets and statistics
1939
    private function _browseDatasets($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine, $refineFields) {
1940
        try {
1941
            $time = microtime(TRUE);
1942
            $query = self :: DATASET_QUERY;
1943
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASET_TYPE . ' exact "' . $type . '")');
1944
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASET_LANGUAGE . ' exact "' . $language . '")');
1945
            $query .= ($funder == NULL) ? '' : (' and (' . self :: DATASET_FUNDER . ' exact "' . $funder . '")');
1946
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1947
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: DATASET_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1948
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1949
            $query .= ($year == NULL) ? '' : (' and (' . self :: DATASET_YEAR . ' exact ' . $year . ')');
1950
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: DATASET_ACCESS_MODE . ' exact "' . $accessMode . '")');
1951

    
1952
            // $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
1953
            $datasource_id_array = explode("||", $datasource);
1954
            if(sizeof($datasource_id_array) > 1 ){
1955
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
1956
            }else{
1957
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE_ID . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE_ID . ' exact "' . $datasource . '") )');
1958
            }
1959
            // $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
1960
            $project_id_array = explode("||", $project);
1961
            if(sizeof($project_id_array) > 1 ){
1962
                $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
1963
            }else{
1964
              $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT_ID . ' exact "' . $project . '")');
1965
            }
1966
            $query .= ($author == NULL) ? '' : (' and (' . self :: DATASET_AUTHOR_ID . ' exact "' . $author . '")');
1967
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1968
            $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):
1969
                    'search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
1970
            if (($response = $this->performGet($completeQuery)) == NULL)
1971
                throw new Exception('no HTTP response');
1972
            if ($response->code != self :: HTTP_OK)
1973
                throw new Exception('HTTP response code ' . $response->code);
1974
            $document = new DOMDocument();
1975
            $document->recover = TRUE;
1976
            if ($document->loadXML($response->body) == FALSE)
1977
                throw new Exception('invalid XML response');
1978
            $xpath = new DOMXPath($document);
1979
            $result = new JObject();
1980
            $result->totalDatasets = $this->parseTotalResults($xpath);
1981
            $result->datasets = $this->parseDatasets($xpath);
1982
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
1983
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1984
                    //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));
1985
            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);
1986
            return $result;
1987
        } catch (Exception $e) {
1988
            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);
1989
            return NULL;
1990
        }
1991
    }
1992

    
1993
    // Perform a browse for projects.
1994
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1995
    // $fundingStream the ID of the fundingStream to use as filter or NULL for no funding stream filtering
1996
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1997
    // $startYear the start year to use as filter or NULL for no start year filtering
1998
    // $endYear the end year to use as filter or NULL for no end year filtering
1999
    // $$sc39 the SC-39 status to use as filter or NULL for no SC-39 status filtering
2000
    // $page the page of results to retrieve
2001
    // $size the size of the page of results to retrieve
2002
    // $locale the locale to use
2003
    // return a result (object) containing projects and statistics
2004
    private function _browseProjects($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine) {
2005
        try {
2006
            $time = microtime(TRUE);
2007
            $query = self :: PROJECT_QUERY;
2008
            if($funder != NULL && (strpos($funder, ',') !== FALSE)){
2009
                $temp='';
2010
                foreach(explode(',',$funder) as $id){
2011
                    if(!empty($id)){
2012
                        $temp.='(' . self :: PROJECT_FUNDER . ' exact "' . $id . '") and';
2013
                    }
2014

    
2015
                }
2016
                $query .=  (' and (' . substr($temp, 0, -3). ')');
2017
            }else{
2018
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PROJECT_FUNDER . ' exact "' . $funder . '")');
2019
            }
2020
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2021
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PROJECT_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2022
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2023
            $query .= ($startYear == NULL) ? '' : (' and (' . self :: PROJECT_START_YEAR . ' exact ' . $startYear . ')');
2024
            $query .= ($endYear == NULL) ? '' : (' and (' . self :: PROJECT_END_YEAR . ' exact ' . $endYear . ')');
2025
            $query .= ($sc39 === NULL) ? '' : (' and (' . self :: PROJECT_SC39 . ' exact ' . ($sc39 ? 'true' : 'false') . ')');
2026
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2027
            $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)
2028
                    :'search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2029
            if (($response = $this->performGet($completeQuery)) == NULL)
2030
                throw new Exception('no HTTP response');
2031
            if ($response->code != self :: HTTP_OK)
2032
                throw new Exception('HTTP response code ' . $response->code);
2033
            $document = new DOMDocument();
2034
            $document->recover = TRUE;
2035
            if ($document->loadXML($response->body) == FALSE)
2036
                throw new Exception('invalid XML response');
2037
            $xpath = new DOMXPath($document);
2038
            $result = new JObject();
2039
            $result->totalProjects = $this->parseTotalResults($xpath);
2040
            $result->projects = $this->parseProjects($xpath);
2041
            $result->statistics = $isRefine? $this->createStatisticsForProjects($xpath):NULL;
2042
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
2043
                    //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));
2044
            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);
2045
            return $result;
2046
        } catch (Exception $e) {
2047
            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);
2048
            return NULL;
2049
        }
2050
    }
2051

    
2052
                
2053

    
2054
    // Perform a browse for organizations.
2055
    // $country the ID of the country to use as filter or NULL for no country filtering
2056
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
2057
    // $page the page of results to retrieve
2058
    // $size the size of the page of results to retrieve
2059
    // $locale the locale to use
2060
    // return a result (object) containing organizations and statistics
2061
    private function _browseOrganizations($country, $type, $page, $size, $locale, $isRefine) {
2062
        try {
2063
            $time = microtime(TRUE);
2064
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
2065
            $query .= ($country == NULL) ? '' : (' and (' . self :: ORGANIZATION_COUNTRY . ' exact "' . $country . '")');
2066
            switch ($type) {
2067
                case 'legalBody':
2068
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_BODY . ' exact true)';
2069
                    break;
2070
                case 'legalPerson':
2071
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_PERSON . ' exact true)';
2072
                    break;
2073
                case 'nonProfit':
2074
                    $query .= ' and (' . self :: ORGANIZATION_NON_PROFIT . ' exact true)';
2075
                    break;
2076
                case 'research':
2077
                    $query .= ' and (' . self :: ORGANIZATION_RESEARCH . ' exact true)';
2078
                    break;
2079
                case 'euInterests':
2080
                    $query .= ' and (' . self :: ORGANIZATION_EU_INTERESTS . ' exact true)';
2081
                    break;
2082
                case 'international':
2083
                    $query .= ' and (' . self :: ORGANIZATION_INTERNATIONAL . ' exact true)';
2084
                    break;
2085
                case 'enterprise':
2086
                    $query .= ' and (' . self :: ORGANIZATION_ENTERPRISE . ' exact true)';
2087
                    break;
2088
                case 'smallMediumEnterprise':
2089
                    $query .= ' and (' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . ' exact true)';
2090
            }
2091
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2092
            $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)
2093
                    :'search?action=searchsTransformer=organizations_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2094
            if (($response = $this->performGet($completeQuery)) == NULL)
2095
                throw new Exception('no HTTP response');
2096
            if ($response->code != self :: HTTP_OK)
2097
                throw new Exception('HTTP response code ' . $response->code);
2098
            $document = new DOMDocument();
2099
            $document->recover = TRUE;
2100
            if ($document->loadXML($response->body) == FALSE)
2101
                throw new Exception('invalid XML response');
2102
            $xpath = new DOMXPath($document);
2103
            $result = new JObject();
2104
            $result->totalOrganizations = $this->parseTotalResults($xpath);
2105
            $result->organizations = $this->parseOrganizations($xpath);
2106
            if($isRefine){
2107
                $result->statistics = $this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
2108
                $result->statistics['type'] = new JObject();
2109
                $result->statistics['type']->id = 'type';
2110
                $result->statistics['type']->title = JText :: _('TYPE');
2111
                $result->statistics['type']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
2112
                $result->statistics['type']->data = array();
2113
                $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
2114
                if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
2115
                    $result->statistics['type']->data['legalBody'] = new JObject();
2116
                    $result->statistics['type']->data['legalBody']->id = 'legalBody';
2117
                    $result->statistics['type']->data['legalBody']->name = JText :: _('LEGAL_BODY');
2118
                    $result->statistics['type']->data['legalBody']->count = $legalBody['true']->count;
2119
                }
2120
                $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
2121
                if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
2122
                    $result->statistics['type']->data['legalPerson'] = new JObject();
2123
                    $result->statistics['type']->data['legalPerson']->id = 'legalPerson';
2124
                    $result->statistics['type']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
2125
                    $result->statistics['type']->data['legalPerson']->count = $legalPerson['true']->count;
2126
                }
2127
                $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
2128
                if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
2129
                    $result->statistics['type']->data['nonProfit'] = new JObject();
2130
                    $result->statistics['type']->data['nonProfit']->id = 'nonProfit';
2131
                    $result->statistics['type']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
2132
                    $result->statistics['type']->data['nonProfit']->count = $nonProfit['true']->count;
2133
                }
2134
                $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
2135
                if (($research != NULL) && array_key_exists('true', $research)) {
2136
                    $result->statistics['type']->data['research'] = new JObject();
2137
                    $result->statistics['type']->data['research']->id = 'research';
2138
                    $result->statistics['type']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
2139
                    $result->statistics['type']->data['research']->count = $research['true']->count;
2140
                }
2141
                $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
2142
                if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
2143
                    $result->statistics['type']->data['euInterests'] = new JObject();
2144
                    $result->statistics['type']->data['euInterests']->id = 'euInterests';
2145
                    $result->statistics['type']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
2146
                    $result->statistics['type']->data['euInterests']->count = $euInterests['true']->count;
2147
                }
2148
                $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
2149
                if (($international != NULL) && array_key_exists('true', $international)) {
2150
                    $result->statistics['type']->data['international'] = new JObject();
2151
                    $result->statistics['type']->data['international']->id = 'international';
2152
                    $result->statistics['type']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
2153
                    $result->statistics['type']->data['international']->count = $international['true']->count;
2154
                }
2155
                $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
2156
                if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
2157
                    $result->statistics['type']->data['enterprise'] = new JObject();
2158
                    $result->statistics['type']->data['enterprise']->id = 'enterprise';
2159
                    $result->statistics['type']->data['enterprise']->name = JText :: _('ENTERPRISE');
2160
                    $result->statistics['type']->data['enterprise']->count = $enterprise['true']->count;
2161
                }
2162
                $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
2163
                if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
2164
                    $result->statistics['type']->data['smallMediumEnterprise'] = new JObject();
2165
                    $result->statistics['type']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
2166
                    $result->statistics['type']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
2167
                    $result->statistics['type']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
2168
                }
2169
                uasort($result->statistics['type']->data, function ($row1, $row2) {
2170
                    return $row2->count - $row1->count;
2171
                });
2172
            }
2173
            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);
2174
            return $result;
2175
        } catch (Exception $e) {
2176
            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);
2177
            return NULL;
2178
        }
2179
    }
2180

    
2181
    // Perform a browse for datasources.
2182
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
2183
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
2184
    // $content the ID of the content to use as filter or NULL for no content filtering
2185
    // $compatibility the ID of the compatibility level to use as filter or NULL for no compatibility status filtering
2186
    // $page the page of results to retrieve
2187
    // $size the size of the page of results to retrieve
2188
    // $locale the locale to use
2189
    // return a result (object) containing datasources and statistics
2190
    private function _browseDatasources($type, $language, $content, $compatibility, $page, $size, $locale, $isRefine) {
2191
        try {
2192
            $time = microtime(TRUE);
2193
            $query = self :: DATASOURCE_QUERY;
2194
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASOURCE_TYPE . ' exact "' . $type . '")');
2195
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASOURCE_LANGUAGE . ' exact "' . $language . '")');
2196
            $query .= ($content == NULL) ? '' : (' and (' . self :: DATASOURCE_CONTENT . ' exact "' . $content . '")');
2197
            $query .= ($compatibility == NULL) ? '' : (' and (' . self :: DATASOURCE_COMPATIBILITY . ' exact "' . $compatibility . '")');
2198
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2199
            $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):
2200
                'search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2201
            if (($response = $this->performGet($completeQuery)) == NULL)
2202
                throw new Exception('no HTTP response');
2203
            if ($response->code != self :: HTTP_OK)
2204
                throw new Exception('HTTP response code ' . $response->code);
2205
            $document = new DOMDocument();
2206
            $document->recover = TRUE;
2207
            if ($document->loadXML($response->body) == FALSE)
2208
                throw new Exception('invalid XML response');
2209
            $xpath = new DOMXPath($document);
2210
            $result = new JObject();
2211
            $result->totalDatasources = $this->parseTotalResults($xpath);
2212
            $result->datasources = $this->parseDatasources($xpath);
2213
            $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;
2214
            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);
2215
            return $result;
2216
        } catch (Exception $e) {
2217
            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);
2218
            return NULL;
2219
        }
2220
    }
2221

    
2222
    // Perform an advanced search for publications.
2223
    // $keywords the keywords to search for (array)
2224
    // $fields the fields to match keywords with (array - possible values are TITLE, AUTHOR, PUBLISHER and SUBJECT)
2225
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2226
    // $types the IDs of the publication types to search for
2227
    // $languages the IDs of the publication languages to search for
2228
    // $funders the IDs of the funders to search for
2229
    // $fundingStreams the IDs of the funding streams to search for
2230
    // $scientificAreas the IDs of the scientific areas to search for
2231
    // $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)
2232
    // $fromMonth start month of the publication date range to search for if $date has value 0
2233
    // $fromYear start year of the publication date range to search for if $date has value 0
2234
    // $toMonth end month of the publication date range to search for if $date has value 0
2235
    // $toYear end year of the publication date range to search for if $date has value 0
2236
    // $accessModes the IDs of the access modes to search for
2237
    // $datasources the IDs of the datasources to search for
2238
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
2239
    // $language the ID of the publication language to use as filter or NULL for no publication language filtering
2240
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2241
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
2242
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2243
    // $year the publication year to use as filter or NULL for no publication year filtering
2244
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
2245
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
2246
    // $page the page of results to retrieve
2247
    // $size the size of the page of results to retrieve
2248
    // $locale the locale to use
2249
    // return a result (object) containing publications and statistics
2250
    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) {
2251
        try {
2252
            $time = microtime(TRUE);
2253
            $query = self :: PUBLICATION_QUERY;
2254
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2255
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2256
                switch ($constraints[$i]) {
2257
                    case self :: ALL:
2258
                        $operator = ' and ';
2259
                        break;
2260
                    case self :: ANY:
2261
                        $operator = ' or ';
2262
                        break;
2263
                    default:
2264
                        $operator = NULL;
2265
                }
2266
                switch ($fields[$i]) {
2267
                    case OpenAireViewAdvancedSearchPublications :: TITLE:
2268
                        $field = self :: PUBLICATION_TITLE;
2269
                        break;
2270
                    case OpenAireViewAdvancedSearchPublications :: AUTHOR:
2271
                        $field = self :: PUBLICATION_AUTHOR;
2272
                        break;
2273
                    case OpenAireViewAdvancedSearchPublications :: PUBLISHER:
2274
                        $field = self :: PUBLICATION_PUBLISHER;
2275
                        break;
2276
                    case OpenAireViewAdvancedSearchPublications :: SUBJECT:
2277
                        $field = self :: PUBLICATION_SUBJECT;
2278
                        break;
2279
                    default:
2280
                        $field = NULL;
2281
                }
2282
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2283
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2284
                                }, $tokens)) . ')');
2285
            }
2286
            $field = self :: PUBLICATION_TYPE;
2287
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($field) {
2288
                                return '(' . $field . ' exact "' . $type . '")';
2289
                            }, $types)) . ')');
2290
            $field = self :: PUBLICATION_LANGUAGE;
2291
            $query .= ($languages == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($language) use ($field) {
2292
                                return '(' . $field . ' exact "' . $language . '")';
2293
                            }, $languages)) . ')');
2294
            $field = self :: PUBLICATION_FUNDER;
2295
            $query .= ($funders == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($funder) use ($field) {
2296
                                return '(' . $field . ' exact "' . $funder . '")';
2297
                            }, $funders)) . ')');
2298
            $field = self :: PUBLICATION_FUNDING_STREAM;
2299
            $query .= ($fundingStreams == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStream) use ($field) {
2300
                                return '(' . $field . ' exact "' . $fundingStream . '")';
2301
                            }, $fundingStreams)) . ')');
2302
            $field = self :: PUBLICATION_SCIENTIFIC_AREA;
2303
            $query .= ($scientificAreas == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($scientificArea) use ($field) {
2304
                                return '(' . $field . ' exact "' . $scientificArea . '")';
2305
                            }, $scientificAreas)) . ')');
2306
            $field = self :: PUBLICATION_FUNDING_STREAM_LEVEL2;
2307
            $query .= ($fundingStreamsLevel2 == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStreamsLevel2) use ($field) {
2308
                                return '(' . $field . ' exact "' . $fundingStreamsLevel2 . '")';
2309
                            }, $fundingStreamsLevel2)) . ')');
2310
            $from = new DateTime();
2311
            $to = new DateTime();
2312
            switch ($date) {
2313
                case -1:
2314
                    break;
2315
                case 0:
2316
                    $from->setDate($fromYear, $fromMonth, 1);
2317
                    $to->setDate($toYear, $toMonth, 1);
2318
                    $to->setDate($toYear, $toMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2319
                    $query .= ' and (' . self :: PUBLICATION_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2320
                    break;
2321
                default:
2322
                    $from->sub(new DateInterval('P' . $date . 'M'));
2323
                    $query .= ' and (' . self :: PUBLICATION_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2324
            }
2325
            $field = self :: PUBLICATION_ACCESS_MODE;
2326
            $query .= ($accessModes == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($accessMode) use ($field) {
2327
                                return '(' . $field . ' exact "' . $accessMode . '")';
2328
                            }, $accessModes)) . ')');
2329
            $field = self :: RESULT_HOSTING_DATASOURCE;
2330
            $query .= ($datasources == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($datasource) use ($field) {
2331
                                return '(' . $field . ' exact "' . $datasource . '")';
2332
                            }, $datasources)) . ')');
2333
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
2334
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
2335
            //$query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
2336
              if($funder != NULL && (strpos($funder, ',') !== FALSE)){
2337
                $temp='';
2338
                foreach(explode(',',$funder) as $id){
2339
                    if(!empty($id)){
2340
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
2341
                    }
2342

    
2343
                }
2344
                $query .=  (' and (' . substr($temp, 0, -3). ')');
2345
            }else{
2346
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
2347
            }
2348
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2349
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2350
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2351
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact "' . $year . '")');
2352
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
2353
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '")');
2354
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2355
            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)
2356
                throw new Exception('no HTTP response');
2357
            if ($response->code != self :: HTTP_OK)
2358
                throw new Exception('HTTP response code ' . $response->code);
2359
            $document = new DOMDocument();
2360
            $document->recover = TRUE;
2361
            if ($document->loadXML($response->body) == FALSE)
2362
                throw new Exception('invalid XML response');
2363
            $xpath = new DOMXPath($document);
2364
            $result = new JObject();
2365
            $result->totalPublications = $this->parseTotalResults($xpath);
2366
            $result->publications = $this->parsePublications($xpath);
2367
            $result->statistics =$this->createStatisticsForPublications($xpath,'Filter');
2368
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,"Filter");
2369
                    //$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));
2370
            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);
2371
            return $result;
2372
        } catch (Exception $e) {
2373
            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);
2374
            return NULL;
2375
        }
2376
    }
2377
    private function _advancedSearchDatasets($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) {
2378
        try {
2379
            $time = microtime(TRUE);
2380
            $query = self :: DATASET_QUERY;
2381
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2382
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2383
                switch ($constraints[$i]) {
2384
                    case self :: ALL:
2385
                        $operator = ' and ';
2386
                        break;
2387
                    case self :: ANY:
2388
                        $operator = ' or ';
2389
                        break;
2390
                    default:
2391
                        $operator = NULL;
2392
                }
2393
                switch ($fields[$i]) {
2394
                    case OpenAireViewAdvancedSearchPublications :: TITLE:
2395
                        $field = self :: PUBLICATION_TITLE;
2396
                        break;
2397
                    case OpenAireViewAdvancedSearchPublications :: AUTHOR:
2398
                        $field = self :: PUBLICATION_AUTHOR;
2399
                        break;
2400
                    case OpenAireViewAdvancedSearchPublications :: PUBLISHER:
2401
                        $field = self :: PUBLICATION_PUBLISHER;
2402
                        break;
2403
                    case OpenAireViewAdvancedSearchPublications :: SUBJECT:
2404
                        $field = self :: PUBLICATION_SUBJECT;
2405
                        break;
2406
                    default:
2407
                        $field = NULL;
2408
                }
2409
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2410
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2411
                                }, $tokens)) . ')');
2412
            }
2413
            $field = self :: PUBLICATION_TYPE;
2414
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($field) {
2415
                                return '(' . $field . ' exact "' . $type . '")';
2416
                            }, $types)) . ')');
2417
            $field = self :: PUBLICATION_LANGUAGE;
2418
            $query .= ($languages == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($language) use ($field) {
2419
                                return '(' . $field . ' exact "' . $language . '")';
2420
                            }, $languages)) . ')');
2421
            $field = self :: PUBLICATION_FUNDER;
2422
            $query .= ($funders == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($funder) use ($field) {
2423
                                return '(' . $field . ' exact "' . $funder . '")';
2424
                            }, $funders)) . ')');
2425
            $field = self :: PUBLICATION_FUNDING_STREAM;
2426
            $query .= ($fundingStreams == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStream) use ($field) {
2427
                                return '(' . $field . ' exact "' . $fundingStream . '")';
2428
                            }, $fundingStreams)) . ')');
2429
            $field = self :: PUBLICATION_SCIENTIFIC_AREA;
2430
            $query .= ($scientificAreas == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($scientificArea) use ($field) {
2431
                                return '(' . $field . ' exact "' . $scientificArea . '")';
2432
                            }, $scientificAreas)) . ')');
2433
            $field = self :: PUBLICATION_FUNDING_STREAM_LEVEL2;
2434
            $query .= ($fundingStreamsLevel2 == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStreamsLevel2) use ($field) {
2435
                                return '(' . $field . ' exact "' . $fundingStreamsLevel2 . '")';
2436
                            }, $fundingStreamsLevel2)) . ')');
2437
            $from = new DateTime();
2438
            $to = new DateTime();
2439
            switch ($date) {
2440
                case -1:
2441
                    break;
2442
                case 0:
2443
                    $from->setDate($fromYear, $fromMonth, 1);
2444
                    $to->setDate($toYear, $toMonth, 1);
2445
                    $to->setDate($toYear, $toMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2446
                    $query .= ' and (' . self :: PUBLICATION_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2447
                    break;
2448
                default:
2449
                    $from->sub(new DateInterval('P' . $date . 'M'));
2450
                    $query .= ' and (' . self :: PUBLICATION_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2451
            }
2452
            $field = self :: PUBLICATION_ACCESS_MODE;
2453
            $query .= ($accessModes == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($accessMode) use ($field) {
2454
                                return '(' . $field . ' exact "' . $accessMode . '")';
2455
                            }, $accessModes)) . ')');
2456
            $field = self :: RESULT_HOSTING_DATASOURCE;
2457
            $query .= ($datasources == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($datasource) use ($field) {
2458
                                return '(' . $field . ' exact "' . $datasource . '")';
2459
                            }, $datasources)) . ')');
2460
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
2461
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
2462
            //$query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
2463
              if($funder != NULL && (strpos($funder, ',') !== FALSE)){
2464
                $temp='';
2465
                foreach(explode(',',$funder) as $id){
2466
                    if(!empty($id)){
2467
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
2468
                    }
2469

    
2470
                }
2471
                $query .=  (' and (' . substr($temp, 0, -3). ')');
2472
            }else{
2473
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
2474
            }
2475
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2476
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2477
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2478
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact "' . $year . '")');
2479
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
2480
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '")');
2481
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2482
            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)
2483
                throw new Exception('no HTTP response');
2484
            if ($response->code != self :: HTTP_OK)
2485
                throw new Exception('HTTP response code ' . $response->code);
2486
            $document = new DOMDocument();
2487
            $document->recover = TRUE;
2488
            if ($document->loadXML($response->body) == FALSE)
2489
                throw new Exception('invalid XML response');
2490
            $xpath = new DOMXPath($document);
2491
            $result = new JObject();
2492
            $result->totalDatasets = $this->parseTotalResults($xpath);
2493
            $result->datasets = $this->parsePublications($xpath);
2494
            $result->statistics =$this->createStatisticsForPublications($xpath,'Filter');
2495
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,"Filter");
2496
                    //$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));
2497
            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);
2498
            return $result;
2499
        } catch (Exception $e) {
2500
            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);
2501
            return NULL;
2502
        }
2503
    }
2504

    
2505
    // Perform an advanced search for projects.
2506
    // $keywords the keywords to search for (array)
2507
    // $fields the fields to match keywords with (array - possible values are ACRONYM, TITLE and KEYWORDS)
2508
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2509
    // $funders the IDs of the funders to search for
2510
    // $fundingStreams the IDs of the funding streams to search for
2511
    // $scientificAreas the IDs of the scientific areas to search for
2512
    // $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)
2513
    // $startFromMonth start month of the start date range to search for if $startDate has value 0
2514
    // $startFromYear start year of the start date range to search for if $startDate has value 0
2515
    // $startToMonth end month of the start date range to search for if $startDate has value 0
2516
    // $startToYear end year of the start date range to search for if $startDate has value 0
2517
    // $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)
2518
    // $endFromMonth start month of the end date range to search for if $endDate has value 0
2519
    // $endFromYear start year of the end date range to search for if $endDate has value 0
2520
    // $endToMonth end month of the end date range to search for if $endDate has value 0
2521
    // $endToYear end year of the end date range to search for if $endDate has value 0
2522
    // $sc39s the IDs of the SC-39 statuses to search for
2523
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2524
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
2525
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2526
    // $startYear the start year to use as filter or NULL for no start year filtering
2527
    // $endYear the end year to use as filter or NULL for no end year filtering
2528
    // $sc39 the ID of the SC-39 status to use as filter or NULL for no SC-39 status filtering
2529
    // $page the page of results to retrieve
2530
    // $size the size of the page of results to retrieve
2531
    // $locale the locale to use
2532
    // return a result (object) containing projects and statistics
2533
    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) {
2534
        try {
2535
            $time = microtime(TRUE);
2536
            $query = self :: PROJECT_QUERY;
2537
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2538
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2539
                switch ($constraints[$i]) {
2540
                    case OpenAireViewAdvancedSearchProjects :: ALL:
2541
                        $operator = ' and ';
2542
                        break;
2543
                    case OpenAireViewAdvancedSearchProjects :: ANY:
2544
                        $operator = ' or ';
2545
                        break;
2546
                    default:
2547
                        $operator = NULL;
2548
                }
2549
                switch ($fields[$i]) {
2550
                    case OpenAireViewAdvancedSearchProjects :: ACRONYM:
2551
                        $field = self :: PROJECT_ACRONYM;
2552
                        break;
2553
                    case OpenAireViewAdvancedSearchProjects :: TITLE:
2554
                        $field = self :: PROJECT_TITLE;
2555
                        break;
2556
                    case OpenAireViewAdvancedSearchProjects :: KEYWORDS:
2557
                        $field = self :: PROJECT_KEYWORDS;
2558
                        break;
2559
                    default:
2560
                        $field = NULL;
2561
                }
2562
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2563
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2564
                                }, $tokens)) . ')');
2565
            }
2566
            $field = self :: PROJECT_FUNDER;
2567
            $query .= ($funders == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($funder) use ($field) {
2568
                                return '(' . $field . ' exact "' . $funder . '")';
2569
                            }, $funders)) . ')');
2570
            $field = self :: PROJECT_FUNDING_STREAM;
2571
            $query .= ($fundingStreams == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStream) use ($field) {
2572
                                return '(' . $field . ' exact "' . $fundingStream . '")';
2573
                            }, $fundingStreams)) . ')');
2574
            $field = self :: PROJECT_SCIENTIFIC_AREA;
2575
            $query .= ($scientificAreas == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($scientificArea) use ($field) {
2576
                                return '(' . $field . ' exact "' . $scientificArea . '")';
2577
                            }, $scientificAreas)) . ')');
2578
            $field = self :: PROJECT_FUNDING_STREAM_LEVEL2;
2579
            $query .= ($fundingStreamsLevel2 == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStreamsLevel2) use ($field) {
2580
                                return '(' . $field . ' exact "' . $fundingStreamsLevel2 . '")';
2581
                            }, $scientificAreas)) . ')');
2582
            $from = new DateTime();
2583
            $to = new DateTime();
2584
            switch ($startDate) {
2585
                case -1:
2586
                    break;
2587
                case 0:
2588
                    $from->setDate($startFromYear, $startFromMonth, 1);
2589
                    $to->setDate($startToYear, $startToMonth, 1);
2590
                    $to->setDate($startToYear, $startToMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2591
                    $query .= ' and (' . self :: PROJECT_START_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2592
                    break;
2593
                default:
2594
                    $from->sub(new DateInterval('P' . $startDate . 'M'));
2595
                    $query .= ' and (' . self :: PROJECT_START_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2596
            }
2597
            $from = new DateTime();
2598
            $to = new DateTime();
2599
            switch ($endDate) {
2600
                case -1:
2601
                    break;
2602
                case 0:
2603
                    $from->setDate($endFromYear, $endFromMonth, 1);
2604
                    $to->setDate($endToYear, $endToMonth, 1);
2605
                    $to->setDate($endToYear, $endToMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2606
                    $query .= ' and (' . self :: PROJECT_END_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2607
                    break;
2608
                default:
2609
                    $from->sub(new DateInterval('P' . $endDate . 'M'));
2610
                    $query .= ' and (' . self :: PROJECT_END_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2611
            }
2612
            $field = self :: PROJECT_SC39;
2613
            $query .= ($sc39s == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($sc39) use ($field) {
2614
                                return '(' . $field . ' exact "' . ($sc39 ? 'true' : 'false') . '")';
2615
                            }, $sc39s)) . ')');
2616
            $query .= ($funder == NULL) ? '' : (' and (' . self :: PROJECT_FUNDER . ' exact "' . $funder . '")');
2617
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2618
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PROJECT_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2619
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2620
            $query .= ($startYear == NULL) ? '' : (' and (' . self :: PROJECT_START_YEAR . ' exact "' . $startYear . '")');
2621
            $query .= ($endYear == NULL) ? '' : (' and (' . self :: PROJECT_END_YEAR . ' exact "' . $endYear . '")');
2622
            $query .= ($sc39 === NULL) ? '' : (' and (' . self :: PROJECT_SC39 . ' exact "' . ($sc39 ? 'true' : 'false') . '")');
2623
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2624
            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)
2625
                throw new Exception('no HTTP response');
2626
            if ($response->code != self :: HTTP_OK)
2627
                throw new Exception('HTTP response code ' . $response->code);
2628
            $document = new DOMDocument();
2629
            $document->recover = TRUE;
2630
            if ($document->loadXML($response->body) == FALSE)
2631
                throw new Exception('invalid XML response');
2632
            $xpath = new DOMXPath($document);
2633
            $result = new JObject();
2634
            $result->totalProjects = $this->parseTotalResults($xpath);
2635
            $result->projects = $this->parseProjects($xpath);
2636
            $result->statistics = $this->createStatisticsForProjects($xpath,"Filter");
2637
                    //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));
2638
            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) {
2639
                                return $sc39 ? 'true' : 'false';
2640
                            }, $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);
2641
            return $result;
2642
        } catch (Exception $e) {
2643
            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) {
2644
                                return $sc39 ? 'true' : 'false';
2645
                            }, $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);
2646
            return NULL;
2647
        }
2648
    }
2649
                
2650
    // Perform an advanced search for organizations.
2651
    // $keywords the keywords to search for (array)
2652
    // $fields the fields to match keywords with (array - possible values are NAME and SHORT_NAME)
2653
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2654
    // $countries the IDs of the countries to search for
2655
    // $types the IDs of the organization types to search for
2656
    // $country the ID of the coutnry to use as filter or NULL for no country filtering
2657
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
2658
    // $page the page of results to retrieve
2659
    // $size the size of the page of results to retrieve
2660
    // $locale the locale to use
2661
    // return a result (object) containing organizations and statistics
2662
    private function _advancedSearchOrganizations($keywords, $fields, $constraints, $countries, $types, $country, $type, $page, $size, $locale) {
2663
        try {
2664
            $time = microtime(TRUE);
2665
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
2666
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2667
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2668
                switch ($constraints[$i]) {
2669
                    case self :: ALL:
2670
                        $operator = ' and ';
2671
                        break;
2672
                    case self :: ANY:
2673
                        $operator = ' or ';
2674
                        break;
2675
                    default:
2676
                        $operator = NULL;
2677
                }
2678
                switch ($fields[$i]) {
2679
                    case OpenAireViewAdvancedSearchOrganizations :: NAME:
2680
                        $field = self :: ORGANIZATION_NAME;
2681
                        break;
2682
                    case OpenAireViewAdvancedSearchOrganizations :: SHORT_NAME:
2683
                        $field = self :: ORGANIZATION_SHORT_NAME;
2684
                        break;
2685
                    default:
2686
                        $field = NULL;
2687
                }
2688
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2689
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2690
                                }, $tokens)) . ')');
2691
            }
2692
            $field = self :: ORGANIZATION_COUNTRY;
2693
            $query .= ($countries == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($country) use ($field) {
2694
                                return '(' . $field . ' exact "' . $country . '")';
2695
                            }, $countries)) . ')');
2696
            $organizationLegalBody = self :: ORGANIZATION_LEGAL_BODY;
2697
            $organizationLegalPerson = self :: ORGANIZATION_LEGAL_PERSON;
2698
            $organizationNonProfit = self :: ORGANIZATION_NON_PROFIT;
2699
            $organizationResearch = self :: ORGANIZATION_RESEARCH;
2700
            $organizationEuInterests = self :: ORGANIZATION_EU_INTERESTS;
2701
            $organizationInternational = self :: ORGANIZATION_INTERNATIONAL;
2702
            $organizationEnterprise = self :: ORGANIZATION_ENTERPRISE;
2703
            $organizationSmallMediumEnterprise = self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE;
2704
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($organizationLegalBody, $organizationLegalPerson, $organizationNonProfit, $organizationResearch, $organizationEuInterests, $organizationInternational, $organizationEnterprise, $organizationSmallMediumEnterprise) {
2705
                                switch ($type) {
2706
                                    case 'legalBody': return '(' . $organizationLegalBody . ' exact true)';
2707
                                    case 'legalPerson': return '(' . $organizationLegalPerson . ' exact true)';
2708
                                    case 'nonProfit': return '(' . $organizationNonProfit . ' exact true)';
2709
                                    case 'research': return '(' . $organizationResearch . ' exact true)';
2710
                                    case 'euInterests': return '(' . $organizationEuInterests . ' exact true)';
2711
                                    case 'international': return '(' . $organizationInternational . ' exact true)';
2712
                                    case 'enterprise': return '(' . $organizationEnterprise . ' exact true)';
2713
                                    case 'smallMediumEnterprise': return '(' . $organizationSmallMediumEnterprise . ' exact true)';
2714
                                }
2715
                            }, $types)) . ')');
2716
            $query .= ($country == NULL) ? '' : (' and (' . self :: ORGANIZATION_COUNTRY . ' exact "' . $country . '")');
2717
            switch ($type) {
2718
                case 'legalBody':
2719
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_BODY . ' exact true)';
2720
                    break;
2721
                case 'legalPerson':
2722
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_PERSON . ' exact true)';
2723
                    break;
2724
                case 'nonProfit':
2725
                    $query .= ' and (' . self :: ORGANIZATION_NON_PROFIT . ' exact true)';
2726
                    break;
2727
                case 'research':
2728
                    $query .= ' and (' . self :: ORGANIZATION_RESEARCH . ' exact true)';
2729
                    break;
2730
                case 'euInterests':
2731
                    $query .= ' and (' . self :: ORGANIZATION_EU_INTERESTS . ' exact true)';
2732
                    break;
2733
                case 'international':
2734
                    $query .= ' and (' . self :: ORGANIZATION_INTERNATIONAL . ' exact true)';
2735
                    break;
2736
                case 'enterprise':
2737
                    $query .= ' and (' . self :: ORGANIZATION_ENTERPRISE . ' exact true)';
2738
                    break;
2739
                case 'smallMediumEnterprise':
2740
                    $query .= ' and (' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . ' exact true)';
2741
            }
2742
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2743
            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)
2744
                throw new Exception('no HTTP response');
2745
            if ($response->code != self :: HTTP_OK)
2746
                throw new Exception('HTTP response code ' . $response->code);
2747
            $document = new DOMDocument();
2748
            $document->recover = TRUE;
2749
            if ($document->loadXML($response->body) == FALSE)
2750
                throw new Exception('invalid XML response');
2751
            $xpath = new DOMXPath($document);
2752
            $result = new JObject();
2753
            $result->totalOrganizations = $this->parseTotalResults($xpath);
2754
            $result->organizations = $this->parseOrganizations($xpath);
2755
            $result->statistics = $this->createStatistics($xpath, array('countryFilter'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
2756
            $result->statistics['typeFilter'] = new JObject();
2757
            $result->statistics['typeFilter']->id = 'typeFilter';
2758
            $result->statistics['typeFilter']->title = JText :: _('TYPE');
2759
            $result->statistics['typeFilter']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
2760
            $result->statistics['typeFilter']->data = array();
2761
            $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
2762
            if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
2763
                $result->statistics['typeFilter']->data['legalBody'] = new JObject();
2764
                $result->statistics['typeFilter']->data['legalBody']->id = 'legalBody';
2765
                $result->statistics['typeFilter']->data['legalBody']->name = JText :: _('LEGAL_BODY');
2766
                $result->statistics['typeFilter']->data['legalBody']->count = $legalBody['true']->count;
2767
            }
2768
            $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
2769
            if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
2770
                $result->statistics['typeFilter']->data['legalPerson'] = new JObject();
2771
                $result->statistics['typeFilter']->data['legalPerson']->id = 'legalPerson';
2772
                $result->statistics['typeFilter']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
2773
                $result->statistics['typeFilter']->data['legalPerson']->count = $legalPerson['true']->count;
2774
            }
2775
            $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
2776
            if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
2777
                $result->statistics['typeFilter']->data['nonProfit'] = new JObject();
2778
                $result->statistics['typeFilter']->data['nonProfit']->id = 'nonProfit';
2779
                $result->statistics['typeFilter']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
2780
                $result->statistics['typeFilter']->data['nonProfit']->count = $nonProfit['true']->count;
2781
            }
2782
            $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
2783
            if (($research != NULL) && array_key_exists('true', $research)) {
2784
                $result->statistics['typeFilter']->data['research'] = new JObject();
2785
                $result->statistics['typeFilter']->data['research']->id = 'research';
2786
                $result->statistics['typeFilter']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
2787
                $result->statistics['typeFilter']->data['research']->count = $research['true']->count;
2788
            }
2789
            $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
2790
            if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
2791
                $result->statistics['typeFilter']->data['euInterests'] = new JObject();
2792
                $result->statistics['typeFilter']->data['euInterests']->id = 'euInterests';
2793
                $result->statistics['typeFilter']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
2794
                $result->statistics['typeFilter']->data['euInterests']->count = $euInterests['true']->count;
2795
            }
2796
            $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
2797
            if (($international != NULL) && array_key_exists('true', $international)) {
2798
                $result->statistics['typeFilter']->data['international'] = new JObject();
2799
                $result->statistics['typeFilter']->data['international']->id = 'international';
2800
                $result->statistics['typeFilter']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
2801
                $result->statistics['typeFilter']->data['international']->count = $international['true']->count;
2802
            }
2803
            $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
2804
            if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
2805
                $result->statistics['typeFilter']->data['enterprise'] = new JObject();
2806
                $result->statistics['typeFilter']->data['enterprise']->id = 'enterprise';
2807
                $result->statistics['typeFilter']->data['enterprise']->name = JText :: _('ENTERPRISE');
2808
                $result->statistics['typeFilter']->data['enterprise']->count = $enterprise['true']->count;
2809
            }
2810
            $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
2811
            if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
2812
                $result->statistics['typeFilter']->data['smallMediumEnterprise'] = new JObject();
2813
                $result->statistics['typeFilter']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
2814
                $result->statistics['typeFilter']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
2815
                $result->statistics['typeFilter']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
2816
            }
2817
            uasort($result->statistics['typeFilter']->data, function ($row1, $row2) {
2818
                return $row2->count - $row1->count;
2819
            });
2820
            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);
2821
            return $result;
2822
        } catch (Exception $e) {
2823
            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);
2824
            return NULL;
2825
        }
2826
    }
2827

    
2828
    // Perform an advanced search for datasources.
2829
    // $keywords the keywords to search for (array)
2830
    // $fields the fields to match keywords with (array - possible values are NAME, ENGLISH_NAME and SUBJECT)
2831
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2832
    // $types the IDs of the datasource types to search for
2833
    // $languages the IDs of the datasource languages to search for
2834
    // $contents the IDs of the contents to search for
2835
    // $compatibilities the IDs of the compatibilities to search for
2836
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
2837
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
2838
    // $content the ID of the content to use as filter or NULL for no content filtering
2839
    // $compatibility the ID of the compatibility to use as filter or NULL for no compatibility filtering
2840
    // $page the page of results to retrieve
2841
    // $size the size of the page of results to retrieve
2842
    // $locale the locale to use
2843
    // return a result (object) containing datasources and statistics
2844
    private function _advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale) {
2845
        try {
2846
            $time = microtime(TRUE);
2847
            $query = self :: DATASOURCE_QUERY;
2848
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2849
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2850
                switch ($constraints[$i]) {
2851
                    case OpenAireViewAdvancedSearchDatasources :: ALL:
2852
                        $operator = ' and ';
2853
                        break;
2854
                    case OpenAireViewAdvancedSearchDatasources :: ANY:
2855
                        $operator = ' or ';
2856
                        break;
2857
                    default:
2858
                        $operator = NULL;
2859
                }
2860
                switch ($fields[$i]) {
2861
                    case OpenAireViewAdvancedSearchDatasources :: NAME:
2862
                        $field = self :: DATASOURCE_NAME;
2863
                        break;
2864
                    case OpenAireViewAdvancedSearchDatasources :: ENGLISH_NAME:
2865
                        $field = self :: DATASOURCE_ENGLISH_NAME;
2866
                        break;
2867
                    case OpenAireViewAdvancedSearchDatasources :: SUBJECT:
2868
                        $field = self :: DATASOURCE_SUBJECT;
2869
                        break;
2870
                    default:
2871
                        $field = NULL;
2872
                }
2873
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2874
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2875
                                }, $tokens)) . ')');
2876
            }
2877
            $field = self :: DATASOURCE_TYPE;
2878
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($field) {
2879
                                return '(' . $field . ' exact "' . $type . '")';
2880
                            }, $types)) . ')');
2881
            $field = self :: DATASOURCE_LANGUAGE;
2882
            $query .= ($languages == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($language) use ($field) {
2883
                                return '(' . $field . ' exact "' . $language . '")';
2884
                            }, $languages)) . ')');
2885
            $field = self :: DATASOURCE_CONTENT;
2886
            $query .= ($contents == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($content) use ($field) {
2887
                                return '(' . $field . ' exact "' . $content . '")';
2888
                            }, $contents)) . ')');
2889
            $field = self :: DATASOURCE_COMPATIBILITY;
2890
            $query .= ($compatibilities == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($compatibility) use ($field) {
2891
                                return '(' . $field . ' exact "' . $compatibility . '")';
2892
                            }, $compatibilities)) . ')');
2893
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASOURCE_TYPE . ' exact "' . $type . '")');
2894
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASOURCE_LANGUAGE . ' exact "' . $language . '")');
2895
            $query .= ($content == NULL) ? '' : (' and (' . self :: DATASOURCE_CONTENT . ' exact "' . $content . '")');
2896
            $query .= ($compatibility == NULL) ? '' : (' and (' . self :: DATASOURCE_COMPATIBILITY . ' exact "' . $compatibility . '")');
2897
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2898
            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)
2899
                throw new Exception('no HTTP response');
2900
            if ($response->code != self :: HTTP_OK)
2901
                throw new Exception('HTTP response code ' . $response->code);
2902
            $document = new DOMDocument();
2903
            $document->recover = TRUE;
2904
            if ($document->loadXML($response->body) == FALSE)
2905
                throw new Exception('invalid XML response');
2906
            $xpath = new DOMXPath($document);
2907
            $result = new JObject();
2908
            $result->totalDatasources = $this->parseTotalResults($xpath);
2909
            $result->datasources = $this->parseDatasources($xpath);
2910
            $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));
2911
            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);
2912
            return $result;
2913
        } catch (Exception $e) {
2914
            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);
2915
            return NULL;
2916
        }
2917
    }
2918

    
2919
    // Retrieve a single publication by identifier.
2920
    // $id the publication identifier
2921
    // $locale the locale to use
2922
    // return a publication (object) or NULL if no such publication exists
2923
    private function _getPublication($id, $locale) {
2924
        try {
2925
            $time = microtime(TRUE);
2926
            $query = self :: PUBLICATION_QUERY . ' and ( (' . self :: PUBLICATION_ID . ' exact "' . $id . '") or (' . self :: RESULT_DUP_ID . ' exact "' . $id . '" ) )';
2927
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2928
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
2929
                throw new Exception('no HTTP response');
2930
            if ($response->code != self :: HTTP_OK)
2931
                throw new Exception('HTTP response code ' . $response->code);
2932
            $document = new DOMDocument();
2933
            $document->recover = TRUE;
2934
            if ($document->loadXML($response->body) == FALSE)
2935
                throw new Exception('invalid XML response');
2936
            $xpath = new DOMXPath($document);
2937
            $publication = $this->parsePublication($xpath, $locale);
2938
            JLog :: add('Retrieved publication in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
2939
            return $publication;
2940
        } catch (Exception $e) {
2941
            JLog :: add('Error retrieving publication (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2942
            return NULL;
2943
        }
2944
    }
2945

    
2946
    // Retrieve results by identifier.
2947
    // $ids the result identifiers
2948
    // $locale the locale to use
2949
    // return a result (object) or NULL if no such result exists
2950
    private function _getResults($ids, $locale) {
2951
        try {
2952
            $time = microtime(TRUE);
2953
            $query = self :: RESULT_QUERY . ' and (';
2954
            $parts = array();
2955
            foreach ($ids as $id) {
2956
                $parts[] = ('(' . self :: RESULT_ID . ' exact "' . $id . '") OR (' . self :: RESULT_DUP_ID . ' exact "' . $id . '") ');
2957
               //  $parts[] = ('(' . self :: RESULT_ID . ' exact "' . $id . '") ');
2958
            }
2959
            $query .= join(" OR ", $parts);
2960
            $query .= ')';
2961
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2962
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&size=10000&locale=' . str_replace('-', '_', $locale))) == NULL)
2963
                throw new Exception('no HTTP response');
2964
            if ($response->code != self :: HTTP_OK)
2965
                throw new Exception('HTTP response code ' . $response->code);
2966
            $document = new DOMDocument();
2967
            $document->recover = TRUE;
2968
            if ($document->loadXML($response->body) == FALSE)
2969
                throw new Exception('invalid XML response');
2970
            $xpath = new DOMXPath($document);
2971
            $results = $this->parseResults($ids,$xpath, $locale);
2972
            JLog :: add('Retrieved results in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
2973
            return $results;
2974
        } catch (Exception $e) {
2975
            JLog :: add('Error retrieving results (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
2976
            return NULL;
2977
        }
2978
    }
2979

    
2980
    // Retrieve publications by identifier.
2981
    // $ids the publication identifiers
2982
    // $locale the locale to use
2983
    // return a publication (object) or NULL if no such publication exists
2984
    private function _getPublications($ids, $locale) {
2985
        try {
2986
            $time = microtime(TRUE);
2987
            $query = self :: PUBLICATION_QUERY . ' and (';
2988
            $parts = array();
2989
            foreach ($ids as $id) {
2990
                $parts[] = '(' . self :: PUBLICATION_ID . ' exact "' . $id . '")';
2991
            }
2992
            $query .= join(" OR ", $parts);
2993
            $query .= ')';
2994
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2995
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
2996
                throw new Exception('no HTTP response');
2997
            if ($response->code != self :: HTTP_OK)
2998
                throw new Exception('HTTP response code ' . $response->code);
2999
            $document = new DOMDocument();
3000
            $document->recover = TRUE;
3001
            if ($document->loadXML($response->body) == FALSE)
3002
                throw new Exception('invalid XML response');
3003
            $xpath = new DOMXPath($document);
3004
            $publications = $this->parsePublications($xpath, $locale);
3005
            JLog :: add('Retrieved publication in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3006
            return $publications;
3007
        } catch (Exception $e) {
3008
            JLog :: add('Error retrieving publication (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3009
            return NULL;
3010
        }
3011
    }
3012

    
3013
    // Retrieve publications by identifier.
3014
    // $ids the publication identifiers
3015
    // $locale the locale to use
3016
    // return a publication (object) or NULL if no such publication exists
3017
    private function _getProjects($ids, $locale) {
3018
        try {
3019
            $time = microtime(TRUE);
3020
            $query = self :: PROJECT_QUERY . ' and (';
3021
            $parts = array();
3022
            foreach ($ids as $id) {
3023
                $parts[] = '(' . self :: PROJECT_ID . ' exact "' . $id . '")';
3024
            }
3025
            $query .= join(" OR ", $parts);
3026
            $query .= ')';
3027
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3028
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3029
                throw new Exception('no HTTP response');
3030
            if ($response->code != self :: HTTP_OK)
3031
                throw new Exception('HTTP response code ' . $response->code);
3032
            $document = new DOMDocument();
3033
            $document->recover = TRUE;
3034
            if ($document->loadXML($response->body) == FALSE)
3035
                throw new Exception('invalid XML response');
3036
            $xpath = new DOMXPath($document);
3037
            $projects = $this->parseProjects($xpath, $locale);
3038
            JLog :: add('Retrieved projects in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3039
            return $projects;
3040
        } catch (Exception $e) {
3041
            JLog :: add('Error retrieving projects (ids: ' . join(",", $ids) . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3042
            return NULL;
3043
        }
3044
    }
3045
// Retrieve projects by code id.
3046
    // $id the project grant agreement code
3047
    // $locale the locale to use
3048
    // return projects or NULL if no such project exists
3049
    private function _getProjectByCodeId($id, $funder, $locale) {
3050
        try {
3051
            $time = microtime(TRUE);
3052
            $query = self :: PROJECT_QUERY . ' and ';
3053
//                    (oaftype=project) and (projectcode_nt exact 731011)
3054
                $query.=' ( projectcode_nt exact "' . $id . '") and ';
3055
                $query.=' ( funderid exact "' . $funder . '")';
3056
            //and (funderid exact "ec__________::EC")'
3057
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3058
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3059
                throw new Exception('no HTTP response');
3060
            if ($response->code != self :: HTTP_OK)
3061
                throw new Exception('HTTP response code ' . $response->code);
3062
            $document = new DOMDocument();
3063
            $document->recover = TRUE;
3064
            if ($document->loadXML($response->body) == FALSE)
3065
                throw new Exception('invalid XML response');
3066
            $xpath = new DOMXPath($document);
3067
            $projects = $this->parseProject($xpath, $locale);
3068
            JLog :: add('Retrieved projects in ' . (microtime(TRUE) - $time) . ' s (id: ' .$id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3069
            return $projects;
3070
        } catch (Exception $e) {
3071
            JLog :: add('Error retrieving projects (id: ' .$id. ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3072
            return NULL;
3073
        }
3074
    }
3075
    // Retrieve datasets by identifier.
3076
    // $ids the datasets identifiers
3077
    // $locale the locale to use
3078
    // return datasets array of (object) or NULL if no such dataset exists
3079
    private function _getDatasets($ids, $locale) {
3080
        try {
3081
            $time = microtime(TRUE);
3082
            $query = self :: DATASET_QUERY . ' and (';
3083
            $parts = array();
3084
            foreach ($ids as $id) {
3085
                $parts[] = '(' . self :: DATASET_ID . ' exact "' . $id . '")';
3086
            }
3087
            $query .= join(" OR ", $parts);
3088
            $query .= ')';
3089
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3090
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3091
                throw new Exception('no HTTP response');
3092
            if ($response->code != self :: HTTP_OK)
3093
                throw new Exception('HTTP response code ' . $response->code);
3094
            $document = new DOMDocument();
3095
            $document->recover = TRUE;
3096
            if ($document->loadXML($response->body) == FALSE)
3097
                throw new Exception('invalid XML response');
3098
            $xpath = new DOMXPath($document);
3099
            $datasets = $this->parseDatasets($xpath, $locale);
3100
            JLog :: add('Retrieved publication in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3101
            return $datasets;
3102
        } catch (Exception $e) {
3103
            JLog :: add('Error retrieving publication (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3104
            return NULL;
3105
        }
3106
    }
3107

    
3108
    // Retrieve a single dataset by identifier.
3109
    // $id the dataset identifier
3110
    // $locale the locale to use
3111
    // return a dataset (object) or NULL if no such dataset exists
3112
    private function _getDataset($id, $locale) {
3113
        try {
3114
            $time = microtime(TRUE);
3115
            $query = self :: DATASET_QUERY . ' and ( (' . self :: DATASET_ID . ' exact "' . $id . '") or (' . self :: RESULT_DUP_ID . ' exact "' . $id . '" ) )';
3116
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3117
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3118
                throw new Exception('no HTTP response');
3119
            if ($response->code != self :: HTTP_OK)
3120
                throw new Exception('HTTP response code ' . $response->code);
3121
            $document = new DOMDocument();
3122
            $document->recover = TRUE;
3123
            if ($document->loadXML($response->body) == FALSE)
3124
                throw new Exception('invalid XML response');
3125
            $xpath = new DOMXPath($document);
3126
            $dataset = $this->parseDataset($xpath, $locale);
3127
            JLog :: add('Retrieved dataset in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3128
            return $dataset;
3129
        } catch (Exception $e) {
3130
            JLog :: add('Error retrieving dataset (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3131
            return NULL;
3132
        }
3133
    }
3134

    
3135
    // Retrieve a single project by identifier.
3136
    // $id the project identifier
3137
    // $locale the locale to use
3138
    // return a project (object) or NULL if no such project exists
3139
    private function _getProject($id, $locale) {
3140
        try {
3141
            $time = microtime(TRUE);
3142
            $query = self :: PROJECT_QUERY . ' and (' . self :: PROJECT_ID . ' exact "' . $id . '")';
3143
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3144
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3145
                throw new Exception('no HTTP response');
3146
            if ($response->code != self :: HTTP_OK)
3147
                throw new Exception('HTTP response code ' . $response->code);
3148
            $document = new DOMDocument();
3149
            $document->recover = TRUE;
3150
            if ($document->loadXML($response->body) == FALSE)
3151
                throw new Exception('invalid XML response');
3152
            $xpath = new DOMXPath($document);
3153
            $project = $this->parseProject($xpath);
3154
            JLog :: add('Retrieved project in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3155
            return $project;
3156
        } catch (Exception $e) {
3157
            JLog :: add('Error retrieving project (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3158
            return NULL;
3159
        }
3160
    }
3161

    
3162
    // Retrieve a single person by identifier.
3163
    // $id the person identifier
3164
    // $locale the locale to use
3165
    // return a person (object) or NULL if no such person exists
3166
    private function _getPerson($id, $locale) {
3167
        try {
3168
            $time = microtime(TRUE);
3169
            $query = self :: PERSON_QUERY . ' and (' . self :: PERSON_ID . ' exact "' . $id . '")';
3170
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3171
            if (($response = $this->performGet('search?action=search&sTransformer=persons_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
            $person = $this->parsePerson($xpath);
3181
            JLog :: add('Retrieved person in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3182
            return $person;
3183
        } catch (Exception $e) {
3184
            JLog :: add('Error retrieving person (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3185
            return NULL;
3186
        }
3187
    }
3188

    
3189
    // Retrieve a single organization by identifier.
3190
    // $id the organization identifier
3191
    // $locale the locale to use
3192
    // return an organization (object) or NULL if no such organization exists
3193
    private function _getOrganization($id, $locale) {
3194
        try {
3195
            $time = microtime(TRUE);
3196
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY . ' and (' . self :: ORGANIZATION_ID . ' exact "' . $id . '")';
3197
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3198
            if (($response = $this->performGet('search?action=search&sTransformer=organizations_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
            $organization = $this->parseOrganization($xpath);
3208
            JLog :: add('Retrieved organization in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3209
            return $organization;
3210
        } catch (Exception $e) {
3211
            JLog :: add('Error retrieving organization (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3212
            return NULL;
3213
        }
3214
    }
3215

    
3216
    // Retrieve the datasources of an organization.
3217
    // $id the organization identifier
3218
    // $size the maximum number of datasources to retrieve
3219
    // $locale the locale to use
3220
    // return a result (object) containing datasources and total
3221
    private function _getOrganizationDatasources($id, $size, $locale) {
3222
        try {
3223
            $time = microtime(TRUE);
3224
            $query = self :: DATASOURCE_QUERY . ' and (' . self :: DATASOURCE_ORGANIZATION . ' exact "' . $id . '")';
3225
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3226
            if (($response = $this->performGet('search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3227
                throw new Exception('no HTTP response');
3228
            if ($response->code != self :: HTTP_OK)
3229
                throw new Exception('HTTP response code ' . $response->code);
3230
            $document = new DOMDocument();
3231
            $document->recover = TRUE;
3232
            if ($document->loadXML($response->body) == FALSE)
3233
                throw new Exception('invalid XML response');
3234
            $xpath = new DOMXPath($document);
3235
            $result = new JObject();
3236
            $result->totalDatasources = $this->parseTotalResults($xpath);
3237
            $result->datasources = $this->parseDatasources($xpath);
3238
            JLog :: add('Retrieved ' . count($result->datasources) . ' organization datasources in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3239
            return $result;
3240
        } catch (Exception $e) {
3241
            JLog :: add('Error retrieving organization datasources (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3242
            return NULL;
3243
        }
3244
    }
3245

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

    
3274
    // Retrieve all the OpenAIRE compatible datasources.
3275
    // $locale the locale to use
3276
    // return the datasources (array) or NULL if any errors occur
3277
    private function _getCompatibleDatasources($locale) {
3278
        try {
3279
            $time = microtime(TRUE);
3280
            $query = self :: DATASOURCE_QUERY .' and (datasourcecompatibilityid <> "hostedBy") '. ' and (' . self :: DATASOURCE_COMPATIBILITY . ' <> "' . self :: DATASOURCE_COMPATIBILITY_NOT_COMPATIBLE . '")';
3281
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3282
            if (($response = $this->performGet('search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&size=1&locale=' . str_replace('-', '_', $locale))) == NULL)
3283
                throw new Exception('no HTTP response');
3284
            if ($response->code != self :: HTTP_OK)
3285
                throw new Exception('HTTP response code ' . $response->code);
3286
            $document = new DOMDocument();
3287
            $document->recover = TRUE;
3288
            if ($document->loadXML($response->body) == FALSE)
3289
                throw new Exception('invalid XML response');
3290
            $xpath = new DOMXPath($document);
3291
            $totalDatasources = $this->parseTotalResults($xpath);
3292
            if ($totalDatasources > 0) {
3293
                if (($response = $this->performGet('search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&size=' . $totalDatasources . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3294
                    throw new Exception('no HTTP response');
3295
                if ($response->code != self :: HTTP_OK)
3296
                    throw new Exception('HTTP response code ' . $response->code);
3297
                $document = new DOMDocument();
3298
                $document->recover = TRUE;
3299
                if ($document->loadXML($response->body) == FALSE)
3300
                    throw new Exception('invalid XML response');
3301
                $xpath = new DOMXPath($document);
3302
                $datasources = $this->parseDatasources($xpath);
3303
            } else
3304
                $datasources = array();
3305
            JLog :: add('Retrieved ' . count($datasources) . ' compatible datasources in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3306
            return $datasources;
3307
        } catch (Exception $e) {
3308
            JLog :: add('Error retrieving compatible datasources (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3309
            return NULL;
3310
        }
3311
    }
3312

    
3313
    // Perform a quick search for projects, searching only by acronym, title or code and funder.
3314
    // $keyword the keyword to search for
3315
    // $funder the funder to search for
3316
    // $limit the maximum number of results to retrieve
3317
    // $locale the locale to use
3318
    // return projects (array) or NULL if any errors occur
3319
    private function _quickSearchProjects($keyword, $funder, $limit, $locale) {
3320
        try {
3321
            $time = microtime(TRUE);
3322
            $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 . '")';
3323
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3324
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&size=' . $limit . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3325
                throw new Exception('no HTTP response');
3326
            if ($response->code != self :: HTTP_OK)
3327
                throw new Exception('HTTP response code ' . $response->code);
3328
            $document = new DOMDocument();
3329
            $document->recover = TRUE;
3330
            if ($document->loadXML($response->body) == FALSE)
3331
                throw new Exception('invalid XML response');
3332
            $xpath = new DOMXPath($document);
3333
            $projects = $this->parseProjects($xpath);
3334
            JLog :: add('Retrieved ' . count($projects) . ' projects in ' . (microtime(TRUE) - $time) . ' s (keyword: ' . $keyword . ', funder: ' . $funder . ', limit: ' . $limit . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3335
            return $projects;
3336
        } catch (Exception $e) {
3337
            JLog :: add('Error retrieving projects (keyword: ' . $keyword . ', funder: ' . $funder . ', limit: ' . $limit . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3338
            return NULL;
3339
        }
3340
    }
3341

    
3342
    // Perform a quick search for organizations, searching only by name or short name.
3343
    // $keyword the keyword to search for
3344
    // $limit the maximum number of results to retrieve
3345
    // $locale the locale to use
3346
    // return organizations (array) or NULL if any errors occur
3347
    private function _quickSearchOrganizations($keyword, $limit, $locale) {
3348
        try {
3349
            $time = microtime(TRUE);
3350
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY . ' and ((' . self :: ORGANIZATION_NAME . ' all "' . $keyword . '") or (' . self :: ORGANIZATION_SHORT_NAME . ' all "' . $keyword . '")) and ' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "openaire____::47ce9e9f4fad46e732cff06419ecaabb||OpenDOAR" ';
3351
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3352
            if (($response = $this->performGet('search?action=search&sTransformer=organizations_openaire&query=' . urlencode($query) . '&size=' . $limit . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3353
                throw new Exception('no HTTP response');
3354
            if ($response->code != self :: HTTP_OK)
3355
                throw new Exception('HTTP response code ' . $response->code);
3356
            $document = new DOMDocument();
3357
            $document->recover = TRUE;
3358
            if ($document->loadXML($response->body) == FALSE)
3359
                throw new Exception('invalid XML response');
3360
            $xpath = new DOMXPath($document);
3361
            $organizations = $this->parseOrganizations($xpath);
3362
            JLog :: add('Retrieved ' . count($organizations) . ' organizations in ' . (microtime(TRUE) - $time) . ' s (keyword: ' . $keyword . ', limit: ' . $limit . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3363
            return $organizations;
3364
        } catch (Exception $e) {
3365
            JLog :: add('Error retrieving organizations (keyword: ' . $keyword . ', limit: ' . $limit . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3366
            return NULL;
3367
        }
3368
    }
3369

    
3370
    // Perform an HTTP GET request.
3371
    // $request the relative URL to connect to
3372
    // return the HTTP response (object)
3373
    private function performGet($request) {
3374
        $request = $this->searchService . $request;
3375
        JLog :: add('Requesting ' . $request, JLog :: INFO, self :: LOG);
3376
        $time = microtime(TRUE);
3377
        $response = $this->http->get($request);
3378
        JLog :: add('Received response in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
3379
        return $response;
3380
    }
3381

    
3382
    // Create statistics based on a search service XML response.
3383
    // $xpath the DOMXPath to parse
3384
    // $ids the identifiers of the statistics to create
3385
    // $titles the titles of the statistics to create
3386
    // $errors the error messages of the statistics to create
3387
    // $data the field names of the statistics to create
3388
    // return statistics (array)
3389
    private function createStatistics($xpath, $ids, $titles, $errors, $data) {
3390
        $statistics = array();
3391
        array_map(function ($id, $title, $error, $data) use ($xpath, &$statistics) {
3392
            $statistics[$id] = new JObject();
3393
            $statistics[$id]->id = $id;
3394
            $statistics[$id]->title = JText :: _($title);
3395
            $statistics[$id]->error = JText :: _($error);
3396
            $statistics[$id]->data = OpenAireModelSearch :: parseStatistics($xpath, $data);
3397
        }
3398
                , $ids, $titles, $errors, $data);
3399
        return $statistics;
3400
    }
3401

    
3402
    // Parse statistics from a search service XML response.
3403
    // $xpath the DOMXPath to parse
3404
    // $category the category to retrieve statistics for
3405
    // return statistics (associative array)
3406
    public function parseStatistics($xpath, $category) {
3407
        if ((($browseResultsNodes = $xpath->query('/response/browseResults')) == FALSE) || (($browseResultsNode = $browseResultsNodes->item(0)) == NULL))
3408
            throw new Exception('error parsing statistics');
3409
        if (($fieldNodes = $xpath->query('./result/field[@name = "' . $category . '"]', $browseResultsNode)) == FALSE)
3410
            throw new Exception('error parsing statistics');
3411
        $statistics = array();
3412
        foreach ($fieldNodes as $fieldNode) {
3413
            if ((($idNodes = $xpath->query('./field[@name = "value"]/@value_original', $fieldNode)) == FALSE) || (($idNode = $idNodes->item(0)) == NULL))
3414
                throw new Exception('error parsing statistics');
3415
            if ((($nameNodes = $xpath->query('./field[@name = "value"]/@value', $fieldNode)) == FALSE) || (($nameNode = $nameNodes->item(0)) == NULL))
3416
                throw new Exception('error parsing statistics');
3417
            if ((($countNodes = $xpath->query('./field[@name = "count"]/@value', $fieldNode)) == FALSE) || (($countNode = $countNodes->item(0)) == NULL))
3418
                throw new Exception('error parsing statistics');
3419
            $statistic = new JObject();
3420
            $statistic->id = trim($idNode->nodeValue);
3421

    
3422
            $statistic->name = trim($nameNode->nodeValue);
3423
             $statistic->name=  str_replace("::", JText :: _('FUNDER_SEPARATOR'), $statistic->name);
3424
            /* if ($category === self :: PUBLICATION_PROJECT) {
3425
              $project =OpenAireModelSearch :: getProject($statistic->name, 'en-GB');
3426
              if($project!==null){
3427
              $statistic->name =  $project->title;
3428
              }
3429
              } */
3430

    
3431
            $statistic->count = intval(trim($countNode->nodeValue));
3432
            $statistics[$statistic->id] = $statistic;
3433
        }
3434
        return $statistics;
3435
    }
3436

    
3437
    // Parse total results from a search service XML response.
3438
    // xpath the DOMXPath to parse
3439
    // return total results (integer)
3440
    private function parseTotalResults($xpath) {
3441
        if ((($totalNodes = $xpath->query('/response/header/total')) == FALSE) || (($totalNode = $totalNodes->item(0)) == NULL))
3442
            throw new Exception('error parsing total results');
3443
        return intval(trim($totalNode->nodeValue));
3444
    }
3445

    
3446
    // Parse publications from a search service XML response.
3447
    // xpath the DOMXPath to parse
3448
    // return results (array)
3449
    private function parseResults($ids,$xpath) {
3450
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
3451
            throw new Exception('error parsing results');
3452
        $publications = array();
3453
        foreach ($resultNodes as $resultNode) {
3454
            if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
3455
                throw new Exception('error parsing results');
3456
            if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
3457
                throw new Exception('error parsing publications');
3458
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
3459
                throw new Exception('error parsing results');
3460
            if (($subjectNodes = $xpath->query('./field[@name = "subject"]', $resultNode)) == FALSE)
3461
                throw new Exception('error parsing results');
3462
            if (($relatedNodes = $xpath->query('./field[@name = "related"]', $resultNode)) == FALSE)
3463
                throw new Exception('error parsing results');
3464
            if (($authorNodes = $xpath->query('./field[@name = "author"]', $resultNode)) == FALSE)
3465
                throw new Exception('error parsing results');
3466
            if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
3467
                throw new Exception('error parsing results');
3468
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
3469
                throw new Exception('error parsing results');
3470
            if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
3471
                throw new Exception('error parsing results');
3472
            if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
3473
                throw new Exception('error parsing results');
3474
            if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
3475
                throw new Exception('error parsing results');
3476
            if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
3477
                throw new Exception('error parsing results');
3478
            $publication = new JObject();
3479
           // $publication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3480
           // $first=$publication->id;
3481
             foreach($idNodes as $idNode){
3482
                 if (in_array(trim($idNode->nodeValue), $ids)) {
3483
                     $publication->id =trim($idNode->nodeValue);
3484
                }
3485
            }
3486
            $publication->source = 'openaire';
3487
            $publication->url = NULL;
3488
            $publication->accessMode = NULL;
3489
            $publication->datasources = array();
3490
            $publication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3491
            $publication->authors = array();
3492
            $publication->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
3493
            $publication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
3494
            $publication->language = (($languageNode = $languageNodes->item(0)) == NULL) ? NULL : trim($languageNode->nodeValue);
3495
            $publication->projects = array();
3496
            $publication->subjects = array();
3497
            $publication->related = array();
3498
            $publication->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
3499
            $publication->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
3500
            foreach ($subjectNodes as $subjectNode) {
3501
                if (($titleNodes = $xpath->query('./@value', $subjectNode)) == FALSE)
3502
                    throw new Exception('error parsing results');
3503
                if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $subjectNode)) == FALSE)
3504
                    throw new Exception('error parsing results');
3505
                if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $subjectNode)) == FALSE)
3506
                    throw new Exception('error parsing results');
3507
                if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $subjectNode)) == FALSE)
3508
                    throw new Exception('error parsing results');
3509
                $subject = new JObject();
3510
                $subject->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3511
                $subject->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
3512
                $subject->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
3513
                $subject->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
3514
                if (($subject->title != NULL) || ($subject->inferred != NULL) || ($subject->trust != NULL) || ($subject->provenance != NULL))
3515
                    $publication->subjects[] = $subject;
3516
            }
3517

    
3518
            foreach ($relatedNodes as $relatedNode) {
3519

    
3520
                if (($titleNodes = $xpath->query('./field[@name= "title"]/@value', $relatedNode)) == FALSE)
3521
                    throw new Exception('error parsing results');
3522
                if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
3523
                    throw new Exception('error parsing results');
3524
                if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
3525
                    throw new Exception('error parsing results');
3526
                if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
3527
                    throw new Exception('error parsing results');
3528
                $related = new JObject();
3529
                $related->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3530
                $related->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
3531
                $related->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
3532
                $related->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
3533
                if (($related->title != NULL) || ($related->inferred != NULL) || ($related->trust != NULL) || ($related->provenance != NULL))
3534
                    $publication->related[] = $related;
3535
            }
3536

    
3537
            foreach ($datasourceNodes as $datasourceNode) {
3538
                if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
3539
                    throw new Exception('error parsing results');
3540
                if (($accessModeNodes = $xpath->query('./field[@name = "accessrightid"]/@value', $datasourceNode)) == FALSE)
3541
                    throw new Exception('error parsing results');
3542
                $datasource = new JObject();
3543
                $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
3544
                $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
3545
                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))))) {
3546
                    $publication->accessMode = $datasource->accessMode;
3547
                    $publication->url = $datasource->url;
3548
                }
3549
                if (($datasource->url != NULL) || ($datasource->accessMode != NULL))
3550
                    $publication->datasources[] = $datasource;
3551
            }
3552
            foreach ($authorNodes as $authorNode) {
3553
                if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
3554
                    throw new Exception('error parsing results');
3555
                if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
3556
                    throw new Exception('error parsing results');
3557
                if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
3558
                    throw new Exception('error parsing results');
3559
                $author = new JObject();
3560
                $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3561
                $author->lastName = NULL;
3562
                $author->firstName = NULL;
3563
                $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
3564
                $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
3565
                if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
3566
                    $publication->authors[] = $author;
3567
                usort($publication->authors, function ($author1, $author2) {
3568
                    return $author1->ranking - $author2->ranking;
3569
                });
3570
            }
3571
            foreach ($projectNodes as $projectNode) {
3572
                if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
3573
                    throw new Exception('error parsing results');
3574
                if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
3575
                    throw new Exception('error parsing results');
3576
                if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
3577
                    throw new Exception('error parsing results');
3578
                if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
3579
                    throw new Exception('error parsing results');
3580
                $project = new JObject();
3581
                $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3582
                $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
3583
                $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3584
                $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
3585
                if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
3586
                    $publication->projects[] = $project;
3587
            }
3588
            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))
3589
                $publications[] = $publication;
3590
        }
3591
        return $publications;
3592
    }
3593

    
3594
    // Parse publications from a search service XML response.
3595
    // xpath the DOMXPath to parse
3596
    // return publications (array)
3597
    private function parsePublications($xpath) {
3598
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
3599
            throw new Exception('error parsing publications');
3600
        $publications = array();
3601
        foreach ($resultNodes as $resultNode) {
3602
            if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
3603
                throw new Exception('error parsing publications');
3604
            if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
3605
                throw new Exception('error parsing publications');
3606
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
3607
                throw new Exception('error parsing publications');
3608
            if (($subjectNodes = $xpath->query('./field[@name = "subject"]', $resultNode)) == FALSE)
3609
                throw new Exception('error parsing publications');
3610
            if (($relatedNodes = $xpath->query('./field[@name = "related"]', $resultNode)) == FALSE)
3611
                throw new Exception('error parsing publications');
3612
            if (($authorNodes = $xpath->query('./field[@name = "hasAuthor"]', $resultNode)) == FALSE)
3613
                throw new Exception('error parsing publications');
3614
            if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
3615
                throw new Exception('error parsing publications');
3616
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
3617
                throw new Exception('error parsing publications');
3618
            if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
3619
                throw new Exception('error parsing publications');
3620
            if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
3621
                throw new Exception('error parsing publications');
3622
            if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
3623
                throw new Exception('error parsing publications');
3624
            if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
3625
                throw new Exception('error parsing publications');
3626
            if (($sourceNodes = $xpath->query('./field[@name = "source"]/@value', $resultNode)) == FALSE)
3627
                throw new Exception('error parsing publication');
3628
            if (($pidNodes = $xpath->query('./field[@name = "pid"]', $resultNode)) == FALSE)
3629
                throw new Exception('error parsing publication');
3630
            if (($accessModeNodes = $xpath->query('./field[@name = "bestaccessright"]/@value', $resultNode)) == FALSE)
3631
                throw new Exception('error parsing publication');
3632
            $publication = new JObject();
3633
            $publication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3634
            $publication->source = 'openaire';
3635
             foreach ($sourceNodes as $sourceNode) {
3636
                if (($source = trim($sourceNode->nodeValue)) != NULL){
3637
                     $publication->source_source = $source;
3638
                }
3639
            }
3640
            $publication->url = NULL;
3641
            $publication->accessMode =(($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
3642
            $publication->datasources = array();
3643
            $publication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3644
            $publication->authors = array();
3645
            $publication->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
3646
            $publication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
3647
            $publication->language = (($languageNode = $languageNodes->item(0)) == NULL) ? NULL : trim($languageNode->nodeValue);
3648
            $publication->projects = array();
3649
            $publication->subjects = array();
3650
            $publication->related = array();
3651
            $publication->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
3652
            $publication->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
3653
            $publication->pids = array();
3654
            foreach ($pidNodes as $pidNode) {
3655
                if (($classNodes = $xpath->query('./field[@name = "classid"]/@value', $pidNode)) == FALSE)
3656
                    throw new Exception('error parsing publication');
3657
                if (($valueNodes = $xpath->query('./field[@name = "value"]/@value', $pidNode)) == FALSE)
3658
                    throw new Exception('error parsing publication');
3659
                $pid = new JObject();
3660
                $pid->clazz = (($classNode = $classNodes->item(0)) == NULL) ? NULL : trim($classNode->nodeValue);
3661
                $pid->value = (($valueNode = $valueNodes->item(0)) == NULL) ? NULL : trim($valueNode->nodeValue);
3662
                if (($pid->clazz != NULL) && ($pid->value != NULL))
3663
                    $publication->pids[] = $pid;
3664
            }
3665
            foreach ($subjectNodes as $subjectNode) {
3666
                if (($titleNodes = $xpath->query('./@value', $subjectNode)) == FALSE)
3667
                    throw new Exception('error parsing publications');
3668
                if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $subjectNode)) == FALSE)
3669
                    throw new Exception('error parsing publications');
3670
                if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $subjectNode)) == FALSE)
3671
                    throw new Exception('error parsing publications');
3672
                if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $subjectNode)) == FALSE)
3673
                    throw new Exception('error parsing publications');
3674
                $subject = new JObject();
3675
                $subject->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3676
                $subject->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
3677
                $subject->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
3678
                $subject->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
3679
                if (($subject->title != NULL) || ($subject->inferred != NULL) || ($subject->trust != NULL) || ($subject->provenance != NULL))
3680
                    $publication->subjects[] = $subject;
3681
            }
3682

    
3683
            foreach ($relatedNodes as $relatedNode) {
3684

    
3685
                if (($titleNodes = $xpath->query('./field[@name= "title"]/@value', $relatedNode)) == FALSE)
3686
                    throw new Exception('error parsing publications');
3687
                if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
3688
                    throw new Exception('error parsing publications');
3689
                if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
3690
                    throw new Exception('error parsing publications');
3691
                if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
3692
                    throw new Exception('error parsing publications');
3693
                $related = new JObject();
3694
                $related->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3695
                $related->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
3696
                $related->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
3697
                $related->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
3698
                if (($related->title != NULL) || ($related->inferred != NULL) || ($related->trust != NULL) || ($related->provenance != NULL))
3699
                    $publication->related[] = $related;
3700
            }
3701

    
3702
            foreach ($datasourceNodes as $datasourceNode) {
3703
                if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
3704
                    throw new Exception('error parsing publications');
3705
                if (($accessModeNodes = $xpath->query('./field[@name = "accessrightid"]/@value', $datasourceNode)) == FALSE)
3706
                    throw new Exception('error parsing publications');
3707
                $datasource = new JObject();
3708
                $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
3709
                $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
3710
                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))))) {
3711
                    $publication->accessMode = $datasource->accessMode;
3712
                    $publication->url = $datasource->url;
3713
                }
3714
                if (($datasource->url != NULL) || ($datasource->accessMode != NULL))
3715
                    $publication->datasources[] = $datasource;
3716
            }
3717
            foreach ($authorNodes as $authorNode) {
3718
                if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
3719
                    throw new Exception('error parsing publications');
3720
                if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
3721
                    throw new Exception('error parsing publications');
3722
                if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
3723
                    throw new Exception('error parsing publications');
3724
                $author = new JObject();
3725
                $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3726
                $author->lastName = NULL;
3727
                $author->firstName = NULL;
3728
                $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
3729
                $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
3730
                if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
3731
                    $publication->authors[] = $author;
3732
                usort($publication->authors, function ($author1, $author2) {
3733
                    return $author1->ranking - $author2->ranking;
3734
                });
3735
            }
3736
            foreach ($projectNodes as $projectNode) {
3737
                if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
3738
                    throw new Exception('error parsing publications');
3739
                if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
3740
                    throw new Exception('error parsing publications');
3741
                if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
3742
                    throw new Exception('error parsing publications');
3743
                if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
3744
                    throw new Exception('error parsing publications');
3745
                if (($fundingNodes = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
3746
                    throw new Exception('error parsing publications');
3747
                $project = new JObject();
3748
                $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3749
                $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
3750
                $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3751
                $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
3752
                $project -> funder = NULL;
3753
                if (($fundingNode = $fundingNodes->item(0)) == NULL)
3754
                    ;
3755
                else {
3756
                    if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
3757
                        throw new Exception('error parsing project');
3758
                    $project -> funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
3759
                    if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
3760
                        throw new Exception('error parsing project');
3761
                    $project -> funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
3762
                }
3763
                if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
3764
                    $publication->projects[] = $project;
3765
            }
3766
            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))
3767
                $publications[] = $publication;
3768
        }
3769
        return $publications;
3770
    }
3771

    
3772
    // Parse datasets from a search service XML response.
3773
    // xpath the DOMXPath to parse
3774
    // return datasets (array)
3775
    private function parseDatasets($xpath) {
3776
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
3777
            throw new Exception('error parsing datasets');
3778
        $datasets = array();
3779
        foreach ($resultNodes as $resultNode) {
3780
            if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
3781
                throw new Exception('error parsing datasets');
3782
            if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
3783
                throw new Exception('error parsing datasets');
3784
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
3785
                throw new Exception('error parsing datasets');
3786
            if (($authorNodes = $xpath->query('./field[@name = "hasAuthor"]', $resultNode)) == FALSE)
3787
                throw new Exception('error parsing datasets');
3788
            if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
3789
                throw new Exception('error parsing datasets');
3790
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
3791
                throw new Exception('error parsing datasets');
3792
            if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
3793
                throw new Exception('error parsing datasets');
3794
            if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
3795
                throw new Exception('error parsing datasets');
3796
            if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
3797
                throw new Exception('error parsing datasets');
3798
            if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
3799
                throw new Exception('error parsing datasets');
3800
            $dataset = new JObject();
3801
            $dataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3802
            $dataset->source = 'openaire';
3803
            $dataset->url = NULL;
3804
            $dataset->accessMode = NULL;
3805
            $dataset->datasources = array();
3806
            $dataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3807
            $dataset->authors = array();
3808
            $dataset->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
3809
            $dataset->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
3810
            $dataset->language = (($languageNode = $languageNodes->item(0)) == NULL) ? NULL : trim($languageNode->nodeValue);
3811
            $dataset->projects = array();
3812
            $dataset->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
3813
            $dataset->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
3814
            foreach ($datasourceNodes as $datasourceNode) {
3815
                if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
3816
                    throw new Exception('error parsing datasets');
3817
                if (($accessModeNodes = $xpath->query('./field[@name = "accessrightid"]/@value', $datasourceNode)) == FALSE)
3818
                    throw new Exception('error parsing datasets');
3819
                $datasource = new JObject();
3820
                $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
3821
                $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
3822
                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))))) {
3823
                    $dataset->accessMode = $datasource->accessMode;
3824
                    $dataset->url = $datasource->url;
3825
                }
3826
                if (($datasource->url != NULL) || ($datasource->accessMode != NULL))
3827
                    $dataset->datasources[] = $datasource;
3828
            }
3829
            foreach ($authorNodes as $authorNode) {
3830
                if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
3831
                    throw new Exception('error parsing datasets');
3832
                if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
3833
                    throw new Exception('error parsing datasets');
3834
                if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
3835
                    throw new Exception('error parsing datasets');
3836
                $author = new JObject();
3837
                $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3838
                $author->lastName = NULL;
3839
                $author->firstName = NULL;
3840
                $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
3841
                $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
3842
                if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
3843
                    $dataset->authors[] = $author;
3844
                usort($dataset->authors, function ($author1, $author2) {
3845
                    return $author1->ranking - $author2->ranking;
3846
                });
3847
            }
3848
            foreach ($projectNodes as $projectNode) {
3849
                if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
3850
                    throw new Exception('error parsing datasets');
3851
                if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
3852
                    throw new Exception('error parsing datasets');
3853
                if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
3854
                    throw new Exception('error parsing datasets');
3855
                if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
3856
                    throw new Exception('error parsing datasets');
3857
                 if (($fundingNodes = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
3858
                    throw new Exception('error parsing datasets');
3859
                $project = new JObject();
3860
                $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3861
                $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
3862
                $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3863
                $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
3864
                if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
3865
                    $dataset->projects[] = $project;
3866
                  $project -> funder = NULL;
3867
                if (($fundingNode = $fundingNodes->item(0)) == NULL)
3868
                    ;
3869
                else {
3870
                    if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
3871
                        throw new Exception('error parsing datasets');
3872
                    $project -> funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
3873
                    if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
3874
                        throw new Exception('error parsing datasets');
3875
                    $project -> funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
3876
                }
3877
            }
3878
            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))
3879
                $datasets[] = $dataset;
3880
        }
3881
        return $datasets;
3882
    }
3883

    
3884
    // Parse projects from a search service XML response.
3885
    // xpath the DOMXPath to parse
3886
    // return projects (array)
3887
    private function parseProjects($xpath) {
3888
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
3889
            throw new Exception('error parsing projects');
3890
        $projects = array();
3891
        foreach ($resultNodes as $resultNode) {
3892
            if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $resultNode)) == FALSE)
3893
                throw new Exception('error parsing projects');
3894
            if (($acronymNodes = $xpath->query('./field[@name = "name"]/@value', $resultNode)) == FALSE)
3895
                throw new Exception('error parsing projects');
3896
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
3897
                throw new Exception('error parsing projects');
3898
            if (($codeNodes = $xpath->query('./field[@name = "code"]/@value', $resultNode)) == FALSE)
3899
                throw new Exception('error parsing projects');
3900
            if (($sc39Nodes = $xpath->query('./field[@name = "ec_sc39"]/@value', $resultNode)) == FALSE)
3901
                throw new Exception('error parsing projects');
3902
            if (($funderNodes = $xpath->query('./field[@name = "funder"]/field[@name = "fundershortname"]/@value', $resultNode)) == FALSE)
3903
                throw new Exception('error parsing projects');
3904
            if (($startYearNodes = $xpath->query('./field[@name = "startyear"]/@value', $resultNode)) == FALSE)
3905
                throw new Exception('error parsing projects');
3906
            if (($endYearNodes = $xpath->query('./field[@name = "endyear"]/@value', $resultNode)) == FALSE)
3907
                throw new Exception('error parsing projects');
3908
            if (($organizationNodes = $xpath->query('./field[@name = "organization"]', $resultNode)) == FALSE)
3909
                throw new Exception('error parsing projects');
3910
            $project = new JObject();
3911
            $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3912
            $project->acronym = ((($acronymNode = $acronymNodes->item(0)) == NULL) || (trim($acronymNode->nodeValue) == self :: UNKNOWN)) ? NULL : trim($acronymNode->nodeValue);
3913
            $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3914
            $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
3915
            $project->sc39 = (($sc39Node = $sc39Nodes->item(0)) == NULL) ? NULL : trim($sc39Node->nodeValue);
3916
            switch ($project->sc39) {
3917
                case 'true':
3918
                    $project->sc39 = TRUE;
3919
                    break;
3920
                case 'false':
3921
                    $project->sc39 = FALSE;
3922
                    break;
3923
                default:
3924
                    $project->sc39 = NULL;
3925
            }
3926
            $project->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
3927
            $project->startYear = (($startYearNode = $startYearNodes->item(0)) == NULL) ? NULL : intval(trim($startYearNode->nodeValue));
3928
            $project->endYear = (($endYearNode = $endYearNodes->item(0)) == NULL) ? NULL : intval(trim($endYearNode->nodeValue));
3929
            $project->organizations = array();
3930
            foreach ($organizationNodes as $organizationNode) {
3931
                if (($idNodes = $xpath->query('./field[@name = "organizationid"]/@value', $organizationNode)) == FALSE)
3932
                    throw new Exception('error parsing projects');
3933
                if (($shortNameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $organizationNode)) == FALSE)
3934
                    throw new Exception('error parsing projects');
3935
                if (($nameNodes = $xpath->query('./field[@name = "legalname"]/@value', $organizationNode)) == FALSE)
3936
                    throw new Exception('error parsing projects');
3937
                $organization = new JObject();
3938
                $organization->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3939
                $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
3940
                $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
3941
                if (($organization->id != NULL) || ($organization->shortName != NULL) || ($organization->name != NULL))
3942
                    $project->organizations[] = $organization;
3943
            }
3944
            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))
3945
                $projects[] = $project;
3946
        }
3947
        return $projects;
3948
    }
3949
//
3950
//    // Parse people from a search service XML response.
3951
//    // xpath the DOMXPath to parse
3952
//    // return people (array)
3953
//    private function parsePeople($xpath) {
3954
//        if (($resultNodes = $xpath->query('/response/results/record')) == FALSE)
3955
//            throw new Exception('error parsing people');
3956
//        $people = array();
3957
//        foreach ($resultNodes as $resultNode) {
3958
//            if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $resultNode)) == FALSE)
3959
//                throw new Exception('error parsing people');
3960
//            if (($lastNameNodes = $xpath->query('./field[@name = "secondnames"]/@value', $resultNode)) == FALSE)
3961
//                throw new Exception('error parsing people');
3962
//            if (($firstNameNodes = $xpath->query('./field[@name = "firstname"]/@value', $resultNode)) == FALSE)
3963
//                throw new Exception('error parsing people');
3964
//            if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $resultNode)) == FALSE)
3965
//                throw new Exception('error parsing people');
3966
//            if (($countryNodes = $xpath->query('./field[@name = "nationalityid"]/@value', $resultNode)) == FALSE)
3967
//                throw new Exception('error parsing people');
3968
//            $person = new JObject();
3969
//            $person->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3970
//            $person->lastName = (($lastNameNode = $lastNameNodes->item(0)) == NULL) ? NULL : trim($lastNameNode->nodeValue);
3971
//            $person->firstName = (($firstNameNode = $firstNameNodes->item(0)) == NULL) ? NULL : trim($firstNameNode->nodeValue);
3972
//            $person->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
3973
//            $person->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
3974
//            if (($person->id != NULL) || ($person->lastName != NULL) || ($person->firstName != NULL) || ($person->fullName != NULL) || ($person->country != NULL))
3975
//                $people[] = $person;
3976
//        }
3977
//        return $people;
3978
//    }
3979

    
3980
    // Parse organizations from a search service XML response.
3981
    // xpath the DOMXPath to parse
3982
    // return organizations (array)
3983
    private function parseOrganizations($xpath) {
3984
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
3985
            throw new Exception('error parsing organizations');
3986
        $organizations = array();
3987
        foreach ($resultNodes as $resultNode) {
3988
            if (($idNodes = $xpath->query('./field[@name = "organizationId"]/@value', $resultNode)) == FALSE)
3989
                throw new Exception('error parsing organizations');
3990
            if (($shortNameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $resultNode)) == FALSE)
3991
                throw new Exception('error parsing organizations');
3992
            if (($nameNodes = $xpath->query('./field[@name = "legalname"]/@value', $resultNode)) == FALSE)
3993
                throw new Exception('error parsing organizations');
3994
            if (($countryNodes = $xpath->query('./field[@name = "countryname"]/@value', $resultNode)) == FALSE)
3995
                throw new Exception('error parsing organizations');
3996
            if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
3997
                throw new Exception('error parsing organizations');
3998
            $organization = new JObject();
3999
            $organization->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4000
            $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
4001
            $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4002
            $organization->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
4003
            $organization->projects = array();
4004
            foreach ($projectNodes as $projectNode) {
4005
                if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
4006
                    throw new Exception('error parsing organizations');
4007
                if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
4008
                    throw new Exception('error parsing organizations');
4009
                if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
4010
                    throw new Exception('error parsing organizations');
4011
                if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
4012
                    throw new Exception('error parsing organizations');
4013
                $project = new JObject();
4014
                $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4015
                $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
4016
                $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4017
                $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
4018
                if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
4019
                    $organization->projects[] = $project;
4020
            }
4021
            if (($organization->id != NULL) || ($organization->shortName != NULL) || ($organization->name != NULL) || ($organization->country != NULL) || ($organization->projects != NULL))
4022
                $organizations[] = $organization;
4023
        }
4024
        return $organizations;
4025
    }
4026

    
4027
    // Parse datasources from a search service XML response.
4028
    // xpath the DOMXPath to parse
4029
    // return datasources (array)
4030
    private function parseDatasources($xpath) {
4031
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
4032
            throw new Exception('error parsing datasources');
4033
        $datasources = array();
4034
        foreach ($resultNodes as $resultNode) {
4035
            if (($idNodes = $xpath->query('./field[@name = "datasourceId"]/@value', $resultNode)) == FALSE)
4036
                throw new Exception('error parsing datasources');
4037
            if (($typeNodes = $xpath->query('./field[@name = "datasourcetypename"]/@value', $resultNode)) == FALSE)
4038
                throw new Exception('error parsing datasources');
4039
            if (($typeIdNodes = $xpath->query('./field[@name = "datasourcetypeuiid"]/@value_original', $resultNode)) == FALSE)
4040
                throw new Exception('error parsing datasources');
4041
            if (($compatibilityNodes = $xpath->query('./field[@name = "openairecompatibilityid"]/@value', $resultNode)) == FALSE)
4042
                throw new Exception('error parsing datasources');
4043
            if (($urlNodes = $xpath->query('./field[@name = "websiteurl"]/@value', $resultNode)) == FALSE)
4044
                throw new Exception('error parsing datasources');
4045
            if (($nameNodes = $xpath->query('./field[@name = "officialname"]/@value', $resultNode)) == FALSE)
4046
                throw new Exception('error parsing datasources');
4047
            if (($englishNameNodes = $xpath->query('./field[@name = "englishname"]/@value', $resultNode)) == FALSE)
4048
                throw new Exception('error parsing datasources');
4049
            if (($itemsNodes = $xpath->query('./field[@name = "odnumberofitems"]/@value', $resultNode)) == FALSE)
4050
                throw new Exception('error parsing datasources');
4051
            if (($dateNodes = $xpath->query('./field[@name = "odnumberofitemsdate"]/@value', $resultNode)) == FALSE)
4052
                throw new Exception('error parsing datasources');
4053
            if (($languageNodes = $xpath->query('./field[@name = "odlanguages"]/@value', $resultNode)) == FALSE)
4054
                throw new Exception('error parsing datasources');
4055
            if (($policyNodes = $xpath->query('./field[@name = "odpolicies"]/@value', $resultNode)) == FALSE)
4056
                throw new Exception('error parsing datasources');
4057
            if (($contentNodes = $xpath->query('./field[@name = "odcontenttypes"]/@value', $resultNode)) == FALSE)
4058
                throw new Exception('error parsing datasources');
4059
            if (($oaiPmhNodes = $xpath->query('./field[@name = "accessinfopackage"]/@value', $resultNode)) == FALSE)
4060
                throw new Exception('error parsing datasources');
4061
            if (($descriptionNodes = $xpath->query('./field[@name = "oddescription"]/@value', $resultNode)) == FALSE)
4062
                throw new Exception('error parsing datasources');
4063
            if (($organizationNodes = $xpath->query('./field[@name = "organization"]', $resultNode)) == FALSE)
4064
                throw new Exception('error parsing datasources');
4065
            $datasource = new JObject();
4066
            $datasource->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4067
            $datasource->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4068
            $datasource->typeId = (($typeIdNode = $typeIdNodes->item(0)) == NULL) ? NULL : trim($typeIdNode->nodeValue);
4069
            $datasource->compatibility = (($compatibilityNode = $compatibilityNodes->item(0)) == NULL) ? NULL : trim($compatibilityNode->nodeValue);
4070
            $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4071
            $datasource->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4072
            $datasource->englishName = (($englishNameNode = $englishNameNodes->item(0)) == NULL) ? NULL : trim($englishNameNode->nodeValue);
4073
            $datasource->items = (($itemsNode = $itemsNodes->item(0)) == NULL) ? NULL : intval(trim($itemsNode->nodeValue));
4074
            $datasource->date = (($dateNode = $dateNodes->item(0)) == NULL) ? NULL : strtotime(trim($dateNode->nodeValue));
4075
            $datasource->languages = array();
4076
            $datasource->policies = array();
4077
            $datasource->contents = array();
4078
            $datasource->oaiPmhUrls = array();
4079
            $datasource->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
4080
            $datasource->organizations = array();
4081
            foreach ($languageNodes as $languageNode) {
4082
                if (trim($languageNode->nodeValue) != NULL)
4083
                    $datasource->languages[] = trim($languageNode->nodeValue);
4084
            }
4085
            foreach ($policyNodes as $policyNode) {
4086
                if (trim($policyNode->nodeValue) != NULL)
4087
                    $datasource->policies[] = trim($policyNode->nodeValue);
4088
            }
4089
            foreach ($contentNodes as $contentNode) {
4090
                if (trim($contentNode->nodeValue) != NULL)
4091
                    $datasource->contents[] = trim($contentNode->nodeValue);
4092
            }
4093
            foreach ($oaiPmhNodes as $oaiPmhNode) {
4094
                if (trim($oaiPmhNode->nodeValue) != NULL)
4095
                    $datasource->oaiPmhUrls[] = trim($oaiPmhNode->nodeValue);
4096
            }
4097
            foreach ($organizationNodes as $organizationNode) {
4098
                if (($idNodes = $xpath->query('./field[@name = "organizationid"]/@value', $organizationNode)) == FALSE)
4099
                    throw new Exception('error parsing datasources');
4100
                if (($shortNameNodes = $xpath->query('./field[@name = "legalname"]/@value', $organizationNode)) == FALSE)
4101
                    throw new Exception('error parsing datasources');
4102
                if (($nameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $organizationNode)) == FALSE)
4103
                    throw new Exception('error parsing datasources');
4104
                if (($countryNodes = $xpath->query('./field[@name = "countryname"]/@value', $organizationNode)) == FALSE)
4105
                    throw new Exception('error parsing datasources');
4106
                $organization = new JObject();
4107
                $organization->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4108
                $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
4109
                $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4110
                $organization->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
4111
                if (($organization->id != NULL) || ($organization->shortName != NULL) || ($organization->name != NULL) || ($organization->country != NULL))
4112
                    $datasource->organizations[] = $organization;
4113
            }
4114
            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))
4115
                $datasources[] = $datasource;
4116
        }
4117
        return $datasources;
4118
    }
4119

    
4120
    // Parse a single publication from a search service XML response.
4121
    // xpath the DOMXPath to parse
4122
    // return publication (object)
4123
    private function parsePublication($xpath, $locale) {
4124
        if ((($resultsNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL)) // result
4125
            throw new Exception('error parsing publication');
4126
        if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
4127
            throw new Exception('error parsing publication');
4128
        if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
4129
            throw new Exception('error parsing publication');
4130
        if (($curationNodes = $xpath->query('./field[@name = "underCuration"]/@value', $resultNode)) == FALSE)
4131
            throw new Exception('error parsing publication');
4132
        if (($authorNodes = $xpath->query('./field[@name = "hasAuthor"]', $resultNode)) == FALSE)
4133
            throw new Exception('error parsing publication');
4134
        if (($dateNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
4135
            throw new Exception('error parsing publication');
4136
        if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
4137
            throw new Exception('error parsing publication');
4138
        if (($journalNodes = $xpath->query('./field[@name = "journal"]/@value', $resultNode)) == FALSE)
4139
            throw new Exception('error parsing publication');
4140
        if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
4141
            throw new Exception('error parsing publication');
4142
        if (($typeNodes = $xpath->query('./field[@name ="resulttypename"]/@value', $resultNode)) == FALSE)
4143
            throw new Exception('error parsing publication');
4144
        if (($subjectNodes = $xpath->query('./field[@name = "subject" and field[@name="inferred" and @value="false"]]', $resultNode)) == FALSE)
4145
            throw new Exception('error parsing publication');
4146
        if (($inferredSubjectNodes = $xpath->query('./field[@name = "subject" and field[@name="inferred" and @value="true"]]', $resultNode)) == FALSE)
4147
            throw new Exception('error parsing publication');
4148
        if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
4149
            throw new Exception('error parsing publication');
4150
        if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
4151
            throw new Exception('error parsing publication');
4152
        if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
4153
            throw new Exception('error parsing publication');
4154
        if (($collectedFromNodes = $xpath->query('./field[@name = "collectedfrom"]', $resultNode)) == FALSE)
4155
            throw new Exception('error parsing publication');
4156
        if (($sourceNodes = $xpath->query('./field[@name = "source"]/@value', $resultNode)) == FALSE)
4157
            throw new Exception('error parsing publication');
4158
        if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
4159
            throw new Exception('error parsing publication');
4160
        if (($pidNodes = $xpath->query('./field[@name = "pid"]', $resultNode)) == FALSE)
4161
            throw new Exception('error parsing publication');
4162
        if (($similarNodes = $xpath->query('./field[@name = "hasAmongTopNSimilarDocuments"]', $resultNode)) == FALSE)
4163
            throw new Exception('error parsing publication');
4164
        if (($relatedNodes = $xpath->query('./field[@name = "isRelatedTo"]', $resultNode)) == FALSE)
4165
            throw new Exception('error parsing publication');
4166
        if (($externalReferenceNodes = $xpath->query('./field[@name = "externalreference"]', $resultNode)) == FALSE)
4167
            throw new Exception('error parsing publication');
4168
        if (($contextNodes = $xpath->query('./field[@name = "context"]', $resultNode)) == FALSE)
4169
            throw new Exception('error parsing publication');
4170
        if (($citationNodes = $xpath->query('./field[@name = "citation"]', $resultNode)) == FALSE)
4171
            throw new Exception('error parsing publication');
4172
         if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
4173
            throw new Exception('error parsing publication');
4174
        $publication = new JObject();
4175
        $publication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4176
        $publication->source = 'openaire';
4177
        $publication->accessMode = NULL;
4178
        $publication->url = NULL;
4179
        $publication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4180
        $publication->underCuration = (($curationNode = $curationNodes->item(0)) == NULL) ? NULL : trim($curationNode->nodeValue);
4181
        $publication->authors = array();
4182
        $publication->year = (($dateNode = $dateNodes->item(0)) == NULL) ? NULL : intval(trim($dateNode->nodeValue));
4183
        $publication->date = ($dateNode == NULL) ? NULL : strtotime(trim($dateNode->nodeValue));
4184
        $publication->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
4185
        $publication->journal = (($journalNode = $journalNodes->item(0)) == NULL) ? NULL : trim($journalNode->nodeValue);
4186
        $publication->languages = array();
4187
        $publication->type = array();
4188
        $publication->subjects = array();
4189
        $publication->categorizedSubjects = array();
4190
        $publication->inferredSubjects = array();
4191
        $publication->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
4192
        $publication->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
4193
        $publication->datasources = array();
4194
        $publication->collectedFrom = array();
4195
        $publication->sources = array();
4196
        $publication->projects = array();
4197
        $publication->pids = array();
4198
        $publication->similarPublications = array();
4199
        $publication->relatedPublications = array();
4200
        $publication->relatedDatasets = array();
4201
        $publication->externalPublications = array();
4202
        $publication->bioentities = array();
4203
        $publication->externalDatasets = array();
4204
        $publication->contexts = array();
4205
        $publication->citations = array();
4206
        foreach ($authorNodes as $authorNode) {
4207
            if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
4208
                throw new Exception('error parsing publication');
4209
            if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
4210
                throw new Exception('error parsing publication');
4211
            if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
4212
                throw new Exception('error parsing publication');
4213
            $author = new JObject();
4214
            $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4215
            $author->lastName = NULL;
4216
            $author->firstName = NULL;
4217
            $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
4218
            $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
4219
            if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
4220
                $publication->authors[] = $author;
4221
            usort($publication->authors, function ($author1, $author2) {
4222
                return $author1->ranking - $author2->ranking;
4223
            });
4224
        }
4225
        foreach ($languageNodes as $languageNode) {
4226
            if ((($language = trim($languageNode->nodeValue)) != NULL) && ($language != self :: UNDETERMINED))
4227
                $publication->languages[] = $language;
4228
        }
4229
        foreach ($subjectNodes as $subjectNode) {
4230
            if (($titleNodes = $xpath->query('./@value', $subjectNode)) == FALSE)
4231
                throw new Exception('error parsing publications');
4232
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $subjectNode)) == FALSE)
4233
                throw new Exception('error parsing publications');
4234
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $subjectNode)) == FALSE)
4235
                throw new Exception('error parsing publications');
4236
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $subjectNode)) == FALSE)
4237
                throw new Exception('error parsing publications');
4238
            if (($taxonomyNodes = $xpath->query('./field[@name = "taxonomy"]/@value', $subjectNode)) == FALSE)
4239
                throw new Exception('error parsing publications');
4240
            $subject = new JObject();
4241
            $subject->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4242
            $subject->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4243
            $subject->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4244
            $subject->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4245
            $subject->taxonomy = (($taxonomyNode = $taxonomyNodes->item(0)) == NULL) ? NULL : trim($taxonomyNode->nodeValue);
4246
            if (($subject->title != NULL) || ($subject->inferred != NULL) || ($subject->trust != NULL) || ($subject->provenance != NULL)){
4247
                if($subject->taxonomy != NULL && $subject->taxonomy != "keyword"){                    
4248
                    $publication->categorizedSubjects[$subject->taxonomy][] =  $subject;
4249
                }else {
4250
                    $publication->subjects[] = $subject;
4251
                }   
4252
                
4253
                   
4254
            }
4255
                
4256
        }
4257
        $inferredSubjectsTempArray = array();
4258
        foreach ($inferredSubjectNodes as $subjectNode) {
4259
            if (($titleNodes = $xpath->query('./@value', $subjectNode)) == FALSE)
4260
                throw new Exception('error parsing publications');
4261
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $subjectNode)) == FALSE)
4262
                throw new Exception('error parsing publications');
4263
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $subjectNode)) == FALSE)
4264
                throw new Exception('error parsing publications');
4265
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $subjectNode)) == FALSE)
4266
                throw new Exception('error parsing publications');
4267
            if (($taxonomyNodes = $xpath->query('./field[@name = "taxonomy"]/@value', $subjectNode)) == FALSE)
4268
                throw new Exception('error parsing publications');
4269

    
4270
            $subject = new JObject();
4271
            $subject->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4272
            $subject->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4273
            $subject->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4274
            $subject->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4275
            $subject->taxonomy = (($taxonomyNode = $taxonomyNodes->item(0)) == NULL) ? NULL : trim($taxonomyNode->nodeValue);
4276

    
4277
            if (($subject->title != NULL) || ($subject->inferred != NULL) || ($subject->trust != NULL) || ($subject->provenance != NULL) || ($subject->taxonomy != NULL)) {
4278
                $miniSubject = new JObject();
4279
                $miniSubject->title = $subject->title;
4280
                $miniSubject->trust = $subject->trust;
4281
                $inferredSubjectsTempArray[$subject->taxonomy][] = $miniSubject;
4282
            }
4283
        }
4284
        //Sort the subjects on trust
4285
        foreach ($inferredSubjectsTempArray as $taxonomyKey => $subjectsValues) {
4286
            usort($subjectsValues, function ($a, $b) {
4287
                if ($a->trust == $b->trust) {
4288
                    return 0;
4289
                }return ($a->trust > $b->trust) ? -1 : 1;
4290
            });
4291
            $publication->inferredSubjects[$taxonomyKey] = $subjectsValues;
4292
        }
4293

    
4294
        foreach ($datasourceNodes as $datasourceNode) {
4295
            if (($idNodes = $xpath->query('./field[@name = "hostedby"]/@value_original', $datasourceNode)) == FALSE)
4296
                throw new Exception('error parsing publication');
4297
            if (($nameNodes = $xpath->query('./field[@name = "hostedbyname"]/@value', $datasourceNode)) == FALSE)
4298
                throw new Exception('error parsing publication');
4299
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
4300
                throw new Exception('error parsing publication');
4301
            if (($accessModeNodes = $xpath->query('./field[@name = "accessrightid"]/@value', $datasourceNode)) == FALSE)
4302
                throw new Exception('error parsing publication');
4303
            if (($typeNameNodes = $xpath->query('./field[@name = "typename"]/@value', $datasourceNode)) == FALSE)
4304
                throw new Exception('error parsing publication');
4305
            $datasource = new JObject();
4306
            $datasource->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4307
            $datasource->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4308
            $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4309
            $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
4310
            $datasource->type = (($typeNameNode = $typeNameNodes->item(0)) == NULL) ? NULL : trim($typeNameNode->nodeValue);
4311

    
4312
            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))))) {
4313
                $publication->accessMode = $datasource->accessMode;
4314
                $publication->url = $datasource->url;
4315

    
4316
                if (!in_array($datasource->type, $publication->type)) {
4317
                    array_push($publication->type, $datasource->type);
4318
                }
4319
            }
4320
            if (($datasource->id != NULL) || ($datasource->name != NULL) || ($datasource->url != NULL) || ($datasource->accessMode != NULL))
4321
                $publication->datasources[] = $datasource;
4322
        }
4323
        foreach ($collectedFromNodes as $collectedFromNode) {
4324
            if (($idNodes = $xpath->query('./field[@name = "collectedfromid"]/@value', $collectedFromNode)) == FALSE)
4325
                throw new Exception('error parsing publication');
4326
            if (($nameNodes = $xpath->query('./field[@name = "collectedfromname"]/@value', $collectedFromNode)) == FALSE)
4327
                throw new Exception('error parsing publication');
4328
            $collectedFrom = new JObject();
4329
            $collectedFrom->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4330
            $collectedFrom->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4331
            if (($collectedFrom->id != NULL) || ($collectedFrom->name != NULL))
4332
                $publication->collectedFrom[] = $collectedFrom;
4333
        }
4334
         foreach ($sourceNodes as $sourceNode) {
4335
            if (($source = trim($sourceNode->nodeValue)) != NULL)
4336
                $publication->sources[] = $source;
4337
        }
4338
        foreach ($projectNodes as $projectNode) {
4339
            if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
4340
                throw new Exception('error parsing publication');
4341
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $projectNode)) == FALSE)
4342
                throw new Exception('error parsing publication');
4343
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $projectNode)) == FALSE)
4344
                throw new Exception('error parsing publication');
4345
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $projectNode)) == FALSE)
4346
                throw new Exception('error parsing publication');
4347
            if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
4348
                throw new Exception('error parsing publication');
4349
            if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
4350
                throw new Exception('error parsing publication');
4351
            if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
4352
                throw new Exception('error parsing publication');
4353
            if (($fundingNodes = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
4354
                throw new Exception('error parsing publication');
4355

    
4356

    
4357
            $project = new JObject();
4358
            $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4359
            $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
4360
            $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4361
            $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
4362
            $project->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4363
            $project->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4364
            $project->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4365
            /*   $project -> funding = new JObject();
4366
              if (($fundingNode = $fundingNodes -> item(0)) == NULL) ;
4367
              else
4368
              {
4369
              if (($funding0Nodes = $xpath -> query('./field[@name = "funding_level_0"]/@value', $fundingNode)) == FALSE)
4370
              throw new Exception('error parsing publication test');
4371
              $project -> funding->funding_level_0 = (($funding0Node = $funding0Nodes -> item(0)) == NULL) ? NULL : trim($funding0Node -> nodeValue);
4372
              } */
4373

    
4374
            $project->funding = new JObject();
4375
            $project->funding->funding_level_0 = NULL;
4376
            $project->funding->funding_level_1 = NULL;
4377
            $project->funding->funding_level_2 = NULL;
4378

    
4379
            if (($fundingNode = $fundingNodes->item(0)) == NULL)
4380
                ;
4381
            else {
4382
                 if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
4383
                    throw new Exception('error parsing project');
4384
                if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
4385
                    throw new Exception('error parsing project');
4386
                if (($funding0Nodes = $xpath->query('./field[@name = "funding_level_0"]', $fundingNode)) == FALSE)
4387
                    throw new Exception('error parsing project');
4388
                if (($funding1Nodes = $xpath->query('./field[@name = "funding_level_1"]', $fundingNode)) == FALSE)
4389
                    throw new Exception('error parsing project');
4390
                if (($funding2Nodes = $xpath->query('./field[@name = "funding_level_2"]', $fundingNode)) == FALSE)
4391
                    throw new Exception('error parsing project');
4392

    
4393
                $project->funding->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
4394
                $project->funding->funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
4395

    
4396
                if (($funding0Node = $funding0Nodes->item(0)) == NULL)
4397
                    ;
4398
                else {
4399
                    if (($funding0NameNodes = $xpath->query('./@value', $funding0Node)) == FALSE)
4400
                        throw new Exception('error parsing publication test');
4401
                    $project->funding->funding_level_0 = (($funding0NameNode = $funding0NameNodes->item(0)) == NULL) ? NULL : trim($funding0NameNode->nodeValue);
4402
                   // $array = explode("::", $project->funding->funding_level_0);
4403
                   // $project->funding->funding_level_0 = $array[sizeof($array) - 1];
4404
                }
4405
                if (($funding1Node = $funding1Nodes->item(0)) == NULL)
4406
                    ;
4407
                else {
4408
                    if (($funding1NameNodes = $xpath->query('./@value', $funding1Node)) == FALSE)
4409
                        throw new Exception('error parsing publication test');
4410
                    $project->funding->funding_level_1 = (($funding1NameNode = $funding1NameNodes->item(0)) == NULL) ? NULL : trim($funding1NameNode->nodeValue);
4411
                   // $array = explode("::", $project->funding->funding_level_1);
4412
                    //$project->funding->funding_level_1 = $array[sizeof($array) - 1];
4413
                }
4414
                if (($funding2Node = $funding2Nodes->item(0)) == NULL)
4415
                    ;
4416
                else {
4417
                    if (($funding2NameNodes = $xpath->query('./@valu', $funding2Node)) == FALSE)
4418
                        throw new Exception('error parsing publication test');
4419
                    $project->funding->funding_level_2 = (($funding2NameNode = $funding2NameNodes->item(0)) == NULL) ? NULL : trim($funding2NameNode->nodeValue);
4420
                   // $array = explode("::", $project->funding->funding_level_2);
4421
                   // $project->funding->funding_level_2 = $array[sizeof($array) - 1];
4422
                }
4423
            }
4424
            //!!!!
4425

    
4426
            if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
4427
                $publication->projects[] = $project;
4428
        }
4429
        foreach ($pidNodes as $pidNode) {
4430
            if (($classNodes = $xpath->query('./field[@name = "classid"]/@value', $pidNode)) == FALSE)
4431
                throw new Exception('error parsing publication');
4432
            if (($valueNodes = $xpath->query('./field[@name = "value"]/@value', $pidNode)) == FALSE)
4433
                throw new Exception('error parsing publication');
4434
            $pid = new JObject();
4435
            $pid->clazz = (($classNode = $classNodes->item(0)) == NULL) ? NULL : trim($classNode->nodeValue);
4436
            $pid->value = (($valueNode = $valueNodes->item(0)) == NULL) ? NULL : trim($valueNode->nodeValue);
4437
            if (($pid->clazz != NULL) && ($pid->value != NULL))
4438
                $publication->pids[] = $pid;
4439
        }
4440
        foreach ($similarNodes as $similarNode) {
4441
            if (($typeNodes = $xpath->query('./field[@name = "resulttypename"]/@value', $similarNode)) == FALSE)
4442
                throw new Exception('error parsing publication');
4443
            if (($typeNameNodes = $xpath->query('./field[@name = "resulttypename"]/@value', $similarNode)) == FALSE)
4444
                throw new Exception('error parsing publication');
4445
            if (($idNodes = $xpath->query('./field[@name = "resultid"]/@value', $similarNode)) == FALSE)
4446
                throw new Exception('error parsing publication');
4447
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $similarNode)) == FALSE)
4448
                throw new Exception('error parsing publication');
4449
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $similarNode)) == FALSE)
4450
                throw new Exception('error parsing publication');
4451
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $similarNode)) == FALSE)
4452
                throw new Exception('error parsing publication');
4453
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $similarNode)) == FALSE)
4454
                throw new Exception('error parsing publication');
4455
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $similarNode)) == FALSE)
4456
                throw new Exception('error parsing publication');
4457
            if (($similarityNodes = $xpath->query('./field[@name = "similarity"]/@value', $similarNode)) == FALSE)
4458
                throw new Exception('error parsing publication');
4459

    
4460
            $similarPublication = new JObject();
4461
            $similarPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4462
            $similarPublication->source = 'openaire';
4463
            $similarPublication->url = NULL;
4464
            $similarPublication->accessMode = NULL;
4465
            $similarPublication->datasources = array();
4466
            $similarPublication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4467
            $similarPublication->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4468
            $similarPublication->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4469
            $similarPublication->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4470
            $similarPublication->authors = array();
4471
            $similarPublication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4472
            $similarPublication->projects = array();
4473
            $similarPublication->embargoEndDate = NULL;
4474
            $similarPublication->description = NULL;
4475
            $similarPublication->similarity = (($similarityNode = $similarityNodes->item(0)) == NULL) ? NULL : trim($similarityNode->nodeValue);
4476
            $similarPublication->similarity = number_format((float) $similarPublication->similarity, 2);
4477
            if (($similarPublication->id != NULL) || ($similarPublication->title != NULL) || ($similarPublication->year != NULL)) {
4478
                $publication->similarPublications[] = $similarPublication;
4479
            }
4480
        }
4481
        foreach ($relatedNodes as $relatedNode) {
4482
            if (($typeNodes = $xpath->query('./field[@name = "resulttypename"]/@value', $relatedNode)) == FALSE)
4483
                throw new Exception('error parsing publication');
4484
            if (($idNodes = $xpath->query('./field[@name = "resultid"]/@value', $relatedNode)) == FALSE)
4485
                throw new Exception('error parsing publication');
4486
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
4487
                throw new Exception('error parsing publication');
4488
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
4489
                throw new Exception('error parsing publication');
4490
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
4491
                throw new Exception('error parsing publication');
4492
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $relatedNode)) == FALSE)
4493
                throw new Exception('error parsing publication');
4494
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $relatedNode)) == FALSE)
4495
                throw new Exception('error parsing publication');
4496
            switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
4497
                case self :: PUBLICATION:
4498
                    $relatedPublication = new JObject();
4499
                    $relatedPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4500
                    $relatedPublication->source = 'openaire';
4501
                    $relatedPublication->url = NULL;
4502
                    $relatedPublication->accessMode = NULL;
4503
                    $relatedPublication->datasources = array();
4504
                    $relatedPublication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4505
                    $relatedPublication->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4506
                    $relatedPublication->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4507
                    $relatedPublication->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4508
                    $relatedPublication->authors = array();
4509
                    $relatedPublication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4510
                    $relatedPublication->projects = array();
4511
                    $relatedPublication->embargoEndDate = NULL;
4512
                    $relatedPublication->description = NULL;
4513
                    if (($relatedPublication->id != NULL) || ($relatedPublication->title != NULL) || ($relatedPublication->year != NULL))
4514
                        $publication->relatedPublications[] = $relatedPublication;
4515
                    break;
4516
                case self :: DATASET:
4517
                    $relatedDataset = new JObject();
4518
                    $relatedDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4519
                    $relatedDataset->source = 'openaire';
4520
                    $relatedDataset->url = NULL;
4521
                    $relatedDataset->accessMode = NULL;
4522
                    $relatedDataset->datasources = array();
4523
                    $relatedDataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4524
                    $relatedDataset->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4525
                    $relatedDataset->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4526
                    $relatedDataset->trust = number_format((float) $relatedDataset->trust, 2);
4527
                    $relatedDataset->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4528
                    $relatedDataset->authors = array();
4529
                    $relatedDataset->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4530
                    $relatedDataset->projects = array();
4531
                    $relatedDataset->embargoEndDate = NULL;
4532
                    $relatedDataset->description = NULL;
4533
                    if (($relatedDataset->id != NULL) || ($relatedDataset->title != NULL) || ($relatedDataset->year != NULL))
4534
                        $publication->relatedDatasets[] = $relatedDataset;
4535
                    break;
4536
            }
4537
        }
4538
        foreach ($externalReferenceNodes as $externalReferenceNode) {
4539
            if (($typeNodes = $xpath->query('./field[@name = "typeid"]/@value', $externalReferenceNode)) == FALSE)
4540
                throw new Exception('error parsing publication');
4541
            if (($idNodes = $xpath->query('./field[@name = "refidentifier"]/@value', $externalReferenceNode)) == FALSE)
4542
                throw new Exception('error parsing publication');
4543
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $externalReferenceNode)) == FALSE)
4544
                throw new Exception('error parsing publication');
4545
            if (($labelNodes = $xpath->query('./field[@name = "label"]/@value', $externalReferenceNode)) == FALSE)
4546
                throw new Exception('error parsing publication');
4547
            if (($siteNameNodes = $xpath->query('./field[@name = "sitename"]/@value', $externalReferenceNode)) == FALSE)
4548
                throw new Exception('error parsing publication');
4549
                    $externalEntity = new JObject();
4550
                    //dedup_wf_001::2cd206acf2cfd37f1a7c28823c63112b
4551
                    $externalEntity-> type = (($typeNode =$typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4552
                    $externalEntity-> id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4553
                    $externalEntity-> url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4554
                    $externalEntity-> title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
4555
                    $externalEntity-> sitename = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
4556
                     if (!isset($publication->bioentities[$externalEntity->sitename])){
4557
                        $bioentities = array();
4558
                        $publication->bioentities[$externalEntity->sitename]=$bioentities;
4559
                     }
4560
                     $publication->bioentities[$externalEntity->sitename] []= $externalEntity;
4561

    
4562
           /* switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
4563
                case self :: PUBLICATION:
4564
                    $externalPublication = new JObject();
4565
                    $externalPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4566
                    $externalPublication->source = NULL;
4567
                    $externalPublication->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4568
                    $externalPublication->accessMode = NULL;
4569
                    $externalPublication->datasources = array();
4570
                    $externalPublication->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
4571
                    $externalPublication->authors = array();
4572
                    $site = new JObject();
4573
                    $site->id = NULL;
4574
                    $site->lastName = NULL;
4575
                    $site->firstName = NULL;
4576
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
4577
                    if ($site->fullName != NULL)
4578
                        $externalPublication->authors[] = $site;
4579
                    $externalPublication->year = NULL;
4580
                    $externalPublication->projects = array();
4581
                    $externalPublication->embargoEndDate = NULL;
4582
                    $externalPublication->description = NULL;
4583
                    if (($externalPublication->id != NULL) || ($externalPublication->url != NULL) || ($externalPublication->title != NULL))
4584
                        $publication->externalPublications[] = $externalPublication;
4585
                    break;
4586
                case self :: DATASET:
4587
                    $externalDataset = new JObject();
4588
                    $externalDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4589
                    $externalDataset->source = NULL;
4590
                    $externalDataset->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4591
                    $externalDataset->accessMode = NULL;
4592
                    $externalDataset->datasources = array();
4593
                    $externalDataset->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
4594
                    $externalDataset->authors = array();
4595
                    $site = new JObject();
4596
                    $site->id = NULL;
4597
                    $site->lastName = NULL;
4598
                    $site->firstName = NULL;
4599
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
4600
                    if ($site->fullName != NULL)
4601
                        $externalDataset->authors[] = $site;
4602
                    $externalDataset->year = NULL;
4603
                    $externalDataset->projects = array();
4604
                    $externalDataset->embargoEndDate = NULL;
4605
                    $externalDataset->description = NULL;
4606
                    if (($externalDataset->id != NULL) || ($externalDataset->url != NULL) || ($externalDataset->title != NULL))
4607
                        $publication->externalDatasets[] = $externalDataset;
4608
            }*/
4609
        }
4610
        foreach ($contextNodes as $contextNode) {
4611
            if (($idNodes = $xpath->query('./@value', $contextNode)) == FALSE)
4612
                throw new Exception('error parsing publication');
4613
            if (($nameNodes = $xpath->query('./@value_original', $contextNode)) == FALSE)
4614
                throw new Exception('error parsing publication');
4615
            if (($typeNodes = $xpath->query('./field[@name = "contexttype"]/@value', $contextNode)) == FALSE)
4616
                throw new Exception('error parsing publication');
4617
            if (($categoryNodes = $xpath->query('./field[@name = "category"]', $contextNode)) == FALSE)
4618
                throw new Exception('error parsing publication');
4619
            $context = new JObject();
4620
            $context->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4621
            $context->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4622
            $context->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4623
            $context->categories = array();
4624
            foreach ($categoryNodes as $categoryNode) {
4625
                if (($idNodes = $xpath->query('./@value_original', $categoryNode)) == FALSE)
4626
                    throw new Exception('error parsing publication');
4627
                if (($nameNodes = $xpath->query('./@value', $categoryNode)) == FALSE)
4628
                    throw new Exception('error parsing publication');
4629
                if (($conceptNodes = $xpath->query('./field[@name = "concept"]', $categoryNode)) == FALSE)
4630
                    throw new Exception('error parsing publication');
4631
                $category = new JObject();
4632
                $category->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4633
                $category->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4634
                $category->concepts = array();
4635
                foreach ($conceptNodes as $conceptNode) {
4636
                    if (($idNodes = $xpath->query('./@value_original', $conceptNode)) == FALSE)
4637
                        throw new Exception('error parsing publication');
4638
                    if (($nameNodes = $xpath->query('./@value', $conceptNode)) == FALSE)
4639
                        throw new Exception('error parsing publication');
4640
                    $concept = new JObject();
4641
                    $concept->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4642
                    $concept->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4643
                    if (($concept->id != NULL) || ($concept->name != NULL))
4644
                        $category->concepts[] = $concept;
4645
                }
4646
                if (($category->id != NULL) || ($category->name != NULL) || ($category->concepts != NULL))
4647
                    $context->categories[] = $category;
4648
            }
4649
            if (($context->id != NULL) || ($context->name != NULL) || ($context->categories != NULL))
4650
                $publication->contexts[] = $context;
4651
        }
4652
        foreach ($citationNodes as $citationNode) {
4653
            if (($titleNodes = $xpath->query('./field[@name = "rawText"]/@value', $citationNode)) == FALSE)
4654
                throw new Exception('error parsing publications');
4655
            if (($idsNodes = $xpath->query('./field[@name = "citationId"]', $citationNode)) == FALSE)
4656
                throw new Exception('error parsing publications');
4657
            $citation = new JObject();
4658
            $citation->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4659
            $citation->ids = array();
4660
            foreach ($idsNodes as $citationIdNode) {
4661
                if (($idNodes = $xpath->query('./field[@name = "id"]/@value', $citationIdNode)) == FALSE)
4662
                    throw new Exception('error parsing publications');
4663
                if (($typeNodes = $xpath->query('./field[@name = "type"]/@value', $citationIdNode)) == FALSE)
4664
                    throw new Exception('error parsing publications');
4665
                if (($confidenceLevelNodes = $xpath->query('./field[@name = "confidenceLevel"]/@value', $citationIdNode)) == FALSE)
4666
                    throw new Exception('error parsing publications');
4667
                $ids = new JObject();
4668
                $ids->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4669
                $ids->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4670
                $ids->confidenceLevel = (($confidenceLevelNode = $confidenceLevelNodes->item(0)) == NULL) ? NULL : trim($confidenceLevelNode->nodeValue);
4671
                $citation->ids[] = $ids;
4672
            }
4673

    
4674
            $publication->citations[] = $citation;
4675
            /*  $subject -> inferred = (($inferredNode = $inferredNodes -> item(0)) == NULL) ? NULL : trim($inferredNode -> nodeValue)=="true"?true:false;
4676
              $subject -> trust = (($trustNode = $trustNodes -> item(0)) == NULL) ? NULL : trim($trustNode -> nodeValue);
4677
              $subject -> provenance = (($provenanceNode = $provenanceNodes -> item(0)) == NULL) ? NULL : trim($provenanceNode -> nodeValue);
4678
              $subject -> taxonomy = (($taxonomyNode = $taxonomyNodes -> item(0)) == NULL) ? NULL : trim($taxonomyNode -> nodeValue);
4679
             */
4680
        }
4681
        return $publication;
4682
    }
4683

    
4684
    // Parse a single dataset from a search service XML response.
4685
    // xpath the DOMXPath to parse
4686
    // return dataset (object)
4687
    private function parseDataset($xpath, $locale) {
4688
        if ((($resultsNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL)) // result
4689
            throw new Exception('error parsing dataset');
4690
        if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
4691
            throw new Exception('error parsing dataset');
4692
        if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
4693
            throw new Exception('error parsing dataset');
4694
        if (($authorNodes = $xpath->query('./field[@name = "hasAuthor"]', $resultNode)) == FALSE)
4695
            throw new Exception('error parsing dataset');
4696
        if (($dateNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
4697
            throw new Exception('error parsing dataset');
4698
        if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
4699
            throw new Exception('error parsing dataset');
4700
        if (($journalNodes = $xpath->query('./field[@name = "journal"]/@value', $resultNode)) == FALSE)
4701
            throw new Exception('error parsing dataset');
4702
        if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
4703
            throw new Exception('error parsing dataset');
4704
        if (($typeNodes = $xpath->query('./field[@name ="resulttypename"]/@value', $resultNode)) == FALSE)
4705
            throw new Exception('error parsing dataset');
4706
        if (($subjectNodes = $xpath->query('./field[@name = "subject"]/@value', $resultNode)) == FALSE)
4707
            throw new Exception('error parsing dataset');
4708
        if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
4709
            throw new Exception('error parsing dataset');
4710
        if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
4711
            throw new Exception('error parsing dataset');
4712
        if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
4713
            throw new Exception('error parsing dataset');
4714
        if (($collectedFromNodes = $xpath->query('./field[@name = "collectedfrom"]', $resultNode)) == FALSE)
4715
            throw new Exception('error parsing dataset');
4716
        if (($sourceNodes = $xpath->query('./field[@name = "source"]/@value', $resultNode)) == FALSE)
4717
            throw new Exception('error parsing dataset');
4718
        if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
4719
            throw new Exception('error parsing dataset');
4720
        if (($pidNodes = $xpath->query('./field[@name = "pid"]', $resultNode)) == FALSE)
4721
            throw new Exception('error parsing dataset');
4722
        if (($relatedNodes = $xpath->query('./field[@name = "isRelatedTo"]', $resultNode)) == FALSE)
4723
            throw new Exception('error parsing dataset');
4724
        if (($externalReferenceNodes = $xpath->query('./field[@name = "externalreference"]', $resultNode)) == FALSE)
4725
            throw new Exception('error parsing dataset');
4726
        if (($contextNodes = $xpath->query('./field[@name = "context"]', $resultNode)) == FALSE)
4727
            throw new Exception('error parsing dataset');
4728
        $dataset = new JObject();
4729
        $dataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4730
        $dataset->source = 'openaire';
4731
        $dataset->accessMode = NULL;
4732
        $dataset->url = NULL;
4733
        $dataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4734
        $dataset->authors = array();
4735
        $dataset->year = (($dateNode = $dateNodes->item(0)) == NULL) ? NULL : intval(trim($dateNode->nodeValue));
4736
        $dataset->date = ($dateNode == NULL) ? NULL : strtotime(trim($dateNode->nodeValue));
4737
        $dataset->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
4738
        $dataset->journal = (($journalNode = $journalNodes->item(0)) == NULL) ? NULL : trim($journalNode->nodeValue);
4739
        $dataset->languages = array();
4740
        $dataset->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4741
        $dataset->subjects = array();
4742
        $dataset->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
4743
        $dataset->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
4744
        $dataset->datasources = array();
4745
        $dataset->collectedFrom = array();
4746
        $dataset->sources = array();
4747
        $dataset->projects = array();
4748
        $dataset->pids = array();
4749
        $dataset->relatedPublications = array();
4750
        $dataset->relatedDatasets = array();
4751
        $dataset->externalPublications = array();
4752
        $dataset->externalDatasets = array();
4753
        $dataset->contexts = array();
4754
        foreach ($authorNodes as $authorNode) {
4755
            if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
4756
                throw new Exception('error parsing dataset');
4757
            if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
4758
                throw new Exception('error parsing dataset');
4759
            if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
4760
                throw new Exception('error parsing publication');
4761
            $author = new JObject();
4762
            $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4763
            $author->lastName = NULL;
4764
            $author->firstName = NULL;
4765
            $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
4766
            $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
4767
            if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
4768
                $dataset->authors[] = $author;
4769
            usort($dataset->authors, function ($author1, $author2) {
4770
                return $author1->ranking - $author2->ranking;
4771
            });
4772
        }
4773
        foreach ($languageNodes as $languageNode) {
4774
            if ((($language = trim($languageNode->nodeValue)) != NULL) && ($language != self :: UNDETERMINED))
4775
                $dataset->languages[] = $language;
4776
        }
4777
        foreach ($subjectNodes as $subjectNode) {
4778
            if (($subject = trim($subjectNode->nodeValue)) != NULL)
4779
                $dataset->subjects[] = $subject;
4780
        }
4781
        foreach ($datasourceNodes as $datasourceNode) {
4782
            if (($idNodes = $xpath->query('./field[@name = "hostedby"]/@value_original', $datasourceNode)) == FALSE)
4783
                throw new Exception('error parsing dataset');
4784
            if (($nameNodes = $xpath->query('./field[@name = "hostedbyname"]/@value', $datasourceNode)) == FALSE)
4785
                throw new Exception('error parsing dataset');
4786
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
4787
                throw new Exception('error parsing dataset');
4788
            if (($accessModeNodes = $xpath->query('./field[@name = "accessrightid"]/@value', $datasourceNode)) == FALSE)
4789
                throw new Exception('error parsing dataset');
4790
            $datasource = new JObject();
4791
            $datasource->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4792
            $datasource->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4793
            $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4794
// TODO
4795
            if (substr($datasource->url, 0, strlen('http://dx.doi.org/http://zenodo.org/record/')) == 'http://dx.doi.org/http://zenodo.org/record/') {
4796
                $url = substr($datasource->url, strlen('http://dx.doi.org/'));
4797
                JLog :: add('Converting datasource URL ' . $datasource->url . ' to ' . $url, JLog :: DEBUG, self :: LOG);
4798
                $datasource->url = $url;
4799
            }
4800
// TODO
4801
            $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
4802
            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))))) {
4803
                $dataset->accessMode = $datasource->accessMode;
4804
                $dataset->url = $datasource->url;
4805
            }
4806
            if (($datasource->id != NULL) || ($datasource->name != NULL) || ($datasource->url != NULL) || ($datasource->accessMode != NULL))
4807
                $dataset->datasources[] = $datasource;
4808
        }
4809
        foreach ($collectedFromNodes as $collectedFromNode) {
4810
            if (($idNodes = $xpath->query('./field[@name = "collectedfromid"]/@value', $collectedFromNode)) == FALSE)
4811
                throw new Exception('error parsing dataset');
4812
            if (($nameNodes = $xpath->query('./field[@name = "collectedfromname"]/@value', $collectedFromNode)) == FALSE)
4813
                throw new Exception('error parsing dataset');
4814
            $collectedFrom = new JObject();
4815
            $collectedFrom->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4816
            $collectedFrom->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4817
            if (($collectedFrom->id != NULL) || ($collectedFrom->name != NULL))
4818
                $dataset->collectedFrom[] = $collectedFrom;
4819
        }
4820
        foreach ($sourceNodes as $sourceNode) {
4821
            if (($source = trim($sourceNode->nodeValue)) != NULL)
4822
                $dataset->sources[] = $source;
4823
        }
4824
        foreach ($projectNodes as $projectNode) {
4825
            if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
4826
                throw new Exception('error parsing publication');
4827
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $projectNode)) == FALSE)
4828
                throw new Exception('error parsing publication');
4829
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $projectNode)) == FALSE)
4830
                throw new Exception('error parsing publication');
4831
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $projectNode)) == FALSE)
4832
                throw new Exception('error parsing publication');
4833
            if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
4834
                throw new Exception('error parsing publication');
4835
            if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
4836
                throw new Exception('error parsing publication');
4837
            if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
4838
                throw new Exception('error parsing publication');
4839
            if (($fundingNodes = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
4840
                throw new Exception('error parsing publication');
4841

    
4842

    
4843
            $project = new JObject();
4844
            $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4845
            $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
4846
            $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4847
            $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
4848
            $project->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4849
            $project->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4850
            $project->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4851
            /*   $project -> funding = new JObject();
4852
              if (($fundingNode = $fundingNodes -> item(0)) == NULL) ;
4853
              else
4854
              {
4855
              if (($funding0Nodes = $xpath -> query('./field[@name = "funding_level_0"]/@value', $fundingNode)) == FALSE)
4856
              throw new Exception('error parsing publication test');
4857
              $project -> funding->funding_level_0 = (($funding0Node = $funding0Nodes -> item(0)) == NULL) ? NULL : trim($funding0Node -> nodeValue);
4858
              } */
4859

    
4860
            $project->funding = new JObject();
4861
            $project->funding->funding_level_0 = NULL;
4862
            $project->funding->funding_level_1 = NULL;
4863
            $project->funding->funding_level_2 = NULL;
4864

    
4865
            if (($fundingNode = $fundingNodes->item(0)) == NULL)
4866
                ;
4867
            else {
4868
                if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
4869
                    throw new Exception('error parsing project');
4870
                if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
4871
                    throw new Exception('error parsing project');
4872
                if (($funding0Nodes = $xpath->query('./field[@name = "funding_level_0"]', $fundingNode)) == FALSE)
4873
                    throw new Exception('error parsing project');
4874
                if (($funding1Nodes = $xpath->query('./field[@name = "funding_level_1"]', $fundingNode)) == FALSE)
4875
                    throw new Exception('error parsing project');
4876
                if (($funding2Nodes = $xpath->query('./field[@name = "funding_level_2"]', $fundingNode)) == FALSE)
4877
                    throw new Exception('error parsing project');
4878
                $project->funding->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
4879
                $project->funding->funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
4880

    
4881
                if (($funding0Node = $funding0Nodes->item(0)) == NULL)
4882
                    ;
4883
                else {
4884
                    if (($funding0NameNodes = $xpath->query('./@value', $funding0Node)) == FALSE)
4885
                        throw new Exception('error parsing publication test');
4886
                    $project->funding->funding_level_0 = (($funding0NameNode = $funding0NameNodes->item(0)) == NULL) ? NULL : trim($funding0NameNode->nodeValue);
4887
                    //$array = explode("::", $project->funding->funding_level_0);
4888
                    //$project->funding->funding_level_0 = $array[sizeof($array) - 1];
4889
                }
4890
                if (($funding1Node = $funding1Nodes->item(0)) == NULL)
4891
                    ;
4892
                else {
4893
                    if (($funding1NameNodes = $xpath->query('./@value', $funding1Node)) == FALSE)
4894
                        throw new Exception('error parsing publication test');
4895
                    $project->funding->funding_level_1 = (($funding1NameNode = $funding1NameNodes->item(0)) == NULL) ? NULL : trim($funding1NameNode->nodeValue);
4896
                    //$array = explode("::", $project->funding->funding_level_1);
4897
                    //$project->funding->funding_level_1 = $array[sizeof($array) - 1];
4898
                }
4899
                if (($funding2Node = $funding2Nodes->item(0)) == NULL)
4900
                    ;
4901
                else {
4902
                    if (($funding2NameNodes = $xpath->query('./@value', $funding2Node)) == FALSE)
4903
                        throw new Exception('error parsing publication test');
4904
                    $project->funding->funding_level_2 = (($funding2NameNode = $funding2NameNodes->item(0)) == NULL) ? NULL : trim($funding2NameNode->nodeValue);
4905
                    //$array = explode("::", $project->funding->funding_level_2);
4906
                    //$project->funding->funding_level_2 = $array[sizeof($array) - 1];
4907
                }
4908
                /* 	if (($idNodes = $xpath -> query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
4909
                  throw new Exception('error parsing dataset');
4910
                  if (($acronymNodes = $xpath -> query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
4911
                  throw new Exception('error parsing dataset');
4912
                  if (($titleNodes = $xpath -> query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
4913
                  throw new Exception('error parsing dataset');
4914
                  if (($codeNodes = $xpath -> query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
4915
                  throw new Exception('error parsing dataset');
4916
                  $project = new JObject();
4917
                  $project -> id = (($idNode = $idNodes -> item(0)) == NULL) ? NULL : trim($idNode -> nodeValue);
4918
                  $project -> acronym = (($acronymNode = $acronymNodes -> item(0)) == NULL) ? NULL : ((trim($acronymNode -> nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode -> nodeValue));
4919
                  $project -> title = (($titleNode = $titleNodes -> item(0)) == NULL) ? NULL : trim($titleNode -> nodeValue);
4920
                  $project -> code = (($codeNode = $codeNodes -> item(0)) == NULL) ? NULL : trim($codeNode -> nodeValue);
4921

    
4922
                 */
4923
            }
4924
            if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
4925
                $dataset->projects[] = $project;
4926
        }
4927
        foreach ($pidNodes as $pidNode) {
4928
            if (($classNodes = $xpath->query('./field[@name = "classid"]/@value', $pidNode)) == FALSE)
4929
                throw new Exception('error parsing dataset');
4930
            if (($valueNodes = $xpath->query('./field[@name = "value"]/@value', $pidNode)) == FALSE)
4931
                throw new Exception('error parsing dataset');
4932
            $pid = new JObject();
4933
            $pid->clazz = (($classNode = $classNodes->item(0)) == NULL) ? NULL : trim($classNode->nodeValue);
4934
            $pid->value = (($valueNode = $valueNodes->item(0)) == NULL) ? NULL : trim($valueNode->nodeValue);
4935
            if (($pid->clazz != NULL) && ($pid->value != NULL))
4936
                $dataset->pids[] = $pid;
4937
        }
4938
        foreach ($relatedNodes as $relatedNode) {
4939
            if (($typeNodes = $xpath->query('./field[@name = "resulttypename"]/@value', $relatedNode)) == FALSE)
4940
                throw new Exception('error parsing publication');
4941
            if (($idNodes = $xpath->query('./field[@name = "resultid"]/@value', $relatedNode)) == FALSE)
4942
                throw new Exception('error parsing publication');
4943
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
4944
                throw new Exception('error parsing publication');
4945
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
4946
                throw new Exception('error parsing publication');
4947
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
4948
                throw new Exception('error parsing publication');
4949
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $relatedNode)) == FALSE)
4950
                throw new Exception('error parsing publication');
4951
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $relatedNode)) == FALSE)
4952
                throw new Exception('error parsing publication');
4953
            switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
4954
                case self :: PUBLICATION:
4955
                    $relatedPublication = new JObject();
4956
                    $relatedPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4957
                    $relatedPublication->source = 'openaire';
4958
                    $relatedPublication->url = NULL;
4959
                    $relatedPublication->accessMode = NULL;
4960
                    $relatedPublication->datasources = array();
4961
                    $relatedPublication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4962
                    $relatedPublication->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4963
                    $relatedPublication->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4964
                    $relatedPublication->trust = ($relatedPublication->trust != null) ? number_format((float) $relatedPublication->trust, 2) : 'NULL';
4965
                    $relatedPublication->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4966
                    $relatedPublication->authors = array();
4967
                    $relatedPublication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4968
                    $relatedPublication->projects = array();
4969
                    $relatedPublication->embargoEndDate = NULL;
4970
                    $relatedPublication->description = NULL;
4971
                    if (($relatedPublication->id != NULL) || ($relatedPublication->title != NULL) || ($relatedPublication->year != NULL))
4972
                        $dataset->relatedPublications[] = $relatedPublication;
4973
                    break;
4974
                case self :: DATASET:
4975
                    $relatedDataset = new JObject();
4976
                    $relatedDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4977
                    $relatedDataset->source = 'openaire';
4978
                    $relatedDataset->url = NULL;
4979
                    $relatedDataset->accessMode = NULL;
4980
                    $relatedDataset->datasources = array();
4981
                    $relatedDataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4982
                    $relatedDataset->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : trim($inferredNode->nodeValue) == "true" ? true : false;
4983
                    $relatedDataset->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4984
                    $relatedDataset->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4985
                    $relatedDataset->authors = array();
4986
                    $relatedDataset->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4987
                    $relatedDataset->projects = array();
4988
                    $relatedDataset->embargoEndDate = NULL;
4989
                    $relatedDataset->description = NULL;
4990
                    if (($relatedDataset->id != NULL) || ($relatedDataset->title != NULL) || ($relatedDataset->year != NULL))
4991
                        $dataset->relatedDatasets[] = $relatedDataset;
4992
                    break;
4993
            }
4994
        }
4995
        foreach ($externalReferenceNodes as $externalReferenceNode) {
4996
            if (($typeNodes = $xpath->query('./field[@name = "typeid"]/@value', $externalReferenceNode)) == FALSE)
4997
                throw new Exception('error parsing publication');
4998
            if (($idNodes = $xpath->query('./field[@name = "refidentifier"]/@value', $externalReferenceNode)) == FALSE)
4999
                throw new Exception('error parsing publication');
5000
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $externalReferenceNode)) == FALSE)
5001
                throw new Exception('error parsing publication');
5002
            if (($labelNodes = $xpath->query('./field[@name = "label"]/@value', $externalReferenceNode)) == FALSE)
5003
                throw new Exception('error parsing publication');
5004
            if (($siteNameNodes = $xpath->query('./field[@name = "sitename"]/@value', $externalReferenceNode)) == FALSE)
5005
                throw new Exception('error parsing publication');
5006
            switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
5007
                case self :: PUBLICATION:
5008
                    $externalPublication = new JObject();
5009
                    $externalPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5010
                    $externalPublication->source = NULL;
5011
                    $externalPublication->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5012
                    $externalPublication->accessMode = NULL;
5013
                    $externalPublication->datasources = array();
5014
                    $externalPublication->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
5015
                    $externalPublication->authors = array();
5016
                    $site = new JObject();
5017
                    $site->id = NULL;
5018
                    $site->lastName = NULL;
5019
                    $site->firstName = NULL;
5020
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
5021
                    if ($site->fullName != NULL)
5022
                        $externalPublication->authors[] = $site;
5023
                    $externalPublication->year = NULL;
5024
                    $externalPublication->projects = array();
5025
                    $externalPublication->embargoEndDate = NULL;
5026
                    $externalPublication->description = NULL;
5027
                    if (($externalPublication->id != NULL) || ($externalPublication->url != NULL) || ($externalPublication->title != NULL))
5028
                        $dataset->externalPublications[] = $externalPublication;
5029
                    break;
5030
                case self :: DATASET:
5031
                    $externalDataset = new JObject();
5032
                    $externalDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5033
                    $externalDataset->source = NULL;
5034
                    $externalDataset->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5035
                    $externalDataset->accessMode = NULL;
5036
                    $externalDataset->datasources = array();
5037
                    $externalDataset->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
5038
                    $externalDataset->authors = array();
5039
                    $site = new JObject();
5040
                    $site->id = NULL;
5041
                    $site->lastName = NULL;
5042
                    $site->firstName = NULL;
5043
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
5044
                    if ($site->fullName != NULL)
5045
                        $externalDataset->authors[] = $site;
5046
                    $externalDataset->year = NULL;
5047
                    $externalDataset->projects = array();
5048
                    $externalDataset->embargoEndDate = NULL;
5049
                    $externalDataset->description = NULL;
5050
                    if (($externalDataset->id != NULL) || ($externalDataset->url != NULL) || ($externalDataset->title != NULL))
5051
                        $dataset->externalDatasets[] = $externalDataset;
5052
            }
5053
        }
5054
        foreach ($contextNodes as $contextNode) {
5055
            if (($idNodes = $xpath->query('./@value', $contextNode)) == FALSE)
5056
                throw new Exception('error parsing dataset');
5057
            if (($nameNodes = $xpath->query('./@value_original', $contextNode)) == FALSE)
5058
                throw new Exception('error parsing dataset');
5059
            if (($categoryNodes = $xpath->query('./field[@name = "category"]', $contextNode)) == FALSE)
5060
                throw new Exception('error parsing dataset');
5061
            $context = new JObject();
5062
            $context->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5063
            $context->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5064
            $context->categories = array();
5065
            foreach ($categoryNodes as $categoryNode) {
5066
                if (($idNodes = $xpath->query('./@value', $categoryNode)) == FALSE)
5067
                    throw new Exception('error parsing dataset');
5068
                if (($nameNodes = $xpath->query('./@value_original', $categoryNode)) == FALSE)
5069
                    throw new Exception('error parsing dataset');
5070
                if (($conceptNodes = $xpath->query('./field[@name = "concept"]', $categoryNode)) == FALSE)
5071
                    throw new Exception('error parsing dataset');
5072
                $category = new JObject();
5073
                $category->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5074
                $category->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5075
                $category->concepts = array();
5076
                foreach ($conceptNodes as $conceptNode) {
5077
                    if (($idNodes = $xpath->query('./@value', $conceptNode)) == FALSE)
5078
                        throw new Exception('error parsing dataset');
5079
                    if (($nameNodes = $xpath->query('./@value_original', $conceptNode)) == FALSE)
5080
                        throw new Exception('error parsing dataset');
5081
                    $concept = new JObject();
5082
                    $concept->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5083
                    $concept->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5084
                    if (($concept->id != NULL) || ($concept->name != NULL))
5085
                        $category->concepts[] = $concept;
5086
                }
5087
                if (($category->id != NULL) || ($category->name != NULL) || ($category->concepts != NULL))
5088
                    $context->categories[] = $category;
5089
            }
5090
            if (($context->id != NULL) || ($context->name != NULL) || ($context->categories != NULL))
5091
                $dataset->contexts[] = $context;
5092
        }
5093
        return $dataset;
5094
    }
5095

    
5096
    // Parse a single project from a search service XML response.
5097
    // xpath the DOMXPath to parse
5098
    // return project (object)
5099
    private function parseProject($xpath) {
5100
        if ((($resultsNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL))
5101
            throw new Exception('error parsing project');
5102
        if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $resultNode)) == FALSE)
5103
                throw new Exception('error parsing projects');
5104
        if (($acronymNodes = $xpath->query('./field[@name = "name"]/@value', $resultNode)) == FALSE)
5105
            throw new Exception('error parsing project');
5106
        if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
5107
            throw new Exception('error parsing project');
5108
        if (($funderNodes = $xpath->query('./field[@name = "funder"]/field[@name = "fundershortname"]/@value', $resultNode)) == FALSE)
5109
            throw new Exception('error parsing project');
5110
        if (($fundingStreamNodes = $xpath->query('./field[@name = "funding_level_0"]/field[@name = "fundingname"]/@value', $resultNode)) == FALSE)
5111
            throw new Exception('error parsing project');
5112
        if (($scientificAreaNodes = $xpath->query('./field[@name = "funding_level_1"]/field[@name = "fundingname"]/@value', $resultNode)) == FALSE)
5113
            throw new Exception('error parsing project');
5114
         if (($fundingStreamLevel2Nodes = $xpath->query('./field[@name = "funding_level_2"]/field[@name = "fundingname"]/@value', $resultNode)) == FALSE)
5115
            throw new Exception('error parsing project');
5116
        if (($callNodes = $xpath->query('./field[@name = "call_identifier"]/@value', $resultNode)) == FALSE)
5117
            throw new Exception('error parsing project');
5118
        if (($codeNodes = $xpath->query('./field[@name = "code"]/@value', $resultNode)) == FALSE)
5119
            throw new Exception('error parsing project');
5120
        if (($startYearNodes = $xpath->query('./field[@name = "startyear"]/@value', $resultNode)) == FALSE)
5121
            throw new Exception('error parsing project');
5122
        if (($startDateNodes = $xpath->query('./field[@name = "startdate"]/@value', $resultNode)) == FALSE)
5123
            throw new Exception('error parsing project');
5124
        if (($endYearNodes = $xpath->query('./field[@name = "endyear"]/@value', $resultNode)) == FALSE)
5125
            throw new Exception('error parsing project');
5126
        if (($endDateNodes = $xpath->query('./field[@name = "enddate"]/@value', $resultNode)) == FALSE)
5127
            throw new Exception('error parsing project');
5128
        if (($sc39Nodes = $xpath->query('./field[@name = "ec_sc39"]/@value', $resultNode)) == FALSE)
5129
            throw new Exception('error parsing project');
5130
        if (($oaMandateNodes = $xpath->query('./field[@name = "oamandatepublications"]/@value', $resultNode)) == FALSE)
5131
            throw new Exception('error parsing project');
5132
        if (($datapilotNodes = $xpath->query('./field[@name = "ecarticle29_3"]/@value', $resultNode)) == FALSE)
5133
            throw new Exception('error parsing project');
5134
        if (($funding0Nodes = $xpath->query('./field[@name = "funding_level_0"]', $resultNode)) == FALSE)
5135
            throw new Exception('error parsing project');
5136
        if (($funding1Nodes = $xpath->query('./field[@name = "funding_level_1"]', $resultNode)) == FALSE)
5137
            throw new Exception('error parsing project');
5138
        if (($funding2Nodes = $xpath->query('./field[@name = "funding_level_2"]', $resultNode)) == FALSE)
5139
            throw new Exception('error parsing project');
5140
        if (($organizationNodes = $xpath->query('./field[@name = "organization"]', $resultNode)) == FALSE)
5141
            throw new Exception('error parsing project');
5142
        if (($urlNodes = $xpath->query('./field[@name = "websiteurl"]/@value', $resultNode)) == FALSE)
5143
            throw new Exception('error parsing datasources');
5144
        $project = new JObject();
5145
        $project->projectId = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5146
        $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
5147
        $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
5148
        $project->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5149
        $project->fundingStream = (($fundingStreamNode = $fundingStreamNodes->item(0)) == NULL) ? NULL : trim($fundingStreamNode->nodeValue);
5150
        $project->scientificArea = (($scientificAreaNode = $scientificAreaNodes->item(0)) == NULL) ? NULL : trim($scientificAreaNode->nodeValue);
5151
        $project->fundingStreamLevel2 = (($fundingStreamLevel2Node = $fundingStreamLevel2Nodes->item(0)) == NULL) ? NULL : trim($fundingStreamLevel2Node->nodeValue);
5152
        $project->call = (($callNode = $callNodes->item(0)) == NULL) ? NULL : trim($callNode->nodeValue);
5153
        $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
5154
        $project->startYear = (($startYearNode = $startYearNodes->item(0)) == NULL) ? NULL : intval(trim($startYearNode->nodeValue));
5155
        $project->startDate = (($startDateNode = $startDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($startDateNode->nodeValue));
5156
        $project->endYear = (($endYearNode = $endYearNodes->item(0)) == NULL) ? NULL : intval(trim($endYearNode->nodeValue));
5157
        $project->endDate = (($endDateNode = $endDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($endDateNode->nodeValue));
5158
        $project->sc39 = (($sc39Node = $sc39Nodes->item(0)) == NULL) ? NULL : trim($sc39Node->nodeValue);
5159
        switch ($project->sc39) {
5160
            case 'true':
5161
                $project->sc39 = TRUE;
5162
                break;
5163
            case 'false':
5164
                $project->sc39 = FALSE;
5165
                break;
5166
            default:
5167
                $project->sc39 = NULL;
5168
        }
5169
        $project->oaMandate = (($oaMandateNode = $oaMandateNodes->item(0)) == NULL) ? NULL : trim($oaMandateNode->nodeValue);
5170
        switch ($project->oaMandate) {
5171
            case 'true':
5172
                $project->oaMandate = TRUE;
5173
                break;
5174
            case 'false':
5175
                $project->oaMandate = FALSE;
5176
                break;
5177
            default:
5178
                $project->oaMandate = NULL;
5179
        }
5180
        $project->dataPilot = (($datapilotNode = $datapilotNodes->item(0)) == NULL) ? NULL : trim($datapilotNode->nodeValue);
5181
        switch ($project->dataPilot) {
5182
            case 'true':
5183
                $project->dataPilot = TRUE;
5184
                break;
5185
            case 'false':
5186
                $project->dataPilot = FALSE;
5187
                break;
5188
            default:
5189
                $project->dataPilot = NULL;
5190
        }
5191
        $project->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5192
        $project->funding = new JObject();
5193
        $project->funding->funding_level_0 = NULL;
5194
        $project->funding->funding_level_1 = NULL;
5195
        $project->funding->funding_level_2 = NULL;
5196
        if (($funding0Node = $funding0Nodes->item(0)) == NULL)
5197
            ;
5198
        else {
5199
            if (($funding0NameNodes = $xpath->query('./field[@name = "fundingname"]/@value', $funding0Node)) == FALSE)
5200
                throw new Exception('error parsing publication test');
5201
            $project->funding->funding_level_0 = (($funding0NameNode = $funding0NameNodes->item(0)) == NULL) ? NULL : trim($funding0NameNode->nodeValue);
5202
        }
5203
        if (($funding1Node = $funding1Nodes->item(0)) == NULL)
5204
            ;
5205
        else {
5206
            if (($funding1NameNodes = $xpath->query('./field[@name = "fundingname"]/@value', $funding1Node)) == FALSE)
5207
                throw new Exception('error parsing publication test');
5208
            $project->funding->funding_level_1 = (($funding1NameNode = $funding1NameNodes->item(0)) == NULL) ? NULL : trim($funding1NameNode->nodeValue);
5209
        }
5210
        if (($funding2Node = $funding2Nodes->item(0)) == NULL)
5211
            ;
5212
        else {
5213
            if (($funding2NameNodes = $xpath->query('./field[@name = "fundingname"]/@value', $funding2Node)) == FALSE)
5214
                throw new Exception('error parsing publication test');
5215
            $project->funding->funding_level_2 = (($funding2NameNode = $funding2NameNodes->item(0)) == NULL) ? NULL : trim($funding2NameNode->nodeValue);
5216
        }
5217
        $project->organizations = array();
5218
        foreach ($organizationNodes as $organizationNode) {
5219
            if (($idNodes = $xpath->query('./field[@name = "organizationid"]/@value', $organizationNode)) == FALSE)
5220
                throw new Exception('error parsing project');
5221
            if (($shortNameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $organizationNode)) == FALSE)
5222
                throw new Exception('error parsing project');
5223
            if (($nameNodes = $xpath->query('./field[@name = "legalname"]/@value', $organizationNode)) == FALSE)
5224
                throw new Exception('error parsing project');
5225
            $organization = new JObject();
5226
            $organization->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5227
            $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
5228
            $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5229
            if (($organization->id != NULL) || ($organization->shortName != NULL) || ($organization->name != NULL))
5230
                $project->organizations[] = $organization;
5231
        }
5232
        return $project;
5233
    }
5234

    
5235
    // Parse a single person from a search service XML response.
5236
    // xpath the DOMXPath to parse
5237
    // return person (object)
5238
    private function parsePerson($xpath) {
5239
        if ((($resultsNodes = $xpath->query('/response/results/record')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL))
5240
            throw new Exception('error parsing person');
5241
        if (($lastNameNodes = $xpath->query('./field[@name = "secondnames"]/@value', $resultNode)) == FALSE)
5242
            throw new Exception('error parsing person');
5243
        if (($firstNameNodes = $xpath->query('./field[@name = "firstname"]/@value', $resultNode)) == FALSE)
5244
            throw new Exception('error parsing person');
5245
        if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $resultNode)) == FALSE)
5246
            throw new Exception('error parsing person');
5247
        if (($countryNodes = $xpath->query('./field[@name = "nationalityname"]/@value', $resultNode)) == FALSE)
5248
            throw new Exception('error parsing person');
5249
        $person = new JObject();
5250
        $person->lastName = (($lastNameNode = $lastNameNodes->item(0)) == NULL) ? NULL : trim($lastNameNode->nodeValue);
5251
        $person->firstName = (($firstNameNode = $firstNameNodes->item(0)) == NULL) ? NULL : trim($firstNameNode->nodeValue);
5252
        $person->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
5253
        $person->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
5254
        return $person;
5255
    }
5256

    
5257
    // Parse a single organization from a search service XML response.
5258
    // xpath the DOMXPath to parse
5259
    // return organization (object)
5260
    private function parseOrganization($xpath) {
5261
        if ((($resultNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultNodes->item(0)) == NULL))
5262
            throw new Exception('error parsing organization');
5263
        if (($shortNameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $resultNode)) == FALSE)
5264
            throw new Exception('error parsing organization');
5265
        if (($nameNodes = $xpath->query('./field[@name = "legalname"]/@value', $resultNode)) == FALSE)
5266
            throw new Exception('error parsing organization');
5267
        if (($urlNodes = $xpath->query('./field[@name = "websiteurl"]/@value', $resultNode)) == FALSE)
5268
            throw new Exception('error parsing organization');
5269
        if (($countryNodes = $xpath->query('./field[@name = "countryname"]/@value', $resultNode)) == FALSE)
5270
            throw new Exception('error parsing organization');
5271
        if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
5272
            throw new Exception('error parsing organization');
5273
        $organization = new JObject();
5274
        $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
5275
        $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5276
        $organization->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5277
        $organization->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
5278
        $organization->projects = array();
5279
        $organization->allFunders=array();
5280
        foreach ($projectNodes as $projectNode) {
5281
            if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
5282
                throw new Exception('error parsing organization');
5283
            if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
5284
                throw new Exception('error parsing organization');
5285
            if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
5286
                throw new Exception('error parsing organization');
5287
            if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
5288
                throw new Exception('error parsing organization');
5289
            $project = new JObject();
5290
            $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5291
            $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
5292
            $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
5293
            $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
5294
            $project->funders = array();
5295
            if (($projectFunders = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
5296
                throw new Exception('error parsing organization');
5297
            foreach ($projectFunders as $projectFunder) {
5298
                $funder = new JObject();
5299
                if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $projectFunder)) == FALSE)
5300
                    throw new Exception('error parsing organization');
5301
                $funder->name=(($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5302
                if (($funderNodes = $xpath->query('./field[@name = "funderid"]/@value', $projectFunder)) == FALSE)
5303
                    throw new Exception('error parsing organization');
5304
                $funder->id=(($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5305
                if (($funderNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $projectFunder)) == FALSE)
5306
                    throw new Exception('error parsing organization');
5307
                $funder->shortname=(($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5308
                if($funder!=null){
5309
                    $organization->allFunders [$funder->id]=$funder;
5310
                    $project->funders [$funder->id]=$funder;
5311

    
5312
                }
5313

    
5314
            }
5315
           $project->funders=array_unique($project->funders);
5316
            if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL)){
5317
                $organization->projects[] = $project;
5318
                //$organization->allFunders =array_merge($organization->allFunders,$project->funders);
5319
            }
5320
        }
5321
        //$organization->allFunders=array_unique($organization->allFunders);
5322
        return $organization;
5323
    }
5324

    
5325
    // Parse a single datasource from a search service XML response.
5326
    // xpath the DOMXPath to parse
5327
    // return datasource (object)
5328
    private function parseDatasource($xpath) {
5329
        if ((($resultsNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL))
5330
            throw new Exception('error parsing datasource');
5331
        if (($originalIdNodes = $xpath->query('./field[@name = "originalId"]/@value', $resultNode)) == FALSE)
5332
            throw new Exception('error parsing datasource');
5333
        if (($nameNodes = $xpath->query('./field[@name = "officialname"]/@value', $resultNode)) == FALSE)
5334
            throw new Exception('error parsing datasource');
5335
        if (($englishNameNodes = $xpath->query('./field[@name = "englishname"]/@value', $resultNode)) == FALSE)
5336
            throw new Exception('error parsing datasource');
5337
        if (($urlNodes = $xpath->query('./field[@name = "websiteurl"]/@value', $resultNode)) == FALSE)
5338
            throw new Exception('error parsing datasource');
5339
        if (($logoNodes = $xpath->query('./field[@name = "logourl"]/@value', $resultNode)) == FALSE)
5340
            throw new Exception('error parsing datasource');
5341
        if (($typeNodes = $xpath->query('./field[@name = "datasourcetypename"]/@value', $resultNode)) == FALSE)
5342
            throw new Exception('error pasrsing datasource');
5343
        if (($itemsNodes = $xpath->query('./field[@name = "odnumberofitems"]/@value', $resultNode)) == FALSE)
5344
            throw new Exception('error parsing datasource');
5345
        if (($dateNodes = $xpath->query('./field[@name = "odnumberofitemsdate"]/@value', $resultNode)) == FALSE)
5346
            throw new Exception('error parsing datasource');
5347
        if (($subjectsNodes = $xpath->query('./field[@name = "odsubjects"]/@value', $resultNode)) == FALSE)
5348
            throw new Exception('error parsing datasource');
5349
        if (($languagesNodes = $xpath->query('./field[@name = "odlanguages"]/@value', $resultNode)) == FALSE)
5350
            throw new Exception('error parsing datasource');
5351
        if (($contentsNodes = $xpath->query('./field[@name = "odcontenttypes"]/@value', $resultNode)) == FALSE)
5352
            throw new Exception('error parsing datasource');
5353
        if (($policiesNodes = $xpath->query('./field[@name = "odpolicies"]/@value', $resultNode)) == FALSE)
5354
            throw new Exception('error parsing datasource');
5355
        if (($compatibilityNodes = $xpath->query('./field[@name = "openairecompatibilityid"]/@value', $resultNode)) == FALSE)
5356
            throw new Exception('error parsing datasource');
5357
        if (($oaiPmhNodes = $xpath->query('./field[@name = "accessinfopackage"]/@value', $resultNode)) == FALSE)
5358
            throw new Exception('error parsing datasources');
5359
        if (($descriptionNodes = $xpath->query('./field[@name = "oddescription"]/@value', $resultNode)) == FALSE)
5360
            throw new Exception('error parsing datasource');
5361
        $datasource = new JObject();
5362
        $datasource->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5363
        $datasource->englishName = (($englishNameNode = $englishNameNodes->item(0)) == NULL) ? NULL : trim($englishNameNode->nodeValue);
5364
        $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5365
        $datasource->logo = (($logoNode = $logoNodes->item(0)) == NULL) ? NULL : trim($logoNode->nodeValue);
5366
        $datasource->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
5367
        $datasource->items = (($itemsNode = $itemsNodes->item(0)) == NULL) ? NULL : intval(trim($itemsNode->nodeValue));
5368
        $datasource->date = (($dateNode = $dateNodes->item(0)) == NULL) ? NULL : strtotime(trim($dateNode->nodeValue));
5369
        $datasource->subjects = (($subjectsNode = $subjectsNodes->item(0)) == NULL) ? NULL : trim($subjectsNode->nodeValue);
5370
        $datasource->languages = (($languagesNode = $languagesNodes->item(0)) == NULL) ? NULL : trim($languagesNode->nodeValue);
5371
        $datasource->contents = (($contentsNode = $contentsNodes->item(0)) == NULL) ? NULL : trim($contentsNode->nodeValue);
5372
        $datasource->policies = (($policiesNode = $policiesNodes->item(0)) == NULL) ? NULL : trim($policiesNode->nodeValue);
5373
        $datasource->compatibility = (($compatibilityNode = $compatibilityNodes->item(0)) == NULL) ? NULL : trim($compatibilityNode->nodeValue);
5374
        $datasource->oaiPmh = (($oaiPmhNode = $oaiPmhNodes->item(0)) == NULL) ? NULL : trim($oaiPmhNode->nodeValue);
5375
        $datasource->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
5376
        $datasource->originalId = (($originalIdNode = $originalIdNodes->item(0)) == NULL) ? NULL : trim($originalIdNode->nodeValue);
5377
        return $datasource;
5378
    }
5379
    private function createStatisticsForPublications($xpath,$filter =''){
5380
        return $this->createStatistics($xpath,
5381
                array('funder'.$filter, 'fundingStream'.$filter,  'fundingStreamLevel1'.$filter, 'fundingStreamLevel2'.$filter, 'project'.$filter, 'year'.$filter, 'accessMode'.$filter,  'type'.$filter, 'language'.$filter,'datasource'.$filter, 'community'.$filter),
5382
                array( 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA','FUNDING_STREAM_LEVEL_2', 'PROJECT', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'DATASOURCE', 'COMMUNITY', 'COMMUNITY'),
5383
                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'),
5384
                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));
5385
    }
5386
   private function createStatisticsForDatasets($xpath){
5387
        return $this->createStatistics($xpath,
5388
                array('funder', 'fundingStream', 'fundingStreamLevel1', 'fundingStreamLevel2', 'year', 'accessMode','type', 'language',  'datasource'),
5389
                array( 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'FUNDING_STREAM_LEVEL_2',  'PUBLICATION_YEAR', 'ACCESS_MODE','TYPE', 'LANGUAGE', 'DATASOURCE'),
5390
                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'),
5391
                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));
5392

    
5393
    }
5394
    private function createStatisticsForProjects($xpath, $filter =''){
5395
        return $this->  createStatistics($xpath,
5396
                array('funder'.$filter, 'fundingStream'.$filter, 'fundingStreamLevel1'.$filter, 'fundingStreamLevel2'.$filter ,  'startYear'.$filter, 'endYear'.$filter, 'sc39'.$filter),
5397
                array('FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'FUNDING_STREAM_LEVEL_2', 'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'),
5398
                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'),
5399
                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));
5400

    
5401
    }
5402
    private function _validateResultsSize($size=10){
5403
        if($size > 50){
5404
            $size = 10;
5405
        }
5406
        return $size;
5407
    }
5408

    
5409
}
(7-7/9)