Project

General

Profile

1
import {Component, ElementRef, Input, Output, ViewChild} from '@angular/core';
2
import {Location} from '@angular/common';
3
import {ActivatedRoute, Router} from '@angular/router';
4
import {Meta, Title} from '@angular/platform-browser';
5

    
6
import {AdvancedField, Filter, Value} from './searchHelperClasses.class';
7
import {SearchCustomFilter, SearchUtilsClass} from './searchUtils.class';
8
import {ModalLoading} from '../../utils/modal/loading.component';
9
import {Dates, Identifier, StringUtils} from '../../utils/string-utils.class';
10
import {ErrorCodes} from '../../utils/properties/errorCodes';
11
import {RouterHelper} from '../../utils/routerHelper.class';
12

    
13
import {PiwikService} from '../../utils/piwik/piwik.service';
14
import {EnvProperties} from '../../utils/properties/env-properties';
15
import {SEOService} from '../../sharedComponents/SEO/SEO.service';
16
import {HelperService} from "../../utils/helper/helper.service";
17
import {SearchFields} from "../../utils/properties/searchFields";
18
import {RefineResultsUtils} from "../../services/servicesUtils/refineResults.class";
19
import {RangeFilter} from "../../utils/rangeFilter/rangeFilterHelperClasses.class";
20
import {ZenodoInformationClass} from "../../deposit/utils/zenodoInformation.class";
21

    
22
declare var UIkit: any;
23

    
24
@Component({
25
  selector: 'new-search-page',
26
  templateUrl: 'newSearchPage.component.html'
27
})
28
export class NewSearchPageComponent {
29
  @ViewChild('offcanvas_element') offcanvasElement: ElementRef;
30

    
31
  @Input() piwikSiteId = null;
32
  @Input() hasPrefix: boolean = true;
33
  @Input() pageTitle = "";
34
  @Input() results = [];
35
  @Input() type;
36
  @Input() entityType;
37
  @Input() searchUtils: SearchUtilsClass = new SearchUtilsClass();
38
  @Input() fieldIds: string[];
39
  @Input() fieldIdsMap;//:{ [key:string]:{ name:string, operator:string, type:string, indexField:string, equalityOperator:string  }} ;
40
  @Input() selectedFields: AdvancedField[];
41
  @ViewChild(ModalLoading) loading: ModalLoading;
42
  @Input() csvParams: string;
43
  @Input() csvPath: string;
44
  @Input() simpleSearchLink: string = "";
45
  @Input() advancedSearchLink: string = "";
46
  @Input() disableForms: boolean = false;
47
  @Input() loadPaging: boolean = true;
48
  @Input() oldTotalResults: number = 0;
49
  @Input() openaireLink: string;
50
  @Input() customFilter: SearchCustomFilter;
51
  @Input() sort: boolean = false;
52
  @Input() searchFormClass: string = "searchForm";
53
  //From simple:
54
  @Input() rangeFilters: RangeFilter[] = [];
55
  @Input() rangeFields: string[][] = [];
56
  @Input() refineFields = [];
57
  @Input() filters = [];
58
  selectedFilters: number = 0;
59
  selectedRangeFilters: number = 0;
60
  private searchFieldsHelper: SearchFields = new SearchFields();
61
  @Input() newQueryButton: boolean = true;
62
  public showUnknownFilters: boolean = false; // when a filter exists in query but has no results, so no filters returned from the query
63
  URLCreatedFilters: Filter[] = [];
64
  URLCreatedRangeFilters: RangeFilter[] = [];
65
  @Input() showRefine: boolean = true;
66
  @Input() tableViewLink: string;
67
  @Input() usedBy: string = "search";
68
  @Input() public zenodoInformation: ZenodoInformationClass = new ZenodoInformationClass();
69
  @Input() showLastIndex: boolean = true;
70
  @Input() showResultCount: boolean = true;
71
  @Input() showMoreFilterValuesInline: boolean = true;
72
  @Input() filterValuesNum: number = 6;
73
  @Input() keywordFields = [];
74
  @Input() simpleView: boolean = true;
75
  @Input() formPlaceholderText = "Type Keywords...";
76
  @Input() resultTypes = null;
77
  @Input() quickFilter: { filter: Filter, selected: boolean, filterId: string, value: string };
78
  @Input() includeOnlyResultsAndFilter:boolean = false;
79
  @Input() lastIndex: boolean = true;
80

    
81
  piwiksub: any;
82
  public parameterNames: string[] = [];
83
  public parameterValues: string[] = [];
84

    
85
  public csvLimit: number = 0;
86
  public pagingLimit: number = 0;
87
  public resultsPerPage: number = 0;
88
  isPiwikEnabled = false;
89
  properties: EnvProperties;
90
  public pageContents = null;
91
  public divContents = null;
92
  public routerHelper: RouterHelper = new RouterHelper();
93
  public errorCodes: ErrorCodes = new ErrorCodes();
94

    
95
  url = null;
96

    
97
  @Input() entitiesSelection:boolean = true;
98
  @Input() showAdvancedSearchLink:boolean = true;
99
  constructor(private route: ActivatedRoute,
100
              private location: Location,
101
              private _meta: Meta,
102
              private _title: Title,
103
              private _piwikService: PiwikService,
104
              private router: Router,
105
              private seoService: SEOService,
106
              private helper: HelperService) {
107
  }
108

    
109
  ngOnInit() {
110
    this.route.data
111
      .subscribe((data: { envSpecific: EnvProperties }) => {
112
        this.properties = data.envSpecific;
113
        //this.getDivContents();
114
        this.getPageContents();
115
        this.pagingLimit = data.envSpecific.pagingLimit;
116
        this.resultsPerPage = data.envSpecific.resultsPerPage;
117
        this.csvLimit = data.envSpecific.csvLimit;
118
        this.isPiwikEnabled = data.envSpecific.enablePiwikTrack;
119
        if (typeof window !== 'undefined') {
120
          this.updateUrl(data.envSpecific.baseLink + location.pathname);
121
          this.url = data.envSpecific.baseLink + location.pathname
122
        }
123
        if (typeof document !== 'undefined' && this.isPiwikEnabled) {
124
          this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe();
125
        }
126
      });
127

    
128
    var description = "Openaire, search, repositories, open access, type, content provider, funder, project, " + this.pageTitle;
129

    
130
    this.updateTitle(this.pageTitle);
131
    this.updateDescription(description);
132

    
133
    this.searchUtils.baseUrl = "/" + this.searchUtils.baseUrl;
134
    this.seoService.createLinkForCanonicalURL(this.properties.baseLink + this.router.url, false);
135

    
136

    
137
  }
138

    
139
  private getPageContents() {
140
    this.helper.getPageHelpContents(this.properties, (this.customFilter) ? this.customFilter.valueId : null, this.router.url).subscribe(contents => {
141

    
142
      this.pageContents = contents;
143
    })
144
  }
145

    
146
  private getDivContents() {
147
    this.helper.getDivHelpContents(this.properties, (this.customFilter) ? this.customFilter.valueId : null, this.router.url).subscribe(contents => {
148
      this.divContents = contents;
149
    })
150
  }
151

    
152
  ngOnDestroy() {
153
    if (this.piwiksub) {
154
      this.piwiksub.unsubscribe();
155
    }
156
  }
157

    
158
  updateDescription(description: string) {
159
    this._meta.updateTag({content: description}, "name='description'");
160
    this._meta.updateTag({content: description}, "property='og:description'");
161
  }
162

    
163
  updateTitle(title: string) {
164
    var _prefix = "";
165
    if (this.hasPrefix) {
166
      _prefix = "OpenAIRE | ";
167
    }
168
    var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title);
169
    this._title.setTitle(_title);
170
    this._meta.updateTag({content: _title}, "property='og:title'");
171
  }
