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 SOFTWARE_QUERY = '(oaftype exact result) and (resulttypeid exact software)';
104
    const BROWSE_SOFTWARE_CACHE_ID = 'browse.software';
105
    const OTHER_QUERY = '(oaftype exact result) and (resulttypeid exact other)';
106
    const BROWSE_OTHER_CACHE_ID = 'browse.other';
107
    const BROWSE_RESULT_CACHE_ID = 'browse.result';
108
    const PROJECT_QUERY = '(oaftype exact project)';
109
    const PROJECT = 'project';
110
    const PROJECT_FUNDER = 'funder';
111
    const PROJECT_FUNDING_STREAM = 'fundinglevel0_id';
112
    const PROJECT_SCIENTIFIC_AREA = 'fundinglevel1_id';
113
    const PROJECT_FUNDING_STREAM_LEVEL2 = 'fundinglevel2_id';
114
    const PROJECT_START_YEAR = 'projectstartyear';
115
    const PROJECT_END_YEAR = 'projectendyear';
116
    const PROJECT_SC39 = 'projectecsc39';
117
    const PROJECT_ACRONYM = 'projectacronym';
118
    const PROJECT_TITLE = 'projecttitle';
119
    const PROJECT_KEYWORDS = 'projectkeywords';
120
    const PROJECT_START_DATE = 'projectstartdate';
121
    const PROJECT_END_DATE = 'projectenddate';
122
    const PROJECT_ID = 'objIdentifier';
123
    const PROJECT_CODE = 'projectcode';
124
    const PERSON_QUERY = '(oaftype exact person)';
125
    // const PERSON_COUNTRY = 'personcountryid';
126
    const PERSON_LAST_NAME = 'personsecondnames';
127
    const PERSON_FIRST_NAME = 'personfirstname';
128
    const PERSON_FULL_NAME = 'personfullname';
129
    const PERSON_ID = 'objIdentifier';
130
    const ORGANIZATION_QUERY = '(oaftype exact organization)';
131
    const ORGANIZATION_QUERY_COMPATIBILITY = 'oaftype exact organization and
132
(reldatasourcecompatibilityid=driver or reldatasourcecompatibilityid=driver-openaire2.0 or
133
reldatasourcecompatibilityid=openaire2.0 or reldatasourcecompatibilityid=openaire3.0 or
134
reldatasourcecompatibilityid=openaire2.0_data or reldatasourcecompatibilityid=hostedBy
135
or relproject=*)';
136
    const ORGANIZATION_COUNTRY = 'organizationcountryname';
137
    const ORGANIZATION_LEGAL_BODY = 'organizationeclegalbody';
138
    const ORGANIZATION_LEGAL_PERSON = 'organizationeclegalperson';
139
    const ORGANIZATION_NON_PROFIT = 'organizationecnonprofit';
140
    const ORGANIZATION_RESEARCH = 'organizationecresearchorganization';
141
    const ORGANIZATION_EU_INTERESTS = 'organizationecinternationalorganizationeurinterests';
142
    const ORGANIZATION_INTERNATIONAL = 'organizationecinternationalorganization';
143
    const ORGANIZATION_ENTERPRISE = 'organizationecenterprise';
144
    const ORGANIZATION_SMALL_MEDIUM_ENTERPRISE = 'organizationecsmevalidated';
145
    const ORGANIZATION_NAME = 'organizationlegalname';
146
    const ORGANIZATION_SHORT_NAME = 'organizationlegalshortname';
147
    const ORGANIZATION_ID = 'objIdentifier';
148
//    const DATASOURCE_QUERY = '(oaftype exact datasource) and (datasourcecompatibilityid <> "UNKNOWN") and (datasourcecompatibilityid <> "hostedBy")';
149
    const DATASOURCE_QUERY = '(oaftype exact datasource) and (datasourcecompatibilityid <> "UNKNOWN")';
150
    const DATASOURCE_QUERY_COMPATIBILITY = '(oaftype exact datasource)';
151
    const DATASOURCE_TYPE = 'datasourcetypeuiname';
152
    const DATASOURCE_LANGUAGE = 'datasourceodlanguages';
153
    const DATASOURCE_CONTENT = 'datasourceodcontenttypes';
154
    const DATASOURCE_COMPATIBILITY = 'datasourcecompatibilityname';
155
    const DATASOURCE_NAME = 'datasourceofficialname';
156
    const DATASOURCE_ENGLISH_NAME = 'datasourceenglishname';
157
    const DATASOURCE_SUBJECT = 'datasourceodsubjects';
158
    const DATASOURCE_ORGANIZATION = 'relorganizationid';
159
    const DATASOURCE_ID = 'objIdentifier';
160
    const DATASOURCE_COMPATIBILITY_NOT_COMPATIBLE = 'notCompatible';
161
    const DATASOURCE_ACCESS_OPEN = 'OPEN';
162
    const DATASOURCE_ACCESS_EMBARGO = 'EMBARGO';
163
    const DATASOURCE_ACCESS_RESTRICTED = 'RESTRICTED';
164
    const DATASOURCE_ACCESS_CLOSED = 'CLOSED';
165
    const UNKNOWN = 'UNKNOWN';
166
    const UNDETERMINED = 'Undetermined';
167
    const PUBLICATION = 'publication';
168
    const DATASET = 'dataset';
169
    const HTTP_OK = 200;
170
    const ALL = 'all';
171
    const ANY = 'any';
172
    private $searchService;
173
    private $publicationStatisticsExistUrl;
174
    private $publicationStatisticsChartUrl;
175
    private $datasourceStatisticsExistUrl;
176
    private $datasourceStatisticsChartUrl;
177
    private $projectStatisticsChartUrl;
178
    private $cache;
179
    private $http;
180

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
476
    // Perform a browse for datasets using cache if enabled.
477
    // $type the ID of the dataset type to use as filter or NULL for no dataset type filtering
478
    // $language the ID of the language to use as filter or NULL for no language filtering
479
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
480
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
481
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
482
    // $year the year of publication to use as filter or NULL for no year filtering
483
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
484
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
485
    // $page the page of results to retrieve
486
    // $size the size of the page of results to retrieve
487
    // $locale the locale to use
488
    // $project the ID of the project to use as filter or NULL for no project filtering
489
    // $author the ID of the author to use as filter or NULL for no author filtering
490
    // return a result (object) containing datasets and statistics
491
    public function browseDatasets($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine, $refineFields = NULL) {
492
        if ($this->cache->getCaching()) {
493
            $cacheId = self :: BROWSE_DATASETS_CACHE_ID . '.' . $type . '.' . $language . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.' . $fundingStreamLevel2 . '.' . $year . '.' . $accessMode . '.' . $datasource . '.' . $page . '.' . $size . '.' . $locale . '.' . $project . '.' . $author.'.'.$isRefine.'.'.$refineFields;
494
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
495
            if ($result === FALSE) {
496
                $result = $this->_browseDatasets($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine,$refineFields);
497
                if ($result !== NULL)
498
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
499
            }
500
        } else
501
            $result = $this->_browseDatasets($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine,$refineFields);
502
        return $result;
503
    }
504
    
505
        public function browseSoftware($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine, $refineFields = NULL) {
506
        if ($this->cache->getCaching()) {
507
            $cacheId = self :: BROWSE_SOFTWARE_CACHE_ID . '.' . $type . '.' . $language . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.' . $fundingStreamLevel2 . '.' . $year . '.' . $accessMode . '.' . $datasource . '.' . $page . '.' . $size . '.' . $locale . '.' . $project . '.' . $author.'.'.$isRefine.'.'.$refineFields;
508
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
509
            if ($result === FALSE) {
510
                $result = $this->_browseSoftware($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine,$refineFields);
511
                if ($result !== NULL)
512
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
513
            }
514
        } else
515
            $result = $this->_browseSoftware($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine,$refineFields);
516
        return $result;
517
    }
518
    
519
        public function browseOther($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine, $refineFields = NULL) {
520
        if ($this->cache->getCaching()) {
521
            $cacheId = self :: BROWSE_OTHER_CACHE_ID . '.' . $type . '.' . $language . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.' . $fundingStreamLevel2 . '.' . $year . '.' . $accessMode . '.' . $datasource . '.' . $page . '.' . $size . '.' . $locale . '.' . $project . '.' . $author.'.'.$isRefine.'.'.$refineFields;
522
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
523
            if ($result === FALSE) {
524
                $result = $this->_browseOther($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine,$refineFields);
525
                if ($result !== NULL)
526
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
527
            }
528
        } else
529
            $result = $this->_browseOther($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine,$refineFields);
530
        return $result;
531
    }
532
        public function browseResults($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine, $refineFields = NULL) {
533
        if ($this->cache->getCaching()) {
534
            $cacheId = self :: BROWSE_RESULT_CACHE_ID . '.' . $type . '.' . $language . '.' . $funder . '.' . $fundingStream . '.' . $scientificArea . '.' . $fundingStreamLevel2 . '.' . $year . '.' . $accessMode . '.' . $datasource . '.' . $page . '.' . $size . '.' . $locale . '.' . $project . '.' . $author.'.'.$isRefine.'.'.$refineFields;
535
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
536
            if ($result === FALSE) {
537
                $result = $this->_browseResults($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine,$refineFields);
538
                if ($result !== NULL)
539
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
540
            }
541
        } else
542
            $result = $this->_browseResults($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine,$refineFields);
543
        return $result;
544
    }
545

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

    
571

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

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

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

    
671

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

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

    
742
    // Perform an advanced search for datasources using cache if enabled.
743
    // $keywords the keywords to search for (array)
744
    // $fields the fields to match keywords with (array - possible values are NAME, ENGLISH_NAME and SUBJECT)
745
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
746
    // $types the IDs of the datasource types to search for
747
    // $languages the IDs of the datasource languages to search for
748
    // $contents the IDs of the contents to search for
749
    // $compatibilities the IDs of the compatibilities to search for
750
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
751
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
752
    // $content the ID of the content to use as filter or NULL for no content filtering
753
    // $compatibility the ID of the compatibility to use as filter or NULL for no compatibility filtering
754
    // $page the page of results to retrieve
755
    // $size the size of the page of results to retrieve
756
    // $locale the locale to use
757
    // return a result (object) containing datasources and statistics
758
    public function advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale) {
759
        if ($this->cache->getCaching()) {
760
            $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;
761
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
762
            if ($result === FALSE) {
763
                $result = $this->_advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale);
764
                if ($result !== NULL)
765
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
766
            }
767
        } else
768
            $result = $this->_advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale);
769
        return $result;
770
    }
771

    
772
    // Retrieve a single publication by identifier using caching if enabled.
773
    // $id the publication identifier
774
    // $locale the locale to use
775
    // return a publication (object) or NULL if no such publication exists
776
    public function getPublication($id, $locale) {
777
        if ($this->cache->getCaching()) {
778
            $cacheId = self :: PUBLICATION_CACHE_ID . '.' . $id . '.' . $locale;
779
            $publication = $this->cache->get($cacheId, self :: CACHE_GROUP);
780
            if ($publication === FALSE) {
781
                $publication = $this->_getPublication($id, $locale);
782
                if ($publication !== NULL)
783
                    $this->cache->store($publication, $cacheId, self :: CACHE_GROUP);
784
            }
785
        } else
786
            $publication = $this->_getPublication($id, $locale);
787
        return $publication;
788
    }
789

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

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

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

    
844
    // Retrieve projects by identifier using caching if enabled.
845
    // $ids the project identifiers
846
    // $locale the locale to use
847
    // return an array of project (object) or NULL if no such projects exists
848
    public function getProjects($ids, $locale) {
849
         if ($this->cache->getCaching()) {
850
            $cacheId = self :: PROJECTS_CACHE_ID . '.' . join(",", $ids) . '.' . $locale;
851
            $projects = $this->cache->get($cacheId, self :: CACHE_GROUP);
852
            if ($projects === FALSE) {
853
                $projects = $this->_getProjects($ids, $locale);
854
                if ($projects !== NULL)
855
                    $this->cache->store($projects, $cacheId, self :: CACHE_GROUP);
856
            }
857
        } else
858
            $projects = $this->_getProjects($ids, $locale);
859
        return $projects;
860
    }
861
    // Retrieve projects by identifier using caching if enabled.
862
    // $ids the project identifiers
863
    // $locale the locale to use
864
    // return an array of project (object) or NULL if no such projects exists
865
    public function getProjectByCodeId($id, $funder, $locale) {
866
         if ($this->cache->getCaching()) {
867
            $cacheId = self :: PROJECT_CACHE_ID . '.' . $id . '.' . $funder . '.' . $locale;
868
            $projects = $this->cache->get($cacheId, self :: CACHE_GROUP);
869
            if ($projects === FALSE) {
870
                $projects = $this->_getProjectByCodeId($id, $funder, $locale);
871
                if ($projects !== NULL)
872
                    $this->cache->store($projects, $cacheId, self :: CACHE_GROUP);
873
            }
874
        } else
875
            $projects = $this->_getProjectByCodeId($id, $funder, $locale);
876
        return $projects;
877
    }
878

    
879
    // Retrieve a single dataset by identifier using caching if enabled.
880
    // $id the dataset identifier
881
    // $locale the locale to use
882
    // return a dataset (object) or NULL if no such dataset exists
883
    public function getDataset($id, $locale) {
884
        if ($this->cache->getCaching()) {
885
            $cacheId = self :: DATASET_CACHE_ID . '.' . $id . '.' . $locale;
886
            $dataset = $this->cache->get($cacheId, self :: CACHE_GROUP);
887
            if ($dataset === FALSE) {
888
                $dataset = $this->_getDataset($id, $locale);
889
                if ($dataset !== NULL)
890
                    $this->cache->store($dataset, $cacheId, self :: CACHE_GROUP);
891
            }
892
        } else
893
            $dataset = $this->_getDataset($id, $locale);
894
        return $dataset;
895
    }
896

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

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

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

    
951
    // Retrieve the datasources of an organization using caching if enabled.
952
    // $id the organization identifier
953
    // $size the maximum number of organizations to retrieve
954
    // $locale the locale to use
955
    // return a result (object) containing datasources and total
956
    public function getOrganizationDatasources($id, $size, $locale) {
957
        if ($this->cache->getCaching()) {
958
            $cacheId = self :: ORGANIZATION_DATASOURCES_CACHE_ID . '.' . $id . '.' . $size . '.' . $locale;
959
            $result = $this->cache->get($cacheId, self :: CACHE_GROUP);
960
            if ($result === FALSE) {
961
                $result = $this->_getOrganizationDatasources($id, $size, $locale);
962
                if ($result !== NULL)
963
                    $this->cache->store($result, $cacheId, self :: CACHE_GROUP);
964
            }
965
        } else
966
            $result = $this->_getOrganizationDatasources($id, $size, $locale);
967
        return $result;
968
    }
969

    
970
    // Retrieve a single datasource by identifier using cache if enabled.
971
    // $id the datasource identifier
972
    // $locale the locale to use
973
    // return a datasource (object) or NULL if no such datasource exists
974
    public function getDatasource($id, $locale, $compatibility = false) {
975
        if ($this->cache->getCaching()) {
976
            $cacheId = self :: DATASOURCE_CACHE_ID . '.' . $id . '.' . $locale . "." . $compatibility;
977
            $datasource = $this->cache->get($cacheId, self :: CACHE_GROUP);
978
            if ($datasource === FALSE) {
979
                $datasource = $this->_getDatasource($id, $locale, $compatibility);
980
                if ($datasource !== NULL)
981
                    $this->cache->store($datasource, $cacheId, self :: CACHE_GROUP);
982
            }
983
        } else
984
            $datasource = $this->_getDatasource($id, $locale, $compatibility);
985
        return $datasource;
986
    }
987

    
988
    // Retrieve all the OpenAIRE compatible datasources using cache if enabled.
989
    // $locale the locale to use
990
    // return the datasources (array) or NULL if any errors occur
991
    public function getCompatibleDatasources($locale) {
992
        if ($this->cache->getCaching()) {
993
            $cacheId = self :: COMPATIBLE_DATASOURCES_CACHE_ID . '.' . $locale;
994
            $datasources = $this->cache->get($cacheId, self :: CACHE_GROUP);
995
            if ($datasources === FALSE) {
996
                $datasources = $this->_getCompatibleDatasources($locale);
997
                if ($datasources !== NULL)
998
                    $this->cache->store($datasources, $cacheId, self :: CACHE_GROUP);
999
            }
1000
        } else
1001
            $datasources = $this->_getCompatibleDatasources($locale);
1002
        return $datasources;
1003
    }
1004

    
1005
    // Perform a quick search for projects, searching only by acronym, title or code and funder and using cahce if enabled.
1006
    // $keyword the keyword to search for
1007
    // $funder the funder to search for
1008
    // $limit the maximum number of results to retrieve
1009
    // $locale the locale to use
1010
    // return projects (array) or NULL if any errors occur
1011
    public function quickSearchProjects($keyword, $funder, $limit, $locale) {
1012
        if ($this->cache->getCaching()) {
1013
            $cacheId = self :: QUICK_SEARCH_PROJECTS_CACHE_ID . '.' . $keyword . '.' . $funder . '.' . $limit . '.' . $locale;
1014
            $projects = $this->cache->get($cacheId, self :: CACHE_GROUP);
1015
            if ($projects === FALSE) {
1016
                $projects = $this->_quickSearchProjects($keyword, $funder, $limit, $locale);
1017
                if ($projects !== NULL)
1018
                    $this->cache->store($projects, $cacheId, self :: CACHE_GROUP);
1019
            }
1020
        } else
1021
            $projects = $this->_quickSearchProjects($keyword, $funder, $limit, $locale);
1022
        return $projects;
1023
    }
1024

    
1025
    // Perform a quick search for organizations, searching only by name or short name and using cache if enabled.
1026
    // $keyword the keyword to search for
1027
    // $limit the maximum number of results to retrieve
1028
    // $locale the locale to use
1029
    // return organizations (array) or NULL if any errors occur
1030
    public function quickSearchOrganizations($keyword, $limit, $locale) {
1031
        JLog :: add('Keyword \'' . $keyword . '\'', JLog :: INFO, self :: LOG);
1032
        if ($this->cache->getCaching()) {
1033
            $cacheId = self :: QUICK_SEARCH_ORGANIZATIONS_CACHE_ID . '.' . $keyword . '.' . $limit . '.' . $locale;
1034
            $organizations = $this->cache->get($cacheId, self :: CACHE_GROUP);
1035
            if ($organizations === FALSE) {
1036
                $organizations = $this->_quickSearchOrganizations($keyword, $limit, $locale);
1037
                if ($organizations !== NULL)
1038
                    $this->cache->store($organizations, $cacheId, self :: CACHE_GROUP);
1039
            }
1040
        } else
1041
            $organizations = $this->_quickSearchOrganizations($keyword, $limit, $locale);
1042
        return $organizations;
1043
    }
1044

    
1045
    // Retrieve publication statistics.
1046
    // $locale the locale to use
1047
    // $allFunders get all fields for funders
1048
    // return statistics (object)
1049
    private function _getPublicationStatistics($locale, $allFunders=false) {
1050
    try {
1051
            $time = microtime(TRUE);
1052
            $query = self :: PUBLICATION_QUERY;
1053
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1054
            /* 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)            
1055
             */
1056
            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)
1057
                throw new Exception('no HTTP response');
1058
            if ($response->code != self :: HTTP_OK)
1059
                throw new Exception('HTTP response code ' . $response->code);
1060
            $document = new DOMDocument();
1061
            $document->recover = TRUE;
1062
            if ($document->loadXML($response->body) == FALSE)
1063
                throw new Exception('invalid XML response');
1064
            $xpath = new DOMXPath($document);
1065
            $statistics=null;
1066
            if($allFunders){
1067
                $statistics = $this->createStatistics($xpath,
1068
                    array('type', 'language', 'funder', 'fundingStream', 'scientificArea', 'fundingStreamLevel2', 'year', 'accessMode', 'datasource', 'community'),
1069
                    array('DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'FUNDING_STREAM_LEVEL_2', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE', 'COMMUNITIES'),
1070
                    array('NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND',
1071
                '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'),
1072
                    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));
1073
            }else{
1074
                $statistics = $this->createStatistics($xpath,
1075
                    array('type', 'language', 'funder',  'year', 'accessMode', 'datasource', 'community'),
1076
                    array('DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'FUNDER',  'PUBLICATION_YEAR', 'ACCESS_MODE', 'DATASOURCE', 'COMMUNITIES'),
1077
                    array('NO_DOCUMENT_TYPE_STATISTICS_FOUND', 'NO_DOCUMENT_LANGUAGE_STATISTICS_FOUND',
1078
                'NO_FUNDER_STATISTICS_FOUND',   'NO_PUBLICATION_YEAR_STATISTICS_FOUND', 'NO_ACCESS_MODE_STATISTICS_FOUND', 'NO_DATASOURCE_STATISTICS_FOUND', 'NO_COMMUNITY_STATISTICS_FOUND'),
1079
                    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));
1080

    
1081
            }
1082
            JLog :: add('Retrieved publication statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1083
            return $statistics;
1084
        } catch (Exception $e) {
1085
            JLog :: add('Error retrieving publication statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1086
            return NULL;
1087
        }
1088
    }
1089

    
1090

    
1091
    // Retrieve dataset statistics.
1092
    // $locale the locale to use
1093
    // return statistics (object)
1094
    private function _getDatasetStatistics($locale, $allFunders=false) {
1095
        try {
1096
            $time = microtime(TRUE);
1097
            $query = self :: DATASET_QUERY;
1098
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1099
            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)
1100
                throw new Exception('no HTTP response');
1101
            if ($response->code != self :: HTTP_OK)
1102
                throw new Exception('HTTP response code ' . $response->code);
1103
            $document = new DOMDocument();
1104
            $document->recover = TRUE;
1105
            if ($document->loadXML($response->body) == FALSE)
1106
                throw new Exception('invalid XML response');
1107
            $xpath = new DOMXPath($document);
1108
            $statistics=null;
1109
            if($allFunders){
1110
                $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));
1111
            }else{
1112
                $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));
1113
            }
1114
            JLog :: add('Retrieved dataset statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1115
            return $statistics;
1116
        } catch (Exception $e) {
1117
            JLog :: add('Error retrieving dataset statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1118
            return NULL;
1119
        }
1120
    }
1121

    
1122
    // Retrieve project statistics.
1123
    // $locale the locale to use
1124
    // return statistics (object)
1125
    private function _getProjectStatistics($locale, $allFunders) {
1126
        try {
1127
            $time = microtime(TRUE);
1128
            $query = self :: PROJECT_QUERY;
1129
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1130
            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)
1131
            //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)
1132
                throw new Exception('no HTTP response');
1133
            if ($response->code != self :: HTTP_OK)
1134
                throw new Exception('HTTP response code ' . $response->code);
1135
            $document = new DOMDocument();
1136
            $document->recover = TRUE;
1137
            if ($document->loadXML($response->body) == FALSE)
1138
                throw new Exception('invalid XML response');
1139
            $statistics=null;
1140
            $xpath = new DOMXPath($document);
1141
            if( $allFunders){
1142
                $statistics = $this->createStatistics($xpath,
1143
                    array('funder', 'fundingStream', 'scientificArea', 'startYear', 'endYear', 'sc39'),
1144
                    array('FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'),
1145
                    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'),
1146
                    array(self :: PROJECT_FUNDER, self :: PROJECT_FUNDING_STREAM, self :: PROJECT_SCIENTIFIC_AREA, self :: PROJECT_START_YEAR, self :: PROJECT_END_YEAR, self :: PROJECT_SC39));
1147
            }else{
1148
                $statistics = $this->createStatistics($xpath,
1149
                    array('funder',   'startYear', 'endYear', 'sc39'),
1150
                    array('FUNDER',   'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'),
1151
                    array('NO_FUNDER_STATISTICS_FOUND', 'NO_START_YEAR_STATISTICS_FOUND', 'NO_END_YEAR_STATISTICS_FOUND', 'NO_SPECIAL_CLAUSE_39_STATISTICS_FOUND'),
1152
                    array(self :: PROJECT_FUNDER,  self :: PROJECT_START_YEAR, self :: PROJECT_END_YEAR, self :: PROJECT_SC39));
1153
            }
1154
            JLog :: add('Retrieved project statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1155
            return $statistics;
1156
        } catch (Exception $e) {
1157
            JLog :: add('Error retrieving project statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1158
            return NULL;
1159
        }
1160
    }
1161

    
1162

    
1163
    // Retrieve organization statistics.
1164
    // $locale the locale to use
1165
    // return statistics (object)
1166
    private function _getOrganizationStatistics($locale) {
1167
        try {
1168
            $time = microtime(TRUE);
1169
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
1170
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1171
            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)
1172
                throw new Exception('no HTTP response');
1173
            if ($response->code != self :: HTTP_OK)
1174
                throw new Exception('HTTP response code ' . $response->code);
1175
            $document = new DOMDocument();
1176
            $document->recover = TRUE;
1177
            if ($document->loadXML($response->body) == FALSE)
1178
                throw new Exception('invalid XML response');
1179
            $xpath = new DOMXPath($document);
1180
            $statistics = $this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
1181
            $statistics['type'] = new JObject();
1182
            $statistics['type']->id = 'type';
1183
            $statistics['type']->title = JText :: _('TYPE');
1184
            $statistics['type']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
1185
            $statistics['type']->data = array();
1186
            $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
1187
            if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
1188
                $statistics['type']->data['legalBody'] = new JObject();
1189
                $statistics['type']->data['legalBody']->id = 'legalBody';
1190
                $statistics['type']->data['legalBody']->name = JText :: _('LEGAL_BODY');
1191
                $statistics['type']->data['legalBody']->count = $legalBody['true']->count;
1192
            }
1193
            $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
1194
            if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
1195
                $statistics['type']->data['legalPerson'] = new JObject();
1196
                $statistics['type']->data['legalPerson']->id = 'legalPerson';
1197
                $statistics['type']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
1198
                $statistics['type']->data['legalPerson']->count = $legalPerson['true']->count;
1199
            }
1200
            $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
1201
            if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
1202
                $statistics['type']->data['nonProfit'] = new JObject();
1203
                $statistics['type']->data['nonProfit']->id = 'nonProfit';
1204
                $statistics['type']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
1205
                $statistics['type']->data['nonProfit']->count = $nonProfit['true']->count;
1206
            }
1207
            $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
1208
            if (($research != NULL) && array_key_exists('true', $research)) {
1209
                $statistics['type']->data['research'] = new JObject();
1210
                $statistics['type']->data['research']->id = 'research';
1211
                $statistics['type']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
1212
                $statistics['type']->data['research']->count = $research['true']->count;
1213
            }
1214
            $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
1215
            if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
1216
                $statistics['type']->data['euInterests'] = new JObject();
1217
                $statistics['type']->data['euInterests']->id = 'euInterests';
1218
                $statistics['type']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
1219
                $statistics['type']->data['euInterests']->count = $euInterests['true']->count;
1220
            }
1221
            $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
1222
            if (($international != NULL) && array_key_exists('true', $international)) {
1223
                $statistics['type']->data['international'] = new JObject();
1224
                $statistics['type']->data['international']->id = 'international';
1225
                $statistics['type']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
1226
                $statistics['type']->data['international']->count = $international['true']->count;
1227
            }
1228
            $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
1229
            if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
1230
                $statistics['type']->data['enterprise'] = new JObject();
1231
                $statistics['type']->data['enterprise']->id = 'enterprise';
1232
                $statistics['type']->data['enterprise']->name = JText :: _('ENTERPRISE');
1233
                $statistics['type']->data['enterprise']->count = $enterprise['true']->count;
1234
            }
1235
            $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
1236
            if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
1237
                $statistics['type']->data['smallMediumEnterprise'] = new JObject();
1238
                $statistics['type']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
1239
                $statistics['type']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
1240
                $statistics['type']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
1241
            }
1242
            uasort($statistics['type']->data, function ($row1, $row2) {
1243
                return $row2->count - $row1->count;
1244
            });
1245
            JLog :: add('Retrieved organization statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1246
            return $statistics;
1247
        } catch (Exception $e) {
1248
            JLog :: add('Error retrieving organization statistics (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1249
            return NULL;
1250
        }
1251
    }
1252

    
1253
    // Retrieve datasource statistics.
1254
    // $locale the locale to use
1255
    // return statistics (object)
1256
    private function _getDatasourceStatistics($locale) {
1257
        try {
1258
            $time = microtime(TRUE);
1259
            $query = self :: DATASOURCE_QUERY;
1260
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1261
            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)
1262
                throw new Exception('no HTTP response');
1263
            if ($response->code != self :: HTTP_OK)
1264
                throw new Exception('HTTP response code ' . $response->code);
1265
            $document = new DOMDocument();
1266
            $document->recover = TRUE;
1267
            if ($document->loadXML($response->body) == FALSE)
1268
                throw new Exception('invalid XML response');
1269
            $xpath = new DOMXPath($document);
1270
            $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));
1271
            JLog :: add('Retrieved datasource statistics in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
1272
            return $statistics;
1273
        } catch (Exception $e) {
1274
            JLog :: add('Error retrieving datasource statistics locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1275
            return NULL;
1276
        }
1277
    }
1278

    
1279
    // Perform a simple search for publications.
1280
    // $keyword the keyword to search for
1281
    // $articles flag to limit searching on articles; if all flags are FALSE no limits apply
1282
    // $books flag to limit searching on books; if all flags are FALSE no limits apply
1283
    // $theses flag to limit searching on books; if all flags are FALSE no limits apply
1284
    // $reports flag to limit searching on reports; if all flags are FALSE no limits apply
1285
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
1286
    // $language the ID of the language to use as filter or NULL for no language filtering
1287
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1288
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
1289
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1290
    // $year the year of publication to use as filter or NULL for no year filtering
1291
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1292
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1293
    // $page the page of results to retrieve
1294
    // $size the size of the page of results to retrieve
1295
    // $locale the locale to use
1296
    // return a result (object) containing publications and statistics
1297
    private function _searchPublications($keyword, $articles, $books, $theses, $reports, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project,$isRefine) {
1298
        try {
1299
                $dois = explode(" ", preg_replace('/\s+/', ' ',$keyword));
1300
                $unique_dois =array_unique($dois);
1301
                $pattern1 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b#';
1302
                $pattern2 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b#';
1303
                if (preg_match($pattern1, $unique_dois[0]) || preg_match($pattern2, $unique_dois[0])) {
1304
                   $result= $this->_searchPublicationsWithDois($unique_dois,$page, $size, $locale,$isRefine);
1305
                    return $result;
1306
                }
1307
            $time = microtime(TRUE);
1308
            $query = self :: PUBLICATION_QUERY;
1309
            $query .= ($keyword == NULL) ? '' : ' and "' . str_replace('"', '\\"', $keyword) . '"';
1310
            $types = array();
1311
            if ($articles) {
1312
                $types[] = self :: PUBLICATION_ARTICLE;
1313
                $types[] = self :: PUBLICATION_PREPRINT;
1314
            }
1315
            if ($books) {
1316
                $types[] = self :: PUBLICATION_BOOK;
1317
                $types[] = self :: PUBLICATION_BOOK_PART;
1318
            }
1319
            if ($theses) {
1320
                $types[] = self :: PUBLICATION_PHD_THESIS;
1321
                $types[] = self :: PUBLICATION_MASTER_THESIS;
1322
                $types[] = self :: PUBLICATION_BACHELOR_THESIS;
1323
            }
1324
            if ($reports) {
1325
                $types[] = self :: PUBLICATION_REPORT;
1326
                $types[] = self :: PUBLICATION_INTERNAL_REPORT;
1327
                $types[] = self :: PUBLICATION_EXTERNAL_REPORT;
1328
            }
1329
            $publicationType = self :: PUBLICATION_TYPE;
1330
            $types = implode(' or ', array_map(function($type) use ($publicationType) {
1331
                        return '(' . $publicationType . ' exact "' . $type . '")';
1332
                    }, $types));
1333
            $query .= ($types == NULL) ? '' : (' and (' . $types . ')');
1334
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
1335
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
1336
             if($funder != NULL && (strpos($funder, ',') !== FALSE)){
1337
                $temp='';
1338
                foreach(explode(',',$funder) as $id){
1339
                    if(!empty($id)){
1340
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
1341
                    }
1342

    
1343
                }
1344
                $query .=  (' and (' . substr($temp, 0, -3). ')');
1345
            }else{
1346
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
1347
            }
1348
            //$query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
1349
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1350
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1351
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1352
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact ' . $year . ')');
1353
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
1354
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '")');
1355
            $query .= ($community == NULL) ? '' : (' and (' . self :: PUBLICATION_CONTEXT . ' exact "' . $community . '")');
