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 +=(countParams == 0 ? "" : " " + this.selectedFields[i].operatorId + " ") + 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
    params+=   " (";
756
    if(forceQuotted){
757
      return this.getQuotedQueryPart(fieldId, '"'+ fieldValue+'"',isSearchAll);
758
    }
759
    if(quotedParts && quotedParts.length == 1 && quotedParts[0] == fieldValue ){
760
      params+=this.getQuotedQueryPart(fieldId, fieldValue,isSearchAll);
761
    }else if( quotedParts && quotedParts.length > 0){
762
      for(let i=0; i< quotedParts.length; i++){
763
        params+=(i>0)?" and ":"";
764
        params+=this.getQuotedQueryPart(fieldId, quotedParts[i],isSearchAll);
765
      }
766
      let startPoint = 0;
767
      let endPoint = 0;
768
      for(let i=0; i< quotedParts.length; i++){
769
        let index = fieldValue.indexOf(quotedParts[i]);
770
        endPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+1]):fieldValue.length;
771
        // console.log(fieldValue.indexOf(quotedParts[i+1]) +" - "+fieldValue.length);
772
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
773
        if(index==startPoint){
774
          startPoint +=quotedParts[i].length;
775
        }else if(startPoint < index){
776
          endPoint = index;
777
        }
778
        // console.log(" SP "+ startPoint+" EP: "+endPoint);
779
        if(decodeURIComponent(fieldValue.substring(startPoint,endPoint)).split(" ").join("").length > 0) {
780
          params += " and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint, endPoint), isSearchAll);
781
        }
782
        // console.log("For "+i+"  " +params+" SP "+ startPoint+" EP: "+endPoint);
783
        // startPoint = (i+1<quotedParts.length)? fieldValue.indexOf(quotedParts[i+i]):fieldValue.length;//(startPoint<index  )?(index + quotedParts[i].length):fieldValue.length;
784
        startPoint = ((i+1<quotedParts.length)?(fieldValue.indexOf(quotedParts[i+1])+quotedParts[i+1].length):(endPoint== index?(index+quotedParts[i].length):endPoint));
785
      }
786
      if(startPoint !=fieldValue.length && decodeURIComponent(fieldValue.substring(startPoint,fieldValue.length)).split(" ").join("").length > 0){
787
        params+=" and " + this.getNoQuotedQueryPart(fieldId, fieldValue.substring(startPoint,fieldValue.length),isSearchAll);
788
      }
789
    }else{
790
      params+=this.getNoQuotedQueryPart(fieldId, fieldValue,isSearchAll);
791
    }
792
    params += ")";
793
    return params;
794
  }
795

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

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

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

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

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

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

    
923
  }
924

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

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

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

    
946
            let selectedFromValue;
947
            let selectedToValue;
948

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

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

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

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

    
1014
    return allFqs;
1015

    
1016
  }
1017

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

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

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

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

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

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

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

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

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

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

    
1187
      };
1188

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

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

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

    
1203
    }
1204

    
1205
    this.URLCreatedFilters = filters;
1206
  }
1207

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

    
1227

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

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

    
1274
  }
1275

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

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

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

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

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