172

    
173
  updateUrl(url: string) {
174
    this._meta.updateTag({content: url}, "property='og:url'");
175
  }
176

    
177

    
178
  clearFilters() {
179
    for (var i = 0; i < this.filters.length; i++) {
180
      for (var j = 0; j < this.filters[i].countSelectedValues; j++) {
181
        if (this.filters[i].values[j].selected) {
182
          this.filters[i].values[j].selected = false;
183
        }
184
        this.filters[i].countSelectedValues = 0;
185
      }
186
    }
187
    this.selectedFilters = 0;
188
    for(let i = 0; i < this.rangeFilters.length; i++) {
189
      this.rangeFilters[i].selectedFromValue = null;
190
      this.rangeFilters[i].selectedToValue = null;
191
    }
192
    this.selectedRangeFilters = 0;
193
    if (this.quickFilter) {
194
      this.removeValueFromQuickFilter();
195
    }
196
    this.goTo(1);
197
    // this.clearKeywords();
198
  }
199

    
200
  goTo(page: number = 1) {
201
    if(this.offcanvasElement) {
202
      UIkit.offcanvas(this.offcanvasElement.nativeElement).hide();
203
    }
204

    
205
    this.searchUtils.page = page;
206
    this.buildPageURLParameters(this.filters, this.rangeFilters, true);
207
    this.router.navigate([this.searchUtils.baseUrl], {queryParams: this.routerHelper.createQueryParams(this.parameterNames, this.parameterValues)});
208
    /* Code For Piwik*/
209
    if (typeof localStorage !== 'undefined') {
210
      //console.log("In PreviousRouteRecorder : "+this.router.url );
211
      localStorage.setItem('previousRoute', this.router.url);
212
    }
213
    if (this.isPiwikEnabled && (typeof document !== 'undefined')) {
214
      this.piwiksub = this._piwikService.trackView(this.properties, this.pageTitle, this.piwikSiteId).subscribe();
215
    }
216
    /* End Piwik Code */
217
  }
218

    
219
  queryChanged() {
220

    
221
    this.goTo(1);
222
  }
223

    
224

    
225
  sizeChanged($event) {
226
    this.searchUtils.size = $event.value;
227
    this.goTo(1);
228
  }
229

    
230
  sortByChanged($event) {
231
    this.searchUtils.sortBy = $event.value;
232
    this.goTo(1);
233
  }
234

    
235

    
236
  getOperatorParameter(parameter: string): string {
237
    for (let id of this.fieldIds) {
238
      if (this.fieldIdsMap[id]["param"] == parameter) {
239
        return this.fieldIdsMap[id]["operator"];
240
      }
241
    }
242
  }
243

    
244
  /*
245
* Get A sub-array of this.refineFields array, which contains the ids of the selected filters
246
*/
247
  public getSelectedFilters(): string[] {
248
    var selected: string[] = [];
249
    for (var i = 0; i < this.filters.length; i++) {
250
      var filter: Filter = this.filters[i];
251
      if (filter.countSelectedValues > 0) {
252
        selected.push(filter.filterId);
253
      }
254
    }
255
    return selected;
256
  }
257

    
258
  /*
259
    * Get A sub-array of this.refineFields array, which contains the ids of the selected parameters
260
    */
261
  private getSelectedParameters(): string[] {
262
    var selected: string[] = [];
263
    for (var i = 0; i < this.refineFields.length; i++) {
264
      if (this.parameterNames.indexOf(this.refineFields[i]) != -1) {
265
        selected.push(this.refineFields[i]);
266
      }
267
    }
268
    return selected;
269
  }
270

    
271
  /*
272
  * Get A sub-array of this.refineFields array, which hides hidden fields (e.g Funding level 0,1,2,..), and contains those that depend on another fields (e.g  Funding level 0 if Funder is selected )
273
  */
274
  public getFields(): string[] {
275
    var selected_filters: string[] = this.getSelectedFilters();
276
    if (selected_filters.length == 0) {
277
      selected_filters = this.getSelectedParameters();
278
    }
279
    var fields: string[] = [];
280
    for (var i = 0; i < this.refineFields.length; i++) {
281
      var dependentTo = this.searchFieldsHelper.DEPENDENT_FIELDS[this.refineFields[i]];
282

    
283
      //if filter is not marked as hidden OR it is hidden but it is dependent to a field that it IS selected
284
      if (this.searchFieldsHelper.HIDDEN_FIELDS.indexOf(this.refineFields[i]) == -1 || (selected_filters.indexOf(dependentTo) != -1) || (selected_filters.indexOf(this.refineFields[i]) != -1)) {
285
        fields.push(this.refineFields[i]);
286
      }
287
    }
288
    return fields;
289
  }
290

    
291
  /*
292
  * Get a query  string of all fields, that want to get from search (e.g. &fields=funderid&fields=projectstartyear&...))
293
  */
294
  public getRefineFieldsQuery(): string {
295

    
296
    var fields: string[] = this.getFields();
297
    var fieldsStr = ""
298
    for (var i = 0; i < fields.length; i++) {
299
      fieldsStr += "&fields=" + fields[i];
300
    }
301
    return "&refine=true" + fieldsStr;
302
  }
303

    
304

    
305
  /*
306
  * Mark as check the new filters that are selected, when you get them from search
307
  */
308
  public checkSelectedFilters(filters: Filter[]) {
309
    this.filters = filters;
310
    for (var i = 0; i < filters.length; i++) {
311
      var filter: Filter = filters[i];
312
      filter.countSelectedValues = 0;
313
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
314
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
315
        for (let filterValue of filter.values) {
316
          if (values.indexOf(StringUtils.quote(filterValue.id)) > -1) {
317
            filterValue.selected = true;
318
            filter.countSelectedValues++;
319
          } else {
320
            filterValue.selected = false;
321

    
322
          }
323
        }
324
      } else if (this.quickFilter && this.quickFilter.filterId == filter.filterId && this.quickFilter.selected) {
325
        for (let filterValue of filter.values) {
326
          if (filterValue.id == this.quickFilter.value) {
327
            filterValue.selected = true;
328
            filter.countSelectedValues++;
329
          } else {
330
            filterValue.selected = false;
331
          }
332
        }
333
      } else {
334
        for (let filterValue of filter.values) {
335
          filterValue.selected = false;
336
        }
337
      }
338
      if (this.quickFilter && filter.filterId == this.quickFilter.filterId) {
339
        this.quickFilter.filter = filter;
340
      }
341
    }
342
    this.filterFilterValues(this.filters);
343
    return filters;
344
  }