1356
            $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT . ' exact "' . $project . '")');
1357
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1358
            $completeQuery='search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size .  '&locale=' . str_replace('-', '_', $locale);
1359
            if($isRefine){
1360
                $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);
1361
            }
1362
            //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)
1363
            if (($response = $this->performGet($completeQuery)) == NULL)
1364
                throw new Exception('no HTTP response');
1365
            if ($response->code != self :: HTTP_OK)
1366
                throw new Exception('HTTP response code ' . $response->code);
1367
            $document = new DOMDocument();
1368
            $document->recover = TRUE;
1369
            if ($document->loadXML($response->body) == FALSE)
1370
                throw new Exception('invalid XML response');
1371
            $xpath = new DOMXPath($document);
1372
            $result = new JObject();
1373
            $result->totalPublications = $this->parseTotalResults($xpath);
1374
            $result->totalDatasets = 0;
1375
            $result->publications = $this->parsePublications($xpath);
1376
            $result->statistics = $isRefine? $this->createStatisticsForPublications($xpath):NULL;
1377
            $result->statistics = self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1378
                    //$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));
1379
            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);
1380
            return $result;
1381
        } catch (Exception $e) {
1382
            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);
1383
            $result->publications = array();
1384
            $result->totalPublications = 0;
1385
            $result->totalDatasets = 0;
1386
            return $result;
1387
        }
1388
    }
1389
 private function _searchPublicationsWithDois($dois, $page, $size, $locale,$isRefine) {
1390
        try {
1391
            $time = microtime(TRUE);
1392
            $query = self :: PUBLICATION_QUERY;
1393
            $query .= ' and (';
1394
            foreach ($dois as $doi) {
1395
                $query .= ' ((pidclassid exact doi) and (pid exact "'.$doi.'")) ';
1396
                $query .= 'OR';
1397
            }
1398
            if(count($dois)>0){
1399
                $query=substr($query, 0, -2);
1400
            }
1401
            $query .= ')';
1402
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1403
            $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)
1404
                    :'search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size   . '&locale=' . str_replace('-', '_', $locale);
1405
            if (($response = $this->performGet($completeQuery)) == NULL)
1406
                throw new Exception('no HTTP response');
1407
            if ($response->code != self :: HTTP_OK)
1408
                throw new Exception('HTTP response code ' . $response->code);
1409
            $document = new DOMDocument();
1410
            $document->recover = TRUE;
1411
            if ($document->loadXML($response->body) == FALSE)
1412
                throw new Exception('invalid XML response');
1413
            $xpath = new DOMXPath($document);
1414
            $result = new JObject();
1415
            $result->totalPublications = $this->parseTotalResults($xpath);
1416
            $result->totalDatasets = 0;
1417
            $result->publications = $this->parsePublications($xpath);
1418
            $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;
1419
            JLog :: add('Simple search for DOIs retrieved ' . count($result->publications) . ' publications in ' . (microtime(TRUE) - $time) . ' s (query: ' . $query. ')', JLog :: INFO, self :: LOG);
1420
            return $result;
1421
        } catch (Exception $e) {
1422
            JLog :: add('Error performing publication simple search for DOIs(query: ' . $query  . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1423
            return NULL;
1424
        }
1425
    }
1426
    // Perform a simple search for datasets.
1427
    // $keyword the keyword to search for
1428
    // $type the ID of the dataset type to use as filter or NULL for no dataset type filtering
1429
    // $language the ID of the language to use as filter or NULL for no language filtering
1430
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1431
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
1432
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1433
    // $year the year of publication to use as filter or NULL for no year filtering
1434
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1435
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1436
    // $page the page of results to retrieve
1437
    // $size the size of the page of results to retrieve
1438
    // $locale the locale to use
1439
    // return a result (object) containing datasets and statistics
1440
    private function _searchDatasets($keyword, $type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $isRefine) {
1441
        try {
1442
                $dois = explode(" ", preg_replace('/\s+/', ' ',$keyword));
1443
                $unique_dois =array_unique($dois);
1444
                $pattern1 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b#';
1445
                $pattern2 = '#\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b#';
1446
                if (preg_match($pattern1, $unique_dois[0]) || preg_match($pattern2, $unique_dois[0])) {
1447
                   $result= $this->_searchDatasetsWithDois($unique_dois,$page, $size, $locale,$isRefine);
1448
                    return $result;
1449
                }
1450
            $time = microtime(TRUE);
1451
            $query = self :: DATASET_QUERY;
1452
            $query .= ($keyword == NULL) ? '' : ' and "' . str_replace('"', '\\"', $keyword) . '"';
1453
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASET_TYPE . ' exact "' . $type . '")');
1454
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASET_LANGUAGE . ' exact "' . $language . '")');
1455
            $query .= ($funder == NULL) ? '' : (' and (' . self :: DATASET_FUNDER . ' exact "' . $funder . '")');
1456
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1457
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: DATASET_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1458
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1459
            $query .= ($year == NULL) ? '' : (' and (' . self :: DATASET_YEAR . ' exact ' . $year . ')');
1460
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: DATASET_ACCESS_MODE . ' exact "' . $accessMode . '")');
1461
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '")');
1462
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1463
            $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):
1464
                    'search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size  . '&locale=' . str_replace('-', '_', $locale);
1465
            if (($response = $this->performGet($completeQuery)) == NULL)
1466
                throw new Exception('no HTTP response');
1467
            if ($response->code != self :: HTTP_OK)
1468
                throw new Exception('HTTP response code ' . $response->code);
1469
            $document = new DOMDocument();
1470
            $document->recover = TRUE;
1471
            if ($document->loadXML($response->body) == FALSE)
1472
                throw new Exception('invalid XML response');
1473
            $xpath = new DOMXPath($document);
1474
            $result = new JObject();
1475
            $result->totalDatasets = $this->parseTotalResults($xpath);
1476
            $result->datasets = $this->parseDatasets($xpath);
1477
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
1478
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1479
                    //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));
1480
            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);
1481
            return $result;
1482
        } catch (Exception $e) {
1483
            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);
1484
            return NULL;
1485
        }
1486
    }
1487

    
1488
 private function _searchDatasetsWithDois($dois, $page, $size, $locale,$isRefine) {
1489
        try {
1490
            $time = microtime(TRUE);
1491
            $query = self :: DATASET_QUERY;
1492
            $query .= ' and (';
1493
            foreach ($dois as $doi) {
1494
                $query .= ' ((pidclassid exact doi) and (pid exact "'.$doi.'")) ';
1495
                $query .= 'OR';
1496
            }
1497
            if(count($dois)>0){
1498
                $query=substr($query, 0, -2);
1499
            }
1500
            $query .= ')';
1501
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1502
            $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)
1503
                    :'search?action=search&sTransformer=results_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size   . '&locale=' . str_replace('-', '_', $locale);
1504
            if (($response = $this->performGet($completeQuery)) == NULL)
1505
                throw new Exception('no HTTP response');
1506
            if ($response->code != self :: HTTP_OK)
1507
                throw new Exception('HTTP response code ' . $response->code);
1508
            $document = new DOMDocument();
1509
            $document->recover = TRUE;
1510
            if ($document->loadXML($response->body) == FALSE)
1511
                throw new Exception('invalid XML response');
1512
            $xpath = new DOMXPath($document);
1513
            $result = new JObject();
1514
            $result->totalPublications = 0;
1515
            $result->totalDatasets = $this->parseTotalResults($xpath);
1516
            $result->datasets = $this->parsePublications($xpath);
1517
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
1518
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1519
                    //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));
1520
            JLog :: add('Simple search for DOIs retrieved ' . count($result->datasets) . ' datasets in ' . (microtime(TRUE) - $time) . ' s (query: ' . $query. ')', JLog :: INFO, self :: LOG);
1521
            return $result;
1522
        } catch (Exception $e) {
1523
            JLog :: add('Error performing dataset simple search for DOIs(query: ' . $query  . ', page: ' . $page . ', size: ' . $size . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
1524
            return NULL;
1525
        }
1526
    }
1527
    // Perform a simple search for projects.
1528
    // $keyword the keyword to search for
1529
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1530
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
1531
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1532
    // $startYear the start year to use as filter or NULL for no start year filtering
1533
    // $endYear the end year to suse as filter or NULL for no end year filtering
1534
    // $sc39 the SC-39 status to use as filter or NULL for no SC-39 status filtering
1535
    // $page the page of results to retrieve
1536
    // $size the size of the page of results to retrieve
1537
    // $locale the locale to use
1538
    // return a result (object) containing projects and statistics
1539
    private function _searchProjects($keyword, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine) {
1540
        try {
1541
            $time = microtime(TRUE);
1542
            $query = self :: PROJECT_QUERY;
1543
            $query .= ($keyword == NULL) ? '' : ' and ((' . self :: PROJECT_ACRONYM . ' = "' . str_replace('"', '\\"', $keyword) . '") or (' . self :: PROJECT_CODE . ' = "' . str_replace('"', '\\"', $keyword) . '") or (' . self :: PROJECT_TITLE . ' = "' . str_replace('"', '\\"', $keyword) . '"))';
1544
            $query .= ($funder == NULL) ? '' : (' and (' . self :: PROJECT_FUNDER . ' exact "' . $funder . '")');
1545
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1546
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PROJECT_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1547
            $query .= ($startYear == NULL) ? '' : (' and (' . self :: PROJECT_START_YEAR . ' exact ' . $startYear . ')');
1548
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM_LEVEL2. ' exact "' . $fundingStreamLevel2 . '")');
1549
            $query .= ($endYear == NULL) ? '' : (' and (' . self :: PROJECT_END_YEAR . ' exact ' . $endYear . ')');
1550
            $query .= ($sc39 === NULL) ? '' : (' and (' . self :: PROJECT_SC39 . ' exact ' . ($sc39 ? 'true' : 'false') . ')');
1551
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1552
            $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)
1553
                    :'search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
1554
            if (($response = $this->performGet($completeQuery)) == NULL)
1555
                throw new Exception('no HTTP response');
1556
            if ($response->code != self :: HTTP_OK)
1557
                throw new Exception('HTTP response code ' . $response->code);
1558
            $document = new DOMDocument();
1559
            $document->recover = TRUE;
1560
            if ($document->loadXML($response->body) == FALSE)
1561
                throw new Exception('invalid XML response');
1562
            $xpath = new DOMXPath($document);
1563
            $result = new JObject();
1564
            $result->totalProjects = $this->parseTotalResults($xpath);
1565
            $result->projects = $this->parseProjects($xpath);
1566
            $result->statistics = $isRefine?$this->createStatisticsForProjects($xpath,''):NULL;
1567
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1568
                    //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));
1569
            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);
1570
            return $result;
1571
        } catch (Exception $e) {
1572
            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);
1573
            return NULL;
1574
        }
1575
    }
1576

    
1577

    
1578
    // Perform a simple search for organizations.
1579
    // $keyword the keyword to search for
1580
    // $country the ID of the country to use as filter or NULL for no country filtering
1581
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
1582
    // $page the page of results to retrieve
1583
    // $size the size of the page of results to retrieve
1584
    // $locale the locale to use
1585
    // return a result (object) containing people and statistics
1586
    private function _searchOrganizations($keyword, $country, $type, $page, $size, $locale, $isRefine) {
1587
        try {
1588
            $time = microtime(TRUE);
1589
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
1590
            $query .= ($keyword == NULL) ? '' : (' and "' . str_replace('"', '\\"', $keyword) . '"');
1591
            $query .= ($country == NULL) ? '' : (' and (' . self :: ORGANIZATION_COUNTRY . ' exact "' . $country . '")');
1592
            switch ($type) {
1593
                case 'legalBody':
1594
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_BODY . ' exact true)';
1595
                    break;
1596
                case 'legalPerson':
1597
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_PERSON . ' exact true)';
1598
                    break;
1599
                case 'nonProfit':
1600
                    $query .= ' and (' . self :: ORGANIZATION_NON_PROFIT . ' exact true)';
1601
                    break;
1602
                case 'research':
1603
                    $query .= ' and (' . self :: ORGANIZATION_RESEARCH . ' exact true)';
1604
                    break;
1605
                case 'euInterests':
1606
                    $query .= ' and (' . self :: ORGANIZATION_EU_INTERESTS . ' exact true)';
1607
                    break;
1608
                case 'international':
1609
                    $query .= ' and (' . self :: ORGANIZATION_INTERNATIONAL . ' exact true)';
1610
                    break;
1611
                case 'enterprise':
1612
                    $query .= ' and (' . self :: ORGANIZATION_ENTERPRISE . ' exact true)';
1613
                    break;
1614
                case 'smallMediumEnterprise':
1615
                    $query .= ' and (' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . ' exact true)';
1616
            }
1617
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1618
            $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)
1619
                    :'search?action=search&sTransformer=organizations_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size .  '&locale=' . str_replace('-', '_', $locale);
1620
            if (($response = $this->performGet($completeQuery)) == NULL)
1621
                throw new Exception('no HTTP response');
1622
            if ($response->code != self :: HTTP_OK)
1623
                throw new Exception('HTTP response code ' . $response->code);
1624
            $document = new DOMDocument();
1625
            $document->recover = TRUE;
1626
            if ($document->loadXML($response->body) == FALSE)
1627
                throw new Exception('invalid XML response');
1628
            $xpath = new DOMXPath($document);
1629
            $result = new JObject();
1630
            $result->totalOrganizations = $this->parseTotalResults($xpath);
1631
            $result->organizations = $this->parseOrganizations($xpath);
1632
            if($isRefine){
1633
                $result->statistics = $this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
1634
                $result->statistics['type'] = new JObject();
1635
                $result->statistics['type']->id = 'type';
1636
                $result->statistics['type']->title = JText :: _('TYPE');
1637
                $result->statistics['type']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
1638
                $result->statistics['type']->data = array();
1639
                $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
1640
                if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
1641
                    $result->statistics['type']->data['legalBody'] = new JObject();
1642
                    $result->statistics['type']->data['legalBody']->id = 'legalBody';
1643
                    $result->statistics['type']->data['legalBody']->name = JText :: _('LEGAL_BODY');
1644
                    $result->statistics['type']->data['legalBody']->count = $legalBody['true']->count;
1645
                }
1646
                $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
1647
                if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
1648
                    $result->statistics['type']->data['legalPerson'] = new JObject();
1649
                    $result->statistics['type']->data['legalPerson']->id = 'legalPerson';
1650
                    $result->statistics['type']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
1651
                    $result->statistics['type']->data['legalPerson']->count = $legalPerson['true']->count;
1652
                }
1653
                $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
1654
                if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
1655
                    $result->statistics['type']->data['nonProfit'] = new JObject();
1656
                    $result->statistics['type']->data['nonProfit']->id = 'nonProfit';
1657
                    $result->statistics['type']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
1658
                    $result->statistics['type']->data['nonProfit']->count = $nonProfit['true']->count;
1659
                }
1660
                $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
1661
                if (($research != NULL) && array_key_exists('true', $research)) {
1662
                    $result->statistics['type']->data['research'] = new JObject();
1663
                    $result->statistics['type']->data['research']->id = 'research';
1664
                    $result->statistics['type']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
1665
                    $result->statistics['type']->data['research']->count = $research['true']->count;
1666
                }
1667
                $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
1668
                if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
1669
                    $result->statistics['type']->data['euInterests'] = new JObject();
1670
                    $result->statistics['type']->data['euInterests']->id = 'euInterests';
1671
                    $result->statistics['type']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
1672
                    $result->statistics['type']->data['euInterests']->count = $euInterests['true']->count;
1673
                }
1674
                $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
1675
                if (($international != NULL) && array_key_exists('true', $international)) {
1676
                    $result->statistics['type']->data['international'] = new JObject();
1677
                    $result->statistics['type']->data['international']->id = 'international';
1678
                    $result->statistics['type']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
1679
                    $result->statistics['type']->data['international']->count = $international['true']->count;
1680
                }
1681
                $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
1682
                if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
1683
                    $result->statistics['type']->data['enterprise'] = new JObject();
1684
                    $result->statistics['type']->data['enterprise']->id = 'enterprise';
1685
                    $result->statistics['type']->data['enterprise']->name = JText :: _('ENTERPRISE');
1686
                    $result->statistics['type']->data['enterprise']->count = $enterprise['true']->count;
1687
                }
1688
                $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
1689
                if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
1690
                    $result->statistics['type']->data['smallMediumEnterprise'] = new JObject();
1691
                    $result->statistics['type']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
1692
                    $result->statistics['type']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
1693
                    $result->statistics['type']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
1694
                }
1695
                uasort($result->statistics['type']->data, function ($row1, $row2) {
1696
                    return $row2->count - $row1->count;
1697
                });
1698
            }
1699
            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);
1700
            return $result;
1701
        } catch (Exception $e) {
1702
            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);
1703
            return NULL;
1704
        }
1705
    }
1706

    
1707
    // Perform a simple search for datasources.
1708
    // $keyword the keyword to search for
1709
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
1710
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
1711
    // $content the ID of the content to use as filter or NULL for no project filtering
1712
    // $compatibility the ID of the compatibility level to use as filter or NULL for no compatibility level filtering
1713
    // $page the page of results to retrieve
1714
    // $size the size of the page of results to retrieve
1715
    // $locale the locale to use
1716
    // return a result (object) containing datasources and statistics
1717
    private function _searchDatasources($keyword, $type, $language, $content, $compatibility, $page, $size, $locale, $isRefine) {
1718
        try {
1719
            $time = microtime(TRUE);
1720
            $query = self :: DATASOURCE_QUERY;
1721
            $query .= ($keyword == NULL) ? '' : (' and "' . str_replace('"', '\\"', $keyword) . '"');
1722
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASOURCE_TYPE . ' exact "' . $type . '")');
1723
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASOURCE_LANGUAGE . ' exact "' . $language . '")');
1724
            $query .= ($content == NULL) ? '' : (' and (' . self :: DATASOURCE_CONTENT . ' exact "' . $content . '")');
1725
            $query .= ($compatibility == NULL) ? '' : (' and (' . self :: DATASOURCE_COMPATIBILITY . ' exact "' . $compatibility . '")');
1726
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1727
            $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)
1728
                    :'search?action=search&sTransformer=datasources_openaire&query=' . urlencode('(' . $query . ')') . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
1729
            if (($response = $this->performGet($completeQuery)) == NULL)
1730
                throw new Exception('no HTTP response');
1731
            if ($response->code != self :: HTTP_OK)
1732
                throw new Exception('HTTP response code ' . $response->code);
1733
            $document = new DOMDocument();
1734
            $document->recover = TRUE;
1735
            if ($document->loadXML($response->body) == FALSE)
1736
                throw new Exception('invalid XML response');
1737
            $xpath = new DOMXPath($document);
1738
            $result = new JObject();
1739
            $result->totalDatasources = $this->parseTotalResults($xpath);
1740
            $result->datasources = $this->parseDatasources($xpath);
1741
            $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;
1742
            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);
1743
            return $result;
1744
        } catch (Exception $e) {
1745
            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);
1746
            return NULL;
1747
        }
1748
    }
1749

    
1750
    // Perform a browse for publications.
1751
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
1752
    // $language the ID of the language to use as filter or NULL for no language filtering
1753
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1754
    // $fundingStream the ID of the fundingStream to use as filter or NULL for no funding stream filtering
1755
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1756
    // $year the year of publication to use as filter or NULL for no year filtering
1757
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1758
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1759
    // $community the ID of the community to use as filter or NULL for no datasource filtering
1760
    // $page the page of results to retrieve
1761
    // $size the size of the page of results to retrieve
1762
    // $locale the locale to use
1763
    // $project the ID of the project to use as filter or NULL for no project filtering
1764
    // $author the ID of the author to use as filter or NULL for no author filtering
1765
    // return a result (object) containing publications and statistics
1766
    private function _browsePublications($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $community, $page, $size, $locale, $project, $author,$isRefine,$refineFields) {
1767
        try {
1768
            $time = microtime(TRUE);
1769
            $query = self :: PUBLICATION_QUERY;
1770
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
1771
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
1772
            if($funder != NULL && (strpos($funder, '---') !== FALSE)){
1773
                $temp='';
1774
                foreach(explode('---',$funder) as $id){
1775
                    if(!empty($id)){
1776
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
1777
                    }
1778

    
1779
                }
1780
                $query .=  (' and (' . substr($temp, 0, -4). ')');
1781
            }else{
1782
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
1783
            }
1784
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1785
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1786
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1787
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact ' . $year . ')');
1788
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
1789
            // $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
1790
            $datasource_id_array = explode("||", $datasource);
1791
            if(sizeof($datasource_id_array) > 1 ){
1792
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
1793
            }else{
1794
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE_ID . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE_ID . ' exact "' . $datasource . '") )');
1795
            }
1796
            // $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT . ' exact "' . $project . '")');
1797
            $project_id_array = explode("||", $project);
1798
            if(sizeof($project_id_array) > 1 ){
1799
                $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT . ' exact "' . $project . '")');
1800
            }else{
1801
              $query .= ($project == NULL) ? '' : (' and (' . self :: PUBLICATION_PROJECT_ID . ' exact "' . $project . '")');
1802
            }
1803
            $query .= ($author == NULL) ? '' : (' and (' . self :: PUBLICATION_AUTHOR_ID . ' exact "' . $author . '")');
1804
            $query .= ($community == NULL) ? '' : (' and (' . self :: PUBLICATION_CONTEXT . ' exact "' . $community . '")');
1805
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
1806
            $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):
1807
                'search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size  . '&locale=' . str_replace('-', '_', $locale);
1808
            if (($response = $this->performGet($completeQuery)) == NULL)
1809
                throw new Exception('no HTTP response');
1810
            if ($response->code != self :: HTTP_OK)
1811
                throw new Exception('HTTP response code ' . $response->code);
1812
            $document = new DOMDocument();
1813
            $document->recover = TRUE;
1814
            if ($document->loadXML($response->body) == FALSE)
1815
                throw new Exception('invalid XML response');
1816
            $xpath = new DOMXPath($document);
1817
            $result = new JObject();
1818
            $result->totalPublications = $this->parseTotalResults($xpath);
1819
            $result->publications = $this->parsePublications($xpath);
1820
            $result->statistics = $isRefine?$this->createStatisticsForPublications($xpath):NULL;
1821
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
1822
                    //$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));
1823
            $result->totalDatasets = 0;
1824
            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);
1825
            return $result;
1826
        } catch (Exception $e) {
1827
            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);
1828
            return NULL;
1829
        }
1830
    }
1831
    public static function pruningStatisticsForFunders($statistics, $funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2,$filter){
1832
        return self::_pruningStatisticsForFunders($statistics, $funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2,$filter);
1833
    }
1834
    private static function _pruningStatisticsForFunders($statistics, $funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2,$filter=''){
1835
        if($statistics==NULL){
1836
            return NULL;
1837
        }
1838
        if($fundingStreamLevel1!=NULL){
1839
           $newData= array();
1840
           foreach ($statistics["fundingStreamLevel2".$filter]->data as $data){
1841
               if(strpos($data->id,$fundingStreamLevel1)!==FALSE){
1842
                   $newData[$data->id]=$data;
1843
               }
1844
           }
1845
           $statistics["fundingStreamLevel2".$filter]->data=$newData;
1846
         }
1847
        if($fundingStream!=NULL){
1848
           $newData= array();
1849
           foreach ($statistics["fundingStreamLevel1".$filter]->data as $data){
1850
               if(strpos($data->id,$fundingStream)!==FALSE){
1851
                   $newData[$data->id]=$data;
1852
               }
1853
           }
1854
           $statistics["fundingStreamLevel1".$filter]->data=$newData;
1855
        }
1856
        if($funder!=NULL){
1857
           $newData= array();
1858
           if(strpos($funder, '---') !== FALSE){
1859
                foreach ($statistics["fundingStream".$filter]->data as $data){
1860
                   foreach(explode('---',$funder) as $id){                       
1861
                       if(!empty($id) && (strpos($data->id,explode("||",$id)[0])!==FALSE)){
1862
                        $newData[$data->id]=$data;
1863
                       }
1864
                   }
1865
               }
1866
           }else{
1867
               foreach ($statistics["fundingStream".$filter]->data as $data){
1868
                   $funder_id= explode("||",$funder)[0];
1869
                    if(strpos($data->id,$funder_id)!==FALSE){
1870
                        $newData[$data->id]=$data;
1871
                    }
1872
                }
1873
           }
1874
           $statistics["fundingStream".$filter]->data=$newData;
1875

    
1876
        }
1877
        return $statistics;
1878
    }
1879
    //Reduces the Funding Fields
1880
    //$funder filter for funder
1881
    //$fundingStream filter for funding stream
1882
    //$fundingStreamLevel1 filter for fundingStreamLevel1
1883
    //$fundingStreamLevel2 filter  for fundingStreamLevel2
1884
    private static function _getFundingFields($funder, $fundingStream, $fundingStreamLevel1, $fundingStreamLevel2, $type){
1885
            $field = self::_getFundingFieldsPerType($type);
1886
            $f = array();
1887
             $f[0]=true;
1888
            for($i=1;$i<4;$i++){
1889
                $f[$i]=false;
1890
            }
1891
            if($fundingStreamLevel2 !== null && !empty($fundingStreamLevel2)){
1892
                $f[3]=true;
1893
           }if($fundingStreamLevel1 !== NULL && strlen($fundingStreamLevel1)>0){
1894
               $f[2]=true;
1895
               $f[3]=true;
1896
            } if($fundingStream !== NULL && strlen($fundingStream)>0){
1897
                $f[1]=true;
1898
                $f[2]=true;
1899
            } if($funder !== NULL && strlen($funder)>0){
1900
                $f[0]=true;
1901
                $f[1]=true;
1902
            }
1903
            $returnedFields='';
1904
            $none=true;
1905
            for($i=0;$i<4;$i++){
1906
                if($f[$i]){
1907
                    $returnedFields.=($f[$i])?$field[$i]:'';
1908
                    $none=false;
1909
                }
1910
            }
1911
            $returnedFields=($none)?$field[0].$field[1]:$returnedFields;
1912
            return $returnedFields;
1913
        }
1914

    
1915
        private function _getFundingFieldsPerType($type){
1916
            $field=array();
1917
             switch ($type) {
1918
                case self::PUBLICATION:
1919
                    $field[3]='&fields=' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2;
1920
                    $field[2]='&fields=' . self :: PUBLICATION_SCIENTIFIC_AREA;
1921
                    $field[1]='&fields=' . self :: PUBLICATION_FUNDING_STREAM;
1922
                    $field[0]='&fields=' . self :: PUBLICATION_FUNDER;
1923
                    break;
1924
                case self::DATASET:
1925
                    $field[3]='&fields=' . self :: DATASET_FUNDING_STREAM_LEVEL2;
1926
                    $field[2]='&fields=' . self :: DATASET_SCIENTIFIC_AREA;
1927
                    $field[1]='&fields=' . self :: DATASET_FUNDING_STREAM;
1928
                    $field[0]='&fields=' . self :: DATASET_FUNDER;
1929
                    break;
1930
                case self::PROJECT:
1931
                    $field[3]='&fields=' . self :: PROJECT_FUNDING_STREAM_LEVEL2;
1932
                    $field[2]='&fields=' . self :: PROJECT_SCIENTIFIC_AREA;
1933
                    $field[1]='&fields=' . self :: PROJECT_FUNDING_STREAM;
1934
                    $field[0]='&fields=' . self :: PROJECT_FUNDER;
1935
                    break;
1936
             }
1937

    
1938
             return $field;
1939
        }
1940
    public function browsePublicationsRaw($query) {
1941
        try {
1942
            $time = microtime(TRUE);
1943

    
1944
            if (($response = $this->performGet($query)) == NULL)
1945
                throw new Exception('no HTTP response');
1946
            if ($response->code != self :: HTTP_OK)
1947
                throw new Exception('HTTP response code ' . $response->code);
1948
            JLog :: add('Browse publications raw  for query:'.$query.' in ' . (microtime(TRUE) - $time) , JLog :: INFO, self :: LOG);
1949
            return $response;
1950
        } catch (Exception $e) {
1951
            JLog :: add('Error performing publications browse raw', JLog :: ERROR, self :: LOG);
1952
            return NULL;
1953
        }
1954
    }
1955
     public function browseProjectsRaw($query) {
1956
        try {
1957
            $time = microtime(TRUE);
1958

    
1959
            if (($response = $this->performGet(str_replace(' ', '+', $query))) == NULL)
1960
                throw new Exception('no HTTP response');
1961
            if ($response->code != self :: HTTP_OK)
1962
                throw new Exception('HTTP response code ' . $response->code);
1963
            JLog :: add('Browse projects raw  for query:'.$query.' in ' . (microtime(TRUE) - $time) , JLog :: INFO, self :: LOG);
1964
            return $response;
1965
        } catch (Exception $e) {
1966
            JLog :: add('Error performing projects browse raw', JLog :: ERROR, self :: LOG);
1967
            return NULL;
1968
        }
1969
    }
1970
    // Perform a browse for datasets.
1971
    // $type the ID of the dataset type to use as filter or NULL for no dataset type filtering
1972
    // $language the ID of the language to use as filter or NULL for no language filtering
1973
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
1974
    // $fundingStream the ID of the fundingStream to use as filter or NULL for no funding stream filtering
1975
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
1976
    // $year the year of publication to use as filter or NULL for no year filtering
1977
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
1978
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
1979
    // $page the page of results to retrieve
1980
    // $size the size of the page of results to retrieve
1981
    // $locale the locale to use
1982
    // $project the ID of the project to use as filter or NULL for no project filtering
1983
    // $author the ID of the author to use as filter or NULL for no author filtering
1984
    // return a result (object) containing datasets and statistics
1985
    private function _browseDatasets($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine, $refineFields) {
1986
        try {
1987
            $time = microtime(TRUE);
1988
            $query = self :: DATASET_QUERY;
1989
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASET_TYPE . ' exact "' . $type . '")');
1990
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASET_LANGUAGE . ' exact "' . $language . '")');
1991
            $query .= ($funder == NULL) ? '' : (' and (' . self :: DATASET_FUNDER . ' exact "' . $funder . '")');
1992
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
1993
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: DATASET_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
1994
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
1995
            $query .= ($year == NULL) ? '' : (' and (' . self :: DATASET_YEAR . ' exact ' . $year . ')');
1996
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: DATASET_ACCESS_MODE . ' exact "' . $accessMode . '")');
1997

    
1998
            // $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
1999
            $datasource_id_array = explode("||", $datasource);
