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() showBreadcrumb:boolean = false;
80
  @Input() lastIndex: boolean = true;
81

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

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

    
96
  url = null;
97

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

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

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

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

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

    
137

    
138
  }
139

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

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

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

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

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

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

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

    
178

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

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

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

    
220
  queryChanged() {
221

    
222
    this.goTo(1);
223
  }
224

    
225

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

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

    
236

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

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

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

    
272
  /*
273
  * 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 )
274
  */
275
  public getFields(): string[] {
276
    var selected_filters: string[] = this.getSelectedFilters();
277
    if (selected_filters.length == 0) {
278
      selected_filters = this.getSelectedParameters();
279
    }
280
    var fields: string[] = [];
281
    for (var i = 0; i < this.refineFields.length; i++) {
282
      var dependentTo = this.searchFieldsHelper.DEPENDENT_FIELDS[this.refineFields[i]];
283

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

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

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

    
305

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

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

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

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

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

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

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

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

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

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

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

    
446
    }
447

    
448
    return filters;
449
  }
450

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

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

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

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

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

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

    
507
  }
508

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

    
515
  }
516

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

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

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

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

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

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

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

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

    
631
            } else {
632
              this.selectedFields.push(new AdvancedField(fieldId, fieldparam, this.fieldIdsMap[fieldId].name, this.fieldIdsMap[fieldId].type, values[j], operators[j]));
633
            }
634
          }
635
        }
636
      }
637
    }
638
    if (params['keyword'] && params['keyword'].length > 0) {
639
      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"));
640
    }
641
    if (this.selectedFields.length == 0) {
642
      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"));
643
    }
644
  }
645

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
924
  }
925

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

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

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

    
947
            let selectedFromValue;
948
            let selectedToValue;
949

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

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

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

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

    
1015
    return allFqs;
1016

    
1017
  }
1018

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

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

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

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

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

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

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

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

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

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

    
1188
      };
1189

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

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

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

    
1204
    }
1205

    
1206
    this.URLCreatedFilters = filters;
1207
  }
1208

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

    
1228

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

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

    
1275
  }
1276

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

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

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

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

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