345

    
346
  /*
347
* Mark as check the new range filters that are selected
348
*/
349
  public checkSelectedRangeFilters(filters: RangeFilter[]) {
350
    //console.log("checkSelectedRangeFilters: parameterNames.length: "+this.parameterNames.length);
351

    
352
    this.rangeFilters = filters;
353
    for (let i = 0; i < filters.length; i++) {
354
      let filter: RangeFilter = filters[i];
355

    
356
      if (this.parameterNames.indexOf(filter.filterId) != -1) {
357
        //console.log(filter.filterId + " "+this.parameterNames.indexOf(filter.filterId) );
358
        let values = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
359
        let operators: string [] = (StringUtils.URIDecode(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
360
        if (values.length == operators.length) {
361
          for (let j = 0; j < values.length; j++) {
362
            if (this.fieldIdsMap[filter.originalFilterIdFrom+"-range-"+filter.originalFilterIdTo].filterType == "range") {
363
              let value: string = StringUtils.unquote(values[j]);
364
              let validDates: boolean = true;
365

    
366
              let years: string[] = (value.substring(5)).split(":");
367
              let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
368
              let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
369
              //console.log("checkSelectedRangeFilters: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
370
              if(yearFrom) {
371
                filter.selectedFromValue = yearFrom;
372
              }
373
              if(yearTo) {
374
                filter.selectedToValue = yearTo;
375
              }
376
              if(yearFrom && yearTo) {
377
                filter.selectedFromAndToValues = yearFrom + "-" + yearTo;
378
              } else if(yearFrom) {
379
                filter.selectedFromAndToValues = "From " + yearFrom;
380
              } else if(yearTo) {
381
                filter.selectedFromAndToValues = "Until " + yearTo;
382
              }
383

    
384
              if(!yearFrom && !yearTo) {
385
                validDates = false;
386
              }
387

    
388
              // if (value.length < 14) {
389
              //   validDates = false;
390
              //   console.log("not valid (length<14)");
391
              // } else {
392
              //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
393
              //     validDates = false;
394
              //     console.log("not valid years");
395
              //   } else {
396
              //     filter.selectedFromValue = value.substring(5, 9);
397
              //     filter.selectedToValue = value.substring(10, 14);
398
              //     console.log(filter);
399
              //   }
400
              // }
401
            }
402
          }
403
        }
404
      } else {
405
        filter.selectedFromValue = null;
406
        filter.selectedToValue = null;
407
      }
408
    }
409
    return this.rangeFilters;
410
  }
411

    
412
  /*
413
  * For Funder filters - if funder selected
414
  */
415
  public filterFilterValues(filters: Filter[]) {
416
    var funders = [];
417
    var funder_prefix = [];
418
    for (var i = 0; i < filters.length; i++) {
419

    
420
      var filter: Filter = filters[i];
421
      //  console.log(filter.filterId);
422
      if (filter.filterId.indexOf("funder") != -1 && this.parameterNames.indexOf(filter.filterId) != -1) {
423
        let funders = (decodeURIComponent(this.parameterValues[this.parameterNames.indexOf(filter.filterId)])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
424
        for (let funder of funders) {
425
          funder_prefix.push(StringUtils.unquote(funder).split("____")[0]);
426
        }
427
        //  console.log(funder_prefix );
428
      } else if (filter.filterId.indexOf("funding") != -1) {
429
        //  console.log(" funding: "+filter.filterId );
430
        var filteredValues = []
431
        for (let filterValue of filter.values) {
432
          var value_prefix = filterValue.id.split("____")[0];
433
          //  console.log("Value prefix: "+value_prefix );
434
          if (funder_prefix.indexOf(value_prefix) != -1) {
435
            //  console.log("here" + value_prefix);
436
            filteredValues.push(filterValue);
437
          }
438

    
439
        }
440
        if (filteredValues.length > 0) {
441
          filter.values = filteredValues;
442
        }
443
      }
444

    
445
    }
446

    
447
    return filters;
448
  }
449

    
450
  public countSelectedFilters(filters: Filter[]): number {
451
    this.selectedFilters = 0;
452
    for (let filter of filters) {
453
      if (filter.countSelectedValues > 0) {
454
        this.selectedFilters += filter.countSelectedValues;
455
      }
456
    }
457
    return this.selectedFilters;
458
  }
459

    
460
  public countSelectedRangeFilters(rangeFilters: RangeFilter[]) : number {
461
    this.selectedRangeFilters = 0;
462
    for(let filter of rangeFilters) {
463
      if(filter.selectedFromValue || filter.selectedToValue) {
464
        this.selectedRangeFilters++;
465
      }
466
    }
467
    return this.selectedRangeFilters;
468
  }
469

    
470
  private clearKeywords() {
471
    if (this.searchUtils.keyword.length > 0) {
472
      this.searchUtils.keyword = '';
473
    }
474
    this.goTo(1);
475
  }
476

    
477
  public removeFilter(value: Value, filter: Filter) {
478
    filter.countSelectedValues--;
479
    this.selectedFilters--;
480
    if (value.selected == true) {
481
      value.selected = false;
482
    }
483
    if (this.quickFilter && this.quickFilter.filterId == filter.filterId) {
484
      this.removeValueFromQuickFilter();
485
    }
486
    this.goTo(1);
487
  }
488

    
489
  public removeRangeFilter(filter: RangeFilter) {
490
    filter.selectedFromValue = null;
491
    filter.selectedToValue = null;
492
    this.goTo(1);
493
  }
494

    
495
  getSelectedValues(filter): any {
496
    var selected = [];
497
    if (filter.countSelectedValues > 0) {
498
      for (var i = 0; i < filter.values.length; i++) {
499
        if (filter.values[i].selected) {
500
          selected.push(filter.values[i]);
501
        }
502
      }
503
    }
504
    return selected;
505

    
506
  }
507

    
508
  filterChanged($event) {
509
    if (this.quickFilter && this.quickFilter.filter) {
510
      this.removeValueFromQuickFilter();
511
    }
512
    this.goTo(1);
513

    
514
  }
515

    
516
  /**
517
   * if there is a change in the values of the quick filter, this function has to be run, to also update the quickFilter
518
   */
519
  removeValueFromQuickFilter() {
520
    if (this.quickFilter.filter.countSelectedValues == 0) {
521
      this.quickFilter.selected = false;
522
    } else {
523
      let isQuickEnabled = false;
524
      for (let filterValue of this.quickFilter.filter.values) {
525
        isQuickEnabled = (filterValue.name == this.quickFilter.value)
526
      }
527
      this.quickFilter.selected = (isQuickEnabled && this.quickFilter.filter.countSelectedValues == 1);
528
    }
529
  }
530

    
531
  // for loading
532
  public openLoading() {
533
    this.loading.open();
534
  }
535

    
536
  public closeLoading() {
537
    this.loading.close();
538
  }
539

    
540
  /**
541
   * Build advanced search Filters based on the URL parameters
542
   * @param params
543
   */
544
  createAdvancedSearchSelectedFiltersFromNewURLParameters(params) {
545
    for (let i = 0; i < Object.keys(params).length; i++) {
546
      if(params["f"+i] && params["fv"+i]   ) {
547
        let fieldId = params["f" + i].split(",")[0];
548
        let operator = (params["f" + i].split(",").length  >1 )?params["f" + i].split(",")[1]:"and";
549
        let fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
550

    
551
        if (!this.fieldIdsMap[fieldId]) {
552
          console.error("Field: " + fieldId + " not found in fieldIds map");
553
          continue;
554
        }
555
        let value: string = StringUtils.URIDecode(params["fv"+i]);
556
        if (this.fieldIdsMap[fieldId].type == "date") {
557
            let validDates: boolean = true;
558
            let dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operator);
559
            if (value.indexOf("range") != -1) {
560
              dateField.dateValue.type = "range";
561
              if (value.length < 26) {
562
                validDates = false;
563
              } else {
564
                if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
565
                  validDates = false;
566
                } else {
567
                  dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
568
                  dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
569
                }
570
              }
571
              //  "rangeYYYY-MM-DD:YYYY-MM-DD"
572
            } else {
573
              dateField.dateValue.setDatesByType(value);
574
            }
575
            if (validDates) {
576
              this.selectedFields.push(dateField);
577
            }
578

    
579
          } else {
580
            this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type,value, operator));
581
          }
582

    
583
        }
584
      }