2000
            if(sizeof($datasource_id_array) > 1 ){
2001
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
2002
            }else{
2003
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE_ID . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE_ID . ' exact "' . $datasource . '") )');
2004
            }
2005
            // $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
2006
            $project_id_array = explode("||", $project);
2007
            if(sizeof($project_id_array) > 1 ){
2008
                $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
2009
            }else{
2010
              $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT_ID . ' exact "' . $project . '")');
2011
            }
2012
            $query .= ($author == NULL) ? '' : (' and (' . self :: DATASET_AUTHOR_ID . ' exact "' . $author . '")');
2013
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2014
            $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):
2015
                    'search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2016
            if (($response = $this->performGet($completeQuery)) == NULL)
2017
                throw new Exception('no HTTP response');
2018
            if ($response->code != self :: HTTP_OK)
2019
                throw new Exception('HTTP response code ' . $response->code);
2020
            $document = new DOMDocument();
2021
            $document->recover = TRUE;
2022
            if ($document->loadXML($response->body) == FALSE)
2023
                throw new Exception('invalid XML response');
2024
            $xpath = new DOMXPath($document);
2025
            $result = new JObject();
2026
            $result->totalDatasets = $this->parseTotalResults($xpath);
2027
            $result->datasets = $this->parseDatasets($xpath);
2028
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
2029
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
2030
                    //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));
2031
            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);
2032
            return $result;
2033
        } catch (Exception $e) {
2034
            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);
2035
            return NULL;
2036
        }
2037
    }
2038
    private function _browseSoftware($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine, $refineFields) {
2039
        try {
2040
            $time = microtime(TRUE);
2041
            $query = self :: SOFTWARE_QUERY;
2042
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASET_TYPE . ' exact "' . $type . '")');
2043
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASET_LANGUAGE . ' exact "' . $language . '")');
2044
            $query .= ($funder == NULL) ? '' : (' and (' . self :: DATASET_FUNDER . ' exact "' . $funder . '")');
2045
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2046
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: DATASET_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2047
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2048
            $query .= ($year == NULL) ? '' : (' and (' . self :: DATASET_YEAR . ' exact ' . $year . ')');
2049
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: DATASET_ACCESS_MODE . ' exact "' . $accessMode . '")');
2050

    
2051
            // $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
2052
            $datasource_id_array = explode("||", $datasource);
2053
            if(sizeof($datasource_id_array) > 1 ){
2054
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
2055
            }else{
2056
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE_ID . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE_ID . ' exact "' . $datasource . '") )');
2057
            }
2058
            // $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
2059
            $project_id_array = explode("||", $project);
2060
            if(sizeof($project_id_array) > 1 ){
2061
                $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
2062
            }else{
2063
              $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT_ID . ' exact "' . $project . '")');
2064
            }
2065
            $query .= ($author == NULL) ? '' : (' and (' . self :: DATASET_AUTHOR_ID . ' exact "' . $author . '")');
2066
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2067
            $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):
2068
                    'search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2069
            if (($response = $this->performGet($completeQuery)) == NULL)
2070
                throw new Exception('no HTTP response');
2071
            if ($response->code != self :: HTTP_OK)
2072
                throw new Exception('HTTP response code ' . $response->code);
2073
            $document = new DOMDocument();
2074
            $document->recover = TRUE;
2075
            if ($document->loadXML($response->body) == FALSE)
2076
                throw new Exception('invalid XML response');
2077
            $xpath = new DOMXPath($document);
2078
            $result = new JObject();
2079
            $result->totalDatasets = $this->parseTotalResults($xpath);
2080
            $result->datasets = $this->parseDatasets($xpath);
2081
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
2082
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
2083
                    //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));
2084
            JLog :: add('Browse retrieved ' . count($result->datasets) . ' software 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);
2085
            return $result;
2086
        } catch (Exception $e) {
2087
            JLog :: add('Error performing software 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);
2088
            return NULL;
2089
        }
2090
    }
2091
private function _browseOther($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine, $refineFields) {
2092
        try {
2093
            $time = microtime(TRUE);
2094
            $query = self :: OTHER_QUERY;
2095
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASET_TYPE . ' exact "' . $type . '")');
2096
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASET_LANGUAGE . ' exact "' . $language . '")');
2097
            $query .= ($funder == NULL) ? '' : (' and (' . self :: DATASET_FUNDER . ' exact "' . $funder . '")');
2098
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2099
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: DATASET_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2100
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2101
            $query .= ($year == NULL) ? '' : (' and (' . self :: DATASET_YEAR . ' exact ' . $year . ')');
2102
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: DATASET_ACCESS_MODE . ' exact "' . $accessMode . '")');
2103

    
2104
            // $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
2105
            $datasource_id_array = explode("||", $datasource);
2106
            if(sizeof($datasource_id_array) > 1 ){
2107
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
2108
            }else{
2109
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE_ID . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE_ID . ' exact "' . $datasource . '") )');
2110
            }
2111
            // $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
2112
            $project_id_array = explode("||", $project);
2113
            if(sizeof($project_id_array) > 1 ){
2114
                $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
2115
            }else{
2116
              $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT_ID . ' exact "' . $project . '")');
2117
            }
2118
//            $query .= ($author == NULL) ? '' : (' and (' . self :: DATASET_AUTHOR_ID . ' exact "' . $author . '")');
2119
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2120
            $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):
2121
                    'search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2122
            if (($response = $this->performGet($completeQuery)) == NULL)
2123
                throw new Exception('no HTTP response');
2124
            if ($response->code != self :: HTTP_OK)
2125
                throw new Exception('HTTP response code ' . $response->code);
2126
            $document = new DOMDocument();
2127
            $document->recover = TRUE;
2128
            if ($document->loadXML($response->body) == FALSE)
2129
                throw new Exception('invalid XML response');
2130
            $xpath = new DOMXPath($document);
2131
            $result = new JObject();
2132
            $result->totalDatasets = $this->parseTotalResults($xpath);
2133
            $result->datasets = $this->parseDatasets($xpath);
2134
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
2135
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
2136
                    //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));
2137
            JLog :: add('Browse retrieved ' . count($result->datasets) . ' other results 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);
2138
            return $result;
2139
        } catch (Exception $e) {
2140
            JLog :: add('Error performing other results 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);
2141
            return NULL;
2142
        }
2143
    }
2144
    private function _browseResults($type, $language, $funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $year, $accessMode, $datasource, $page, $size, $locale, $project, $author, $isRefine, $refineFields) {
2145
        try {
2146
            $time = microtime(TRUE);
2147
            $query = self :: RESULT_QUERY;
2148
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASET_TYPE . ' exact "' . $type . '")');
2149
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASET_LANGUAGE . ' exact "' . $language . '")');
2150
            $query .= ($funder == NULL) ? '' : (' and (' . self :: DATASET_FUNDER . ' exact "' . $funder . '")');
2151
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2152
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: DATASET_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2153
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: DATASET_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2154
            $query .= ($year == NULL) ? '' : (' and (' . self :: DATASET_YEAR . ' exact ' . $year . ')');
2155
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: DATASET_ACCESS_MODE . ' exact "' . $accessMode . '")');
2156

    
2157
            // $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
2158
            $datasource_id_array = explode("||", $datasource);
2159
            if(sizeof($datasource_id_array) > 1 ){
2160
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE . ' exact "' . $datasource . '") )');
2161
            }else{
2162
                $query .= ($datasource == NULL) ? '' : (' and ((' . self :: RESULT_HOSTING_DATASOURCE_ID . ' exact "' . $datasource . '") or (' . self :: RESULT_COLLECTED_FROM_DATASOURCE_ID . ' exact "' . $datasource . '") )');
2163
            }
2164
            // $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
2165
            $project_id_array = explode("||", $project);
2166
            if(sizeof($project_id_array) > 1 ){
2167
                $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT . ' exact "' . $project . '")');
2168
            }else{
2169
              $query .= ($project == NULL) ? '' : (' and (' . self :: DATASET_PROJECT_ID . ' exact "' . $project . '")');
2170
            }
2171
//            $query .= ($author == NULL) ? '' : (' and (' . self :: DATASET_AUTHOR_ID . ' exact "' . $author . '")');
2172
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2173
            $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):
2174
                    'search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2175
            if (($response = $this->performGet($completeQuery)) == NULL)
2176
                throw new Exception('no HTTP response');
2177
            if ($response->code != self :: HTTP_OK)
2178
                throw new Exception('HTTP response code ' . $response->code);
2179
            $document = new DOMDocument();
2180
            $document->recover = TRUE;
2181
            if ($document->loadXML($response->body) == FALSE)
2182
                throw new Exception('invalid XML response');
2183
            $xpath = new DOMXPath($document);
2184
            $result = new JObject();
2185
            $result->totalDatasets = $this->parseTotalResults($xpath);
2186
            $result->datasets = $this->parseDatasets($xpath);
2187
            $result->statistics = $isRefine?$this->createStatisticsForDatasets($xpath):NULL;
2188
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
2189
                    //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));
2190
            JLog :: add('Browse retrieved ' . count($result->datasets) . ' other results 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);
2191
            return $result;
2192
        } catch (Exception $e) {
2193
            JLog :: add('Error performing research results 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);
2194
            return NULL;
2195
        }
2196
    }
2197
    // Perform a browse for projects.
2198
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2199
    // $fundingStream the ID of the fundingStream to use as filter or NULL for no funding stream filtering
2200
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2201
    // $startYear the start year to use as filter or NULL for no start year filtering
2202
    // $endYear the end year to use as filter or NULL for no end year filtering
2203
    // $$sc39 the SC-39 status to use as filter or NULL for no SC-39 status filtering
2204
    // $page the page of results to retrieve
2205
    // $size the size of the page of results to retrieve
2206
    // $locale the locale to use
2207
    // return a result (object) containing projects and statistics
2208
    private function _browseProjects($funder, $fundingStream, $scientificArea, $fundingStreamLevel2, $startYear, $endYear, $sc39, $page, $size, $locale, $isRefine) {
2209
        try {
2210
            $time = microtime(TRUE);
2211
            $query = self :: PROJECT_QUERY;
2212
            if($funder != NULL && (strpos($funder, ',') !== FALSE)){
2213
                $temp='';
2214
                foreach(explode(',',$funder) as $id){
2215
                    if(!empty($id)){
2216
                        $temp.='(' . self :: PROJECT_FUNDER . ' exact "' . $id . '") and';
2217
                    }
2218

    
2219
                }
2220
                $query .=  (' and (' . substr($temp, 0, -3). ')');
2221
            }else{
2222
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PROJECT_FUNDER . ' exact "' . $funder . '")');
2223
            }
2224
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2225
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PROJECT_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2226
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2227
            $query .= ($startYear == NULL) ? '' : (' and (' . self :: PROJECT_START_YEAR . ' exact ' . $startYear . ')');
2228
            $query .= ($endYear == NULL) ? '' : (' and (' . self :: PROJECT_END_YEAR . ' exact ' . $endYear . ')');
2229
            $query .= ($sc39 === NULL) ? '' : (' and (' . self :: PROJECT_SC39 . ' exact ' . ($sc39 ? 'true' : 'false') . ')');
2230
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2231
            $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)
2232
                    :'search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2233
            if (($response = $this->performGet($completeQuery)) == NULL)
2234
                throw new Exception('no HTTP response');
2235
            if ($response->code != self :: HTTP_OK)
2236
                throw new Exception('HTTP response code ' . $response->code);
2237
            $document = new DOMDocument();
2238
            $document->recover = TRUE;
2239
            if ($document->loadXML($response->body) == FALSE)
2240
                throw new Exception('invalid XML response');
2241
            $xpath = new DOMXPath($document);
2242
            $result = new JObject();
2243
            $result->totalProjects = $this->parseTotalResults($xpath);
2244
            $result->projects = $this->parseProjects($xpath);
2245
            $result->statistics = $isRefine? $this->createStatisticsForProjects($xpath):NULL;
2246
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,'');
2247
                    //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));
2248
            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);
2249
            return $result;
2250
        } catch (Exception $e) {
2251
            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);
2252
            return NULL;
2253
        }
2254
    }
2255

    
2256
                
2257

    
2258
    // Perform a browse for organizations.
2259
    // $country the ID of the country to use as filter or NULL for no country filtering
2260
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
2261
    // $page the page of results to retrieve
2262
    // $size the size of the page of results to retrieve
2263
    // $locale the locale to use
2264
    // return a result (object) containing organizations and statistics
2265
    private function _browseOrganizations($country, $type, $page, $size, $locale, $isRefine) {
2266
        try {
2267
            $time = microtime(TRUE);
2268
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
2269
            $query .= ($country == NULL) ? '' : (' and (' . self :: ORGANIZATION_COUNTRY . ' exact "' . $country . '")');
2270
            switch ($type) {
2271
                case 'legalBody':
2272
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_BODY . ' exact true)';
2273
                    break;
2274
                case 'legalPerson':
2275
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_PERSON . ' exact true)';
2276
                    break;
2277
                case 'nonProfit':
2278
                    $query .= ' and (' . self :: ORGANIZATION_NON_PROFIT . ' exact true)';
2279
                    break;
2280
                case 'research':
2281
                    $query .= ' and (' . self :: ORGANIZATION_RESEARCH . ' exact true)';
2282
                    break;
2283
                case 'euInterests':
2284
                    $query .= ' and (' . self :: ORGANIZATION_EU_INTERESTS . ' exact true)';
2285
                    break;
2286
                case 'international':
2287
                    $query .= ' and (' . self :: ORGANIZATION_INTERNATIONAL . ' exact true)';
2288
                    break;
2289
                case 'enterprise':
2290
                    $query .= ' and (' . self :: ORGANIZATION_ENTERPRISE . ' exact true)';
2291
                    break;
2292
                case 'smallMediumEnterprise':
2293
                    $query .= ' and (' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . ' exact true)';
2294
            }
2295
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2296
            $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)
2297
                    :'search?action=searchsTransformer=organizations_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2298
            if (($response = $this->performGet($completeQuery)) == NULL)
2299
                throw new Exception('no HTTP response');
2300
            if ($response->code != self :: HTTP_OK)
2301
                throw new Exception('HTTP response code ' . $response->code);
2302
            $document = new DOMDocument();
2303
            $document->recover = TRUE;
2304
            if ($document->loadXML($response->body) == FALSE)
2305
                throw new Exception('invalid XML response');
2306
            $xpath = new DOMXPath($document);
2307
            $result = new JObject();
2308
            $result->totalOrganizations = $this->parseTotalResults($xpath);
2309
            $result->organizations = $this->parseOrganizations($xpath);
2310
            if($isRefine){
2311
                $result->statistics = $this->createStatistics($xpath, array('country'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
2312
                $result->statistics['type'] = new JObject();
2313
                $result->statistics['type']->id = 'type';
2314
                $result->statistics['type']->title = JText :: _('TYPE');
2315
                $result->statistics['type']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
2316
                $result->statistics['type']->data = array();
2317
                $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
2318
                if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
2319
                    $result->statistics['type']->data['legalBody'] = new JObject();
2320
                    $result->statistics['type']->data['legalBody']->id = 'legalBody';
2321
                    $result->statistics['type']->data['legalBody']->name = JText :: _('LEGAL_BODY');
2322
                    $result->statistics['type']->data['legalBody']->count = $legalBody['true']->count;
2323
                }
2324
                $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
2325
                if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
2326
                    $result->statistics['type']->data['legalPerson'] = new JObject();
2327
                    $result->statistics['type']->data['legalPerson']->id = 'legalPerson';
2328
                    $result->statistics['type']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
2329
                    $result->statistics['type']->data['legalPerson']->count = $legalPerson['true']->count;
2330
                }
2331
                $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
2332
                if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
2333
                    $result->statistics['type']->data['nonProfit'] = new JObject();
2334
                    $result->statistics['type']->data['nonProfit']->id = 'nonProfit';
2335
                    $result->statistics['type']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
2336
                    $result->statistics['type']->data['nonProfit']->count = $nonProfit['true']->count;
2337
                }
2338
                $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
2339
                if (($research != NULL) && array_key_exists('true', $research)) {
2340
                    $result->statistics['type']->data['research'] = new JObject();
2341
                    $result->statistics['type']->data['research']->id = 'research';
2342
                    $result->statistics['type']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
2343
                    $result->statistics['type']->data['research']->count = $research['true']->count;
2344
                }
2345
                $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
2346
                if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
2347
                    $result->statistics['type']->data['euInterests'] = new JObject();
2348
                    $result->statistics['type']->data['euInterests']->id = 'euInterests';
2349
                    $result->statistics['type']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
2350
                    $result->statistics['type']->data['euInterests']->count = $euInterests['true']->count;
2351
                }
2352
                $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
2353
                if (($international != NULL) && array_key_exists('true', $international)) {
2354
                    $result->statistics['type']->data['international'] = new JObject();
2355
                    $result->statistics['type']->data['international']->id = 'international';
2356
                    $result->statistics['type']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
2357
                    $result->statistics['type']->data['international']->count = $international['true']->count;
2358
                }
2359
                $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
2360
                if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
2361
                    $result->statistics['type']->data['enterprise'] = new JObject();
2362
                    $result->statistics['type']->data['enterprise']->id = 'enterprise';
2363
                    $result->statistics['type']->data['enterprise']->name = JText :: _('ENTERPRISE');
2364
                    $result->statistics['type']->data['enterprise']->count = $enterprise['true']->count;
2365
                }
2366
                $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
2367
                if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
2368
                    $result->statistics['type']->data['smallMediumEnterprise'] = new JObject();
2369
                    $result->statistics['type']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
2370
                    $result->statistics['type']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
2371
                    $result->statistics['type']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
2372
                }
2373
                uasort($result->statistics['type']->data, function ($row1, $row2) {
2374
                    return $row2->count - $row1->count;
2375
                });
2376
            }
2377
            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);
2378
            return $result;
2379
        } catch (Exception $e) {
2380
            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);
2381
            return NULL;
2382
        }
2383
    }
2384

    
2385
    // Perform a browse for datasources.
2386
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
2387
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
2388
    // $content the ID of the content to use as filter or NULL for no content filtering
2389
    // $compatibility the ID of the compatibility level to use as filter or NULL for no compatibility status filtering
2390
    // $page the page of results to retrieve
2391
    // $size the size of the page of results to retrieve
2392
    // $locale the locale to use
2393
    // return a result (object) containing datasources and statistics
2394
    private function _browseDatasources($type, $language, $content, $compatibility, $page, $size, $locale, $isRefine) {
2395
        try {
2396
            $time = microtime(TRUE);
2397
            $query = self :: DATASOURCE_QUERY;
2398
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASOURCE_TYPE . ' exact "' . $type . '")');
2399
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASOURCE_LANGUAGE . ' exact "' . $language . '")');
2400
            $query .= ($content == NULL) ? '' : (' and (' . self :: DATASOURCE_CONTENT . ' exact "' . $content . '")');
2401
            $query .= ($compatibility == NULL) ? '' : (' and (' . self :: DATASOURCE_COMPATIBILITY . ' exact "' . $compatibility . '")');
2402
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2403
            $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):
2404
                'search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&page=' . $page . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale);
2405
            if (($response = $this->performGet($completeQuery)) == NULL)
2406
                throw new Exception('no HTTP response');
2407
            if ($response->code != self :: HTTP_OK)
2408
                throw new Exception('HTTP response code ' . $response->code);
2409
            $document = new DOMDocument();
2410
            $document->recover = TRUE;
2411
            if ($document->loadXML($response->body) == FALSE)
2412
                throw new Exception('invalid XML response');
2413
            $xpath = new DOMXPath($document);
2414
            $result = new JObject();
2415
            $result->totalDatasources = $this->parseTotalResults($xpath);
2416
            $result->datasources = $this->parseDatasources($xpath);
2417
            $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;
2418
            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);
2419
            return $result;
2420
        } catch (Exception $e) {
2421
            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);
2422
            return NULL;
2423
        }
2424
    }
2425

    
2426
    // Perform an advanced search for publications.
2427
    // $keywords the keywords to search for (array)
2428
    // $fields the fields to match keywords with (array - possible values are TITLE, AUTHOR, PUBLISHER and SUBJECT)
2429
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2430
    // $types the IDs of the publication types to search for
2431
    // $languages the IDs of the publication languages to search for
2432
    // $funders the IDs of the funders to search for
2433
    // $fundingStreams the IDs of the funding streams to search for
2434
    // $scientificAreas the IDs of the scientific areas to search for
2435
    // $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)
2436
    // $fromMonth start month of the publication date range to search for if $date has value 0
2437
    // $fromYear start year of the publication date range to search for if $date has value 0
2438
    // $toMonth end month of the publication date range to search for if $date has value 0
2439
    // $toYear end year of the publication date range to search for if $date has value 0
2440
    // $accessModes the IDs of the access modes to search for
2441
    // $datasources the IDs of the datasources to search for
2442
    // $type the ID of the publication type to use as filter or NULL for no publication type filtering
2443
    // $language the ID of the publication language to use as filter or NULL for no publication language filtering
2444
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2445
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
2446
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2447
    // $year the publication year to use as filter or NULL for no publication year filtering
2448
    // $accessMode the ID of the access mode to use as filter or NULL for no access mode filtering
2449
    // $datasource the ID of the datasource to use as filter or NULL for no datasource filtering
2450
    // $page the page of results to retrieve
2451
    // $size the size of the page of results to retrieve
2452
    // $locale the locale to use
2453
    // return a result (object) containing publications and statistics
2454
    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) {
2455
        try {
2456
            $time = microtime(TRUE);
2457
            $query = self :: PUBLICATION_QUERY;
2458
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2459
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2460
                switch ($constraints[$i]) {
2461
                    case self :: ALL:
2462
                        $operator = ' and ';
2463
                        break;
2464
                    case self :: ANY:
2465
                        $operator = ' or ';
2466
                        break;
2467
                    default:
2468
                        $operator = NULL;
2469
                }
2470
                switch ($fields[$i]) {
2471
                    case OpenAireViewAdvancedSearchPublications :: TITLE:
2472
                        $field = self :: PUBLICATION_TITLE;
2473
                        break;
2474
                    case OpenAireViewAdvancedSearchPublications :: AUTHOR:
2475
                        $field = self :: PUBLICATION_AUTHOR;
2476
                        break;
2477
                    case OpenAireViewAdvancedSearchPublications :: PUBLISHER:
2478
                        $field = self :: PUBLICATION_PUBLISHER;
2479
                        break;
2480
                    case OpenAireViewAdvancedSearchPublications :: SUBJECT:
2481
                        $field = self :: PUBLICATION_SUBJECT;
2482
                        break;
2483
                    default:
2484
                        $field = NULL;
2485
                }
2486
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2487
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2488
                                }, $tokens)) . ')');
2489
            }
2490
            $field = self :: PUBLICATION_TYPE;
2491
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($field) {
2492
                                return '(' . $field . ' exact "' . $type . '")';
2493
                            }, $types)) . ')');
2494
            $field = self :: PUBLICATION_LANGUAGE;
2495
            $query .= ($languages == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($language) use ($field) {
2496
                                return '(' . $field . ' exact "' . $language . '")';
2497
                            }, $languages)) . ')');
2498
            $field = self :: PUBLICATION_FUNDER;
2499
            $query .= ($funders == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($funder) use ($field) {
2500
                                return '(' . $field . ' exact "' . $funder . '")';
2501
                            }, $funders)) . ')');
2502
            $field = self :: PUBLICATION_FUNDING_STREAM;
2503
            $query .= ($fundingStreams == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStream) use ($field) {
2504
                                return '(' . $field . ' exact "' . $fundingStream . '")';
2505
                            }, $fundingStreams)) . ')');
2506
            $field = self :: PUBLICATION_SCIENTIFIC_AREA;
2507
            $query .= ($scientificAreas == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($scientificArea) use ($field) {
2508
                                return '(' . $field . ' exact "' . $scientificArea . '")';
2509
                            }, $scientificAreas)) . ')');
2510
            $field = self :: PUBLICATION_FUNDING_STREAM_LEVEL2;
2511
            $query .= ($fundingStreamsLevel2 == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStreamsLevel2) use ($field) {
2512
                                return '(' . $field . ' exact "' . $fundingStreamsLevel2 . '")';
2513
                            }, $fundingStreamsLevel2)) . ')');
2514
            $from = new DateTime();
2515
            $to = new DateTime();
2516
            switch ($date) {
2517
                case -1:
2518
                    break;
2519
                case 0:
2520
                    $from->setDate($fromYear, $fromMonth, 1);
2521
                    $to->setDate($toYear, $toMonth, 1);
2522
                    $to->setDate($toYear, $toMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2523
                    $query .= ' and (' . self :: PUBLICATION_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2524
                    break;
2525
                default:
2526
                    $from->sub(new DateInterval('P' . $date . 'M'));
2527
                    $query .= ' and (' . self :: PUBLICATION_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2528
            }
2529
            $field = self :: PUBLICATION_ACCESS_MODE;
2530
            $query .= ($accessModes == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($accessMode) use ($field) {
2531
                                return '(' . $field . ' exact "' . $accessMode . '")';
2532
                            }, $accessModes)) . ')');
2533
            $field = self :: RESULT_HOSTING_DATASOURCE;
2534
            $query .= ($datasources == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($datasource) use ($field) {
2535
                                return '(' . $field . ' exact "' . $datasource . '")';
2536
                            }, $datasources)) . ')');
2537
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
2538
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
2539
            //$query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
2540
              if($funder != NULL && (strpos($funder, ',') !== FALSE)){
2541
                $temp='';
2542
                foreach(explode(',',$funder) as $id){
2543
                    if(!empty($id)){
2544
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
2545
                    }
2546

    
2547
                }
2548
                $query .=  (' and (' . substr($temp, 0, -3). ')');
2549
            }else{
2550
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
2551
            }
2552
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2553
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2554
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2555
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact "' . $year . '")');
2556
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
2557
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '")');
2558
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2559
            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)
2560
                throw new Exception('no HTTP response');
2561
            if ($response->code != self :: HTTP_OK)
2562
                throw new Exception('HTTP response code ' . $response->code);
2563
            $document = new DOMDocument();
2564
            $document->recover = TRUE;
2565
            if ($document->loadXML($response->body) == FALSE)
2566
                throw new Exception('invalid XML response');
2567
            $xpath = new DOMXPath($document);
2568
            $result = new JObject();
2569
            $result->totalPublications = $this->parseTotalResults($xpath);
2570
            $result->publications = $this->parsePublications($xpath);
2571
            $result->statistics =$this->createStatisticsForPublications($xpath,'Filter');
2572
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,"Filter");
2573
                    //$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));
2574
            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);
2575
            return $result;
2576
        } catch (Exception $e) {
2577
            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);
2578
            return NULL;
2579
        }
2580
    }
2581
    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) {
2582
        try {
2583
            $time = microtime(TRUE);
2584
            $query = self :: DATASET_QUERY;
2585
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2586
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2587
                switch ($constraints[$i]) {
2588
                    case self :: ALL:
2589
                        $operator = ' and ';
2590
                        break;
2591
                    case self :: ANY:
2592
                        $operator = ' or ';
2593
                        break;
2594
                    default:
2595
                        $operator = NULL;
2596
                }
2597
                switch ($fields[$i]) {
2598
                    case OpenAireViewAdvancedSearchPublications :: TITLE:
2599
                        $field = self :: PUBLICATION_TITLE;
2600
                        break;
2601
                    case OpenAireViewAdvancedSearchPublications :: AUTHOR:
2602
                        $field = self :: PUBLICATION_AUTHOR;
2603
                        break;
2604
                    case OpenAireViewAdvancedSearchPublications :: PUBLISHER:
2605
                        $field = self :: PUBLICATION_PUBLISHER;
2606
                        break;
2607
                    case OpenAireViewAdvancedSearchPublications :: SUBJECT:
2608
                        $field = self :: PUBLICATION_SUBJECT;
2609
                        break;
2610
                    default:
2611
                        $field = NULL;
2612
                }
2613
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2614
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2615
                                }, $tokens)) . ')');
2616
            }
2617
            $field = self :: PUBLICATION_TYPE;
2618
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($field) {
2619
                                return '(' . $field . ' exact "' . $type . '")';
2620
                            }, $types)) . ')');
2621
            $field = self :: PUBLICATION_LANGUAGE;
2622
            $query .= ($languages == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($language) use ($field) {
2623
                                return '(' . $field . ' exact "' . $language . '")';
2624
                            }, $languages)) . ')');
2625
            $field = self :: PUBLICATION_FUNDER;
2626
            $query .= ($funders == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($funder) use ($field) {
2627
                                return '(' . $field . ' exact "' . $funder . '")';
2628
                            }, $funders)) . ')');
2629
            $field = self :: PUBLICATION_FUNDING_STREAM;
2630
            $query .= ($fundingStreams == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStream) use ($field) {
2631
                                return '(' . $field . ' exact "' . $fundingStream . '")';
2632
                            }, $fundingStreams)) . ')');
2633
            $field = self :: PUBLICATION_SCIENTIFIC_AREA;
2634
            $query .= ($scientificAreas == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($scientificArea) use ($field) {
2635
                                return '(' . $field . ' exact "' . $scientificArea . '")';
2636
                            }, $scientificAreas)) . ')');
2637
            $field = self :: PUBLICATION_FUNDING_STREAM_LEVEL2;
2638
            $query .= ($fundingStreamsLevel2 == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStreamsLevel2) use ($field) {
2639
                                return '(' . $field . ' exact "' . $fundingStreamsLevel2 . '")';
2640
                            }, $fundingStreamsLevel2)) . ')');
2641
            $from = new DateTime();
2642
            $to = new DateTime();
2643
            switch ($date) {
2644
                case -1:
2645
                    break;
2646
                case 0:
2647
                    $from->setDate($fromYear, $fromMonth, 1);
2648
                    $to->setDate($toYear, $toMonth, 1);
2649
                    $to->setDate($toYear, $toMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2650
                    $query .= ' and (' . self :: PUBLICATION_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2651
                    break;
2652
                default:
2653
                    $from->sub(new DateInterval('P' . $date . 'M'));
2654
                    $query .= ' and (' . self :: PUBLICATION_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2655
            }
2656
            $field = self :: PUBLICATION_ACCESS_MODE;
2657
            $query .= ($accessModes == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($accessMode) use ($field) {
2658
                                return '(' . $field . ' exact "' . $accessMode . '")';
2659
                            }, $accessModes)) . ')');
2660
            $field = self :: RESULT_HOSTING_DATASOURCE;
2661
            $query .= ($datasources == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($datasource) use ($field) {
2662
                                return '(' . $field . ' exact "' . $datasource . '")';
2663
                            }, $datasources)) . ')');
2664
            $query .= ($type == NULL) ? '' : (' and (' . self :: PUBLICATION_TYPE . ' exact "' . $type . '")');
2665
            $query .= ($language == NULL) ? '' : (' and (' . self :: PUBLICATION_LANGUAGE . ' exact "' . $language . '")');
2666
            //$query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
2667
              if($funder != NULL && (strpos($funder, ',') !== FALSE)){
2668
                $temp='';
2669
                foreach(explode(',',$funder) as $id){
2670
                    if(!empty($id)){
2671
                        $temp.='(' . self :: PUBLICATION_FUNDER . ' exact "' . $id . '") and';
2672
                    }
2673

    
2674
                }
2675
                $query .=  (' and (' . substr($temp, 0, -3). ')');
2676
            }else{
2677
                $query .= ($funder == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDER . ' exact "' . $funder . '")');
2678
            }