585
  }
586
  /**
587
   * Build advanced search Filters based on the URL parameters
588
   * @param params
589
   */
590
  createAdvancedSearchSelectedFiltersFromURLParameters(params) {
591
    this.createAdvancedSearchSelectedFiltersFromNewURLParameters(params);
592
    for (var i = 0; i < this.fieldIds.length; i++) {
593
      var fieldId = this.fieldIds[i];
594
      var fieldparam = (this.fieldIdsMap[fieldId]) ? this.fieldIdsMap[fieldId].param : "";
595
      if (!this.fieldIdsMap[fieldId]) {
596
        console.error("Field: " + fieldId + " not found in fieldIds map");
597
        continue;
598
      }
599

    
600
      var operatorId = this.getOperatorParameter(fieldparam);
601
      if (params[fieldparam] != undefined && params[operatorId] != undefined) {
602
        var values: string [] = StringUtils.URIDecode(params[fieldparam]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
603
        var operators: string [] = (StringUtils.URIDecode(params[operatorId])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
604
        if (values.length == operators.length) {
605
          for (var j = 0; j < values.length; j++) {
606
            if (this.fieldIdsMap[fieldId].type == "date") {
607
              var value: string = StringUtils.unquote(values[j]);
608
              var validDates: boolean = true;
609
              var dateField: AdvancedField = new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, value, operators[j]);
610
              if (value.indexOf("range") != -1) {
611
                dateField.dateValue.type = "range";
612
                if (value.length < 26) {
613
                  validDates = false;
614
                } else {
615
                  if (!Dates.isValidDate(value.substring(5, 15)) || !Dates.isValidDate(value.substring(16, 26))) {
616
                    validDates = false;
617
                  } else {
618
                    dateField.dateValue.from = Dates.getDateFromString(value.substring(5, 15));
619
                    dateField.dateValue.to = Dates.getDateFromString(value.substring(16, 26));
620
                  }
621
                }
622
                //  "rangeYYYY-MM-DD:YYYY-MM-DD"
623
              } else {
624
                dateField.dateValue.setDatesByType(value);
625
              }
626
              if (validDates) {
627
                this.selectedFields.push(dateField);
628
              }
629

    
630
            } else {
631
              this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, values[j], operators[j]));
632
            }
633
          }
634
        }
635
      }
636
    }
637
    if (params['keyword'] && params['keyword'].length > 0) {
638
      this.selectedFields.push(new AdvancedField(this.fieldIds[0], this.fieldIdsMap[this.fieldIds[0]].param, this.fieldIdsMap[this.fieldIds[0]].name, this.fieldIdsMap[this.fieldIds[0]].type, params['keyword'], "and"));
639
    }
640
    if (this.selectedFields.length == 0) {
641
      this.selectedFields.push(new AdvancedField(this.fieldIds[0], this.fieldIdsMap[this.fieldIds[0]].param, this.fieldIdsMap[this.fieldIds[0]].name, this.fieldIdsMap[this.fieldIds[0]].type, "", "and"));
642
    }
643
  }
644

    
645
  /**
646
   * Create Search API query based on the selected fields of the advanced form
647
   */
648
  getSearchAPIQueryForAdvancedSearhFields() {
649

    
650
    var params = "";
651
    var countParams = 0;
652
    for (var i = 0; i < this.selectedFields.length; i++) {
653
      if (this.fieldIdsMap[this.selectedFields[i].id] != undefined && (this.selectedFields[i].value != "" || this.selectedFields[i].type == "date")) {
654
        //console.log("createQueryParameters::"+this.selectedFields[i].type);
655
        if (this.selectedFields[i].type == "date") {
656
          if (this.selectedFields[i].dateValue.type != "any") {
657
            params += (countParams == 0 ? "" : this.selectedFields[i].operatorId) + " " + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.from)) + " "
658
              + StringUtils.URIEncode(Dates.getDateToString(this.selectedFields[i].dateValue.to)) + '"' + " ";
659
          }
660
        } else {
661
          if (this.selectedFields[i].id == "q") {
662
            // console.log(this.selectedFields[i].value)
663
/*            var op = "";
664
            var doisParams = "";
665
            if ((this.entityType == 'publication' || this.entityType == 'dataset' || this.entityType == 'software' || this.entityType == 'other' || this.entityType == "result")) {
666
              var DOIs: Identifier[] = Identifier.getIdentifiersFromString(this.selectedFields[i].value);
667
              for (let identifier of DOIs) {
668
                // console.log(identifier)
669
                // pidclassid exact \"doi\" and pid exact \"10.1016/j.nima.2015.11.134\"
670
                //and (authorid exact \"0000-0001-7291-3210 \" )"
671
                if(identifier.class == "ORCID"){
672
                  doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + identifier.id + '")';
673
                }else{
674
                  doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  identifier.id + '")';
675
                }
676
              }
677
            }
678
            if (doisParams.length > 0) {
679
              params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId ,countParams,true, true) + " or " + doisParams;
680
            } else {
681
              params += this.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId,countParams,true);
682
            }*/
683
            params += NewSearchPageComponent.createKeywordQuery(this.entityType,this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams);
684
            //TODO deposit case
685
            // console.log(this.usedBy)
686
            // console.log(this.keywordFields)
687

    
688
            if(this.usedBy == "deposit") {
689

    
690
              if(this.keywordFields.length > 0) {
691
                params += " or ("
692
              }
693
              for(let j=0; j< this.keywordFields.length ; j++) {
694
                if(j > 0) {
695
                  params += " or "
696
                }
697
                params += NewSearchPageComponent.createQuotedKeywordQuery(this.selectedFields[i].value, this.keywordFields[j].name, " or ", countParams,false);
698
                // let field = this.keywordFields[i];
699
                //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
700
                // params += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
701
              }
702
              if(this.keywordFields.length > 0) {
703
                params += " ) "
704
              }
705
            }
706

    
707
          } else if (countParams == 0 && this.selectedFields[i].operatorId == "not" && this.fieldIdsMap[this.selectedFields[i].id].equalityOperator != "=") {
708
            params += " " + this.selectedFields[i].id + " <> " + '"' + StringUtils.URIEncode(this.selectedFields[i].value) + '"' + " ";
709
          } else if(this.fieldIdsMap[this.selectedFields[i].id].equalityOperator == "=") {
710
            params+=NewSearchPageComponent.createQuotedKeywordQuery(this.selectedFields[i].value, this.selectedFields[i].id, this.selectedFields[i].operatorId, countParams, false);
711
          }else{
712
              params += (countParams == 0 ? "" : this.selectedFields[i].operatorId + " ") + this.selectedFields[i].id + this.fieldIdsMap[this.selectedFields[i].id].equalityOperator + '"' + encodeURIComponent(this.selectedFields[i].value) + '"' + " ";
713

    
714
          }
715
        }
716
        countParams++;
717
      }