2679
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2680
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PUBLICATION_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2681
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PUBLICATION_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2682
            $query .= ($year == NULL) ? '' : (' and (' . self :: PUBLICATION_YEAR . ' exact "' . $year . '")');
2683
            $query .= ($accessMode == NULL) ? '' : (' and (' . self :: PUBLICATION_ACCESS_MODE . ' exact "' . $accessMode . '")');
2684
            $query .= ($datasource == NULL) ? '' : (' and (' . self :: RESULT_HOSTING_DATASOURCE . ' exact "' . $datasource . '")');
2685
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2686
            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)
2687
                throw new Exception('no HTTP response');
2688
            if ($response->code != self :: HTTP_OK)
2689
                throw new Exception('HTTP response code ' . $response->code);
2690
            $document = new DOMDocument();
2691
            $document->recover = TRUE;
2692
            if ($document->loadXML($response->body) == FALSE)
2693
                throw new Exception('invalid XML response');
2694
            $xpath = new DOMXPath($document);
2695
            $result = new JObject();
2696
            $result->totalDatasets = $this->parseTotalResults($xpath);
2697
            $result->datasets = $this->parsePublications($xpath);
2698
            $result->statistics =$this->createStatisticsForPublications($xpath,'Filter');
2699
            $result->statistics=self ::_pruningStatisticsForFunders($result->statistics,$funder, $fundingStream, $scientificArea, $fundingStreamLevel2,"Filter");
2700
                    //$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));
2701
            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);
2702
            return $result;
2703
        } catch (Exception $e) {
2704
            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);
2705
            return NULL;
2706
        }
2707
    }
2708

    
2709
    // Perform an advanced search for projects.
2710
    // $keywords the keywords to search for (array)
2711
    // $fields the fields to match keywords with (array - possible values are ACRONYM, TITLE and KEYWORDS)
2712
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2713
    // $funders the IDs of the funders to search for
2714
    // $fundingStreams the IDs of the funding streams to search for
2715
    // $scientificAreas the IDs of the scientific areas to search for
2716
    // $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)
2717
    // $startFromMonth start month of the start date range to search for if $startDate has value 0
2718
    // $startFromYear start year of the start date range to search for if $startDate has value 0
2719
    // $startToMonth end month of the start date range to search for if $startDate has value 0
2720
    // $startToYear end year of the start date range to search for if $startDate has value 0
2721
    // $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)
2722
    // $endFromMonth start month of the end date range to search for if $endDate has value 0
2723
    // $endFromYear start year of the end date range to search for if $endDate has value 0
2724
    // $endToMonth end month of the end date range to search for if $endDate has value 0
2725
    // $endToYear end year of the end date range to search for if $endDate has value 0
2726
    // $sc39s the IDs of the SC-39 statuses to search for
2727
    // $funder the ID of the funder to use as filter or NULL for no funder filtering
2728
    // $fundingStream the ID of the funding stream to use as filter or NULL for no funding stream filtering
2729
    // $scientificArea the ID of the scientific area to use as filter or NULL for no scientific area filtering
2730
    // $startYear the start year to use as filter or NULL for no start year filtering
2731
    // $endYear the end year to use as filter or NULL for no end year filtering
2732
    // $sc39 the ID of the SC-39 status to use as filter or NULL for no SC-39 status filtering
2733
    // $page the page of results to retrieve
2734
    // $size the size of the page of results to retrieve
2735
    // $locale the locale to use
2736
    // return a result (object) containing projects and statistics
2737
    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) {
2738
        try {
2739
            $time = microtime(TRUE);
2740
            $query = self :: PROJECT_QUERY;
2741
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2742
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2743
                switch ($constraints[$i]) {
2744
                    case OpenAireViewAdvancedSearchProjects :: ALL:
2745
                        $operator = ' and ';
2746
                        break;
2747
                    case OpenAireViewAdvancedSearchProjects :: ANY:
2748
                        $operator = ' or ';
2749
                        break;
2750
                    default:
2751
                        $operator = NULL;
2752
                }
2753
                switch ($fields[$i]) {
2754
                    case OpenAireViewAdvancedSearchProjects :: ACRONYM:
2755
                        $field = self :: PROJECT_ACRONYM;
2756
                        break;
2757
                    case OpenAireViewAdvancedSearchProjects :: TITLE:
2758
                        $field = self :: PROJECT_TITLE;
2759
                        break;
2760
                    case OpenAireViewAdvancedSearchProjects :: KEYWORDS:
2761
                        $field = self :: PROJECT_KEYWORDS;
2762
                        break;
2763
                    default:
2764
                        $field = NULL;
2765
                }
2766
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2767
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2768
                                }, $tokens)) . ')');
2769
            }
2770
            $field = self :: PROJECT_FUNDER;
2771
            $query .= ($funders == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($funder) use ($field) {
2772
                                return '(' . $field . ' exact "' . $funder . '")';
2773
                            }, $funders)) . ')');
2774
            $field = self :: PROJECT_FUNDING_STREAM;
2775
            $query .= ($fundingStreams == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStream) use ($field) {
2776
                                return '(' . $field . ' exact "' . $fundingStream . '")';
2777
                            }, $fundingStreams)) . ')');
2778
            $field = self :: PROJECT_SCIENTIFIC_AREA;
2779
            $query .= ($scientificAreas == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($scientificArea) use ($field) {
2780
                                return '(' . $field . ' exact "' . $scientificArea . '")';
2781
                            }, $scientificAreas)) . ')');
2782
            $field = self :: PROJECT_FUNDING_STREAM_LEVEL2;
2783
            $query .= ($fundingStreamsLevel2 == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($fundingStreamsLevel2) use ($field) {
2784
                                return '(' . $field . ' exact "' . $fundingStreamsLevel2 . '")';
2785
                            }, $scientificAreas)) . ')');
2786
            $from = new DateTime();
2787
            $to = new DateTime();
2788
            switch ($startDate) {
2789
                case -1:
2790
                    break;
2791
                case 0:
2792
                    $from->setDate($startFromYear, $startFromMonth, 1);
2793
                    $to->setDate($startToYear, $startToMonth, 1);
2794
                    $to->setDate($startToYear, $startToMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2795
                    $query .= ' and (' . self :: PROJECT_START_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2796
                    break;
2797
                default:
2798
                    $from->sub(new DateInterval('P' . $startDate . 'M'));
2799
                    $query .= ' and (' . self :: PROJECT_START_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2800
            }
2801
            $from = new DateTime();
2802
            $to = new DateTime();
2803
            switch ($endDate) {
2804
                case -1:
2805
                    break;
2806
                case 0:
2807
                    $from->setDate($endFromYear, $endFromMonth, 1);
2808
                    $to->setDate($endToYear, $endToMonth, 1);
2809
                    $to->setDate($endToYear, $endToMonth, date('t', $to->getTimestamp())); // update to with the last day of that month
2810
                    $query .= ' and (' . self :: PROJECT_END_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2811
                    break;
2812
                default:
2813
                    $from->sub(new DateInterval('P' . $endDate . 'M'));
2814
                    $query .= ' and (' . self :: PROJECT_END_DATE . ' within "' . date('Y-m-d', $from->getTimestamp()) . ' ' . date('Y-m-d', $to->getTimestamp()) . '")';
2815
            }
2816
            $field = self :: PROJECT_SC39;
2817
            $query .= ($sc39s == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($sc39) use ($field) {
2818
                                return '(' . $field . ' exact "' . ($sc39 ? 'true' : 'false') . '")';
2819
                            }, $sc39s)) . ')');
2820
            $query .= ($funder == NULL) ? '' : (' and (' . self :: PROJECT_FUNDER . ' exact "' . $funder . '")');
2821
            $query .= ($fundingStream == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM . ' exact "' . $fundingStream . '")');
2822
            $query .= ($scientificArea == NULL) ? '' : (' and (' . self :: PROJECT_SCIENTIFIC_AREA . ' exact "' . $scientificArea . '")');
2823
            $query .= ($fundingStreamLevel2 == NULL) ? '' : (' and (' . self :: PROJECT_FUNDING_STREAM_LEVEL2 . ' exact "' . $fundingStreamLevel2 . '")');
2824
            $query .= ($startYear == NULL) ? '' : (' and (' . self :: PROJECT_START_YEAR . ' exact "' . $startYear . '")');
2825
            $query .= ($endYear == NULL) ? '' : (' and (' . self :: PROJECT_END_YEAR . ' exact "' . $endYear . '")');
2826
            $query .= ($sc39 === NULL) ? '' : (' and (' . self :: PROJECT_SC39 . ' exact "' . ($sc39 ? 'true' : 'false') . '")');
2827
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2828
            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)
2829
                throw new Exception('no HTTP response');
2830
            if ($response->code != self :: HTTP_OK)
2831
                throw new Exception('HTTP response code ' . $response->code);
2832
            $document = new DOMDocument();
2833
            $document->recover = TRUE;
2834
            if ($document->loadXML($response->body) == FALSE)
2835
                throw new Exception('invalid XML response');
2836
            $xpath = new DOMXPath($document);
2837
            $result = new JObject();
2838
            $result->totalProjects = $this->parseTotalResults($xpath);
2839
            $result->projects = $this->parseProjects($xpath);
2840
            $result->statistics = $this->createStatisticsForProjects($xpath,"Filter");
2841
                    //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));
2842
            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) {
2843
                                return $sc39 ? 'true' : 'false';
2844
                            }, $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);
2845
            return $result;
2846
        } catch (Exception $e) {
2847
            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) {
2848
                                return $sc39 ? 'true' : 'false';
2849
                            }, $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);
2850
            return NULL;
2851
        }
2852
    }
2853
                
2854
    // Perform an advanced search for organizations.
2855
    // $keywords the keywords to search for (array)
2856
    // $fields the fields to match keywords with (array - possible values are NAME and SHORT_NAME)
2857
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
2858
    // $countries the IDs of the countries to search for
2859
    // $types the IDs of the organization types to search for
2860
    // $country the ID of the coutnry to use as filter or NULL for no country filtering
2861
    // $type the ID of the organization type to use as filter or NULL for no organization type filtering
2862
    // $page the page of results to retrieve
2863
    // $size the size of the page of results to retrieve
2864
    // $locale the locale to use
2865
    // return a result (object) containing organizations and statistics
2866
    private function _advancedSearchOrganizations($keywords, $fields, $constraints, $countries, $types, $country, $type, $page, $size, $locale) {
2867
        try {
2868
            $time = microtime(TRUE);
2869
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY;
2870
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
2871
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
2872
                switch ($constraints[$i]) {
2873
                    case self :: ALL:
2874
                        $operator = ' and ';
2875
                        break;
2876
                    case self :: ANY:
2877
                        $operator = ' or ';
2878
                        break;
2879
                    default:
2880
                        $operator = NULL;
2881
                }
2882
                switch ($fields[$i]) {
2883
                    case OpenAireViewAdvancedSearchOrganizations :: NAME:
2884
                        $field = self :: ORGANIZATION_NAME;
2885
                        break;
2886
                    case OpenAireViewAdvancedSearchOrganizations :: SHORT_NAME:
2887
                        $field = self :: ORGANIZATION_SHORT_NAME;
2888
                        break;
2889
                    default:
2890
                        $field = NULL;
2891
                }
2892
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
2893
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
2894
                                }, $tokens)) . ')');
2895
            }
2896
            $field = self :: ORGANIZATION_COUNTRY;
2897
            $query .= ($countries == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($country) use ($field) {
2898
                                return '(' . $field . ' exact "' . $country . '")';
2899
                            }, $countries)) . ')');
2900
            $organizationLegalBody = self :: ORGANIZATION_LEGAL_BODY;
2901
            $organizationLegalPerson = self :: ORGANIZATION_LEGAL_PERSON;
2902
            $organizationNonProfit = self :: ORGANIZATION_NON_PROFIT;
2903
            $organizationResearch = self :: ORGANIZATION_RESEARCH;
2904
            $organizationEuInterests = self :: ORGANIZATION_EU_INTERESTS;
2905
            $organizationInternational = self :: ORGANIZATION_INTERNATIONAL;
2906
            $organizationEnterprise = self :: ORGANIZATION_ENTERPRISE;
2907
            $organizationSmallMediumEnterprise = self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE;
2908
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($organizationLegalBody, $organizationLegalPerson, $organizationNonProfit, $organizationResearch, $organizationEuInterests, $organizationInternational, $organizationEnterprise, $organizationSmallMediumEnterprise) {
2909
                                switch ($type) {
2910
                                    case 'legalBody': return '(' . $organizationLegalBody . ' exact true)';
2911
                                    case 'legalPerson': return '(' . $organizationLegalPerson . ' exact true)';
2912
                                    case 'nonProfit': return '(' . $organizationNonProfit . ' exact true)';
2913
                                    case 'research': return '(' . $organizationResearch . ' exact true)';
2914
                                    case 'euInterests': return '(' . $organizationEuInterests . ' exact true)';
2915
                                    case 'international': return '(' . $organizationInternational . ' exact true)';
2916
                                    case 'enterprise': return '(' . $organizationEnterprise . ' exact true)';
2917
                                    case 'smallMediumEnterprise': return '(' . $organizationSmallMediumEnterprise . ' exact true)';
2918
                                }
2919
                            }, $types)) . ')');
2920
            $query .= ($country == NULL) ? '' : (' and (' . self :: ORGANIZATION_COUNTRY . ' exact "' . $country . '")');
2921
            switch ($type) {
2922
                case 'legalBody':
2923
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_BODY . ' exact true)';
2924
                    break;
2925
                case 'legalPerson':
2926
                    $query .= ' and (' . self :: ORGANIZATION_LEGAL_PERSON . ' exact true)';
2927
                    break;
2928
                case 'nonProfit':
2929
                    $query .= ' and (' . self :: ORGANIZATION_NON_PROFIT . ' exact true)';
2930
                    break;
2931
                case 'research':
2932
                    $query .= ' and (' . self :: ORGANIZATION_RESEARCH . ' exact true)';
2933
                    break;
2934
                case 'euInterests':
2935
                    $query .= ' and (' . self :: ORGANIZATION_EU_INTERESTS . ' exact true)';
2936
                    break;
2937
                case 'international':
2938
                    $query .= ' and (' . self :: ORGANIZATION_INTERNATIONAL . ' exact true)';
2939
                    break;
2940
                case 'enterprise':
2941
                    $query .= ' and (' . self :: ORGANIZATION_ENTERPRISE . ' exact true)';
2942
                    break;
2943
                case 'smallMediumEnterprise':
2944
                    $query .= ' and (' . self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE . ' exact true)';
2945
            }
2946
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
2947
            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)
2948
                throw new Exception('no HTTP response');
2949
            if ($response->code != self :: HTTP_OK)
2950
                throw new Exception('HTTP response code ' . $response->code);
2951
            $document = new DOMDocument();
2952
            $document->recover = TRUE;
2953
            if ($document->loadXML($response->body) == FALSE)
2954
                throw new Exception('invalid XML response');
2955
            $xpath = new DOMXPath($document);
2956
            $result = new JObject();
2957
            $result->totalOrganizations = $this->parseTotalResults($xpath);
2958
            $result->organizations = $this->parseOrganizations($xpath);
2959
            $result->statistics = $this->createStatistics($xpath, array('countryFilter'), array('COUNTRY'), array('NO_COUNTRY_STATISTICS_FOUND'), array(self :: ORGANIZATION_COUNTRY));
2960
            $result->statistics['typeFilter'] = new JObject();
2961
            $result->statistics['typeFilter']->id = 'typeFilter';
2962
            $result->statistics['typeFilter']->title = JText :: _('TYPE');
2963
            $result->statistics['typeFilter']->error = JText :: _('NO_TYPE_STATISTICS_FOUND');
2964
            $result->statistics['typeFilter']->data = array();
2965
            $legalBody = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_BODY);
2966
            if (($legalBody != NULL) && array_key_exists('true', $legalBody)) {
2967
                $result->statistics['typeFilter']->data['legalBody'] = new JObject();
2968
                $result->statistics['typeFilter']->data['legalBody']->id = 'legalBody';
2969
                $result->statistics['typeFilter']->data['legalBody']->name = JText :: _('LEGAL_BODY');
2970
                $result->statistics['typeFilter']->data['legalBody']->count = $legalBody['true']->count;
2971
            }
2972
            $legalPerson = $this->parseStatistics($xpath, self :: ORGANIZATION_LEGAL_PERSON);
2973
            if (($legalPerson != NULL) && array_key_exists('true', $legalPerson)) {
2974
                $result->statistics['typeFilter']->data['legalPerson'] = new JObject();
2975
                $result->statistics['typeFilter']->data['legalPerson']->id = 'legalPerson';
2976
                $result->statistics['typeFilter']->data['legalPerson']->name = JText :: _('LEGAL_PERSON');
2977
                $result->statistics['typeFilter']->data['legalPerson']->count = $legalPerson['true']->count;
2978
            }
2979
            $nonProfit = $this->parseStatistics($xpath, self :: ORGANIZATION_NON_PROFIT);
2980
            if (($nonProfit != NULL) && array_key_exists('true', $nonProfit)) {
2981
                $result->statistics['typeFilter']->data['nonProfit'] = new JObject();
2982
                $result->statistics['typeFilter']->data['nonProfit']->id = 'nonProfit';
2983
                $result->statistics['typeFilter']->data['nonProfit']->name = JText :: _('NON_PROFIT_ORGANIZATION');
2984
                $result->statistics['typeFilter']->data['nonProfit']->count = $nonProfit['true']->count;
2985
            }
2986
            $research = $this->parseStatistics($xpath, self :: ORGANIZATION_RESEARCH);
2987
            if (($research != NULL) && array_key_exists('true', $research)) {
2988
                $result->statistics['typeFilter']->data['research'] = new JObject();
2989
                $result->statistics['typeFilter']->data['research']->id = 'research';
2990
                $result->statistics['typeFilter']->data['research']->name = JText :: _('RESEARCH_ORGANIZATION');
2991
                $result->statistics['typeFilter']->data['research']->count = $research['true']->count;
2992
            }
2993
            $euInterests = $this->parseStatistics($xpath, self :: ORGANIZATION_EU_INTERESTS);
2994
            if (($euInterests != NULL) && array_key_exists('true', $euInterests)) {
2995
                $result->statistics['typeFilter']->data['euInterests'] = new JObject();
2996
                $result->statistics['typeFilter']->data['euInterests']->id = 'euInterests';
2997
                $result->statistics['typeFilter']->data['euInterests']->name = JText :: _('EU_INTERESTS_ORGANIZATION');
2998
                $result->statistics['typeFilter']->data['euInterests']->count = $euInterests['true']->count;
2999
            }
3000
            $international = $this->parseStatistics($xpath, self :: ORGANIZATION_INTERNATIONAL);
3001
            if (($international != NULL) && array_key_exists('true', $international)) {
3002
                $result->statistics['typeFilter']->data['international'] = new JObject();
3003
                $result->statistics['typeFilter']->data['international']->id = 'international';
3004
                $result->statistics['typeFilter']->data['international']->name = JText :: _('INTERNATIONAL_ORGANIZATION');
3005
                $result->statistics['typeFilter']->data['international']->count = $international['true']->count;
3006
            }
3007
            $enterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_ENTERPRISE);
3008
            if (($enterprise != NULL) && array_key_exists('true', $enterprise)) {
3009
                $result->statistics['typeFilter']->data['enterprise'] = new JObject();
3010
                $result->statistics['typeFilter']->data['enterprise']->id = 'enterprise';
3011
                $result->statistics['typeFilter']->data['enterprise']->name = JText :: _('ENTERPRISE');
3012
                $result->statistics['typeFilter']->data['enterprise']->count = $enterprise['true']->count;
3013
            }
3014
            $smallMediumEnterprise = $this->parseStatistics($xpath, self :: ORGANIZATION_SMALL_MEDIUM_ENTERPRISE);
3015
            if (($smallMediumEnterprise != NULL) && array_key_exists('true', $smallMediumEnterprise)) {
3016
                $result->statistics['typeFilter']->data['smallMediumEnterprise'] = new JObject();
3017
                $result->statistics['typeFilter']->data['smallMediumEnterprise']->id = 'smallMediumEnterprise';
3018
                $result->statistics['typeFilter']->data['smallMediumEnterprise']->name = JText :: _('SMALL_MEDIUM_ENTERPRISE');
3019
                $result->statistics['typeFilter']->data['smallMediumEnterprise']->count = $smallMediumEnterprise['true']->count;
3020
            }
3021
            uasort($result->statistics['typeFilter']->data, function ($row1, $row2) {
3022
                return $row2->count - $row1->count;
3023
            });
3024
            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);
3025
            return $result;
3026
        } catch (Exception $e) {
3027
            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);
3028
            return NULL;
3029
        }
3030
    }
3031

    
3032
    // Perform an advanced search for datasources.
3033
    // $keywords the keywords to search for (array)
3034
    // $fields the fields to match keywords with (array - possible values are NAME, ENGLISH_NAME and SUBJECT)
3035
    // $constraints the constraints to apply to keywords (array - possible values are ALL and ANY)
3036
    // $types the IDs of the datasource types to search for
3037
    // $languages the IDs of the datasource languages to search for
3038
    // $contents the IDs of the contents to search for
3039
    // $compatibilities the IDs of the compatibilities to search for
3040
    // $type the ID of the datasource type to use as filter or NULL for no datasource type filtering
3041
    // $language the ID of the datasource language to use as filter or NULL for no datasource language filtering
3042
    // $content the ID of the content to use as filter or NULL for no content filtering
3043
    // $compatibility the ID of the compatibility to use as filter or NULL for no compatibility filtering
3044
    // $page the page of results to retrieve
3045
    // $size the size of the page of results to retrieve
3046
    // $locale the locale to use
3047
    // return a result (object) containing datasources and statistics
3048
    private function _advancedSearchDatasources($keywords, $fields, $constraints, $types, $languages, $contents, $compatibilities, $type, $language, $content, $compatibility, $page, $size, $locale) {
3049
        try {
3050
            $time = microtime(TRUE);
3051
            $query = self :: DATASOURCE_QUERY;
3052
            for ($i = 0; ($i < count($keywords)) && ($i < count($fields)) && ($i < count($constraints)); $i++) {
3053
                $tokens = preg_split('/\s/', $keywords[$i], NULL, PREG_SPLIT_NO_EMPTY);
3054
                switch ($constraints[$i]) {
3055
                    case OpenAireViewAdvancedSearchDatasources :: ALL:
3056
                        $operator = ' and ';
3057
                        break;
3058
                    case OpenAireViewAdvancedSearchDatasources :: ANY:
3059
                        $operator = ' or ';
3060
                        break;
3061
                    default:
3062
                        $operator = NULL;
3063
                }
3064
                switch ($fields[$i]) {
3065
                    case OpenAireViewAdvancedSearchDatasources :: NAME:
3066
                        $field = self :: DATASOURCE_NAME;
3067
                        break;
3068
                    case OpenAireViewAdvancedSearchDatasources :: ENGLISH_NAME:
3069
                        $field = self :: DATASOURCE_ENGLISH_NAME;
3070
                        break;
3071
                    case OpenAireViewAdvancedSearchDatasources :: SUBJECT:
3072
                        $field = self :: DATASOURCE_SUBJECT;
3073
                        break;
3074
                    default:
3075
                        $field = NULL;
3076
                }
3077
                $query .= ($tokens == NULL) ? '' : (' and (' . implode($operator, array_map(function ($keyword) use ($field) {
3078
                                    return '(' . (($field == NULL) ? '' : ($field . ' = ')) . '"' . str_replace('"', '\\"', $keyword) . '")';
3079
                                }, $tokens)) . ')');
3080
            }
3081
            $field = self :: DATASOURCE_TYPE;
3082
            $query .= ($types == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($type) use ($field) {
3083
                                return '(' . $field . ' exact "' . $type . '")';
3084
                            }, $types)) . ')');
3085
            $field = self :: DATASOURCE_LANGUAGE;
3086
            $query .= ($languages == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($language) use ($field) {
3087
                                return '(' . $field . ' exact "' . $language . '")';
3088
                            }, $languages)) . ')');
3089
            $field = self :: DATASOURCE_CONTENT;
3090
            $query .= ($contents == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($content) use ($field) {
3091
                                return '(' . $field . ' exact "' . $content . '")';
3092
                            }, $contents)) . ')');
3093
            $field = self :: DATASOURCE_COMPATIBILITY;
3094
            $query .= ($compatibilities == NULL) ? '' : (' and (' . implode(' or ', array_map(function ($compatibility) use ($field) {
3095
                                return '(' . $field . ' exact "' . $compatibility . '")';
3096
                            }, $compatibilities)) . ')');
3097
            $query .= ($type == NULL) ? '' : (' and (' . self :: DATASOURCE_TYPE . ' exact "' . $type . '")');
3098
            $query .= ($language == NULL) ? '' : (' and (' . self :: DATASOURCE_LANGUAGE . ' exact "' . $language . '")');
3099
            $query .= ($content == NULL) ? '' : (' and (' . self :: DATASOURCE_CONTENT . ' exact "' . $content . '")');
3100
            $query .= ($compatibility == NULL) ? '' : (' and (' . self :: DATASOURCE_COMPATIBILITY . ' exact "' . $compatibility . '")');
3101
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3102
            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)
3103
                throw new Exception('no HTTP response');
3104
            if ($response->code != self :: HTTP_OK)
3105
                throw new Exception('HTTP response code ' . $response->code);
3106
            $document = new DOMDocument();
3107
            $document->recover = TRUE;
3108
            if ($document->loadXML($response->body) == FALSE)
3109
                throw new Exception('invalid XML response');
3110
            $xpath = new DOMXPath($document);
3111
            $result = new JObject();
3112
            $result->totalDatasources = $this->parseTotalResults($xpath);
3113
            $result->datasources = $this->parseDatasources($xpath);
3114
            $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));
3115
            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);
3116
            return $result;
3117
        } catch (Exception $e) {
3118
            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);
3119
            return NULL;
3120
        }
3121
    }
3122

    
3123
    // Retrieve a single publication by identifier.
3124
    // $id the publication identifier
3125
    // $locale the locale to use
3126
    // return a publication (object) or NULL if no such publication exists
3127
    private function _getPublication($id, $locale) {
3128
        try {
3129
            $time = microtime(TRUE);
3130
            $query = self :: PUBLICATION_QUERY . ' and ( (' . self :: PUBLICATION_ID . ' exact "' . $id . '") or (' . self :: RESULT_DUP_ID . ' exact "' . $id . '" ) )';
3131
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3132
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3133
                throw new Exception('no HTTP response');
3134
            if ($response->code != self :: HTTP_OK)
3135
                throw new Exception('HTTP response code ' . $response->code);
3136
            $document = new DOMDocument();
3137
            $document->recover = TRUE;
3138
            if ($document->loadXML($response->body) == FALSE)
3139
                throw new Exception('invalid XML response');
3140
            $xpath = new DOMXPath($document);
3141
            $publication = $this->parsePublication($xpath, $locale);
3142
            JLog :: add('Retrieved publication in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3143
            return $publication;
3144
        } catch (Exception $e) {
3145
            JLog :: add('Error retrieving publication (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3146
            return NULL;
3147
        }
3148
    }
3149

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

    
3184
    // Retrieve publications by identifier.
3185
    // $ids the publication identifiers
3186
    // $locale the locale to use
3187
    // return a publication (object) or NULL if no such publication exists
3188
    private function _getPublications($ids, $locale) {
3189
        try {
3190
            $time = microtime(TRUE);
3191
            $query = self :: PUBLICATION_QUERY . ' and (';
3192
            $parts = array();
3193
            foreach ($ids as $id) {
3194
                $parts[] = '(' . self :: PUBLICATION_ID . ' exact "' . $id . '")';
3195
            }
3196
            $query .= join(" OR ", $parts);
3197
            $query .= ')';
3198
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3199
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3200
                throw new Exception('no HTTP response');
3201
            if ($response->code != self :: HTTP_OK)
3202
                throw new Exception('HTTP response code ' . $response->code);
3203
            $document = new DOMDocument();
3204
            $document->recover = TRUE;
3205
            if ($document->loadXML($response->body) == FALSE)
3206
                throw new Exception('invalid XML response');
3207
            $xpath = new DOMXPath($document);
3208
            $publications = $this->parsePublications($xpath, $locale);
3209
            JLog :: add('Retrieved publication in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3210
            return $publications;
3211
        } catch (Exception $e) {
3212
            JLog :: add('Error retrieving publication (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3213
            return NULL;
3214
        }
3215
    }
3216

    
3217
    // Retrieve publications by identifier.
3218
    // $ids the publication identifiers
3219
    // $locale the locale to use
3220
    // return a publication (object) or NULL if no such publication exists
3221
    private function _getProjects($ids, $locale) {
3222
        try {
3223
            $time = microtime(TRUE);
3224
            $query = self :: PROJECT_QUERY . ' and (';
3225
            $parts = array();
3226
            foreach ($ids as $id) {
3227
                $parts[] = '(' . self :: PROJECT_ID . ' exact "' . $id . '")';
3228
            }
3229
            $query .= join(" OR ", $parts);
3230
            $query .= ')';
3231
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3232
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3233
                throw new Exception('no HTTP response');
3234
            if ($response->code != self :: HTTP_OK)
3235
                throw new Exception('HTTP response code ' . $response->code);
3236
            $document = new DOMDocument();
3237
            $document->recover = TRUE;
3238
            if ($document->loadXML($response->body) == FALSE)
3239
                throw new Exception('invalid XML response');
3240
            $xpath = new DOMXPath($document);
3241
            $projects = $this->parseProjects($xpath, $locale);
3242
            JLog :: add('Retrieved projects in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3243
            return $projects;
3244
        } catch (Exception $e) {
3245
            JLog :: add('Error retrieving projects (ids: ' . join(",", $ids) . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3246
            return NULL;
3247
        }
3248
    }
3249
// Retrieve projects by code id.
3250
    // $id the project grant agreement code
3251
    // $locale the locale to use
3252
    // return projects or NULL if no such project exists
3253
    private function _getProjectByCodeId($id, $funder, $locale) {
3254
        try {
3255
            $time = microtime(TRUE);
3256
            $query = self :: PROJECT_QUERY . ' and ';
3257
//                    (oaftype=project) and (projectcode_nt exact 731011)
3258
                $query.=' ( projectcode_nt exact "' . $id . '") and ';
3259
                $query.=' ( funderid exact "' . $funder . '")';
3260
            //and (funderid exact "ec__________::EC")'
3261
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3262
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3263
                throw new Exception('no HTTP response');
3264
            if ($response->code != self :: HTTP_OK)
3265
                throw new Exception('HTTP response code ' . $response->code);
3266
            $document = new DOMDocument();
3267
            $document->recover = TRUE;
3268
            if ($document->loadXML($response->body) == FALSE)
3269
                throw new Exception('invalid XML response');
3270
            $xpath = new DOMXPath($document);
3271
            $projects = $this->parseProject($xpath, $locale);
3272
            JLog :: add('Retrieved projects in ' . (microtime(TRUE) - $time) . ' s (id: ' .$id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3273
            return $projects;
3274
        } catch (Exception $e) {
3275
            JLog :: add('Error retrieving projects (id: ' .$id. ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3276
            return NULL;
3277
        }
3278
    }
3279
    // Retrieve datasets by identifier.
3280
    // $ids the datasets identifiers
3281
    // $locale the locale to use
3282
    // return datasets array of (object) or NULL if no such dataset exists
3283
    private function _getDatasets($ids, $locale) {
3284
        try {
3285
            $time = microtime(TRUE);
3286
            $query = self :: DATASET_QUERY . ' and (';
3287
            $parts = array();
3288
            foreach ($ids as $id) {
3289
                $parts[] = '(' . self :: DATASET_ID . ' exact "' . $id . '")';
3290
            }
3291
            $query .= join(" OR ", $parts);
3292
            $query .= ')';
3293
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3294
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3295
                throw new Exception('no HTTP response');
3296
            if ($response->code != self :: HTTP_OK)
3297
                throw new Exception('HTTP response code ' . $response->code);
3298
            $document = new DOMDocument();
3299
            $document->recover = TRUE;
3300
            if ($document->loadXML($response->body) == FALSE)
3301
                throw new Exception('invalid XML response');
3302
            $xpath = new DOMXPath($document);
3303
            $datasets = $this->parseDatasets($xpath, $locale);
3304
            JLog :: add('Retrieved publication in ' . (microtime(TRUE) - $time) . ' s (ids: ' . join(",", $ids) . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3305
            return $datasets;
3306
        } catch (Exception $e) {
3307
            JLog :: add('Error retrieving publication (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3308
            return NULL;
3309
        }
3310
    }
3311

    
3312
    // Retrieve a single dataset by identifier.
3313
    // $id the dataset identifier
3314
    // $locale the locale to use
3315
    // return a dataset (object) or NULL if no such dataset exists
3316
    private function _getDataset($id, $locale) {
3317
        try {
3318
            $time = microtime(TRUE);
3319
            $query = self :: DATASET_QUERY . ' and ( (' . self :: DATASET_ID . ' exact "' . $id . '") or (' . self :: RESULT_DUP_ID . ' exact "' . $id . '" ) )';
3320
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3321
            if (($response = $this->performGet('search?action=search&sTransformer=results_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3322
                throw new Exception('no HTTP response');
3323
            if ($response->code != self :: HTTP_OK)
3324
                throw new Exception('HTTP response code ' . $response->code);
3325
            $document = new DOMDocument();
3326
            $document->recover = TRUE;
3327
            if ($document->loadXML($response->body) == FALSE)
3328
                throw new Exception('invalid XML response');
3329
            $xpath = new DOMXPath($document);
3330
            $dataset = $this->parseDataset($xpath, $locale);
3331
            JLog :: add('Retrieved dataset in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3332
            return $dataset;
3333
        } catch (Exception $e) {
3334
            JLog :: add('Error retrieving dataset (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3335
            return NULL;
3336
        }
3337
    }
3338

    
3339
    // Retrieve a single project by identifier.
3340
    // $id the project identifier
3341
    // $locale the locale to use
3342
    // return a project (object) or NULL if no such project exists
3343
    private function _getProject($id, $locale) {
3344
        try {
3345
            $time = microtime(TRUE);
3346
            $query = self :: PROJECT_QUERY . ' and (' . self :: PROJECT_ID . ' exact "' . $id . '")';
3347
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3348
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3349
                throw new Exception('no HTTP response');
3350
            if ($response->code != self :: HTTP_OK)
3351
                throw new Exception('HTTP response code ' . $response->code);
3352
            $document = new DOMDocument();
3353
            $document->recover = TRUE;
3354
            if ($document->loadXML($response->body) == FALSE)
3355
                throw new Exception('invalid XML response');
3356
            $xpath = new DOMXPath($document);
3357
            $project = $this->parseProject($xpath);
3358
            JLog :: add('Retrieved project in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3359
            return $project;
3360
        } catch (Exception $e) {
3361
            JLog :: add('Error retrieving project (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3362
            return NULL;
3363
        }
3364
    }
3365

    
3366
    // Retrieve a single person by identifier.
3367
    // $id the person identifier
3368
    // $locale the locale to use
3369
    // return a person (object) or NULL if no such person exists
3370
    private function _getPerson($id, $locale) {
3371
        try {
3372
            $time = microtime(TRUE);
3373
            $query = self :: PERSON_QUERY . ' and (' . self :: PERSON_ID . ' exact "' . $id . '")';
3374
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3375
            if (($response = $this->performGet('search?action=search&sTransformer=persons_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3376
                throw new Exception('no HTTP response');
3377
            if ($response->code != self :: HTTP_OK)
3378
                throw new Exception('HTTP response code ' . $response->code);
3379
            $document = new DOMDocument();
3380
            $document->recover = TRUE;
3381
            if ($document->loadXML($response->body) == FALSE)
3382
                throw new Exception('invalid XML response');
3383
            $xpath = new DOMXPath($document);
3384
            $person = $this->parsePerson($xpath);
3385
            JLog :: add('Retrieved person in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3386
            return $person;
3387
        } catch (Exception $e) {
3388
            JLog :: add('Error retrieving person (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3389
            return NULL;
3390
        }
3391
    }
3392

    
3393
    // Retrieve a single organization by identifier.
3394
    // $id the organization identifier
3395
    // $locale the locale to use
3396
    // return an organization (object) or NULL if no such organization exists
3397
    private function _getOrganization($id, $locale) {
3398
        try {
3399
            $time = microtime(TRUE);
3400
            $query = self :: ORGANIZATION_QUERY_COMPATIBILITY . ' and (' . self :: ORGANIZATION_ID . ' exact "' . $id . '")';
3401
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3402
            if (($response = $this->performGet('search?action=search&sTransformer=organizations_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3403
                throw new Exception('no HTTP response');
3404
            if ($response->code != self :: HTTP_OK)
3405
                throw new Exception('HTTP response code ' . $response->code);
3406
            $document = new DOMDocument();
3407
            $document->recover = TRUE;
3408
            if ($document->loadXML($response->body) == FALSE)
3409
                throw new Exception('invalid XML response');
3410
            $xpath = new DOMXPath($document);
3411
            $organization = $this->parseOrganization($xpath);
3412
            JLog :: add('Retrieved organization in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3413
            return $organization;
3414
        } catch (Exception $e) {
3415
            JLog :: add('Error retrieving organization (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3416
            return NULL;
3417
        }
3418
    }
3419

    
3420
    // Retrieve the datasources of an organization.
3421
    // $id the organization identifier
3422
    // $size the maximum number of datasources to retrieve
3423
    // $locale the locale to use
3424
    // return a result (object) containing datasources and total
3425
    private function _getOrganizationDatasources($id, $size, $locale) {
3426
        try {
3427
            $time = microtime(TRUE);
3428
            $query = self :: DATASOURCE_QUERY . ' and (' . self :: DATASOURCE_ORGANIZATION . ' exact "' . $id . '")';
3429
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3430
            if (($response = $this->performGet('search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&size=' . $size . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3431
                throw new Exception('no HTTP response');
3432
            if ($response->code != self :: HTTP_OK)
3433
                throw new Exception('HTTP response code ' . $response->code);
3434
            $document = new DOMDocument();
3435
            $document->recover = TRUE;
3436
            if ($document->loadXML($response->body) == FALSE)
3437
                throw new Exception('invalid XML response');
3438
            $xpath = new DOMXPath($document);
3439
            $result = new JObject();
3440
            $result->totalDatasources = $this->parseTotalResults($xpath);
3441
            $result->datasources = $this->parseDatasources($xpath);
3442
            JLog :: add('Retrieved ' . count($result->datasources) . ' organization datasources in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3443
            return $result;
3444
        } catch (Exception $e) {
3445
            JLog :: add('Error retrieving organization datasources (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3446
            return NULL;
3447
        }
3448
    }
3449

    
3450
    // Retrieve a single datasource by identifier.
3451
    // $id the datasource identifier
3452
    // $locale the locale to use
3453
    // return a datasource (object) or NULL if no such datasource exists
3454
    private function _getDatasource($id, $locale, $compatibility = false) {
3455
        try {
3456
            $time = microtime(TRUE);
3457
            $datasource_query = $compatibility ? self::DATASOURCE_QUERY_COMPATIBILITY : self::DATASOURCE_QUERY;
3458
            $query = $datasource_query . ' and (' . self :: DATASOURCE_ID . ' exact "' . $id . '")';
3459
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3460
            if (($response = $this->performGet('search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3461
                throw new Exception('no HTTP response');
3462
            if ($response->code != self :: HTTP_OK)
3463
                throw new Exception('HTTP response code ' . $response->code);
3464
            $document = new DOMDocument();
3465
            $document->recover = TRUE;
3466
            if ($document->loadXML($response->body) == FALSE)
3467
                throw new Exception('invalid XML response');
3468
            $xpath = new DOMXPath($document);
3469
            $datasource = $this->parseDatasource($xpath);
3470
            JLog :: add('Retrieved datasource in ' . (microtime(TRUE) - $time) . ' s (id: ' . $id . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3471
            return $datasource;
3472
        } catch (Exception $e) {
3473
            JLog :: add('Error retrieving datasource (id: ' . $id . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3474
            return NULL;
3475
        }
3476
    }
3477

    
3478
    // Retrieve all the OpenAIRE compatible datasources.
3479
    // $locale the locale to use
3480
    // return the datasources (array) or NULL if any errors occur
3481
    private function _getCompatibleDatasources($locale) {
3482
        try {
3483
            $time = microtime(TRUE);
3484
            $query = self :: DATASOURCE_QUERY .' and (datasourcecompatibilityid <> "hostedBy") '. ' and (' . self :: DATASOURCE_COMPATIBILITY . ' <> "' . self :: DATASOURCE_COMPATIBILITY_NOT_COMPATIBLE . '")';
3485
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3486
            if (($response = $this->performGet('search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&size=1&locale=' . str_replace('-', '_', $locale))) == NULL)
3487
                throw new Exception('no HTTP response');
3488
            if ($response->code != self :: HTTP_OK)
3489
                throw new Exception('HTTP response code ' . $response->code);
3490
            $document = new DOMDocument();
3491
            $document->recover = TRUE;
3492
            if ($document->loadXML($response->body) == FALSE)
3493
                throw new Exception('invalid XML response');
3494
            $xpath = new DOMXPath($document);
3495
            $totalDatasources = $this->parseTotalResults($xpath);
3496
            if ($totalDatasources > 0) {
3497
                if (($response = $this->performGet('search?action=search&sTransformer=datasources_openaire&query=' . urlencode($query) . '&size=' . $totalDatasources . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3498
                    throw new Exception('no HTTP response');
3499
                if ($response->code != self :: HTTP_OK)
3500
                    throw new Exception('HTTP response code ' . $response->code);
3501
                $document = new DOMDocument();
3502
                $document->recover = TRUE;
3503
                if ($document->loadXML($response->body) == FALSE)
3504
                    throw new Exception('invalid XML response');
3505
                $xpath = new DOMXPath($document);
3506
                $datasources = $this->parseDatasources($xpath);
3507
            } else
3508
                $datasources = array();
3509
            JLog :: add('Retrieved ' . count($datasources) . ' compatible datasources in ' . (microtime(TRUE) - $time) . ' s (locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3510
            return $datasources;
3511
        } catch (Exception $e) {
3512
            JLog :: add('Error retrieving compatible datasources (locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3513
            return NULL;
3514
        }
3515
    }
3516

    
3517
    // Perform a quick search for projects, searching only by acronym, title or code and funder.
3518
    // $keyword the keyword to search for
3519
    // $funder the funder to search for
3520
    // $limit the maximum number of results to retrieve
3521
    // $locale the locale to use
3522
    // return projects (array) or NULL if any errors occur
3523
    private function _quickSearchProjects($keyword, $funder, $limit, $locale) {
3524
        try {
3525
            $time = microtime(TRUE);
3526
            $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 . '")';
3527
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3528
            if (($response = $this->performGet('search?action=search&sTransformer=projects_openaire&query=' . urlencode($query) . '&size=' . $limit . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3529
                throw new Exception('no HTTP response');
3530
            if ($response->code != self :: HTTP_OK)
3531
                throw new Exception('HTTP response code ' . $response->code);
3532
            $document = new DOMDocument();
3533
            $document->recover = TRUE;
3534
            if ($document->loadXML($response->body) == FALSE)
3535
                throw new Exception('invalid XML response');
3536
            $xpath = new DOMXPath($document);
3537
            $projects = $this->parseProjects($xpath);
3538
            JLog :: add('Retrieved ' . count($projects) . ' projects in ' . (microtime(TRUE) - $time) . ' s (keyword: ' . $keyword . ', funder: ' . $funder . ', limit: ' . $limit . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3539
            return $projects;
3540
        } catch (Exception $e) {
3541
            JLog :: add('Error retrieving projects (keyword: ' . $keyword . ', funder: ' . $funder . ', limit: ' . $limit . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3542
            return NULL;
3543
        }
3544
    }
3545

    
3546
    // Perform a quick search for organizations, searching only by name or short name.
3547
    // $keyword the keyword to search for
3548
    // $limit the maximum number of results to retrieve
3549
    // $locale the locale to use
3550
    // return organizations (array) or NULL if any errors occur
3551
    private function _quickSearchOrganizations($keyword, $limit, $locale) {
3552
        try {
3553
            $time = microtime(TRUE);
3554
            $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" ';
3555
            JLog :: add('Generated query is \'' . $query . '\'', JLog :: INFO, self :: LOG);
3556
            if (($response = $this->performGet('search?action=search&sTransformer=organizations_openaire&query=' . urlencode($query) . '&size=' . $limit . '&locale=' . str_replace('-', '_', $locale))) == NULL)
3557
                throw new Exception('no HTTP response');
3558
            if ($response->code != self :: HTTP_OK)
3559
                throw new Exception('HTTP response code ' . $response->code);
3560
            $document = new DOMDocument();
3561
            $document->recover = TRUE;
3562
            if ($document->loadXML($response->body) == FALSE)
3563
                throw new Exception('invalid XML response');
3564
            $xpath = new DOMXPath($document);
3565
            $organizations = $this->parseOrganizations($xpath);
3566
            JLog :: add('Retrieved ' . count($organizations) . ' organizations in ' . (microtime(TRUE) - $time) . ' s (keyword: ' . $keyword . ', limit: ' . $limit . ', locale: ' . $locale . ')', JLog :: INFO, self :: LOG);
3567
            return $organizations;
3568
        } catch (Exception $e) {
3569
            JLog :: add('Error retrieving organizations (keyword: ' . $keyword . ', limit: ' . $limit . ', locale: ' . $locale . '): ' . $e->getMessage(), JLog :: ERROR, self :: LOG);
3570
            return NULL;
3571
        }
3572
    }
3573

    
3574
    // Perform an HTTP GET request.
3575
    // $request the relative URL to connect to
3576
    // return the HTTP response (object)
3577
    private function performGet($request) {
3578
        $request = $this->searchService . $request;
3579
        JLog :: add('Requesting ' . $request, JLog :: INFO, self :: LOG);
3580
        $time = microtime(TRUE);
3581
        $response = $this->http->get($request);
3582
        JLog :: add('Received response in ' . (microtime(TRUE) - $time) . ' s', JLog :: INFO, self :: LOG);
3583
        return $response;
3584
    }
3585

    
3586
    // Create statistics based on a search service XML response.
3587
    // $xpath the DOMXPath to parse
3588
    // $ids the identifiers of the statistics to create
3589
    // $titles the titles of the statistics to create
3590
    // $errors the error messages of the statistics to create
3591
    // $data the field names of the statistics to create
3592
    // return statistics (array)
3593
    private function createStatistics($xpath, $ids, $titles, $errors, $data) {
3594
        $statistics = array();
3595
        array_map(function ($id, $title, $error, $data) use ($xpath, &$statistics) {
3596
            $statistics[$id] = new JObject();
3597
            $statistics[$id]->id = $id;
3598
            $statistics[$id]->title = JText :: _($title);
3599
            $statistics[$id]->error = JText :: _($error);
3600
            $statistics[$id]->data = OpenAireModelSearch :: parseStatistics($xpath, $data);
3601
        }
3602
                , $ids, $titles, $errors, $data);
3603
        return $statistics;
3604
    }
3605

    
3606
    // Parse statistics from a search service XML response.
3607
    // $xpath the DOMXPath to parse
3608
    // $category the category to retrieve statistics for
3609
    // return statistics (associative array)
3610
    public function parseStatistics($xpath, $category) {
3611
        if ((($browseResultsNodes = $xpath->query('/response/browseResults')) == FALSE) || (($browseResultsNode = $browseResultsNodes->item(0)) == NULL))
3612
            throw new Exception('error parsing statistics');
3613
        if (($fieldNodes = $xpath->query('./result/field[@name = "' . $category . '"]', $browseResultsNode)) == FALSE)
3614
            throw new Exception('error parsing statistics');
3615
        $statistics = array();
3616
        foreach ($fieldNodes as $fieldNode) {
3617
            if ((($idNodes = $xpath->query('./field[@name = "value"]/@value_original', $fieldNode)) == FALSE) || (($idNode = $idNodes->item(0)) == NULL))
3618
                throw new Exception('error parsing statistics');
3619
            if ((($nameNodes = $xpath->query('./field[@name = "value"]/@value', $fieldNode)) == FALSE) || (($nameNode = $nameNodes->item(0)) == NULL))
3620
                throw new Exception('error parsing statistics');
3621
            if ((($countNodes = $xpath->query('./field[@name = "count"]/@value', $fieldNode)) == FALSE) || (($countNode = $countNodes->item(0)) == NULL))
3622
                throw new Exception('error parsing statistics');
3623
            $statistic = new JObject();
3624
            $statistic->id = trim($idNode->nodeValue);
3625

    
3626
            $statistic->name = trim($nameNode->nodeValue);
3627
             $statistic->name=  str_replace("::", JText :: _('FUNDER_SEPARATOR'), $statistic->name);
3628
            /* if ($category === self :: PUBLICATION_PROJECT) {
3629
              $project =OpenAireModelSearch :: getProject($statistic->name, 'en-GB');
3630
              if($project!==null){
3631
              $statistic->name =  $project->title;
3632
              }
3633
              } */
3634

    
3635
            $statistic->count = intval(trim($countNode->nodeValue));
3636
            $statistics[$statistic->id] = $statistic;
3637
        }
3638
        return $statistics;
3639
    }
3640

    
3641
    // Parse total results from a search service XML response.
3642
    // xpath the DOMXPath to parse
3643
    // return total results (integer)
3644
    private function parseTotalResults($xpath) {
3645
        if ((($totalNodes = $xpath->query('/response/header/total')) == FALSE) || (($totalNode = $totalNodes->item(0)) == NULL))
3646
            throw new Exception('error parsing total results');
3647
        return intval(trim($totalNode->nodeValue));
3648
    }
3649

    
3650
    // Parse publications from a search service XML response.
3651
    // xpath the DOMXPath to parse
3652
    // return results (array)
3653
    private function parseResults($ids,$xpath) {
3654
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
3655
            throw new Exception('error parsing results');
3656
        $publications = array();
3657
        foreach ($resultNodes as $resultNode) {
3658
            if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
3659
                throw new Exception('error parsing results');
3660
            if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
3661
                throw new Exception('error parsing publications');
3662
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
3663
                throw new Exception('error parsing results');
3664
            if (($subjectNodes = $xpath->query('./field[@name = "subject"]', $resultNode)) == FALSE)
3665
                throw new Exception('error parsing results');
3666
            if (($relatedNodes = $xpath->query('./field[@name = "related"]', $resultNode)) == FALSE)
3667
                throw new Exception('error parsing results');
3668
            if (($authorNodes = $xpath->query('./field[@name = "author"]', $resultNode)) == FALSE)
3669
                throw new Exception('error parsing results');
3670
            if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
3671
                throw new Exception('error parsing results');
3672
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
3673
                throw new Exception('error parsing results');
3674
            if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
3675
                throw new Exception('error parsing results');
3676
            if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
3677
                throw new Exception('error parsing results');
3678
            if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
3679
                throw new Exception('error parsing results');
3680
//            if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
3681
//                throw new Exception('error parsing results');
3682
            $publication = new JObject();
3683
           // $publication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3684
           // $first=$publication->id;
3685
             foreach($idNodes as $idNode){
3686
                 if (in_array(trim($idNode->nodeValue), $ids)) {
3687
                     $publication->id =trim($idNode->nodeValue);
3688
                }
3689
            }
3690
            $publication->source = 'openaire';
3691
            $publication->url = NULL;
3692
            $publication->accessMode = NULL;
3693
            $publication->datasources = array();
3694
            $publication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3695
            $publication->authors = array();
3696
            $publication->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
3697
            $publication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
3698
            $publication->language = (($languageNode = $languageNodes->item(0)) == NULL) ? NULL : trim($languageNode->nodeValue);
3699
            $publication->projects = array();
3700
            $publication->subjects = array();
3701
            $publication->related = array();
3702
            $publication->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
3703
//            $publication->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
3704
            foreach ($subjectNodes as $subjectNode) {
3705
                if (($titleNodes = $xpath->query('./@value', $subjectNode)) == FALSE)
3706
                    throw new Exception('error parsing results');
3707
                if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $subjectNode)) == FALSE)
3708
                    throw new Exception('error parsing results');
3709
                if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $subjectNode)) == FALSE)
3710
                    throw new Exception('error parsing results');
3711
                if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $subjectNode)) == FALSE)
3712
                    throw new Exception('error parsing results');
3713
                $subject = new JObject();
3714
                $subject->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3715
                $subject->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
3716
                $subject->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
3717
                $subject->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
3718
                if (($subject->title != NULL) || ($subject->inferred != NULL) || ($subject->trust != NULL) || ($subject->provenance != NULL))
3719
                    $publication->subjects[] = $subject;
3720
            }
3721

    
3722
            foreach ($relatedNodes as $relatedNode) {
3723

    
3724
                if (($titleNodes = $xpath->query('./field[@name= "title"]/@value', $relatedNode)) == FALSE)
3725
                    throw new Exception('error parsing results');
3726
                if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
3727
                    throw new Exception('error parsing results');
3728
                if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
3729
                    throw new Exception('error parsing results');
3730
                if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
3731
                    throw new Exception('error parsing results');
3732
                $related = new JObject();
3733
                $related->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3734
                $related->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
3735
                $related->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
3736
                $related->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
3737
                if (($related->title != NULL) || ($related->inferred != NULL) || ($related->trust != NULL) || ($related->provenance != NULL))
3738
                    $publication->related[] = $related;
3739
            }
3740

    
3741
            foreach ($datasourceNodes as $datasourceNode) {
3742
                if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
3743
                    throw new Exception('error parsing results');
3744
                if (($accessModeNodes = $xpath->query('./field[@name = "accessrightid"]/@value', $datasourceNode)) == FALSE)
3745
                    throw new Exception('error parsing results');
3746
                $datasource = new JObject();
3747
                $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
3748
                $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
3749
                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))))) {
3750
                    $publication->accessMode = $datasource->accessMode;
3751
                    $publication->url = $datasource->url;
3752
                }
3753
                if (($datasource->url != NULL) || ($datasource->accessMode != NULL))
3754
                    $publication->datasources[] = $datasource;
3755
            }
3756
            foreach ($authorNodes as $authorNode) {
3757
                if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
3758
                    throw new Exception('error parsing results');
3759
                if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
3760
                    throw new Exception('error parsing results');
3761
                if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
3762
                    throw new Exception('error parsing results');
3763
                $author = new JObject();
3764
                $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3765
                $author->lastName = NULL;
3766
                $author->firstName = NULL;
3767
                $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
3768
                $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
3769
                if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
3770
                    $publication->authors[] = $author;
3771
                usort($publication->authors, function ($author1, $author2) {
3772
                    return $author1->ranking - $author2->ranking;
3773
                });
3774
            }
3775
            foreach ($projectNodes as $projectNode) {
3776
                if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
3777
                    throw new Exception('error parsing results');
3778
                if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
3779
                    throw new Exception('error parsing results');
3780
                if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
3781
                    throw new Exception('error parsing results');
3782
                if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
3783
                    throw new Exception('error parsing results');
3784
                $project = new JObject();
3785
                $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3786
                $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
3787
                $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3788
                $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
3789
                if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
3790
                    $publication->projects[] = $project;
3791
            }
3792
            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))
3793
                $publications[] = $publication;
3794
        }
3795
        return $publications;
3796
    }
3797

    
3798
    // Parse publications from a search service XML response.
3799
    // xpath the DOMXPath to parse
3800
    // return publications (array)
3801
    private function parsePublications($xpath) {
3802
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
3803
            throw new Exception('error parsing publications');
3804
        $publications = array();
3805
        foreach ($resultNodes as $resultNode) {
3806
            if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
3807
                throw new Exception('error parsing publications');
3808
            if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
3809
                throw new Exception('error parsing publications');
3810
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
3811
                throw new Exception('error parsing publications');
3812
            if (($subjectNodes = $xpath->query('./field[@name = "subject"]', $resultNode)) == FALSE)
3813
                throw new Exception('error parsing publications');
3814
            if (($relatedNodes = $xpath->query('./field[@name = "related"]', $resultNode)) == FALSE)
3815
                throw new Exception('error parsing publications');
3816
            if (($authorNodes = $xpath->query('./field[@name = "hasAuthor"]', $resultNode)) == FALSE)
3817
                throw new Exception('error parsing publications');
3818
            if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
3819
                throw new Exception('error parsing publications');
3820
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
3821
                throw new Exception('error parsing publications');
3822
            if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
3823
                throw new Exception('error parsing publications');
3824
            if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
3825
                throw new Exception('error parsing publications');
3826
            if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
3827
                throw new Exception('error parsing publications');
3828
//            if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
3829
//                throw new Exception('error parsing publications');
3830
            if (($sourceNodes = $xpath->query('./field[@name = "source"]/@value', $resultNode)) == FALSE)
3831
                throw new Exception('error parsing publication');
3832
            if (($pidNodes = $xpath->query('./field[@name = "pid"]', $resultNode)) == FALSE)
3833
                throw new Exception('error parsing publication');
3834
            if (($accessModeNodes = $xpath->query('./field[@name = "bestaccessright"]/@value', $resultNode)) == FALSE)
3835
                throw new Exception('error parsing publication');
3836
            $publication = new JObject();
3837
            $publication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3838
            $publication->source = 'openaire';
3839
             foreach ($sourceNodes as $sourceNode) {
3840
                if (($source = trim($sourceNode->nodeValue)) != NULL){
3841
                     $publication->source_source = $source;
3842
                }
3843
            }
3844
            $publication->url = NULL;
3845
            $publication->accessMode =(($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
3846
            $publication->datasources = array();
3847
            $publication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3848
            $publication->authors = array();
3849
            $publication->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
3850
            $publication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
3851
            $publication->language = (($languageNode = $languageNodes->item(0)) == NULL) ? NULL : trim($languageNode->nodeValue);
3852
            $publication->projects = array();
3853
            $publication->subjects = array();
3854
            $publication->related = array();
3855
            $publication->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
3856
//            $publication->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
3857
            $publication->pids = array();
3858
            foreach ($pidNodes as $pidNode) {
3859
                if (($classNodes = $xpath->query('./field[@name = "classid"]/@value', $pidNode)) == FALSE)
3860
                    throw new Exception('error parsing publication');
3861
                if (($valueNodes = $xpath->query('./field[@name = "value"]/@value', $pidNode)) == FALSE)
3862
                    throw new Exception('error parsing publication');
3863
                $pid = new JObject();
3864
                $pid->clazz = (($classNode = $classNodes->item(0)) == NULL) ? NULL : trim($classNode->nodeValue);
3865
                $pid->value = (($valueNode = $valueNodes->item(0)) == NULL) ? NULL : trim($valueNode->nodeValue);
3866
                if (($pid->clazz != NULL) && ($pid->value != NULL))
3867
                    $publication->pids[] = $pid;
3868
            }
3869
            foreach ($subjectNodes as $subjectNode) {
3870
                if (($titleNodes = $xpath->query('./@value', $subjectNode)) == FALSE)
3871
                    throw new Exception('error parsing publications');
3872
                if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $subjectNode)) == FALSE)
3873
                    throw new Exception('error parsing publications');
3874
                if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $subjectNode)) == FALSE)
3875
                    throw new Exception('error parsing publications');
3876
                if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $subjectNode)) == FALSE)
3877
                    throw new Exception('error parsing publications');
3878
                $subject = new JObject();
3879
                $subject->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3880
                $subject->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
3881
                $subject->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
3882
                $subject->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
3883
                if (($subject->title != NULL) || ($subject->inferred != NULL) || ($subject->trust != NULL) || ($subject->provenance != NULL))
3884
                    $publication->subjects[] = $subject;
3885
            }
3886

    
3887
            foreach ($relatedNodes as $relatedNode) {
3888

    
3889
                if (($titleNodes = $xpath->query('./field[@name= "title"]/@value', $relatedNode)) == FALSE)
3890
                    throw new Exception('error parsing publications');
3891
                if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
3892
                    throw new Exception('error parsing publications');
3893
                if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
3894
                    throw new Exception('error parsing publications');
3895
                if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
3896
                    throw new Exception('error parsing publications');
3897
                $related = new JObject();
3898
                $related->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3899
                $related->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
3900
                $related->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
3901
                $related->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
3902
                if (($related->title != NULL) || ($related->inferred != NULL) || ($related->trust != NULL) || ($related->provenance != NULL))
3903
                    $publication->related[] = $related;
3904
            }
3905

    
3906
            foreach ($datasourceNodes as $datasourceNode) {
3907
                if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
3908
                    throw new Exception('error parsing publications');
3909
                if (($accessModeNodes = $xpath->query('./field[@name = "accessrightid"]/@value', $datasourceNode)) == FALSE)
3910
                    throw new Exception('error parsing publications');
3911
                $datasource = new JObject();
3912
                $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
3913
                $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
3914
                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))))) {
3915
                    $publication->accessMode = $datasource->accessMode;
3916
                    $publication->url = $datasource->url;
3917
                }
3918
                if (($datasource->url != NULL) || ($datasource->accessMode != NULL))
3919
                    $publication->datasources[] = $datasource;
3920
            }
3921
            foreach ($authorNodes as $authorNode) {
3922
                if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
3923
                    throw new Exception('error parsing publications');
3924
                if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
3925
                    throw new Exception('error parsing publications');
3926
                if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
3927
                    throw new Exception('error parsing publications');
3928
                $author = new JObject();
3929
                $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3930
                $author->lastName = NULL;
3931
                $author->firstName = NULL;
3932
                $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
3933
                $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
3934
                if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
3935
                    $publication->authors[] = $author;
3936
                usort($publication->authors, function ($author1, $author2) {
3937
                    return $author1->ranking - $author2->ranking;
3938
                });
3939
            }
3940
            foreach ($projectNodes as $projectNode) {
3941
                if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
3942
                    throw new Exception('error parsing publications');
3943
                if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
3944
                    throw new Exception('error parsing publications');
3945
                if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
3946
                    throw new Exception('error parsing publications');
3947
                if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
3948
                    throw new Exception('error parsing publications');
3949
                if (($fundingNodes = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
3950
                    throw new Exception('error parsing publications');
3951
                $project = new JObject();
3952
                $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
3953
                $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
3954
                $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
3955
                $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
3956
                $project -> funder = NULL;
3957
                if (($fundingNode = $fundingNodes->item(0)) == NULL)
3958
                    ;
3959
                else {
3960
                    if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
3961
                        throw new Exception('error parsing project');
3962
                    $project -> funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
3963
                    if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
3964
                        throw new Exception('error parsing project');
3965
                    $project -> funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
3966
                }
3967
                if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
3968
                    $publication->projects[] = $project;
3969
            }
3970
            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))
3971
                $publications[] = $publication;
3972
        }
3973
        return $publications;
3974
    }
3975

    
3976
    // Parse datasets from a search service XML response.
3977
    // xpath the DOMXPath to parse
3978
    // return datasets (array)
3979
    private function parseDatasets($xpath) {
3980
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
3981
            throw new Exception('error parsing datasets');
3982
        $datasets = array();
3983
        foreach ($resultNodes as $resultNode) {
3984
            if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
3985
                throw new Exception('error parsing datasets');
3986
            if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
3987
                throw new Exception('error parsing datasets');
3988
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
3989
                throw new Exception('error parsing datasets');
3990
            if (($authorNodes = $xpath->query('./field[@name = "hasAuthor"]', $resultNode)) == FALSE)
3991
                throw new Exception('error parsing datasets');
3992
            if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
3993
                throw new Exception('error parsing datasets');
3994
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
3995
                throw new Exception('error parsing datasets');
3996
            if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
3997
                throw new Exception('error parsing datasets');
3998
            if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
3999
                throw new Exception('error parsing datasets');
4000
            if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
4001
                throw new Exception('error parsing datasets');
4002
//            if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
4003
//                throw new Exception('error parsing datasets');
4004
            $dataset = new JObject();
4005
            $dataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4006
            $dataset->source = 'openaire';
4007
            $dataset->url = NULL;
4008
            $dataset->accessMode = NULL;
4009
            $dataset->datasources = array();
4010
            $dataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4011
            $dataset->authors = array();
4012
            $dataset->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
4013
            $dataset->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4014
            $dataset->language = (($languageNode = $languageNodes->item(0)) == NULL) ? NULL : trim($languageNode->nodeValue);
4015
            $dataset->projects = array();
4016
            $dataset->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
4017
//            $dataset->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
4018
            foreach ($datasourceNodes as $datasourceNode) {
4019
                if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
4020
                    throw new Exception('error parsing datasets');
4021
                if (($accessModeNodes = $xpath->query('./field[@name = "accessrightid"]/@value', $datasourceNode)) == FALSE)
4022
                    throw new Exception('error parsing datasets');
4023
                $datasource = new JObject();
4024
                $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4025
                $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
4026
                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))))) {
4027
                    $dataset->accessMode = $datasource->accessMode;
4028
                    $dataset->url = $datasource->url;
4029
                }
4030
                if (($datasource->url != NULL) || ($datasource->accessMode != NULL))
4031
                    $dataset->datasources[] = $datasource;
4032
            }
4033
            foreach ($authorNodes as $authorNode) {
4034
                if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
4035
                    throw new Exception('error parsing datasets');
4036
                if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
4037
                    throw new Exception('error parsing datasets');
4038
                if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
4039
                    throw new Exception('error parsing datasets');
4040
                $author = new JObject();
4041
                $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4042
                $author->lastName = NULL;
4043
                $author->firstName = NULL;
4044
                $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
4045
                $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
4046
                if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
4047
                    $dataset->authors[] = $author;
4048
                usort($dataset->authors, function ($author1, $author2) {
4049
                    return $author1->ranking - $author2->ranking;
4050
                });
4051
            }
4052
            foreach ($projectNodes as $projectNode) {
4053
                if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
4054
                    throw new Exception('error parsing datasets');
4055
                if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
4056
                    throw new Exception('error parsing datasets');
4057
                if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
4058
                    throw new Exception('error parsing datasets');
4059
                if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
4060
                    throw new Exception('error parsing datasets');
4061
                 if (($fundingNodes = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
4062
                    throw new Exception('error parsing datasets');
4063
                $project = new JObject();
4064
                $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4065
                $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
4066
                $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4067
                $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
4068
                if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
4069
                    $dataset->projects[] = $project;
4070
                  $project -> funder = NULL;
4071
                if (($fundingNode = $fundingNodes->item(0)) == NULL)
4072
                    ;
4073
                else {
4074
                    if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
4075
                        throw new Exception('error parsing datasets');
4076
                    $project -> funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
4077
                    if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
4078
                        throw new Exception('error parsing datasets');
4079
                    $project -> funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
4080
                }
4081
            }
4082
            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))
4083
                $datasets[] = $dataset;
4084
        }
4085
        return $datasets;
4086
    }
4087

    
4088
    // Parse projects from a search service XML response.
4089
    // xpath the DOMXPath to parse
4090
    // return projects (array)
4091
    private function parseProjects($xpath) {
4092
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
4093
            throw new Exception('error parsing projects');
4094
        $projects = array();
4095
        foreach ($resultNodes as $resultNode) {
4096
            if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $resultNode)) == FALSE)
4097
                throw new Exception('error parsing projects');
4098
            if (($acronymNodes = $xpath->query('./field[@name = "name"]/@value', $resultNode)) == FALSE)
4099
                throw new Exception('error parsing projects');
4100
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
4101
                throw new Exception('error parsing projects');
4102
            if (($codeNodes = $xpath->query('./field[@name = "code"]/@value', $resultNode)) == FALSE)
4103
                throw new Exception('error parsing projects');
4104
            if (($sc39Nodes = $xpath->query('./field[@name = "ec_sc39"]/@value', $resultNode)) == FALSE)
4105
                throw new Exception('error parsing projects');
4106
            if (($funderNodes = $xpath->query('./field[@name = "funder"]/field[@name = "fundershortname"]/@value', $resultNode)) == FALSE)
4107
                throw new Exception('error parsing projects');
4108
            if (($startYearNodes = $xpath->query('./field[@name = "startyear"]/@value', $resultNode)) == FALSE)
4109
                throw new Exception('error parsing projects');
4110
            if (($endYearNodes = $xpath->query('./field[@name = "endyear"]/@value', $resultNode)) == FALSE)
4111
                throw new Exception('error parsing projects');
4112
            if (($organizationNodes = $xpath->query('./field[@name = "organization"]', $resultNode)) == FALSE)
4113
                throw new Exception('error parsing projects');
4114
            $project = new JObject();
4115
            $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4116
            $project->acronym = ((($acronymNode = $acronymNodes->item(0)) == NULL) || (trim($acronymNode->nodeValue) == self :: UNKNOWN)) ? NULL : trim($acronymNode->nodeValue);
4117
            $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4118
            $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
4119
            $project->sc39 = (($sc39Node = $sc39Nodes->item(0)) == NULL) ? NULL : trim($sc39Node->nodeValue);
4120
            switch ($project->sc39) {
4121
                case 'true':
4122
                    $project->sc39 = TRUE;
4123
                    break;
4124
                case 'false':
4125
                    $project->sc39 = FALSE;
4126
                    break;
4127
                default:
4128
                    $project->sc39 = NULL;
4129
            }
4130
            $project->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
4131
            $project->startYear = (($startYearNode = $startYearNodes->item(0)) == NULL) ? NULL : intval(trim($startYearNode->nodeValue));
4132
            $project->endYear = (($endYearNode = $endYearNodes->item(0)) == NULL) ? NULL : intval(trim($endYearNode->nodeValue));
4133
            $project->organizations = array();
4134
            foreach ($organizationNodes as $organizationNode) {
4135
                if (($idNodes = $xpath->query('./field[@name = "organizationid"]/@value', $organizationNode)) == FALSE)
4136
                    throw new Exception('error parsing projects');
4137
                if (($shortNameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $organizationNode)) == FALSE)
4138
                    throw new Exception('error parsing projects');
4139
                if (($nameNodes = $xpath->query('./field[@name = "legalname"]/@value', $organizationNode)) == FALSE)
4140
                    throw new Exception('error parsing projects');
4141
                $organization = new JObject();
4142
                $organization->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4143
                $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
4144
                $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4145
                if (($organization->id != NULL) || ($organization->shortName != NULL) || ($organization->name != NULL))
4146
                    $project->organizations[] = $organization;
4147
            }
4148
            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))
4149
                $projects[] = $project;
4150
        }
4151
        return $projects;
4152
    }
4153
//
4154
//    // Parse people from a search service XML response.
4155
//    // xpath the DOMXPath to parse
4156
//    // return people (array)
4157
//    private function parsePeople($xpath) {
4158
//        if (($resultNodes = $xpath->query('/response/results/record')) == FALSE)
4159
//            throw new Exception('error parsing people');
4160
//        $people = array();
4161
//        foreach ($resultNodes as $resultNode) {
4162
//            if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $resultNode)) == FALSE)
4163
//                throw new Exception('error parsing people');
4164
//            if (($lastNameNodes = $xpath->query('./field[@name = "secondnames"]/@value', $resultNode)) == FALSE)
4165
//                throw new Exception('error parsing people');
4166
//            if (($firstNameNodes = $xpath->query('./field[@name = "firstname"]/@value', $resultNode)) == FALSE)
4167
//                throw new Exception('error parsing people');
4168
//            if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $resultNode)) == FALSE)
4169
//                throw new Exception('error parsing people');
4170
//            if (($countryNodes = $xpath->query('./field[@name = "nationalityid"]/@value', $resultNode)) == FALSE)
4171
//                throw new Exception('error parsing people');
4172
//            $person = new JObject();
4173
//            $person->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4174
//            $person->lastName = (($lastNameNode = $lastNameNodes->item(0)) == NULL) ? NULL : trim($lastNameNode->nodeValue);
4175
//            $person->firstName = (($firstNameNode = $firstNameNodes->item(0)) == NULL) ? NULL : trim($firstNameNode->nodeValue);
4176
//            $person->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
4177
//            $person->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
4178
//            if (($person->id != NULL) || ($person->lastName != NULL) || ($person->firstName != NULL) || ($person->fullName != NULL) || ($person->country != NULL))
4179
//                $people[] = $person;
4180
//        }
4181
//        return $people;
4182
//    }
4183

    
4184
    // Parse organizations from a search service XML response.
4185
    // xpath the DOMXPath to parse
4186
    // return organizations (array)
4187
    private function parseOrganizations($xpath) {
4188
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
4189
            throw new Exception('error parsing organizations');
4190
        $organizations = array();
4191
        foreach ($resultNodes as $resultNode) {
4192
            if (($idNodes = $xpath->query('./field[@name = "organizationId"]/@value', $resultNode)) == FALSE)
4193
                throw new Exception('error parsing organizations');
4194
            if (($shortNameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $resultNode)) == FALSE)
4195
                throw new Exception('error parsing organizations');
4196
            if (($nameNodes = $xpath->query('./field[@name = "legalname"]/@value', $resultNode)) == FALSE)
4197
                throw new Exception('error parsing organizations');
4198
            if (($countryNodes = $xpath->query('./field[@name = "countryname"]/@value', $resultNode)) == FALSE)
4199
                throw new Exception('error parsing organizations');
4200
            if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
4201
                throw new Exception('error parsing organizations');
4202
            $organization = new JObject();
4203
            $organization->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4204
            $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
4205
            $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4206
            $organization->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
4207
            $organization->projects = array();
4208
            foreach ($projectNodes as $projectNode) {
4209
                if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
4210
                    throw new Exception('error parsing organizations');
4211
                if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
4212
                    throw new Exception('error parsing organizations');
4213
                if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
4214
                    throw new Exception('error parsing organizations');
4215
                if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
4216
                    throw new Exception('error parsing organizations');
4217
                $project = new JObject();
4218
                $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4219
                $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
4220
                $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4221
                $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
4222
                if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
4223
                    $organization->projects[] = $project;
4224
            }
4225
            if (($organization->id != NULL) || ($organization->shortName != NULL) || ($organization->name != NULL) || ($organization->country != NULL) || ($organization->projects != NULL))
4226
                $organizations[] = $organization;
4227
        }
4228
        return $organizations;
4229
    }
4230

    
4231
    // Parse datasources from a search service XML response.
4232
    // xpath the DOMXPath to parse
4233
    // return datasources (array)
4234
    private function parseDatasources($xpath) {
4235
        if (($resultNodes = $xpath->query('/response/results/result')) == FALSE)
4236
            throw new Exception('error parsing datasources');
4237
        $datasources = array();
4238
        foreach ($resultNodes as $resultNode) {
4239
            if (($idNodes = $xpath->query('./field[@name = "datasourceId"]/@value', $resultNode)) == FALSE)
4240
                throw new Exception('error parsing datasources');
4241
            if (($typeNodes = $xpath->query('./field[@name = "datasourcetypename"]/@value', $resultNode)) == FALSE)
4242
                throw new Exception('error parsing datasources');
4243
            if (($typeIdNodes = $xpath->query('./field[@name = "datasourcetypeuiid"]/@value_original', $resultNode)) == FALSE)
4244
                throw new Exception('error parsing datasources');
4245
            if (($compatibilityNodes = $xpath->query('./field[@name = "openairecompatibilityid"]/@value', $resultNode)) == FALSE)
4246
                throw new Exception('error parsing datasources');
4247
            if (($urlNodes = $xpath->query('./field[@name = "websiteurl"]/@value', $resultNode)) == FALSE)
4248
                throw new Exception('error parsing datasources');
4249
            if (($nameNodes = $xpath->query('./field[@name = "officialname"]/@value', $resultNode)) == FALSE)
4250
                throw new Exception('error parsing datasources');
4251
            if (($englishNameNodes = $xpath->query('./field[@name = "englishname"]/@value', $resultNode)) == FALSE)
4252
                throw new Exception('error parsing datasources');
4253
            if (($itemsNodes = $xpath->query('./field[@name = "odnumberofitems"]/@value', $resultNode)) == FALSE)
4254
                throw new Exception('error parsing datasources');
4255
            if (($dateNodes = $xpath->query('./field[@name = "odnumberofitemsdate"]/@value', $resultNode)) == FALSE)
4256
                throw new Exception('error parsing datasources');
4257
            if (($languageNodes = $xpath->query('./field[@name = "odlanguages"]/@value', $resultNode)) == FALSE)
4258
                throw new Exception('error parsing datasources');
4259
            if (($policyNodes = $xpath->query('./field[@name = "odpolicies"]/@value', $resultNode)) == FALSE)
4260
                throw new Exception('error parsing datasources');
4261
            if (($contentNodes = $xpath->query('./field[@name = "odcontenttypes"]/@value', $resultNode)) == FALSE)
4262
                throw new Exception('error parsing datasources');
4263
            if (($oaiPmhNodes = $xpath->query('./field[@name = "accessinfopackage"]/@value', $resultNode)) == FALSE)
4264
                throw new Exception('error parsing datasources');
4265
//            if (($descriptionNodes = $xpath->query('./field[@name = "oddescription"]/@value', $resultNode)) == FALSE)
4266
//                throw new Exception('error parsing datasources');
4267
            if (($organizationNodes = $xpath->query('./field[@name = "organization"]', $resultNode)) == FALSE)
4268
                throw new Exception('error parsing datasources');
4269
            $datasource = new JObject();
4270
            $datasource->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4271
            $datasource->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4272
            $datasource->typeId = (($typeIdNode = $typeIdNodes->item(0)) == NULL) ? NULL : trim($typeIdNode->nodeValue);
4273
            $datasource->compatibility = (($compatibilityNode = $compatibilityNodes->item(0)) == NULL) ? NULL : trim($compatibilityNode->nodeValue);
4274
            $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4275
            $datasource->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4276
            $datasource->englishName = (($englishNameNode = $englishNameNodes->item(0)) == NULL) ? NULL : trim($englishNameNode->nodeValue);
4277
            $datasource->items = (($itemsNode = $itemsNodes->item(0)) == NULL) ? NULL : intval(trim($itemsNode->nodeValue));
4278
            $datasource->date = (($dateNode = $dateNodes->item(0)) == NULL) ? NULL : strtotime(trim($dateNode->nodeValue));
4279
            $datasource->languages = array();
4280
            $datasource->policies = array();
4281
            $datasource->contents = array();
4282
            $datasource->oaiPmhUrls = array();
4283
//            $datasource->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
4284
            $datasource->organizations = array();
4285
            foreach ($languageNodes as $languageNode) {
4286
                if (trim($languageNode->nodeValue) != NULL)
4287
                    $datasource->languages[] = trim($languageNode->nodeValue);
4288
            }
4289
            foreach ($policyNodes as $policyNode) {
4290
                if (trim($policyNode->nodeValue) != NULL)
4291
                    $datasource->policies[] = trim($policyNode->nodeValue);
4292
            }
4293
            foreach ($contentNodes as $contentNode) {
4294
                if (trim($contentNode->nodeValue) != NULL)
4295
                    $datasource->contents[] = trim($contentNode->nodeValue);
4296
            }
4297
            foreach ($oaiPmhNodes as $oaiPmhNode) {
4298
                if (trim($oaiPmhNode->nodeValue) != NULL)
4299
                    $datasource->oaiPmhUrls[] = trim($oaiPmhNode->nodeValue);
4300
            }
4301
            foreach ($organizationNodes as $organizationNode) {
4302
                if (($idNodes = $xpath->query('./field[@name = "organizationid"]/@value', $organizationNode)) == FALSE)
4303
                    throw new Exception('error parsing datasources');
4304
                if (($shortNameNodes = $xpath->query('./field[@name = "legalname"]/@value', $organizationNode)) == FALSE)
4305
                    throw new Exception('error parsing datasources');
4306
                if (($nameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $organizationNode)) == FALSE)
4307
                    throw new Exception('error parsing datasources');
4308
                if (($countryNodes = $xpath->query('./field[@name = "countryname"]/@value', $organizationNode)) == FALSE)
4309
                    throw new Exception('error parsing datasources');
4310
                $organization = new JObject();
4311
                $organization->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4312
                $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
4313
                $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4314
                $organization->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
4315
                if (($organization->id != NULL) || ($organization->shortName != NULL) || ($organization->name != NULL) || ($organization->country != NULL))
4316
                    $datasource->organizations[] = $organization;
4317
            }
4318
            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))
4319
                $datasources[] = $datasource;
4320
        }
4321
        return $datasources;
4322
    }
4323

    
4324
    // Parse a single publication from a search service XML response.
4325
    // xpath the DOMXPath to parse
4326
    // return publication (object)
4327
    private function parsePublication($xpath, $locale) {
4328
        if ((($resultsNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL)) // result
4329
            throw new Exception('error parsing publication');
4330
        if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
4331
            throw new Exception('error parsing publication');
4332
        if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
4333
            throw new Exception('error parsing publication');
4334
        if (($curationNodes = $xpath->query('./field[@name = "underCuration"]/@value', $resultNode)) == FALSE)
4335
            throw new Exception('error parsing publication');
4336
        if (($authorNodes = $xpath->query('./field[@name = "hasAuthor"]', $resultNode)) == FALSE)
4337
            throw new Exception('error parsing publication');
4338
        if (($dateNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
4339
            throw new Exception('error parsing publication');
4340
        if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
4341
            throw new Exception('error parsing publication');
4342
        if (($journalNodes = $xpath->query('./field[@name = "journal"]/@value', $resultNode)) == FALSE)
4343
            throw new Exception('error parsing publication');
4344
        if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
4345
            throw new Exception('error parsing publication');
4346
        if (($typeNodes = $xpath->query('./field[@name ="resulttypename"]/@value', $resultNode)) == FALSE)
4347
            throw new Exception('error parsing publication');
4348
        if (($subjectNodes = $xpath->query('./field[@name = "subject" and field[@name="inferred" and @value="false"]]', $resultNode)) == FALSE)
4349
            throw new Exception('error parsing publication');
4350
        if (($inferredSubjectNodes = $xpath->query('./field[@name = "subject" and field[@name="inferred" and @value="true"]]', $resultNode)) == FALSE)
4351
            throw new Exception('error parsing publication');
4352
        if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
4353
            throw new Exception('error parsing publication');
4354
//        if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
4355
//            throw new Exception('error parsing publication');
4356
        if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
4357
            throw new Exception('error parsing publication');
4358
        if (($collectedFromNodes = $xpath->query('./field[@name = "collectedfrom"]', $resultNode)) == FALSE)
4359
            throw new Exception('error parsing publication');
4360
        if (($sourceNodes = $xpath->query('./field[@name = "source"]/@value', $resultNode)) == FALSE)
4361
            throw new Exception('error parsing publication');
4362
        if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
4363
            throw new Exception('error parsing publication');
4364
        if (($pidNodes = $xpath->query('./field[@name = "pid"]', $resultNode)) == FALSE)
4365
            throw new Exception('error parsing publication');
4366
        if (($similarNodes = $xpath->query('./field[@name = "hasAmongTopNSimilarDocuments"]', $resultNode)) == FALSE)
4367
            throw new Exception('error parsing publication');
4368
        if (($relatedNodes = $xpath->query('./field[@name = "isRelatedTo"]', $resultNode)) == FALSE)
4369
            throw new Exception('error parsing publication');
4370
        if (($externalReferenceNodes = $xpath->query('./field[@name = "externalreference"]', $resultNode)) == FALSE)
4371
            throw new Exception('error parsing publication');
4372
        if (($contextNodes = $xpath->query('./field[@name = "context"]', $resultNode)) == FALSE)
4373
            throw new Exception('error parsing publication');
4374
        if (($citationNodes = $xpath->query('./field[@name = "citation"]', $resultNode)) == FALSE)
4375
            throw new Exception('error parsing publication');
4376
         if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
4377
            throw new Exception('error parsing publication');
4378
        $publication = new JObject();
4379
        $publication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4380
        $publication->source = 'openaire';
4381
        $publication->accessMode = NULL;
4382
        $publication->url = NULL;
4383
        $publication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4384
        $publication->underCuration = (($curationNode = $curationNodes->item(0)) == NULL) ? NULL : trim($curationNode->nodeValue);
4385
        $publication->authors = array();
4386
        $publication->year = (($dateNode = $dateNodes->item(0)) == NULL) ? NULL : intval(trim($dateNode->nodeValue));
4387
        $publication->date = ($dateNode == NULL) ? NULL : strtotime(trim($dateNode->nodeValue));
4388
        $publication->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
4389
        $publication->journal = (($journalNode = $journalNodes->item(0)) == NULL) ? NULL : trim($journalNode->nodeValue);
4390
        $publication->languages = array();
4391
        $publication->type = array();
4392
        $publication->subjects = array();
4393
        $publication->categorizedSubjects = array();
4394
        $publication->inferredSubjects = array();
4395
        $publication->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
4396
//        $publication->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
4397
        $publication->datasources = array();
4398
        $publication->collectedFrom = array();
4399
        $publication->sources = array();
4400
        $publication->projects = array();
4401
        $publication->pids = array();
4402
        $publication->similarPublications = array();
4403
        $publication->relatedPublications = array();
4404
        $publication->relatedDatasets = array();
4405
        $publication->externalPublications = array();
4406
        $publication->bioentities = array();
4407
        $publication->externalDatasets = array();
4408
        $publication->contexts = array();
4409
        $publication->citations = array();
4410
        foreach ($authorNodes as $authorNode) {
4411
            if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
4412
                throw new Exception('error parsing publication');
4413
            if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
4414
                throw new Exception('error parsing publication');
4415
            if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
4416
                throw new Exception('error parsing publication');
4417
            $author = new JObject();
4418
            $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4419
            $author->lastName = NULL;
4420
            $author->firstName = NULL;
4421
            $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
4422
            $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
4423
            if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
4424
                $publication->authors[] = $author;
4425
            usort($publication->authors, function ($author1, $author2) {
4426
                return $author1->ranking - $author2->ranking;
4427
            });
4428
        }
4429
        foreach ($languageNodes as $languageNode) {
4430
            if ((($language = trim($languageNode->nodeValue)) != NULL) && ($language != self :: UNDETERMINED))
4431
                $publication->languages[] = $language;
4432
        }
4433
        foreach ($subjectNodes as $subjectNode) {
4434
            if (($titleNodes = $xpath->query('./@value', $subjectNode)) == FALSE)
4435
                throw new Exception('error parsing publications');
4436
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $subjectNode)) == FALSE)
4437
                throw new Exception('error parsing publications');
4438
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $subjectNode)) == FALSE)
4439
                throw new Exception('error parsing publications');
4440
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $subjectNode)) == FALSE)
4441
                throw new Exception('error parsing publications');