718
    }
719

    
720
    if (this.customFilter) {
721
      params += (countParams == 0 ? "" : " and ") + this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId));
722
    }
723
    // console.log("ParameterS:")
724
    // console.log(params)
725
    return params;
726
  }
727
  public static createKeywordQuery(entityType:string, value:string, id, operatorId, countParams=0){
728
    let params = "";
729
    let doisParams = "";
730
    if ((entityType == 'publication' || entityType == 'dataset' || entityType == 'software' || entityType == 'other' || entityType == "result")) {
731
      var DOIs: Identifier[] = Identifier.getIdentifiersFromString(value);
732
      for (let identifier of DOIs) {
733
        // console.log(identifier)
734
        // pidclassid exact \"doi\" and pid exact \"10.1016/j.nima.2015.11.134\"
735
        //and (authorid exact \"0000-0001-7291-3210 \" )"
736
        if(identifier.class == "ORCID"){
737
          doisParams += (doisParams.length > 0 ? " or " : "") +'(authorid="' + identifier.id + '")';
738
        }else{
739
          doisParams += (doisParams.length > 0 ? " or " : "") +'(pidclassid exact "' + identifier.class + '" and pid="' +  identifier.id + '")';
740
        }
741
      }
742
    }
743
    if (doisParams.length > 0) {
744
      params += this.createQuotedKeywordQuery(value, id, operatorId ,countParams,true, true) + " or " + doisParams;
745
    } else {
746
      params += this.createQuotedKeywordQuery(value, id, operatorId,countParams,true);
747
    }
748
    return params;
749

    
750
  }
751
  private static createQuotedKeywordQuery(fieldValue, fieldId, fieldOperator, countParams:number, isSearchAll:boolean, forceQuotted:boolean=false){
752
    let params = "";
753
    let quotedParts = (fieldValue)?fieldValue.match(/(["'])(.*?)*?\1/g):[];
754
    params+= (countParams == 0 ? "" : fieldOperator) + " (";
755
    if(forceQuotted){
756
      return this.getQuotedQueryPart(fieldId, '"'+ fieldValue+'"',isSearchAll);
757
    }
758
    if(quotedParts && quotedParts.length == 1 && quotedParts[0] == fieldValue ){
759
      params+=this.getQuotedQueryPart(fieldId, fieldValue,isSearchAll);
760
    }else if( quotedParts && quotedParts.length > 0){
761
      for(let i=0; i< quotedParts.length; i++){
762
        params+=(i>0)?" and ":"";
763
        params+=this.getQuotedQueryPart(fieldId, quotedParts[i],isSearchAll);
764
      }
765
      let startPoint = 0;
766
      let endPoint = 0;
767
      for(let i=0; i< quotedParts.length; i++){
768
        let index = fieldValue.indexOf(quotedParts[i]);
769
        endPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+1]):fieldValue.length;
770
        // console.log(fieldValue.indexOf(quotedParts[i+1]) +" - "+fieldValue.length);
771
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
772
        if(index==startPoint){
773
          startPoint +=quotedParts[i].length;
774
        }else if(startPoint < index){
775
          endPoint = index;
776
        }
777
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
778
        if(decodeURIComponent(fieldValue.substring(startPoint,endPoint)).split(" ").join("").length > 0) {
779
          params += " and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint, endPoint), isSearchAll);
780
        }
781
        // console.log("For "+i+"  " +params+" SP "+ startPoint+" EP: "+endPoint);
782
        // startPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+i]):fieldValue.length;//(startPoint<index  )?(index + quotedParts[i].length):fieldValue.length;
783
        startPoint = ((i+1<quotedParts.length)?(fieldValue.indexOf(quotedParts[i+1])+quotedParts[i+1].length):(endPoint== index?(index+quotedParts[i].length):endPoint));
784
      }
785
      if(startPoint !=fieldValue.length && decodeURIComponent(fieldValue.substring(startPoint,fieldValue.length)).split(" ").join("").length > 0){
786
        params+=" and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint,fieldValue.length),isSearchAll);
787
      }
788
    }else{
789
      params+=this.getNoQuotedQueryPart(fieldId, fieldValue,isSearchAll);
790
    }
791
    params += " )";
792
    return params;
793
  }
794

    
795
  private static getQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
796
      return (isSearchAll?"__all":fieldId)+" exact "+StringUtils.URIEncode(value);
797
  }
798
  private static getNoQuotedQueryPart(fieldId:string, value:string,  isSearchAll:boolean){
799
    if(isSearchAll){
800
      return StringUtils.URIEncode(value);
801
    }else{
802
      return fieldId+"="+ StringUtils.URIEncode(value);
803
    }
804
  }
805

    
806
  /**
807
   * Create Search API query based on the filters of refine fields
808
   * @param URLparams
809
   * @param firstLoad
810
   */
811
  getSearchAPIQueryForRefineFields(URLparams, firstLoad: boolean) {
812

    
813
    var allFqs = "";
814
    // console.log(this.refineFields)
815
    for (var i = 0; i < this.refineFields.length; i++) {
816
      var filterId = this.refineFields[i];
817

    
818
      if (URLparams[filterId] != undefined) {
819
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterId]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
820
        var countvalues = 0;
821
        var fq = "";
822
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
823
        // console.info(filterId, filterOp);
824
        for (let value of values) {
825
          countvalues++;
826
          var paramId = this.fieldIdsMap[filterId].param;
827
          // parameters+='&' + paramId+ '='+ value;//+"&" + this.fieldIdsMap[paramId].operator + "="+((countvalues == 1)?"and":"or");
828
          fq += (fq.length > 0 ? " " + filterOp + " " : "") + filterId + " exact " + (value);
829
        }
830
        if (countvalues > 0) {
831
          fq = "&fq=" + StringUtils.URIEncode(fq);
832
        }
833
        allFqs += fq;
834
      }
835
    }
836
    if (this.customFilter) {
837
      allFqs += "&fq=" + StringUtils.URIEncode(this.customFilter.queryFieldName + " exact " + StringUtils.quote((this.customFilter.valueId)));
838
    }