4442
            if (($taxonomyNodes = $xpath->query('./field[@name = "taxonomy"]/@value', $subjectNode)) == FALSE)
4443
                throw new Exception('error parsing publications');
4444
            $subject = new JObject();
4445
            $subject->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4446
            $subject->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
4447
            $subject->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4448
            $subject->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4449
            $subject->taxonomy = (($taxonomyNode = $taxonomyNodes->item(0)) == NULL) ? NULL : trim($taxonomyNode->nodeValue);
4450
            if (($subject->title != NULL) || ($subject->inferred != NULL) || ($subject->trust != NULL) || ($subject->provenance != NULL)){
4451
                if($subject->taxonomy != NULL && $subject->taxonomy != "keyword"){                    
4452
                    $publication->categorizedSubjects[$subject->taxonomy][] =  $subject;
4453
                }else {
4454
                    $publication->subjects[] = $subject;
4455
                }   
4456
                
4457
                   
4458
            }
4459
                
4460
        }
4461
        $inferredSubjectsTempArray = array();
4462
        foreach ($inferredSubjectNodes as $subjectNode) {
4463
            if (($titleNodes = $xpath->query('./@value', $subjectNode)) == FALSE)
4464
                throw new Exception('error parsing publications');
4465
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $subjectNode)) == FALSE)
4466
                throw new Exception('error parsing publications');
4467
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $subjectNode)) == FALSE)
4468
                throw new Exception('error parsing publications');
4469
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $subjectNode)) == FALSE)
4470
                throw new Exception('error parsing publications');
4471
            if (($taxonomyNodes = $xpath->query('./field[@name = "taxonomy"]/@value', $subjectNode)) == FALSE)
4472
                throw new Exception('error parsing publications');
4473

    
4474
            $subject = new JObject();
4475
            $subject->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4476
            $subject->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
4477
            $subject->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4478
            $subject->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4479
            $subject->taxonomy = (($taxonomyNode = $taxonomyNodes->item(0)) == NULL) ? NULL : trim($taxonomyNode->nodeValue);
4480

    
4481
            if (($subject->title != NULL) || ($subject->inferred != NULL) || ($subject->trust != NULL) || ($subject->provenance != NULL) || ($subject->taxonomy != NULL)) {
4482
                $miniSubject = new JObject();
4483
                $miniSubject->title = $subject->title;
4484
                $miniSubject->trust = $subject->trust;
4485
                $inferredSubjectsTempArray[$subject->taxonomy][] = $miniSubject;
4486
            }
4487
        }
4488
        //Sort the subjects on trust
4489
        foreach ($inferredSubjectsTempArray as $taxonomyKey => $subjectsValues) {
4490
            usort($subjectsValues, function ($a, $b) {
4491
                if ($a->trust == $b->trust) {
4492
                    return 0;
4493
                }return ($a->trust > $b->trust) ? -1 : 1;
4494
            });
4495
            $publication->inferredSubjects[$taxonomyKey] = $subjectsValues;
4496
        }
4497

    
4498
        foreach ($datasourceNodes as $datasourceNode) {
4499
            if (($idNodes = $xpath->query('./field[@name = "hostedby"]/@value_original', $datasourceNode)) == FALSE)
4500
                throw new Exception('error parsing publication');
4501
            if (($nameNodes = $xpath->query('./field[@name = "hostedbyname"]/@value', $datasourceNode)) == FALSE)
4502
                throw new Exception('error parsing publication');
4503
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
4504
                throw new Exception('error parsing publication');
4505
            if (($accessModeNodes = $xpath->query('./field[@name = "accessrightid"]/@value', $datasourceNode)) == FALSE)
4506
                throw new Exception('error parsing publication');
4507
            if (($typeNameNodes = $xpath->query('./field[@name = "typename"]/@value', $datasourceNode)) == FALSE)
4508
                throw new Exception('error parsing publication');
4509
            $datasource = new JObject();
4510
            $datasource->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4511
            $datasource->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4512
            $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4513
            $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
4514
            $datasource->type = (($typeNameNode = $typeNameNodes->item(0)) == NULL) ? NULL : trim($typeNameNode->nodeValue);
4515

    
4516
            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))))) {
4517
                $publication->accessMode = $datasource->accessMode;
4518
                $publication->url = $datasource->url;
4519

    
4520
                if (!in_array($datasource->type, $publication->type)) {
4521
                    array_push($publication->type, $datasource->type);
4522
                }
4523
            }
4524
            if (($datasource->id != NULL) || ($datasource->name != NULL) || ($datasource->url != NULL) || ($datasource->accessMode != NULL))
4525
                $publication->datasources[] = $datasource;
4526
        }
4527
        foreach ($collectedFromNodes as $collectedFromNode) {
4528
            if (($idNodes = $xpath->query('./field[@name = "collectedfromid"]/@value', $collectedFromNode)) == FALSE)
4529
                throw new Exception('error parsing publication');
4530
            if (($nameNodes = $xpath->query('./field[@name = "collectedfromname"]/@value', $collectedFromNode)) == FALSE)
4531
                throw new Exception('error parsing publication');
4532
            $collectedFrom = new JObject();
4533
            $collectedFrom->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4534
            $collectedFrom->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4535
            if (($collectedFrom->id != NULL) || ($collectedFrom->name != NULL))
4536
                $publication->collectedFrom[] = $collectedFrom;
4537
        }
4538
         foreach ($sourceNodes as $sourceNode) {
4539
            if (($source = trim($sourceNode->nodeValue)) != NULL)
4540
                $publication->sources[] = $source;
4541
        }
4542
        foreach ($projectNodes as $projectNode) {
4543
            if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
4544
                throw new Exception('error parsing publication');
4545
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $projectNode)) == FALSE)
4546
                throw new Exception('error parsing publication');
4547
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $projectNode)) == FALSE)
4548
                throw new Exception('error parsing publication');
4549
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $projectNode)) == FALSE)
4550
                throw new Exception('error parsing publication');
4551
            if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
4552
                throw new Exception('error parsing publication');
4553
            if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
4554
                throw new Exception('error parsing publication');
4555
            if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
4556
                throw new Exception('error parsing publication');
4557
            if (($fundingNodes = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
4558
                throw new Exception('error parsing publication');
4559

    
4560

    
4561
            $project = new JObject();
4562
            $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4563
            $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
4564
            $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4565
            $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
4566
            $project->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
4567
            $project->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4568
            $project->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4569
            /*   $project -> funding = new JObject();
4570
              if (($fundingNode = $fundingNodes -> item(0)) == NULL) ;
4571
              else
4572
              {
4573
              if (($funding0Nodes = $xpath -> query('./field[@name = "funding_level_0"]/@value', $fundingNode)) == FALSE)
4574
              throw new Exception('error parsing publication test');
4575
              $project -> funding->funding_level_0 = (($funding0Node = $funding0Nodes -> item(0)) == NULL) ? NULL : trim($funding0Node -> nodeValue);
4576
              } */
4577

    
4578
            $project->funding = new JObject();
4579
            $project->funding->funding_level_0 = NULL;
4580
            $project->funding->funding_level_1 = NULL;
4581
            $project->funding->funding_level_2 = NULL;
4582

    
4583
            if (($fundingNode = $fundingNodes->item(0)) == NULL)
4584
                ;
4585
            else {
4586
                 if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
4587
                    throw new Exception('error parsing project');
4588
                if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
4589
                    throw new Exception('error parsing project');
4590
                if (($funding0Nodes = $xpath->query('./field[@name = "funding_level_0"]', $fundingNode)) == FALSE)
4591
                    throw new Exception('error parsing project');
4592
                if (($funding1Nodes = $xpath->query('./field[@name = "funding_level_1"]', $fundingNode)) == FALSE)
4593
                    throw new Exception('error parsing project');
4594
                if (($funding2Nodes = $xpath->query('./field[@name = "funding_level_2"]', $fundingNode)) == FALSE)
4595
                    throw new Exception('error parsing project');
4596

    
4597
                $project->funding->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
4598
                $project->funding->funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
4599

    
4600
                if (($funding0Node = $funding0Nodes->item(0)) == NULL)
4601
                    ;
4602
                else {
4603
                    if (($funding0NameNodes = $xpath->query('./@value', $funding0Node)) == FALSE)
4604
                        throw new Exception('error parsing publication test');
4605
                    $project->funding->funding_level_0 = (($funding0NameNode = $funding0NameNodes->item(0)) == NULL) ? NULL : trim($funding0NameNode->nodeValue);
4606
                   // $array = explode("::", $project->funding->funding_level_0);
4607
                   // $project->funding->funding_level_0 = $array[sizeof($array) - 1];
4608
                }
4609
                if (($funding1Node = $funding1Nodes->item(0)) == NULL)
4610
                    ;
4611
                else {
4612
                    if (($funding1NameNodes = $xpath->query('./@value', $funding1Node)) == FALSE)
4613
                        throw new Exception('error parsing publication test');
4614
                    $project->funding->funding_level_1 = (($funding1NameNode = $funding1NameNodes->item(0)) == NULL) ? NULL : trim($funding1NameNode->nodeValue);
4615
                   // $array = explode("::", $project->funding->funding_level_1);
4616
                    //$project->funding->funding_level_1 = $array[sizeof($array) - 1];
4617
                }
4618
                if (($funding2Node = $funding2Nodes->item(0)) == NULL)
4619
                    ;
4620
                else {
4621
                    if (($funding2NameNodes = $xpath->query('./@valu', $funding2Node)) == FALSE)
4622
                        throw new Exception('error parsing publication test');
4623
                    $project->funding->funding_level_2 = (($funding2NameNode = $funding2NameNodes->item(0)) == NULL) ? NULL : trim($funding2NameNode->nodeValue);
4624
                   // $array = explode("::", $project->funding->funding_level_2);
4625
                   // $project->funding->funding_level_2 = $array[sizeof($array) - 1];
4626
                }
4627
            }
4628
            //!!!!
4629

    
4630
            if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
4631
                $publication->projects[] = $project;
4632
        }
4633
        foreach ($pidNodes as $pidNode) {
4634
            if (($classNodes = $xpath->query('./field[@name = "classid"]/@value', $pidNode)) == FALSE)
4635
                throw new Exception('error parsing publication');
4636
            if (($valueNodes = $xpath->query('./field[@name = "value"]/@value', $pidNode)) == FALSE)
4637
                throw new Exception('error parsing publication');
4638
            $pid = new JObject();
4639
            $pid->clazz = (($classNode = $classNodes->item(0)) == NULL) ? NULL : trim($classNode->nodeValue);
4640
            $pid->value = (($valueNode = $valueNodes->item(0)) == NULL) ? NULL : trim($valueNode->nodeValue);
4641
            if (($pid->clazz != NULL) && ($pid->value != NULL))
4642
                $publication->pids[] = $pid;
4643
        }
4644
        foreach ($similarNodes as $similarNode) {
4645
            if (($typeNodes = $xpath->query('./field[@name = "resulttypename"]/@value', $similarNode)) == FALSE)
4646
                throw new Exception('error parsing publication');
4647
            if (($typeNameNodes = $xpath->query('./field[@name = "resulttypename"]/@value', $similarNode)) == FALSE)
4648
                throw new Exception('error parsing publication');
4649
            if (($idNodes = $xpath->query('./field[@name = "resultid"]/@value', $similarNode)) == FALSE)
4650
                throw new Exception('error parsing publication');
4651
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $similarNode)) == FALSE)
4652
                throw new Exception('error parsing publication');
4653
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $similarNode)) == FALSE)
4654
                throw new Exception('error parsing publication');
4655
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $similarNode)) == FALSE)
4656
                throw new Exception('error parsing publication');
4657
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $similarNode)) == FALSE)
4658
                throw new Exception('error parsing publication');
4659
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $similarNode)) == FALSE)
4660
                throw new Exception('error parsing publication');
4661
            if (($similarityNodes = $xpath->query('./field[@name = "similarity"]/@value', $similarNode)) == FALSE)
4662
                throw new Exception('error parsing publication');
4663

    
4664
            $similarPublication = new JObject();
4665
            $similarPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4666
            $similarPublication->source = 'openaire';
4667
            $similarPublication->url = NULL;
4668
            $similarPublication->accessMode = NULL;
4669
            $similarPublication->datasources = array();
4670
            $similarPublication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4671
            $similarPublication->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
4672
            $similarPublication->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4673
            $similarPublication->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4674
            $similarPublication->authors = array();
4675
            $similarPublication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4676
            $similarPublication->projects = array();
4677
            $similarPublication->embargoEndDate = NULL;
4678
            $similarPublication->description = NULL;
4679
            $similarPublication->similarity = (($similarityNode = $similarityNodes->item(0)) == NULL) ? NULL : trim($similarityNode->nodeValue);
4680
            $similarPublication->similarity = number_format((float) $similarPublication->similarity, 2);
4681
            if (($similarPublication->id != NULL) || ($similarPublication->title != NULL) || ($similarPublication->year != NULL)) {
4682
                $publication->similarPublications[] = $similarPublication;
4683
            }
4684
        }
4685
        foreach ($relatedNodes as $relatedNode) {
4686
            if (($typeNodes = $xpath->query('./field[@name = "resulttypename"]/@value', $relatedNode)) == FALSE)
4687
                throw new Exception('error parsing publication');
4688
            if (($idNodes = $xpath->query('./field[@name = "resultid"]/@value', $relatedNode)) == FALSE)
4689
                throw new Exception('error parsing publication');
4690
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
4691
                throw new Exception('error parsing publication');
4692
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
4693
                throw new Exception('error parsing publication');
4694
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
4695
                throw new Exception('error parsing publication');
4696
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $relatedNode)) == FALSE)
4697
                throw new Exception('error parsing publication');
4698
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $relatedNode)) == FALSE)
4699
                throw new Exception('error parsing publication');
4700
            switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
4701
                case self :: PUBLICATION:
4702
                    $relatedPublication = new JObject();
4703
                    $relatedPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4704
                    $relatedPublication->source = 'openaire';
4705
                    $relatedPublication->url = NULL;
4706
                    $relatedPublication->accessMode = NULL;
4707
                    $relatedPublication->datasources = array();
4708
                    $relatedPublication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4709
                    $relatedPublication->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
4710
                    $relatedPublication->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4711
                    $relatedPublication->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4712
                    $relatedPublication->authors = array();
4713
                    $relatedPublication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4714
                    $relatedPublication->projects = array();
4715
                    $relatedPublication->embargoEndDate = NULL;
4716
                    $relatedPublication->description = NULL;
4717
                    if (($relatedPublication->id != NULL) || ($relatedPublication->title != NULL) || ($relatedPublication->year != NULL))
4718
                        $publication->relatedPublications[] = $relatedPublication;
4719
                    break;
4720
                case self :: DATASET:
4721
                    $relatedDataset = new JObject();
4722
                    $relatedDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4723
                    $relatedDataset->source = 'openaire';
4724
                    $relatedDataset->url = NULL;
4725
                    $relatedDataset->accessMode = NULL;
4726
                    $relatedDataset->datasources = array();
4727
                    $relatedDataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4728
                    $relatedDataset->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
4729
                    $relatedDataset->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
4730
                    $relatedDataset->trust = number_format((float) $relatedDataset->trust, 2);
4731
                    $relatedDataset->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
4732
                    $relatedDataset->authors = array();
4733
                    $relatedDataset->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
4734
                    $relatedDataset->projects = array();
4735
                    $relatedDataset->embargoEndDate = NULL;
4736
                    $relatedDataset->description = NULL;
4737
                    if (($relatedDataset->id != NULL) || ($relatedDataset->title != NULL) || ($relatedDataset->year != NULL))
4738
                        $publication->relatedDatasets[] = $relatedDataset;
4739
                    break;
4740
            }
4741
        }
4742
        foreach ($externalReferenceNodes as $externalReferenceNode) {
4743
            if (($typeNodes = $xpath->query('./field[@name = "typeid"]/@value', $externalReferenceNode)) == FALSE)
4744
                throw new Exception('error parsing publication');
4745
            if (($idNodes = $xpath->query('./field[@name = "refidentifier"]/@value', $externalReferenceNode)) == FALSE)
4746
                throw new Exception('error parsing publication');
4747
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $externalReferenceNode)) == FALSE)
4748
                throw new Exception('error parsing publication');
4749
            if (($labelNodes = $xpath->query('./field[@name = "label"]/@value', $externalReferenceNode)) == FALSE)
4750
                throw new Exception('error parsing publication');
4751
            if (($siteNameNodes = $xpath->query('./field[@name = "sitename"]/@value', $externalReferenceNode)) == FALSE)
4752
                throw new Exception('error parsing publication');
4753
                    $externalEntity = new JObject();
4754
                    //dedup_wf_001::2cd206acf2cfd37f1a7c28823c63112b
4755
                    $externalEntity-> type = (($typeNode =$typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4756
                    $externalEntity-> id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4757
                    $externalEntity-> url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4758
                    $externalEntity-> title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
4759
                    $externalEntity-> sitename = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
4760
                     if (!isset($publication->bioentities[$externalEntity->sitename])){
4761
                        $bioentities = array();
4762
                        $publication->bioentities[$externalEntity->sitename]=$bioentities;
4763
                     }
4764
                     $publication->bioentities[$externalEntity->sitename] []= $externalEntity;
4765

    
4766
           /* switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
4767
                case self :: PUBLICATION:
4768
                    $externalPublication = new JObject();
4769
                    $externalPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4770
                    $externalPublication->source = NULL;
4771
                    $externalPublication->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4772
                    $externalPublication->accessMode = NULL;
4773
                    $externalPublication->datasources = array();
4774
                    $externalPublication->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
4775
                    $externalPublication->authors = array();
4776
                    $site = new JObject();
4777
                    $site->id = NULL;
4778
                    $site->lastName = NULL;
4779
                    $site->firstName = NULL;
4780
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
4781
                    if ($site->fullName != NULL)
4782
                        $externalPublication->authors[] = $site;
4783
                    $externalPublication->year = NULL;
4784
                    $externalPublication->projects = array();
4785
                    $externalPublication->embargoEndDate = NULL;
4786
                    $externalPublication->description = NULL;
4787
                    if (($externalPublication->id != NULL) || ($externalPublication->url != NULL) || ($externalPublication->title != NULL))
4788
                        $publication->externalPublications[] = $externalPublication;
4789
                    break;
4790
                case self :: DATASET:
4791
                    $externalDataset = new JObject();
4792
                    $externalDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4793
                    $externalDataset->source = NULL;
4794
                    $externalDataset->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4795
                    $externalDataset->accessMode = NULL;
4796
                    $externalDataset->datasources = array();
4797
                    $externalDataset->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
4798
                    $externalDataset->authors = array();
4799
                    $site = new JObject();
4800
                    $site->id = NULL;
4801
                    $site->lastName = NULL;
4802
                    $site->firstName = NULL;
4803
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
4804
                    if ($site->fullName != NULL)
4805
                        $externalDataset->authors[] = $site;
4806
                    $externalDataset->year = NULL;
4807
                    $externalDataset->projects = array();
4808
                    $externalDataset->embargoEndDate = NULL;
4809
                    $externalDataset->description = NULL;
4810
                    if (($externalDataset->id != NULL) || ($externalDataset->url != NULL) || ($externalDataset->title != NULL))
4811
                        $publication->externalDatasets[] = $externalDataset;
4812
            }*/
4813
        }
4814
        foreach ($contextNodes as $contextNode) {
4815
            if (($idNodes = $xpath->query('./@value', $contextNode)) == FALSE)
4816
                throw new Exception('error parsing publication');
4817
            if (($nameNodes = $xpath->query('./@value_original', $contextNode)) == FALSE)
4818
                throw new Exception('error parsing publication');
4819
            if (($typeNodes = $xpath->query('./field[@name = "contexttype"]/@value', $contextNode)) == FALSE)
4820
                throw new Exception('error parsing publication');
4821
            if (($categoryNodes = $xpath->query('./field[@name = "category"]', $contextNode)) == FALSE)
4822
                throw new Exception('error parsing publication');
4823
            $context = new JObject();
4824
            $context->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4825
            $context->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4826
            $context->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4827
            $context->categories = array();
4828
            foreach ($categoryNodes as $categoryNode) {
4829
                if (($idNodes = $xpath->query('./@value_original', $categoryNode)) == FALSE)
4830
                    throw new Exception('error parsing publication');
4831
                if (($nameNodes = $xpath->query('./@value', $categoryNode)) == FALSE)
4832
                    throw new Exception('error parsing publication');
4833
                if (($conceptNodes = $xpath->query('./field[@name = "concept"]', $categoryNode)) == FALSE)
4834
                    throw new Exception('error parsing publication');
4835
                $category = new JObject();
4836
                $category->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4837
                $category->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4838
                $category->concepts = array();
4839
                foreach ($conceptNodes as $conceptNode) {
4840
                    if (($idNodes = $xpath->query('./@value_original', $conceptNode)) == FALSE)
4841
                        throw new Exception('error parsing publication');
4842
                    if (($nameNodes = $xpath->query('./@value', $conceptNode)) == FALSE)
4843
                        throw new Exception('error parsing publication');
4844
                    $concept = new JObject();
4845
                    $concept->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4846
                    $concept->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4847
                    if (($concept->id != NULL) || ($concept->name != NULL))
4848
                        $category->concepts[] = $concept;
4849
                }
4850
                if (($category->id != NULL) || ($category->name != NULL) || ($category->concepts != NULL))
4851
                    $context->categories[] = $category;
4852
            }
4853
            if (($context->id != NULL) || ($context->name != NULL) || ($context->categories != NULL))
4854
                $publication->contexts[] = $context;
4855
        }
4856
        foreach ($citationNodes as $citationNode) {
4857
            if (($titleNodes = $xpath->query('./field[@name = "rawText"]/@value', $citationNode)) == FALSE)
4858
                throw new Exception('error parsing publications');
4859
            if (($idsNodes = $xpath->query('./field[@name = "citationId"]', $citationNode)) == FALSE)
4860
                throw new Exception('error parsing publications');
4861
            $citation = new JObject();
4862
            $citation->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4863
            $citation->ids = array();
4864
            foreach ($idsNodes as $citationIdNode) {
4865
                if (($idNodes = $xpath->query('./field[@name = "id"]/@value', $citationIdNode)) == FALSE)
4866
                    throw new Exception('error parsing publications');
4867
                if (($typeNodes = $xpath->query('./field[@name = "type"]/@value', $citationIdNode)) == FALSE)
4868
                    throw new Exception('error parsing publications');
4869
                if (($confidenceLevelNodes = $xpath->query('./field[@name = "confidenceLevel"]/@value', $citationIdNode)) == FALSE)
4870
                    throw new Exception('error parsing publications');
4871
                $ids = new JObject();
4872
                $ids->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4873
                $ids->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4874
                $ids->confidenceLevel = (($confidenceLevelNode = $confidenceLevelNodes->item(0)) == NULL) ? NULL : trim($confidenceLevelNode->nodeValue);
4875
                $citation->ids[] = $ids;
4876
            }
4877

    
4878
            $publication->citations[] = $citation;
4879
            /*  $subject -> inferred = (($inferredNode = $inferredNodes -> item(0)) == NULL) ? NULL : trim($inferredNode -> nodeValue)=="true"?true:false;
4880
              $subject -> trust = (($trustNode = $trustNodes -> item(0)) == NULL) ? NULL : trim($trustNode -> nodeValue);
4881
              $subject -> provenance = (($provenanceNode = $provenanceNodes -> item(0)) == NULL) ? NULL : trim($provenanceNode -> nodeValue);
4882
              $subject -> taxonomy = (($taxonomyNode = $taxonomyNodes -> item(0)) == NULL) ? NULL : trim($taxonomyNode -> nodeValue);
4883
             */
4884
        }
4885
        return $publication;
4886
    }
4887

    
4888
    // Parse a single dataset from a search service XML response.
4889
    // xpath the DOMXPath to parse
4890
    // return dataset (object)
4891
    private function parseDataset($xpath, $locale) {
4892
        if ((($resultsNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL)) // result
4893
            throw new Exception('error parsing dataset');
4894
        if (($idNodes = $xpath->query('./field[@name = "resultId"]/@value', $resultNode)) == FALSE)
4895
            throw new Exception('error parsing dataset');
4896
        if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
4897
            throw new Exception('error parsing dataset');
4898
        if (($authorNodes = $xpath->query('./field[@name = "hasAuthor"]', $resultNode)) == FALSE)
4899
            throw new Exception('error parsing dataset');
4900
        if (($dateNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $resultNode)) == FALSE)
4901
            throw new Exception('error parsing dataset');
4902
        if (($publisherNodes = $xpath->query('./field[@name = "publisher"]/@value', $resultNode)) == FALSE)
4903
            throw new Exception('error parsing dataset');
4904
        if (($journalNodes = $xpath->query('./field[@name = "journal"]/@value', $resultNode)) == FALSE)
4905
            throw new Exception('error parsing dataset');
4906
        if (($languageNodes = $xpath->query('./field[@name = "language"]/@value', $resultNode)) == FALSE)
4907
            throw new Exception('error parsing dataset');
4908
        if (($typeNodes = $xpath->query('./field[@name ="resulttypename"]/@value', $resultNode)) == FALSE)
4909
            throw new Exception('error parsing dataset');
4910
        if (($subjectNodes = $xpath->query('./field[@name = "subject"]/@value', $resultNode)) == FALSE)
4911
            throw new Exception('error parsing dataset');
4912
        if (($embargoEndDateNodes = $xpath->query('./field[@name = "embargoenddate"]/@value', $resultNode)) == FALSE)
4913
            throw new Exception('error parsing dataset');
4914
//        if (($descriptionNodes = $xpath->query('./field[@name = "description"]/@value', $resultNode)) == FALSE)
4915
//            throw new Exception('error parsing dataset');
4916
        if (($datasourceNodes = $xpath->query('./field[@name = "datasource"]', $resultNode)) == FALSE)
4917
            throw new Exception('error parsing dataset');
4918
        if (($collectedFromNodes = $xpath->query('./field[@name = "collectedfrom"]', $resultNode)) == FALSE)
4919
            throw new Exception('error parsing dataset');
4920
        if (($sourceNodes = $xpath->query('./field[@name = "source"]/@value', $resultNode)) == FALSE)
4921
            throw new Exception('error parsing dataset');
4922
        if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
4923
            throw new Exception('error parsing dataset');
4924
        if (($pidNodes = $xpath->query('./field[@name = "pid"]', $resultNode)) == FALSE)
4925
            throw new Exception('error parsing dataset');
4926
        if (($relatedNodes = $xpath->query('./field[@name = "isRelatedTo"]', $resultNode)) == FALSE)
4927
            throw new Exception('error parsing dataset');
4928
        if (($externalReferenceNodes = $xpath->query('./field[@name = "externalreference"]', $resultNode)) == FALSE)
4929
            throw new Exception('error parsing dataset');
4930
        if (($contextNodes = $xpath->query('./field[@name = "context"]', $resultNode)) == FALSE)
4931
            throw new Exception('error parsing dataset');
4932
        $dataset = new JObject();
4933
        $dataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4934
        $dataset->source = 'openaire';
4935
        $dataset->accessMode = NULL;
4936
        $dataset->url = NULL;
4937
        $dataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
4938
        $dataset->authors = array();
4939
        $dataset->year = (($dateNode = $dateNodes->item(0)) == NULL) ? NULL : intval(trim($dateNode->nodeValue));
4940
        $dataset->date = ($dateNode == NULL) ? NULL : strtotime(trim($dateNode->nodeValue));
4941
        $dataset->publisher = (($publisherNode = $publisherNodes->item(0)) == NULL) ? NULL : trim($publisherNode->nodeValue);
4942
        $dataset->journal = (($journalNode = $journalNodes->item(0)) == NULL) ? NULL : trim($journalNode->nodeValue);
4943
        $dataset->languages = array();
4944
        $dataset->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
4945
        $dataset->subjects = array();
4946
        $dataset->embargoEndDate = (($embargoEndDateNode = $embargoEndDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($embargoEndDateNode->nodeValue));
4947
//        $dataset->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
4948
        $dataset->datasources = array();
4949
        $dataset->collectedFrom = array();
4950
        $dataset->sources = array();
4951
        $dataset->projects = array();
4952
        $dataset->pids = array();
4953
        $dataset->relatedPublications = array();
4954
        $dataset->relatedDatasets = array();
4955
        $dataset->externalPublications = array();
4956
        $dataset->externalDatasets = array();
4957
        $dataset->contexts = array();
4958
        foreach ($authorNodes as $authorNode) {
4959
            if (($idNodes = $xpath->query('./field[@name = "personId"]/@value', $authorNode)) == FALSE)
4960
                throw new Exception('error parsing dataset');
4961
            if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $authorNode)) == FALSE)
4962
                throw new Exception('error parsing dataset');
4963
            if (($rankingNodes = $xpath->query('./field[@name = "ranking"]/@value', $authorNode)) == FALSE)
4964
                throw new Exception('error parsing publication');
4965
            $author = new JObject();
4966
            $author->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4967
            $author->lastName = NULL;
4968
            $author->firstName = NULL;
4969
            $author->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
4970
            $author->ranking = (($rankingNode = $rankingNodes->item(0)) == NULL) ? 0 : intval(trim($rankingNode->nodeValue));
4971
            if (($author->id != NULL) || ($author->lastName != NULL) || ($author->firstName != NULL) || ($author->fullName != NULL))
4972
                $dataset->authors[] = $author;
4973
            usort($dataset->authors, function ($author1, $author2) {
4974
                return $author1->ranking - $author2->ranking;
4975
            });
4976
        }
4977
        foreach ($languageNodes as $languageNode) {
4978
            if ((($language = trim($languageNode->nodeValue)) != NULL) && ($language != self :: UNDETERMINED))
4979
                $dataset->languages[] = $language;
4980
        }
4981
        foreach ($subjectNodes as $subjectNode) {
4982
            if (($subject = trim($subjectNode->nodeValue)) != NULL)
4983
                $dataset->subjects[] = $subject;
4984
        }
4985
        foreach ($datasourceNodes as $datasourceNode) {
4986
            if (($idNodes = $xpath->query('./field[@name = "hostedby"]/@value_original', $datasourceNode)) == FALSE)
4987
                throw new Exception('error parsing dataset');
4988
            if (($nameNodes = $xpath->query('./field[@name = "hostedbyname"]/@value', $datasourceNode)) == FALSE)
4989
                throw new Exception('error parsing dataset');
4990
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $datasourceNode)) == FALSE)
4991
                throw new Exception('error parsing dataset');
4992
            if (($accessModeNodes = $xpath->query('./field[@name = "accessrightid"]/@value', $datasourceNode)) == FALSE)
4993
                throw new Exception('error parsing dataset');
4994
            $datasource = new JObject();
4995
            $datasource->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
4996
            $datasource->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
4997
            $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
4998
// TODO
4999
            if (substr($datasource->url, 0, strlen('http://dx.doi.org/http://zenodo.org/record/')) == 'http://dx.doi.org/http://zenodo.org/record/') {
5000
                $url = substr($datasource->url, strlen('http://dx.doi.org/'));
5001
                JLog :: add('Converting datasource URL ' . $datasource->url . ' to ' . $url, JLog :: DEBUG, self :: LOG);
5002
                $datasource->url = $url;
5003
            }
5004
// TODO
5005
            $datasource->accessMode = (($accessModeNode = $accessModeNodes->item(0)) == NULL) ? NULL : trim($accessModeNode->nodeValue);
5006
            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))))) {
5007
                $dataset->accessMode = $datasource->accessMode;
5008
                $dataset->url = $datasource->url;
5009
            }
5010
            if (($datasource->id != NULL) || ($datasource->name != NULL) || ($datasource->url != NULL) || ($datasource->accessMode != NULL))
5011
                $dataset->datasources[] = $datasource;
5012
        }
5013
        foreach ($collectedFromNodes as $collectedFromNode) {
5014
            if (($idNodes = $xpath->query('./field[@name = "collectedfromid"]/@value', $collectedFromNode)) == FALSE)
5015
                throw new Exception('error parsing dataset');
5016
            if (($nameNodes = $xpath->query('./field[@name = "collectedfromname"]/@value', $collectedFromNode)) == FALSE)
5017
                throw new Exception('error parsing dataset');
5018
            $collectedFrom = new JObject();
5019
            $collectedFrom->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5020
            $collectedFrom->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5021
            if (($collectedFrom->id != NULL) || ($collectedFrom->name != NULL))
5022
                $dataset->collectedFrom[] = $collectedFrom;
5023
        }
5024
        foreach ($sourceNodes as $sourceNode) {
5025
            if (($source = trim($sourceNode->nodeValue)) != NULL)
5026
                $dataset->sources[] = $source;
5027
        }
5028
        foreach ($projectNodes as $projectNode) {
5029
            if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
5030
                throw new Exception('error parsing publication');
5031
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $projectNode)) == FALSE)
5032
                throw new Exception('error parsing publication');
5033
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $projectNode)) == FALSE)
5034
                throw new Exception('error parsing publication');
5035
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $projectNode)) == FALSE)
5036
                throw new Exception('error parsing publication');
5037
            if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
5038
                throw new Exception('error parsing publication');
5039
            if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
5040
                throw new Exception('error parsing publication');
5041
            if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
5042
                throw new Exception('error parsing publication');
5043
            if (($fundingNodes = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
5044
                throw new Exception('error parsing publication');
5045

    
5046

    
5047
            $project = new JObject();
5048
            $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5049
            $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
5050
            $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
5051
            $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
5052
            $project->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
5053
            $project->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
5054
            $project->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
5055
            /*   $project -> funding = new JObject();
5056
              if (($fundingNode = $fundingNodes -> item(0)) == NULL) ;
5057
              else
5058
              {
5059
              if (($funding0Nodes = $xpath -> query('./field[@name = "funding_level_0"]/@value', $fundingNode)) == FALSE)
5060
              throw new Exception('error parsing publication test');
5061
              $project -> funding->funding_level_0 = (($funding0Node = $funding0Nodes -> item(0)) == NULL) ? NULL : trim($funding0Node -> nodeValue);
5062
              } */
5063

    
5064
            $project->funding = new JObject();
5065
            $project->funding->funding_level_0 = NULL;
5066
            $project->funding->funding_level_1 = NULL;
5067
            $project->funding->funding_level_2 = NULL;
5068

    
5069
            if (($fundingNode = $fundingNodes->item(0)) == NULL)
5070
                ;
5071
            else {
5072
                if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $fundingNode)) == FALSE)
5073
                    throw new Exception('error parsing project');
5074
                if (($funderShortNameNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $fundingNode)) == FALSE)
5075
                    throw new Exception('error parsing project');
5076
                if (($funding0Nodes = $xpath->query('./field[@name = "funding_level_0"]', $fundingNode)) == FALSE)
5077
                    throw new Exception('error parsing project');
5078
                if (($funding1Nodes = $xpath->query('./field[@name = "funding_level_1"]', $fundingNode)) == FALSE)
5079
                    throw new Exception('error parsing project');
5080
                if (($funding2Nodes = $xpath->query('./field[@name = "funding_level_2"]', $fundingNode)) == FALSE)
5081
                    throw new Exception('error parsing project');
5082
                $project->funding->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5083
                $project->funding->funderShortName = (($funderShortNameNode = $funderShortNameNodes->item(0)) == NULL) ? NULL : trim($funderShortNameNode->nodeValue);
5084

    
5085
                if (($funding0Node = $funding0Nodes->item(0)) == NULL)
5086
                    ;
5087
                else {
5088
                    if (($funding0NameNodes = $xpath->query('./@value', $funding0Node)) == FALSE)
5089
                        throw new Exception('error parsing publication test');
5090
                    $project->funding->funding_level_0 = (($funding0NameNode = $funding0NameNodes->item(0)) == NULL) ? NULL : trim($funding0NameNode->nodeValue);
5091
                    //$array = explode("::", $project->funding->funding_level_0);
5092
                    //$project->funding->funding_level_0 = $array[sizeof($array) - 1];
5093
                }
5094
                if (($funding1Node = $funding1Nodes->item(0)) == NULL)
5095
                    ;
5096
                else {
5097
                    if (($funding1NameNodes = $xpath->query('./@value', $funding1Node)) == FALSE)
5098
                        throw new Exception('error parsing publication test');
5099
                    $project->funding->funding_level_1 = (($funding1NameNode = $funding1NameNodes->item(0)) == NULL) ? NULL : trim($funding1NameNode->nodeValue);
5100
                    //$array = explode("::", $project->funding->funding_level_1);
5101
                    //$project->funding->funding_level_1 = $array[sizeof($array) - 1];
5102
                }
5103
                if (($funding2Node = $funding2Nodes->item(0)) == NULL)
5104
                    ;
5105
                else {
5106
                    if (($funding2NameNodes = $xpath->query('./@value', $funding2Node)) == FALSE)
5107
                        throw new Exception('error parsing publication test');
5108
                    $project->funding->funding_level_2 = (($funding2NameNode = $funding2NameNodes->item(0)) == NULL) ? NULL : trim($funding2NameNode->nodeValue);
5109
                    //$array = explode("::", $project->funding->funding_level_2);
5110
                    //$project->funding->funding_level_2 = $array[sizeof($array) - 1];
5111
                }
5112
                /* 	if (($idNodes = $xpath -> query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
5113
                  throw new Exception('error parsing dataset');
5114
                  if (($acronymNodes = $xpath -> query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
5115
                  throw new Exception('error parsing dataset');
5116
                  if (($titleNodes = $xpath -> query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
5117
                  throw new Exception('error parsing dataset');
5118
                  if (($codeNodes = $xpath -> query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
5119
                  throw new Exception('error parsing dataset');
5120
                  $project = new JObject();
5121
                  $project -> id = (($idNode = $idNodes -> item(0)) == NULL) ? NULL : trim($idNode -> nodeValue);
5122
                  $project -> acronym = (($acronymNode = $acronymNodes -> item(0)) == NULL) ? NULL : ((trim($acronymNode -> nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode -> nodeValue));
5123
                  $project -> title = (($titleNode = $titleNodes -> item(0)) == NULL) ? NULL : trim($titleNode -> nodeValue);
5124
                  $project -> code = (($codeNode = $codeNodes -> item(0)) == NULL) ? NULL : trim($codeNode -> nodeValue);
5125

    
5126
                 */
5127
            }
5128
            if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL))
5129
                $dataset->projects[] = $project;
5130
        }
5131
        foreach ($pidNodes as $pidNode) {
5132
            if (($classNodes = $xpath->query('./field[@name = "classid"]/@value', $pidNode)) == FALSE)
5133
                throw new Exception('error parsing dataset');
5134
            if (($valueNodes = $xpath->query('./field[@name = "value"]/@value', $pidNode)) == FALSE)
5135
                throw new Exception('error parsing dataset');
5136
            $pid = new JObject();
5137
            $pid->clazz = (($classNode = $classNodes->item(0)) == NULL) ? NULL : trim($classNode->nodeValue);
5138
            $pid->value = (($valueNode = $valueNodes->item(0)) == NULL) ? NULL : trim($valueNode->nodeValue);
5139
            if (($pid->clazz != NULL) && ($pid->value != NULL))
5140
                $dataset->pids[] = $pid;
5141
        }