839

    
840
    if (this.quickFilter && this.entityType == "result") {
841
      if((firstLoad && URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)   || URLparams["qf"] == "true"
842
        || ((URLparams[this.quickFilter.filterId] != undefined && StringUtils.URIDecode(URLparams[this.quickFilter.filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1).indexOf(StringUtils.quote(this.quickFilter.value)) != -1))) {
843
        this.quickFilter.selected = true;
844
      } else {
845
        this.quickFilter.selected = false;
846
      }
847
      if ((firstLoad && URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == undefined)
848
      ||( URLparams[this.quickFilter.filterId] == undefined && URLparams["qf"] == "true")) {
849
        allFqs += "&fq=resultbestaccessright exact " + StringUtils.quote(this.quickFilter.value);
850
      }
851
    }
852

    
853
    if (this.entityType == "result") {
854
      if (URLparams["type"]) {
855
        let types = URLparams["type"].split(",");
856
        if(types.indexOf("publications")!=-1 && types.indexOf("datasets")!=-1 && types.indexOf("software")!=-1 && types.indexOf("other")!=-1 ){
857
          allFqs += "&type=results";
858
        }else{
859
          for (let type of types) {
860
            allFqs += "&type=" + type;
861
          }
862
        }
863
      }else{
864
        allFqs += "&type=results";
865
      }
866
    } else if (this.entityType == "publication") {
867
      allFqs += "&type=publications";
868
    } else if (this.entityType == "dataset") {
869
      allFqs += "&type=datasets";
870
    } else if (this.entityType == "software") {
871
      allFqs += "&type=software";
872
    } else if (this.entityType == "other") {
873
      allFqs += "&type=other";
874
    } else if(this.entityType == "project") {
875
      allFqs += "&type=projects";
876
    } else if(this.entityType == "organization") {
877
      allFqs += "&type=organizations";
878
    } else if(this.entityType == "dataprovider") {
879
      allFqs += "&type=datasources";
880
    }
881
    // console.log("AllFqs (check type): "+allFqs);
882
    // console.log("type: "+this.entityType);
883
    // var keyword = URLparams['keyword'];
884
    // var doiQuery = "";
885
    // var keywordQuery = "";
886
    // if((keyword && keyword.length > 0)){
887
    //   if((this.type == 'publications' ||this.type == 'research data' || this.type == 'software' || this.type == 'other research products')){
888
    //     var DOIs:string[] = DOI.getDOIsFromString(keyword);
889
    //     var doisParams = "";
890
    //
891
    //     for(var i =0 ;i < DOIs.length; i++){
892
    //       doisParams+=(doisParams.length > 0?"&":"")+'doi="'+ DOIs[i]+'"';
893
    //     }
894
    //     if(doisParams.length > 0){
895
    //       doiQuery += "&"+doisParams;
896
    //     }else {
897
    //       keywordQuery += "&q="+StringUtils.URIEncode(keyword);
898
    //     }
899
    //   }else{
900
    //     if(this.usedBy == "deposit") {
901
    //       if(this.keywordFields.length > 0) {
902
    //         keywordQuery = "&fq=";
903
    //       }
904
    //
905
    //       for(let i=0; i< this.keywordFields.length ; i++) {
906
    //         if(i > 0) {
907
    //           keywordQuery += " or ";
908
    //         }
909
    //         let field = this.keywordFields[i];
910
    //         //keywordQuery += field.name+field.equalityOperator+StringUtils.URIEncode(keyword);
911
    //         keywordQuery += field.name+field.equalityOperator+StringUtils.quote(StringUtils.URIEncode(keyword));
912
    //       }
913
    //     } else {
914
    //       keywordQuery += "&q=" + StringUtils.URIEncode(keyword);
915
    //     }
916
    //
917
    //   }
918
    // }
919
    //TODO add DOI?
920
     return allFqs;
921

    
922
  }
923

    
924
  /**
925
   * Create Search API query based on the filters of refine fields
926
   * @param URLparams
927
   */
928
  getSearchAPIQueryForRangeFields(URLparams) {
929
    let allFqs = "";
930
    for (let i = 0; i < this.rangeFields.length; i++) {
931
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
932
      let filterParam = this.searchFieldsHelper.getFieldParam(filterId, this.entityType);
933

    
934
      if (URLparams[filterParam] != undefined) {
935
        let values = (StringUtils.URIDecode(StringUtils.URIDecode(URLparams[filterParam]))).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
936
        var countvalues = 0;
937
        var fq = "";
938
        var fqFrom = "";
939
        var fqTo = "";
940
        let filterOp: string = this.searchFieldsHelper.getFieldOperator(filterId);
941

    
942
        for (let value of values) {
943
          if (this.fieldIdsMap[filterId].filterType == "range") {
944

    
945
            let selectedFromValue;
946
            let selectedToValue;
947

    
948
            let years: string[] = (value.substring(5)).split(":");
949
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
950
            //(Number.isInteger(parseInt(years[0], 10)) ? years[0] : null);
951
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
952
            //console.log("getSearchAPIQueryForRangeFields: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
953
            if(yearFrom) {
954
              selectedFromValue = yearFrom;
955
            }
956
            if(yearTo) {
957
              selectedToValue = yearTo;
958
            }
959
            if(yearFrom || yearTo) {
960

    
961
            // if (value.length <= 14) {
962
            //   if(Dates.isValidYear(value.substring(5, 9))) {
963
            //     selectedFromValue = value.substring(5, 9);
964
            //   }
965
            //   if(Dates.isValidYear(value.substring(10, 14))) {
966
            //     selectedToValue = value.substring(10, 14);
967
            //   }
968

    
969
              if(this.rangeFields[i][0] == this.rangeFields[i][1]) {
970
                //console.log(selectedFromValue + " - "+selectedToValue);
971
                if (selectedFromValue && selectedToValue) {
972
                  let equalityOp = this.fieldIdsMap[filterId].equalityOperator;
973
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + " " + selectedToValue + "\"";
974
                  fq = "&fq=" + StringUtils.URIEncode(fq);
975
                } else if (selectedFromValue) {
976
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
977
                  if(equalityOp == " = ") {
978
                    equalityOp = " >= ";
979
                  }
980
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedFromValue + "\"";
981
                  fq = "&fq=" + StringUtils.URIEncode(fq);
982
                } else if (selectedToValue) {
983
                  let equalityOp = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
984
                  if(equalityOp == " = ") {
985
                    equalityOp = " <= ";
986
                  }
987
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOp + "\"" + selectedToValue + "\"";
988
                  fq = "&fq=" + StringUtils.URIEncode(fq);
989
                }
990
              } else {
991
                let equalityOpFrom = this.fieldIdsMap[this.rangeFields[i][0]].equalityOperator;
992
                let equalityOpTo = this.fieldIdsMap[this.rangeFields[i][1]].equalityOperator;
993

    
994
                if (selectedFromValue) {
995
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][0] + equalityOpFrom + "\"" + selectedFromValue + "\"";
996
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
997
                }
998
                if (selectedToValue) {
999
                  fq += (fq.length > 0 ? " " + filterOp + " " : "") + this.rangeFields[i][1] + equalityOpTo + "\"" + selectedToValue + "\"";
1000
                  // fq = "&fq=" + StringUtils.URIEncode(fq);
1001
                }
1002
                if(selectedFromValue || selectedToValue) {
1003
                  fq = "&fq=" + StringUtils.URIEncode(fq);
1004
                }
1005
              }
1006
            }
1007
          }
1008
        }
1009
        allFqs += fq +fqFrom + fqTo;
1010
      }
1011
    }
1012

    
1013
    return allFqs;
1014

    
1015
  }
1016

    
1017
  /**
1018
   * Sets parameterNames and parameterValues arrays
1019
   * used in paging, advanced search link, Goto()
1020
   * @param filters either query filters or filters defined by the URL parameters
1021
   * @param rangeFilters defined by the URL parameters
1022
   * @param includePage
1023
   */
1024
  buildPageURLParameters(filters:Filter[], rangeFilters: RangeFilter[], includePage: boolean) {
1025
    this.parameterNames.splice(0, this.parameterNames.length);
1026
    this.parameterValues.splice(0, this.parameterValues.length);
1027
    for (var i = 0; i < this.selectedFields.length; i++) {
1028
      //default operator is and
1029
      this.parameterNames.push("f"+i);
1030
      this.parameterValues.push(this.selectedFields[i].id + (this.selectedFields[i].operatorId!='and'?(","+this.selectedFields[i].operatorId):''));
1031
      this.parameterNames.push("fv"+i);
1032
      if (this.selectedFields[i].type == "date") {
1033

    
1034
        if (this.selectedFields[i].dateValue.type == "range") {
1035
          this.parameterValues.push(StringUtils.URIEncode("range" + Dates.getDateToString(this.selectedFields[i].dateValue.from) + ":" + Dates.getDateToString(this.selectedFields[i].dateValue.to)));
1036
        } else {
1037
          this.parameterValues.push(StringUtils.URIEncode(this.selectedFields[i].dateValue.type));
1038
        }
1039

    
1040
      } else {
1041
        // console.log(this.selectedFields[i].value +" " + StringUtils.URIEncode(this.selectedFields[i].value))
1042
        this.parameterValues.push(StringUtils.URIEncode(this.selectedFields[i].value));
1043
      }
1044
    }
1045
    if (includePage && this.searchUtils.page != 1) {
1046
      this.parameterNames.push("page");
1047
      this.parameterValues.push("" + this.searchUtils.page);
1048
    }
1049

    
1050
    if (this.searchUtils.size != this.resultsPerPage) {
1051
      this.parameterNames.push("size");
1052
      this.parameterValues.push("" + this.searchUtils.size);
1053
    }
1054

    
1055
    if (this.sort && this.searchUtils.sortBy) {
1056
      this.parameterNames.push("sortBy");
1057
      this.parameterValues.push(this.searchUtils.sortBy);
1058
    }
1059
    for (let filter of filters) {
1060
      var filterLimits = "";
1061
      if (filter.countSelectedValues > 0) {
1062
        for (let value of filter.values) {
1063
          if (value.selected == true) {
1064
            filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + (value.id) + '"';
1065
          }
1066
        }
1067
        if (filterLimits.length > 0) {
1068
          this.parameterNames.push(filter.filterId);
1069
          this.parameterValues.push(filterLimits);
1070
        }
1071
      }
1072
    }
1073
    for (let filter of rangeFilters) {
1074
      var filterLimits = "";
1075
      let yearFrom: string = (Dates.isValidYear(filter.selectedFromValue) ? filter.selectedFromValue : null);
1076
      let yearTo: string = (Dates.isValidYear(filter.selectedToValue) ? filter.selectedToValue : null);
1077
      if(yearFrom || yearTo) {
1078
        this.parameterNames.push(filter.filterId);
1079
        this.parameterValues.push("range" + (yearFrom ? yearFrom : "") + ":" + (yearTo ? yearTo : ""));
1080
      }
1081
      // if (filter.countSelectedValues > 0) {
1082
      //   for (let value of filter.values) {
1083
      //     if (value.selected == true) {
1084
      //       filterLimits += ((filterLimits.length == 0) ? '' : ',') + '"' + (value.id) + '"';
1085
      //     }
1086
      //   }
1087
      //   if (filterLimits.length > 0) {
1088
      //     this.parameterNames.push(filter.filterId);
1089
      //     this.parameterValues.push(filterLimits);
1090
      //   }
1091
      // }
1092
    }
1093
    if (this.searchUtils.keyword.length > 0) {
1094
      this.parameterNames.push("keyword");
1095
      this.parameterValues.push(this.searchUtils.keyword);
1096
    }
1097

    
1098
    if (this.resultTypes && this.entityType == "result") {
1099
      let values = [];
1100
      if (this.resultTypes.publication) {
1101
        values.push("publications");
1102
      }
1103
      if (this.resultTypes.dataset) {
1104
        values.push("datasets");
1105
      }
1106
      if (this.resultTypes.software) {
1107
        values.push("software");
1108
      }
1109
      if (this.resultTypes.other) {
1110
        values.push("other");
1111
      }
1112
      if (values.length > 0) {
1113
        this.parameterNames.push("type");
1114
        this.parameterValues.push(values.join(","));
1115
      }
1116
      if(this.quickFilter) {
1117
        this.parameterNames.push("qf");
1118
        this.parameterValues.push("" + this.quickFilter.selected);
1119
      }
1120
    }
1121

    
1122
    // if (this.searchUtils.size != this.resultsPerPage) {
1123
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'size=' + this.searchUtils.size;
1124
    //   this.parameterNames.push("size");
1125
    //   this.parameterValues.push("" + this.searchUtils.size);
1126
    // }
1127
    // if (this.sort && this.searchUtils.sortBy) {
1128
    //   // allLimits += ((allLimits.length == 0) ? '?' : '&') + 'sortBy=' + this.searchUtils.sortBy;
1129
    //   this.parameterNames.push("sortBy");
1130
    //   this.parameterValues.push(this.searchUtils.sortBy);
1131
    // }
1132
    // console.log(this.parameterNames)
1133
    // console.log(this.parameterValues)
1134
  }
1135

    
1136
  /**
1137
   * create filters based on URL params
1138
   * @param URLparams
1139
   */
1140
  getRefineFiltersFromURL(URLparams) {
1141
    let fields = new SearchFields();
1142
    let filters: Filter[] = [];
1143
    for (let i = 0; i < this.refineFields.length; i++) {
1144
      let filterId = this.refineFields[i];
1145
      if (URLparams[filterId] != undefined) {
1146
        let filter = new Filter();
1147
        filter.title = fields.getFieldName(filterId, this.entityType);
1148
        filter.filterId = filterId;
1149
        filter.originalFilterId = filterId;
1150
        filter.values = [];
1151
        let values = StringUtils.URIDecode(URLparams[filterId]).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1152
        for (let value of values) {
1153

    
1154
          let v: Value = new Value();
1155
          v.name = RefineResultsUtils.keepPartAfterCharacters(StringUtils.unquote(value), "||");
1156
          v.id = StringUtils.unquote(value);
1157
          v.selected = true;
1158
          filter.values.push(v);
1159
          // console.log(v)
1160
          filter.countSelectedValues++;
1161
        }
1162
        filters.push(filter)
1163
      }
1164
    }
1165

    
1166
    if (this.quickFilter) {
1167
      if (this.entityType == "result" && (URLparams[this.quickFilter.filterId] == undefined) && (URLparams["qf"] == undefined || URLparams["qf"] == "true")) {
1168
        let filter = new Filter();
1169
        filter.title = fields.getFieldName(this.quickFilter.filterId, this.entityType);
1170
        filter.filterId = this.quickFilter.filterId;
1171
        filter.originalFilterId = this.quickFilter.filterId;
1172
        filter.values = [];
1173
        let v: Value = new Value();
1174
        v.name = this.quickFilter.value;
1175
        v.id = this.quickFilter.value;
1176
        v.selected = true;
1177
        filter.values.push(v);
1178
        filter.countSelectedValues = 1;
1179
        filters.push(filter)
1180
      }
1181
    }
1182
    if (this.entityType == "result") {
1183
      this.resultTypes = null;
1184
      this.resultTypes = {
1185

    
1186
      };
1187

    
1188
      if (URLparams["type"]) {
1189

    
1190
        this.resultTypes['publication'] = (URLparams["type"].split(",").indexOf("publications") != -1);
1191
        this.resultTypes['dataset'] = (URLparams["type"].split(",").indexOf("datasets") != -1);
1192
        this.resultTypes['software'] = (URLparams["type"].split(",").indexOf("software") != -1);
1193
        this.resultTypes['other'] = (URLparams["type"].split(",").indexOf("other") != -1);
1194

    
1195
      } else {
1196
        this.resultTypes['publication'] = true;
1197
        this.resultTypes['dataset'] = true;
1198
        this.resultTypes['software'] = true;
1199
        this.resultTypes['other'] = true;
1200
      }
1201

    
1202
    }
1203

    
1204
    this.URLCreatedFilters = filters;
1205
  }