5142
        foreach ($relatedNodes as $relatedNode) {
5143
            if (($typeNodes = $xpath->query('./field[@name = "resulttypename"]/@value', $relatedNode)) == FALSE)
5144
                throw new Exception('error parsing publication');
5145
            if (($idNodes = $xpath->query('./field[@name = "resultid"]/@value', $relatedNode)) == FALSE)
5146
                throw new Exception('error parsing publication');
5147
            if (($inferredNodes = $xpath->query('./field[@name = "inferred"]/@value', $relatedNode)) == FALSE)
5148
                throw new Exception('error parsing publication');
5149
            if (($trustNodes = $xpath->query('./field[@name = "trust"]/@value', $relatedNode)) == FALSE)
5150
                throw new Exception('error parsing publication');
5151
            if (($provenanceNodes = $xpath->query('./field[@name = "provenance"]/@value', $relatedNode)) == FALSE)
5152
                throw new Exception('error parsing publication');
5153
            if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $relatedNode)) == FALSE)
5154
                throw new Exception('error parsing publication');
5155
            if (($yearNodes = $xpath->query('./field[@name = "dateofacceptance"]/@value', $relatedNode)) == FALSE)
5156
                throw new Exception('error parsing publication');
5157
            switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
5158
                case self :: PUBLICATION:
5159
                    $relatedPublication = new JObject();
5160
                    $relatedPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5161
                    $relatedPublication->source = 'openaire';
5162
                    $relatedPublication->url = NULL;
5163
                    $relatedPublication->accessMode = NULL;
5164
                    $relatedPublication->datasources = array();
5165
                    $relatedPublication->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
5166
                    $relatedPublication->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
5167
                    $relatedPublication->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
5168
                    $relatedPublication->trust = ($relatedPublication->trust != null) ? number_format((float) $relatedPublication->trust, 2) : 'NULL';
5169
                    $relatedPublication->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
5170
                    $relatedPublication->authors = array();
5171
                    $relatedPublication->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
5172
                    $relatedPublication->projects = array();
5173
                    $relatedPublication->embargoEndDate = NULL;
5174
                    $relatedPublication->description = NULL;
5175
                    if (($relatedPublication->id != NULL) || ($relatedPublication->title != NULL) || ($relatedPublication->year != NULL))
5176
                        $dataset->relatedPublications[] = $relatedPublication;
5177
                    break;
5178
                case self :: DATASET:
5179
                    $relatedDataset = new JObject();
5180
                    $relatedDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5181
                    $relatedDataset->source = 'openaire';
5182
                    $relatedDataset->url = NULL;
5183
                    $relatedDataset->accessMode = NULL;
5184
                    $relatedDataset->datasources = array();
5185
                    $relatedDataset->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
5186
                    $relatedDataset->inferred = (($inferredNode = $inferredNodes->item(0)) == NULL) ? NULL : (trim($inferredNode->nodeValue) == "true" ? true : false);
5187
                    $relatedDataset->trust = (($trustNode = $trustNodes->item(0)) == NULL) ? NULL : trim($trustNode->nodeValue);
5188
                    $relatedDataset->provenance = (($provenanceNode = $provenanceNodes->item(0)) == NULL) ? NULL : trim($provenanceNode->nodeValue);
5189
                    $relatedDataset->authors = array();
5190
                    $relatedDataset->year = (($yearNode = $yearNodes->item(0)) == NULL) ? NULL : intval(trim($yearNode->nodeValue));
5191
                    $relatedDataset->projects = array();
5192
                    $relatedDataset->embargoEndDate = NULL;
5193
                    $relatedDataset->description = NULL;
5194
                    if (($relatedDataset->id != NULL) || ($relatedDataset->title != NULL) || ($relatedDataset->year != NULL))
5195
                        $dataset->relatedDatasets[] = $relatedDataset;
5196
                    break;
5197
            }
5198
        }
5199
        foreach ($externalReferenceNodes as $externalReferenceNode) {
5200
            if (($typeNodes = $xpath->query('./field[@name = "typeid"]/@value', $externalReferenceNode)) == FALSE)
5201
                throw new Exception('error parsing publication');
5202
            if (($idNodes = $xpath->query('./field[@name = "refidentifier"]/@value', $externalReferenceNode)) == FALSE)
5203
                throw new Exception('error parsing publication');
5204
            if (($urlNodes = $xpath->query('./field[@name = "url"]/@value', $externalReferenceNode)) == FALSE)
5205
                throw new Exception('error parsing publication');
5206
            if (($labelNodes = $xpath->query('./field[@name = "label"]/@value', $externalReferenceNode)) == FALSE)
5207
                throw new Exception('error parsing publication');
5208
            if (($siteNameNodes = $xpath->query('./field[@name = "sitename"]/@value', $externalReferenceNode)) == FALSE)
5209
                throw new Exception('error parsing publication');
5210
            switch ((($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue)) {
5211
                case self :: PUBLICATION:
5212
                    $externalPublication = new JObject();
5213
                    $externalPublication->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5214
                    $externalPublication->source = NULL;
5215
                    $externalPublication->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5216
                    $externalPublication->accessMode = NULL;
5217
                    $externalPublication->datasources = array();
5218
                    $externalPublication->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
5219
                    $externalPublication->authors = array();
5220
                    $site = new JObject();
5221
                    $site->id = NULL;
5222
                    $site->lastName = NULL;
5223
                    $site->firstName = NULL;
5224
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
5225
                    if ($site->fullName != NULL)
5226
                        $externalPublication->authors[] = $site;
5227
                    $externalPublication->year = NULL;
5228
                    $externalPublication->projects = array();
5229
                    $externalPublication->embargoEndDate = NULL;
5230
                    $externalPublication->description = NULL;
5231
                    if (($externalPublication->id != NULL) || ($externalPublication->url != NULL) || ($externalPublication->title != NULL))
5232
                        $dataset->externalPublications[] = $externalPublication;
5233
                    break;
5234
                case self :: DATASET:
5235
                    $externalDataset = new JObject();
5236
                    $externalDataset->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5237
                    $externalDataset->source = NULL;
5238
                    $externalDataset->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5239
                    $externalDataset->accessMode = NULL;
5240
                    $externalDataset->datasources = array();
5241
                    $externalDataset->title = (($labelNode = $labelNodes->item(0)) == NULL) ? NULL : trim($labelNode->nodeValue);
5242
                    $externalDataset->authors = array();
5243
                    $site = new JObject();
5244
                    $site->id = NULL;
5245
                    $site->lastName = NULL;
5246
                    $site->firstName = NULL;
5247
                    $site->fullName = (($siteNameNode = $siteNameNodes->item(0)) == NULL) ? NULL : trim($siteNameNode->nodeValue);
5248
                    if ($site->fullName != NULL)
5249
                        $externalDataset->authors[] = $site;
5250
                    $externalDataset->year = NULL;
5251
                    $externalDataset->projects = array();
5252
                    $externalDataset->embargoEndDate = NULL;
5253
                    $externalDataset->description = NULL;
5254
                    if (($externalDataset->id != NULL) || ($externalDataset->url != NULL) || ($externalDataset->title != NULL))
5255
                        $dataset->externalDatasets[] = $externalDataset;
5256
            }
5257
        }
5258
        foreach ($contextNodes as $contextNode) {
5259
            if (($idNodes = $xpath->query('./@value', $contextNode)) == FALSE)
5260
                throw new Exception('error parsing dataset');
5261
            if (($nameNodes = $xpath->query('./@value_original', $contextNode)) == FALSE)
5262
                throw new Exception('error parsing dataset');
5263
            if (($categoryNodes = $xpath->query('./field[@name = "category"]', $contextNode)) == FALSE)
5264
                throw new Exception('error parsing dataset');
5265
            $context = new JObject();
5266
            $context->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5267
            $context->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5268
            $context->categories = array();
5269
            foreach ($categoryNodes as $categoryNode) {
5270
                if (($idNodes = $xpath->query('./@value', $categoryNode)) == FALSE)
5271
                    throw new Exception('error parsing dataset');
5272
                if (($nameNodes = $xpath->query('./@value_original', $categoryNode)) == FALSE)
5273
                    throw new Exception('error parsing dataset');
5274
                if (($conceptNodes = $xpath->query('./field[@name = "concept"]', $categoryNode)) == FALSE)
5275
                    throw new Exception('error parsing dataset');
5276
                $category = new JObject();
5277
                $category->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5278
                $category->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5279
                $category->concepts = array();
5280
                foreach ($conceptNodes as $conceptNode) {
5281
                    if (($idNodes = $xpath->query('./@value', $conceptNode)) == FALSE)
5282
                        throw new Exception('error parsing dataset');
5283
                    if (($nameNodes = $xpath->query('./@value_original', $conceptNode)) == FALSE)
5284
                        throw new Exception('error parsing dataset');
5285
                    $concept = new JObject();
5286
                    $concept->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5287
                    $concept->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5288
                    if (($concept->id != NULL) || ($concept->name != NULL))
5289
                        $category->concepts[] = $concept;
5290
                }
5291
                if (($category->id != NULL) || ($category->name != NULL) || ($category->concepts != NULL))
5292
                    $context->categories[] = $category;
5293
            }
5294
            if (($context->id != NULL) || ($context->name != NULL) || ($context->categories != NULL))
5295
                $dataset->contexts[] = $context;
5296
        }
5297
        return $dataset;
5298
    }
5299

    
5300
    // Parse a single project from a search service XML response.
5301
    // xpath the DOMXPath to parse
5302
    // return project (object)
5303
    private function parseProject($xpath) {
5304
        if ((($resultsNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL))
5305
            throw new Exception('error parsing project');
5306
        if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $resultNode)) == FALSE)
5307
                throw new Exception('error parsing projects');
5308
        if (($acronymNodes = $xpath->query('./field[@name = "name"]/@value', $resultNode)) == FALSE)
5309
            throw new Exception('error parsing project');
5310
        if (($titleNodes = $xpath->query('./field[@name = "title"]/@value', $resultNode)) == FALSE)
5311
            throw new Exception('error parsing project');
5312
        if (($funderNodes = $xpath->query('./field[@name = "funder"]/field[@name = "fundershortname"]/@value', $resultNode)) == FALSE)
5313
            throw new Exception('error parsing project');
5314
        if (($fundingStreamNodes = $xpath->query('./field[@name = "funding_level_0"]/field[@name = "fundingname"]/@value', $resultNode)) == FALSE)
5315
            throw new Exception('error parsing project');
5316
        if (($scientificAreaNodes = $xpath->query('./field[@name = "funding_level_1"]/field[@name = "fundingname"]/@value', $resultNode)) == FALSE)
5317
            throw new Exception('error parsing project');
5318
         if (($fundingStreamLevel2Nodes = $xpath->query('./field[@name = "funding_level_2"]/field[@name = "fundingname"]/@value', $resultNode)) == FALSE)
5319
            throw new Exception('error parsing project');
5320
        if (($callNodes = $xpath->query('./field[@name = "call_identifier"]/@value', $resultNode)) == FALSE)
5321
            throw new Exception('error parsing project');
5322
        if (($codeNodes = $xpath->query('./field[@name = "code"]/@value', $resultNode)) == FALSE)
5323
            throw new Exception('error parsing project');
5324
        if (($startYearNodes = $xpath->query('./field[@name = "startyear"]/@value', $resultNode)) == FALSE)
5325
            throw new Exception('error parsing project');
5326
        if (($startDateNodes = $xpath->query('./field[@name = "startdate"]/@value', $resultNode)) == FALSE)
5327
            throw new Exception('error parsing project');
5328
        if (($endYearNodes = $xpath->query('./field[@name = "endyear"]/@value', $resultNode)) == FALSE)
5329
            throw new Exception('error parsing project');
5330
        if (($endDateNodes = $xpath->query('./field[@name = "enddate"]/@value', $resultNode)) == FALSE)
5331
            throw new Exception('error parsing project');
5332
        if (($sc39Nodes = $xpath->query('./field[@name = "ec_sc39"]/@value', $resultNode)) == FALSE)
5333
            throw new Exception('error parsing project');
5334
        if (($oaMandateNodes = $xpath->query('./field[@name = "oamandatepublications"]/@value', $resultNode)) == FALSE)
5335
            throw new Exception('error parsing project');
5336
        if (($datapilotNodes = $xpath->query('./field[@name = "ecarticle29_3"]/@value', $resultNode)) == FALSE)
5337
            throw new Exception('error parsing project');
5338
        if (($funding0Nodes = $xpath->query('./field[@name = "funding_level_0"]', $resultNode)) == FALSE)
5339
            throw new Exception('error parsing project');
5340
        if (($funding1Nodes = $xpath->query('./field[@name = "funding_level_1"]', $resultNode)) == FALSE)
5341
            throw new Exception('error parsing project');
5342
        if (($funding2Nodes = $xpath->query('./field[@name = "funding_level_2"]', $resultNode)) == FALSE)
5343
            throw new Exception('error parsing project');
5344
        if (($organizationNodes = $xpath->query('./field[@name = "organization"]', $resultNode)) == FALSE)
5345
            throw new Exception('error parsing project');
5346
        if (($urlNodes = $xpath->query('./field[@name = "websiteurl"]/@value', $resultNode)) == FALSE)
5347
            throw new Exception('error parsing datasources');
5348
        $project = new JObject();
5349
        $project->projectId = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5350
        $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
5351
        $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
5352
        $project->funder = (($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5353
        $project->fundingStream = (($fundingStreamNode = $fundingStreamNodes->item(0)) == NULL) ? NULL : trim($fundingStreamNode->nodeValue);
5354
        $project->scientificArea = (($scientificAreaNode = $scientificAreaNodes->item(0)) == NULL) ? NULL : trim($scientificAreaNode->nodeValue);
5355
        $project->fundingStreamLevel2 = (($fundingStreamLevel2Node = $fundingStreamLevel2Nodes->item(0)) == NULL) ? NULL : trim($fundingStreamLevel2Node->nodeValue);
5356
        $project->call = (($callNode = $callNodes->item(0)) == NULL) ? NULL : trim($callNode->nodeValue);
5357
        $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
5358
        $project->startYear = (($startYearNode = $startYearNodes->item(0)) == NULL) ? NULL : intval(trim($startYearNode->nodeValue));
5359
        $project->startDate = (($startDateNode = $startDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($startDateNode->nodeValue));
5360
        $project->endYear = (($endYearNode = $endYearNodes->item(0)) == NULL) ? NULL : intval(trim($endYearNode->nodeValue));
5361
        $project->endDate = (($endDateNode = $endDateNodes->item(0)) == NULL) ? NULL : strtotime(trim($endDateNode->nodeValue));
5362
        $project->sc39 = (($sc39Node = $sc39Nodes->item(0)) == NULL) ? NULL : trim($sc39Node->nodeValue);
5363
        switch ($project->sc39) {
5364
            case 'true':
5365
                $project->sc39 = TRUE;
5366
                break;
5367
            case 'false':
5368
                $project->sc39 = FALSE;
5369
                break;
5370
            default:
5371
                $project->sc39 = NULL;
5372
        }
5373
        $project->oaMandate = (($oaMandateNode = $oaMandateNodes->item(0)) == NULL) ? NULL : trim($oaMandateNode->nodeValue);
5374
        switch ($project->oaMandate) {
5375
            case 'true':
5376
                $project->oaMandate = TRUE;
5377
                break;
5378
            case 'false':
5379
                $project->oaMandate = FALSE;
5380
                break;
5381
            default:
5382
                $project->oaMandate = NULL;
5383
        }
5384
        $project->dataPilot = (($datapilotNode = $datapilotNodes->item(0)) == NULL) ? NULL : trim($datapilotNode->nodeValue);
5385
        switch ($project->dataPilot) {
5386
            case 'true':
5387
                $project->dataPilot = TRUE;
5388
                break;
5389
            case 'false':
5390
                $project->dataPilot = FALSE;
5391
                break;
5392
            default:
5393
                $project->dataPilot = NULL;
5394
        }
5395
        $project->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5396
        $project->funding = new JObject();
5397
        $project->funding->funding_level_0 = NULL;
5398
        $project->funding->funding_level_1 = NULL;
5399
        $project->funding->funding_level_2 = NULL;
5400
        if (($funding0Node = $funding0Nodes->item(0)) == NULL)
5401
            ;
5402
        else {
5403
            if (($funding0NameNodes = $xpath->query('./field[@name = "fundingname"]/@value', $funding0Node)) == FALSE)
5404
                throw new Exception('error parsing publication test');
5405
            $project->funding->funding_level_0 = (($funding0NameNode = $funding0NameNodes->item(0)) == NULL) ? NULL : trim($funding0NameNode->nodeValue);
5406
        }
5407
        if (($funding1Node = $funding1Nodes->item(0)) == NULL)
5408
            ;
5409
        else {
5410
            if (($funding1NameNodes = $xpath->query('./field[@name = "fundingname"]/@value', $funding1Node)) == FALSE)
5411
                throw new Exception('error parsing publication test');
5412
            $project->funding->funding_level_1 = (($funding1NameNode = $funding1NameNodes->item(0)) == NULL) ? NULL : trim($funding1NameNode->nodeValue);
5413
        }
5414
        if (($funding2Node = $funding2Nodes->item(0)) == NULL)
5415
            ;
5416
        else {
5417
            if (($funding2NameNodes = $xpath->query('./field[@name = "fundingname"]/@value', $funding2Node)) == FALSE)
5418
                throw new Exception('error parsing publication test');
5419
            $project->funding->funding_level_2 = (($funding2NameNode = $funding2NameNodes->item(0)) == NULL) ? NULL : trim($funding2NameNode->nodeValue);
5420
        }
5421
        $project->organizations = array();
5422
        foreach ($organizationNodes as $organizationNode) {
5423
            if (($idNodes = $xpath->query('./field[@name = "organizationid"]/@value', $organizationNode)) == FALSE)
5424
                throw new Exception('error parsing project');
5425
            if (($shortNameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $organizationNode)) == FALSE)
5426
                throw new Exception('error parsing project');
5427
            if (($nameNodes = $xpath->query('./field[@name = "legalname"]/@value', $organizationNode)) == FALSE)
5428
                throw new Exception('error parsing project');
5429
            $organization = new JObject();
5430
            $organization->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5431
            $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
5432
            $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5433
            if (($organization->id != NULL) || ($organization->shortName != NULL) || ($organization->name != NULL))
5434
                $project->organizations[] = $organization;
5435
        }
5436
        return $project;
5437
    }
5438

    
5439
    // Parse a single person from a search service XML response.
5440
    // xpath the DOMXPath to parse
5441
    // return person (object)
5442
    private function parsePerson($xpath) {
5443
        if ((($resultsNodes = $xpath->query('/response/results/record')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL))
5444
            throw new Exception('error parsing person');
5445
        if (($lastNameNodes = $xpath->query('./field[@name = "secondnames"]/@value', $resultNode)) == FALSE)
5446
            throw new Exception('error parsing person');
5447
        if (($firstNameNodes = $xpath->query('./field[@name = "firstname"]/@value', $resultNode)) == FALSE)
5448
            throw new Exception('error parsing person');
5449
        if (($fullNameNodes = $xpath->query('./field[@name = "fullname"]/@value', $resultNode)) == FALSE)
5450
            throw new Exception('error parsing person');
5451
        if (($countryNodes = $xpath->query('./field[@name = "nationalityname"]/@value', $resultNode)) == FALSE)
5452
            throw new Exception('error parsing person');
5453
        $person = new JObject();
5454
        $person->lastName = (($lastNameNode = $lastNameNodes->item(0)) == NULL) ? NULL : trim($lastNameNode->nodeValue);
5455
        $person->firstName = (($firstNameNode = $firstNameNodes->item(0)) == NULL) ? NULL : trim($firstNameNode->nodeValue);
5456
        $person->fullName = (($fullNameNode = $fullNameNodes->item(0)) == NULL) ? NULL : trim($fullNameNode->nodeValue);
5457
        $person->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
5458
        return $person;
5459
    }
5460

    
5461
    // Parse a single organization from a search service XML response.
5462
    // xpath the DOMXPath to parse
5463
    // return organization (object)
5464
    private function parseOrganization($xpath) {
5465
        if ((($resultNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultNodes->item(0)) == NULL))
5466
            throw new Exception('error parsing organization');
5467
        if (($shortNameNodes = $xpath->query('./field[@name = "legalshortname"]/@value', $resultNode)) == FALSE)
5468
            throw new Exception('error parsing organization');
5469
        if (($nameNodes = $xpath->query('./field[@name = "legalname"]/@value', $resultNode)) == FALSE)
5470
            throw new Exception('error parsing organization');
5471
        if (($urlNodes = $xpath->query('./field[@name = "websiteurl"]/@value', $resultNode)) == FALSE)
5472
            throw new Exception('error parsing organization');
5473
        if (($countryNodes = $xpath->query('./field[@name = "countryname"]/@value', $resultNode)) == FALSE)
5474
            throw new Exception('error parsing organization');
5475
        if (($projectNodes = $xpath->query('./field[@name = "project"]', $resultNode)) == FALSE)
5476
            throw new Exception('error parsing organization');
5477
        $organization = new JObject();
5478
        $organization->shortName = (($shortNameNode = $shortNameNodes->item(0)) == NULL) ? NULL : trim($shortNameNode->nodeValue);
5479
        $organization->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5480
        $organization->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5481
        $organization->country = (($countryNode = $countryNodes->item(0)) == NULL) ? NULL : trim($countryNode->nodeValue);
5482
        $organization->projects = array();
5483
        $organization->allFunders=array();
5484
        foreach ($projectNodes as $projectNode) {
5485
            if (($idNodes = $xpath->query('./field[@name = "projectId"]/@value', $projectNode)) == FALSE)
5486
                throw new Exception('error parsing organization');
5487
            if (($acronymNodes = $xpath->query('./field[@name = "projectacronym"]/@value', $projectNode)) == FALSE)
5488
                throw new Exception('error parsing organization');
5489
            if (($titleNodes = $xpath->query('./field[@name = "projecttitle"]/@value', $projectNode)) == FALSE)
5490
                throw new Exception('error parsing organization');
5491
            if (($codeNodes = $xpath->query('./field[@name = "projectcode"]/@value', $projectNode)) == FALSE)
5492
                throw new Exception('error parsing organization');
5493
            $project = new JObject();
5494
            $project->id = (($idNode = $idNodes->item(0)) == NULL) ? NULL : trim($idNode->nodeValue);
5495
            $project->acronym = (($acronymNode = $acronymNodes->item(0)) == NULL) ? NULL : ((trim($acronymNode->nodeValue) == self :: UNKNOWN) ? NULL : trim($acronymNode->nodeValue));
5496
            $project->title = (($titleNode = $titleNodes->item(0)) == NULL) ? NULL : trim($titleNode->nodeValue);
5497
            $project->code = (($codeNode = $codeNodes->item(0)) == NULL) ? NULL : trim($codeNode->nodeValue);
5498
            $project->funders = array();
5499
            if (($projectFunders = $xpath->query('./field[@name = "funding"]', $projectNode)) == FALSE)
5500
                throw new Exception('error parsing organization');
5501
            foreach ($projectFunders as $projectFunder) {
5502
                $funder = new JObject();
5503
                if (($funderNodes = $xpath->query('./field[@name = "funder"]/@value', $projectFunder)) == FALSE)
5504
                    throw new Exception('error parsing organization');
5505
                $funder->name=(($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5506
                if (($funderNodes = $xpath->query('./field[@name = "funderid"]/@value', $projectFunder)) == FALSE)
5507
                    throw new Exception('error parsing organization');
5508
                $funder->id=(($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5509
                if (($funderNodes = $xpath->query('./field[@name = "fundershortname"]/@value', $projectFunder)) == FALSE)
5510
                    throw new Exception('error parsing organization');
5511
                $funder->shortname=(($funderNode = $funderNodes->item(0)) == NULL) ? NULL : trim($funderNode->nodeValue);
5512
                if($funder!=null){
5513
                    $organization->allFunders [$funder->id]=$funder;
5514
                    $project->funders [$funder->id]=$funder;
5515

    
5516
                }
5517

    
5518
            }
5519
           $project->funders=array_unique($project->funders);
5520
            if (($project->id != NULL) || ($project->acronym != NULL) || ($project->title != NULL) || ($project->code != NULL)){
5521
                $organization->projects[] = $project;
5522
                //$organization->allFunders =array_merge($organization->allFunders,$project->funders);
5523
            }
5524
        }
5525
        //$organization->allFunders=array_unique($organization->allFunders);
5526
        return $organization;
5527
    }
5528

    
5529
    // Parse a single datasource from a search service XML response.
5530
    // xpath the DOMXPath to parse
5531
    // return datasource (object)
5532
    private function parseDatasource($xpath) {
5533
        if ((($resultsNodes = $xpath->query('/response/results/result')) == FALSE) || (($resultNode = $resultsNodes->item(0)) == NULL))
5534
            throw new Exception('error parsing datasource');
5535
        if (($originalIdNodes = $xpath->query('./field[@name = "originalId"]/@value', $resultNode)) == FALSE)
5536
            throw new Exception('error parsing datasource');
5537
        if (($nameNodes = $xpath->query('./field[@name = "officialname"]/@value', $resultNode)) == FALSE)
5538
            throw new Exception('error parsing datasource');
5539
        if (($englishNameNodes = $xpath->query('./field[@name = "englishname"]/@value', $resultNode)) == FALSE)
5540
            throw new Exception('error parsing datasource');
5541
        if (($urlNodes = $xpath->query('./field[@name = "websiteurl"]/@value', $resultNode)) == FALSE)
5542
            throw new Exception('error parsing datasource');
5543
        if (($logoNodes = $xpath->query('./field[@name = "logourl"]/@value', $resultNode)) == FALSE)
5544
            throw new Exception('error parsing datasource');
5545
        if (($typeNodes = $xpath->query('./field[@name = "datasourcetypename"]/@value', $resultNode)) == FALSE)
5546
            throw new Exception('error pasrsing datasource');
5547
        if (($itemsNodes = $xpath->query('./field[@name = "odnumberofitems"]/@value', $resultNode)) == FALSE)
5548
            throw new Exception('error parsing datasource');
5549
        if (($dateNodes = $xpath->query('./field[@name = "odnumberofitemsdate"]/@value', $resultNode)) == FALSE)
5550
            throw new Exception('error parsing datasource');
5551
        if (($subjectsNodes = $xpath->query('./field[@name = "odsubjects"]/@value', $resultNode)) == FALSE)
5552
            throw new Exception('error parsing datasource');
5553
        if (($languagesNodes = $xpath->query('./field[@name = "odlanguages"]/@value', $resultNode)) == FALSE)
5554
            throw new Exception('error parsing datasource');
5555
        if (($contentsNodes = $xpath->query('./field[@name = "odcontenttypes"]/@value', $resultNode)) == FALSE)
5556
            throw new Exception('error parsing datasource');
5557
        if (($policiesNodes = $xpath->query('./field[@name = "odpolicies"]/@value', $resultNode)) == FALSE)
5558
            throw new Exception('error parsing datasource');
5559
        if (($compatibilityNodes = $xpath->query('./field[@name = "openairecompatibilityid"]/@value', $resultNode)) == FALSE)
5560
            throw new Exception('error parsing datasource');
5561
        if (($oaiPmhNodes = $xpath->query('./field[@name = "accessinfopackage"]/@value', $resultNode)) == FALSE)
5562
            throw new Exception('error parsing datasources');
5563
//        if (($descriptionNodes = $xpath->query('./field[@name = "oddescription"]/@value', $resultNode)) == FALSE)
5564
//            throw new Exception('error parsing datasource');
5565
        $datasource = new JObject();
5566
        $datasource->name = (($nameNode = $nameNodes->item(0)) == NULL) ? NULL : trim($nameNode->nodeValue);
5567
        $datasource->englishName = (($englishNameNode = $englishNameNodes->item(0)) == NULL) ? NULL : trim($englishNameNode->nodeValue);
5568
        $datasource->url = (($urlNode = $urlNodes->item(0)) == NULL) ? NULL : trim($urlNode->nodeValue);
5569
        $datasource->logo = (($logoNode = $logoNodes->item(0)) == NULL) ? NULL : trim($logoNode->nodeValue);
5570
        $datasource->type = (($typeNode = $typeNodes->item(0)) == NULL) ? NULL : trim($typeNode->nodeValue);
5571
        $datasource->items = (($itemsNode = $itemsNodes->item(0)) == NULL) ? NULL : intval(trim($itemsNode->nodeValue));
5572
        $datasource->date = (($dateNode = $dateNodes->item(0)) == NULL) ? NULL : strtotime(trim($dateNode->nodeValue));
5573
        $datasource->subjects = (($subjectsNode = $subjectsNodes->item(0)) == NULL) ? NULL : trim($subjectsNode->nodeValue);
5574
        $datasource->languages = (($languagesNode = $languagesNodes->item(0)) == NULL) ? NULL : trim($languagesNode->nodeValue);
5575
        $datasource->contents = (($contentsNode = $contentsNodes->item(0)) == NULL) ? NULL : trim($contentsNode->nodeValue);
5576
        $datasource->policies = (($policiesNode = $policiesNodes->item(0)) == NULL) ? NULL : trim($policiesNode->nodeValue);
5577
        $datasource->compatibility = (($compatibilityNode = $compatibilityNodes->item(0)) == NULL) ? NULL : trim($compatibilityNode->nodeValue);
5578
        $datasource->oaiPmh = (($oaiPmhNode = $oaiPmhNodes->item(0)) == NULL) ? NULL : trim($oaiPmhNode->nodeValue);
5579
//        $datasource->description = (($descriptionNode = $descriptionNodes->item(0)) == NULL) ? NULL : trim($descriptionNode->nodeValue);
5580
        $datasource->originalId = (($originalIdNode = $originalIdNodes->item(0)) == NULL) ? NULL : trim($originalIdNode->nodeValue);
5581
        return $datasource;
5582
    }
5583
    private function createStatisticsForPublications($xpath,$filter =''){
5584
        return $this->createStatistics($xpath,
5585
                array('funder'.$filter, 'fundingStream'.$filter,  'fundingStreamLevel1'.$filter, 'fundingStreamLevel2'.$filter, 'project'.$filter, 'year'.$filter, 'accessMode'.$filter,  'type'.$filter, 'language'.$filter,'datasource'.$filter, 'community'.$filter),
5586
                array( 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA','FUNDING_STREAM_LEVEL_2', 'PROJECT', 'PUBLICATION_YEAR', 'ACCESS_MODE', 'DOCUMENT_TYPE', 'DOCUMENT_LANGUAGE', 'DATASOURCE', 'COMMUNITY', 'COMMUNITY'),
5587
                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'),
5588
                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));
5589
    }
5590
   private function createStatisticsForDatasets($xpath){
5591
        return $this->createStatistics($xpath,
5592
                array('funder', 'fundingStream', 'fundingStreamLevel1', 'fundingStreamLevel2', 'year', 'accessMode','type', 'language',  'datasource'),
5593
                array( 'FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'FUNDING_STREAM_LEVEL_2',  'PUBLICATION_YEAR', 'ACCESS_MODE','TYPE', 'LANGUAGE', 'DATASOURCE'),
5594
                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'),
5595
                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));
5596

    
5597
    }
5598
    private function createStatisticsForProjects($xpath, $filter =''){
5599
        return $this->  createStatistics($xpath,
5600
                array('funder'.$filter, 'fundingStream'.$filter, 'fundingStreamLevel1'.$filter, 'fundingStreamLevel2'.$filter ,  'startYear'.$filter, 'endYear'.$filter, 'sc39'.$filter),
5601
                array('FUNDER', 'FUNDING_STREAM', 'SCIENTIFIC_AREA', 'FUNDING_STREAM_LEVEL_2', 'START_YEAR', 'END_YEAR', 'SPECIAL_CLAUSE_39'),
5602
                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'),
5603
                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));
5604

    
5605
    }
5606
    private function _validateResultsSize($size=10){
5607
        if($size > 50){
5608
            $size = 10;
5609
        }
5610
        return $size;
5611
    }
5612

    
5613
}
(2-2/2)