1206

    
1207
  /**
1208
   * create range filters based on URL params
1209
   * @param URLparams
1210
   */
1211
  getRangeFiltersFromURL(URLparams) {
1212
    let fields = new SearchFields();
1213
    let filters: RangeFilter[] = [];
1214
    for (let i = 0; i < this.rangeFields.length; i++) {
1215
      let filterId = this.rangeFields[i][0]+"-range-"+this.rangeFields[i][1];
1216
      let filterParam = fields.getFieldParam(filterId, this.entityType);
1217
      //console.log("rangeFilter (from url): filterId - filterParam");
1218
      //console.log(filterId + " - "+ filterParam);
1219
      if (URLparams[filterParam] != undefined) {
1220
        let filter = new RangeFilter();
1221
        filter.title = fields.getFieldName(filterId, this.entityType);
1222
        filter.filterId = filterParam;
1223
        filter.originalFilterIdFrom = this.rangeFields[i][0];
1224
        filter.originalFilterIdTo = this.rangeFields[i][1];
1225

    
1226

    
1227
        let values = (decodeURIComponent(URLparams[filterParam])).split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/, -1);
1228
        for (let j = 0; j < values.length; j++) {
1229
          if (this.fieldIdsMap[filterId].filterType == "range") {
1230
            let value: string = StringUtils.unquote(values[j]);
1231
            let validDates: boolean = true;
1232
            // if (value.length < 14) {
1233
            //   validDates = false;
1234
            // } else {
1235
            //   if (!Dates.isValidYear(value.substring(5, 9)) || !Dates.isValidYear(value.substring(10, 14))) {
1236
            //     validDates = false;
1237
            //   } else {
1238
            //     filter.selectedFromValue = value.substring(5, 9);
1239
            //     filter.selectedToValue = value.substring(10, 14);
1240
            //   }
1241
            // }
1242
            let years: string[] = (value.substring(5)).split(":");
1243
            let yearFrom: string = (Dates.isValidYear(years[0]) ? years[0] : null);
1244
            let yearTo: string = (Dates.isValidYear(years[1]) ? years[1] : null);
1245
            //console.log("getRangeFiltersFromURL: yearFrom: " + yearFrom + " - yearTo: "+yearTo);
1246
            if(yearFrom) {
1247
              filter.selectedFromValue = yearFrom;
1248
              //filter.selectedFromAndToValues = yearFrom;
1249
            }
1250
            /*if(yearFrom && yearTo) {
1251
              filter.selectedFromAndToValues += "-";
1252
            }*/
1253
            if(yearTo) {
1254
              filter.selectedToValue = yearTo;
1255
              //filter.selectedFromAndToValues += yearTo;
1256
            }
1257
            //console.log("filter.selectedFromAndToValues: "+filter.selectedFromAndToValues);
1258
            if(!yearFrom && !yearTo) {
1259
              validDates = false;
1260
            }
1261

    
1262
          }
1263
        }
1264
        //console.log(filters);
1265
        filters.push(filter)
1266
      }
1267
    }
1268
    // console.log("Empty Filters");
1269
    // console.log(filters);
1270
    this.URLCreatedRangeFilters = filters;
1271
    // return filters;
1272

    
1273
  }
1274

    
1275
  /**
1276
   * Checks if query has no results, display Filters from URL parameters
1277
   * Mark checked  the selected filters
1278
   * Count the checked
1279
   * @param filters
1280
   */
1281
  public prepareFiltersToShow(filters: Filter[], totalResults): Filter[] {
1282
    if (this.URLCreatedFilters.length > 0 && totalResults == 0) {
1283
      this.showUnknownFilters = true;
1284
      this.filters = this.URLCreatedFilters;
1285
    } else if (totalResults != 0) {
1286
      this.showUnknownFilters = false;
1287
      this.filters = filters;
1288
    }
1289
    this.buildPageURLParameters(this.URLCreatedFilters, this.URLCreatedRangeFilters, true);
1290
    //this.checkSelectedRangeFilters(this.rangeFilters);
1291

    
1292
    this.checkSelectedFilters(this.filters);
1293
    this.countSelectedFilters(this.filters);
1294
    return this.filters;
1295
  }
1296

    
1297
  /**
1298
   * Mark checked  the selected range filters
1299
   */
1300
  public prepareRangeFiltersToShow() {
1301
    this.rangeFilters = RangeFilter.parse(this.rangeFields, this.entityType); // OK
1302

    
1303
    //this.buildPageURLRangeParameters(this.rangeFilters, true);
1304
    this.checkSelectedRangeFilters(this.rangeFilters);
1305
    this.countSelectedRangeFilters(this.rangeFilters);
1306
    return this.rangeFilters;
1307
  }
1308

    
1309
  /**
1310
   * Used to set the variables and search page, and prepare it before the getResults query
1311
   * @param fieldIds
1312
   * @param selectedFields
1313
   * @param refineFields
1314
   * @param rangeFields
1315
   * @param fieldIdsMap
1316
   * @param customFilter
1317
   * @param params
1318
   * @param entityType
1319
   * @param quickFilter
1320
   */
1321
  prepareSearchPage(fieldIds, selectedFields, refineFields, rangeFields, fieldIdsMap, customFilter, params, entityType, quickFilter=null){
1322
    // console.log(this.refineFields);
1323
    this.entityType = entityType;
1324
    this.fieldIds = fieldIds;
1325
    this.selectedFields = selectedFields;
1326
    this.refineFields = refineFields;
1327
    this.rangeFields = rangeFields;
1328
    this.fieldIdsMap = fieldIdsMap;
1329
    this.customFilter = customFilter;
1330
    this.quickFilter = quickFilter;
1331
    this.getRangeFiltersFromURL(params);
1332
    this.getRefineFiltersFromURL(params);
1333
    this.createAdvancedSearchSelectedFiltersFromURLParameters(params);
1334
  }
1335
}
(20-20/55)