All files / universal.klown/gpii/node_modules/matchMakerFramework/src MatchMakerUtilities.js

100% Statements 290/290
93.69% Branches 104/111
100% Functions 80/80
100% Lines 289/289

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873                                        9x 9x   9x     9x 9x                 9x 9x                 9x 157x           157x     157x   157x             9x 36039x                               9x   1174x 1174x   1174x                     9x 874x 874x 884x     874x 218x   874x           9x 3804x 6929x 6929x 4478x     2451x                         9x 1353x 1353x 1353x                           9x 1763x 1763x 8432x 8432x 8432x 7448x     1763x                               9x 159x 585x 585x 585x   585x 585x   585x                                   9x       318x   387x   64x 64x 64x 60x         318x                                   9x 157x 157x   157x 177x     177x     177x   177x 177x 177x 177x 685x 289x       157x       9x 222x   222x 175x   222x                                   9x   188x 188x 737x 147x       188x   188x 69x 69x     69x 147x 147x     147x 43x       104x     511x 301x     210x   15x       104x         104x 95x 95x       95x 95x         9x 9x                                       9x 9x 24x 24x 24x 24x                                           9x 289x 325x 234x 234x 109x 109x 109x                                             9x   177x 12x 12x   12x 12x 12x             9x 177x 107x   107x 85x               9x 291x   291x     291x 291x 291x 1771x       291x 85x   471x 5x 5x           291x   2920x 927x     1993x 85x     1908x                       9x 159x       159x 179x     179x 179x 291x 291x               179x 21x     159x                         9x 163x 163x 183x 183x 119x     163x                   9x 583x 3001x                                 9x 157x 581x 581x 581x                                         9x 158x   585x 585x   585x   365x         9x 1812x     9x 4201x     9x 277x     9x 64x     9x 1049x 1049x 150x   150x 786x     150x 144x 144x   168x   114x     54x       168x 168x 168x 168x       1049x                             9x 157x 177x 177x 965x 210x 755x 107x 107x 584x 18x         177x                                               9x 172x 172x 717x   172x 172x 193x 193x 1049x   1049x     172x     9x 24x 8x 8x 8x         16x 22x 16x                           9x 18x 18x 18x 24x 16x 8x 8x 8x 8x         18x 26x 26x   26x 4x       18x                     9x 10x 10x 12x 12x 12x 18x 2x 2x   16x       10x               9x   10x   10x 10x 12x   20x 6x 2x     4x     10x     14x     12x   10x     9x                                     9x   14275x 29872x 35208x     35155x 35155x 29800x         5408x 5408x 5208x       14275x      
/*!
GPII Matchmaker Framework - Utilities
 
Copyright 2012 OCAD University
Copyright 2012 Antranig Basman
Copyright 2014 Raising the Floor - international
 
Licensed under the New BSD license. You may not use this file except in
compliance with this License.
 
The research leading to these results has received funding from the European Union's
Seventh Framework Programme (FP7/2007-2013) under grant agreement no. 289016.
 
You may obtain a copy of the License at
https://github.com/GPII/universal/blob/master/LICENSE.txt
*/
 
/* eslint-env browser */
/* eslint strict: ["error", "function"] */
 
var fluid = fluid || require("infusion"),
    gpii = fluid.registerNamespace("gpii");
 
(function () {
 
    "use strict";
    fluid.registerNamespace("gpii.matchMakerFramework.utils");
    fluid.registerNamespace("gpii.matchMakerFramework");
 
    /**
     * APP_SETTING_PRIORITY: the priority that an application is given if the user has application
     *    specific settings in their NP set for that application, but has no explicit priority for
     *    that application. * MIN_USER_PRIORITY: If an explicit priority is set by the user for an application, this is
     *    the minimum value it should have, to avoid conflicting with system generated priorities.
     */
 
    gpii.matchMakerFramework.APP_SETTING_PRIORITY = 512;
    gpii.matchMakerFramework.MIN_USER_PRIORITY = 1024;
 
    /*
     * responsible for building the input payload to the matchmaker, via a bunch of helper functions
     *
     * @params initialPayload {Object}: The initial payload sent to the matchmaking framework. It should as a
     *   minimum contain: userToken, preferences, deviceContext, solutionsRegistryEntries
     *   The values from this object will become part of the new matchmaker input object returned from this function,
     */
    gpii.matchMakerFramework.utils.preProcess = function (initialPayload) {
        var matchMakerInput = fluid.extend({
            activeContexts: [], // set later in the process
            environmentReporter: {}, // for holding any environment information
            inferredCommonTerms: gpii.matchMakerFramework.utils.inferCommonTerms(initialPayload.preferences, initialPayload.fullSolutionsRegistry),
            specialPreferences: gpii.matchMakerFramework.utils.findSpecialPreferences(initialPayload.preferences)
        }, fluid.copy(initialPayload));
        gpii.matchMakerFramework.utils.addCapabilitiesInformation(matchMakerInput);
        // remove full solutions registry from the payload, now that we've used it
        // to avoid sending a too large payload to the matchmaker (see GPII-1880)
        delete matchMakerInput.fullSolutionsRegistry;
 
        return matchMakerInput;
    };
 
    /**
     * extracts the capabilities from a settingshandler block based on the `capabilities` entry
     * and the inputPaths of the capabilitiesTransformations block
     */
    gpii.matchMakerFramework.utils.extractCapabilities = function (settingsHandler) {
        return fluid.model.transform.collectInputPaths(settingsHandler.capabilitiesTransformations || {});
    };
 
    /**
     * Takes an array of paths as input and returns them in the ontology provided via the transform spec.
     * The result will be an array list of el-paths in the ontology transformed to.
     *
     * @param paths {Array} An array of supported capabilities by a solution (as returned by the
     *     gpii.matchMakerFramework.utils.computeCapabilitiesFromSolution function)
     * @param transformSpec {Object} transformation rules to transform the input paths from the solution
     *    registry format into the format desired in the output array. If if one would like the result
     *    as a list of ISO24751 el-paths and the solutionsregistry transformations are given in
     *    the flat format, a transformation rules for 'flat' to ISO24751 should be given
     * @return {Array} An array of el-paths to all the input paths of the given capabilities in the
     *    ontology produced by the transformSpec
     */
    gpii.matchMakerFramework.utils.transformCapabilitiesToOntologizedLeaves = function (paths, transformSpec) {
        // Input paths are flat so need to be transformed into hierarchical
        var skel = gpii.matchMakerFramework.utils.pathsToSkeleton(paths, true);
        var hskeleton = fluid.model.transformWithRules(skel, transformSpec);
 
        return gpii.matchMakerFramework.utils.computeLeaves(hskeleton);
    };
 
    /**
     * Given a solution entry, all the capabilities of that solution will be calculated based on
     * input paths in the transformations (specified in the capabilitiesTransformations block) and
     * on the list in the capabilities block of that solution
     *
     * @param solution {Object} A single solution entry, as can be found in the solutions registry
     * @return {Array} An array capabilities supported by the given solution
    */
    gpii.matchMakerFramework.utils.computeCapabilitiesFromSolution = function (solution) {
        var paths = [];
        fluid.each(solution.settingsHandlers, function (handlerBlock) {
            paths = paths.concat(gpii.matchMakerFramework.utils.extractCapabilities(handlerBlock));
        });
        // grab the capabilities block from the solution if present:
        if (solution.capabilities) {
            paths = paths.concat(solution.capabilities);
        }
        return paths;
    };
 
    /**
     * Helper function for gpii.matchMakerFramework.utils.computeLeaves - see description there
     */
    var computeLeavesImpl = function (model, path, paths) {
        fluid.each(model, function (value, key) {
            var newPath = fluid.pathUtil.composePath(path, key.toString());
            if (fluid.isPrimitive(value)) {
                paths.push(newPath);
            }
            else {
                computeLeavesImpl(value, newPath, paths);
            }
        });
    };
 
    /**
     * Function to extract all leaves (i.e. primitive end points) from an object. More specifically,
     * it takes a object (eg. prefs set) and finds all leaves - for each leaf found the path is
     * to an array as an el-path, one path for each leaf.
     *
     * @param model {Object} the object from which to subtract leaves
     * @return {Array} an array of el-paths, one entry for each leaf found in the object
     */
    gpii.matchMakerFramework.utils.computeLeaves = function (model) {
        var paths = [];
        computeLeavesImpl(model, "", paths);
        return paths;
    };
 
    /**
     * Given a array of el-paths, this function creates an object with a structure that includes
     * all the el-paths in the array. Each of the entries will have the value passed as parameter or
     * defaulting to {} (i.e. the empty object);
     *
     * @param paths {Array} an array of el-paths that should be present in the resulting object
     * @param value {Any} the value that should be assigned to each of the keys given in the el-path array,
     *      if no @value is given, this defaults to the empty object ({})
     * @return {Object} and object with a structure containing all the el-paths, where each path has
     *     the value given in the parameter.
     */
    gpii.matchMakerFramework.utils.pathsToSkeleton = function (paths, value) {
        var togo = {};
        for (var i = 0; i < paths.length; ++i) {
            var path = paths[i];
            var existing = fluid.get(togo, path, fluid.model.escapedGetConfig);
            if (!existing) {
                fluid.set(togo, path, value || {}, fluid.model.escapedSetConfig);
            }
        }
        return togo;
    };
 
    /**
     * Given a list of solutions and capabilities, ontologize the capabilities and generate a skeleton based on those.
     *
     * @param solutions {Object} list of solution entries in the same format as the solutions registry\
     * @param capabilities {Object} (array)listings of solution capabilities, keyed by solution ID
     * @param transformSpec {Object} transformation rules to translate from the format the input paths are
     *     given in in the solutions entries' capabilitiesTransformations block, to the ontology
     *     that the skeleton should be in
     * @return {Object} an object listing the same solutions as the input payload, but where each
     *     solution block instead contains three keys: 'solution' which contains the original solution
     *     entry. 'skeleton' which contains the capabilities of the solution. 'index' which contains
     *     the solution id.
     */
    gpii.matchMakerFramework.utils.expandSolutions = function (solutions, capabilities, transformSpec) {
        return fluid.transform(solutions, function (solution, solutionId) {
            var solutionIdObj = {};
            solutionIdObj["http://registry.gpii.net/applications/" + solutionId] = {};
            var transformedId = fluid.model.transformWithRules(solutionIdObj, transformSpec);
 
            var paths = gpii.matchMakerFramework.utils.transformCapabilitiesToOntologizedLeaves(capabilities[solutionId], transformSpec);
            var skeleton = fluid.extend(true, {}, gpii.matchMakerFramework.utils.pathsToSkeleton(paths), transformedId);
 
            return {
                solution: solution,
                skeleton: skeleton,
                index: solutionId
            };
        });
    };
 
    /**
     * Based on the /enabled terms from a users' NP set and the /enabled capabilities from the solution,
     * this function returns what the 'active' value of the solution should be.
     *
     * @param specialPreferences {Object} the specialPreferences value of the relevant context (from the value of the same name in the match maker input payload)
     * @param specialCapabilities {Array} the solutions specialCapabilities (from the value of the same name in the match maker input payload)
     * @param solution {Object} the solution registry entry of the solution for which to decide the 'active' value
     * @param solutionId {String} the solution id
     * @return {boolean} the value of the 'active' flag of the solution.
     **/
    gpii.matchMakerFramework.utils.getActiveValueFromEnabledTerms = function (specialPreferences, specialCapabilities, solution, solutionId) {
        var active;
 
        // see if solution has any enabled flags:
        fluid.each(specialCapabilities, function (term) {
            // if we have an /enabled term and this is not just a settings transformation:
            if (term.endsWith("/enabled") && solution.capabilities && solution.capabilities.includes(term)) {
                // set the active flag based on the users' preference value (from solution specific pref or general pref)
                var applicationBlockKey = gpii.matchMakerFramework.utils.makeApplicationTerm(solutionId);
                active = fluid.get(specialPreferences[applicationBlockKey], term, fluid.model.escapedGetConfig);
                if (active === undefined) {
                    active = fluid.get(specialPreferences, term, fluid.model.escapedGetConfig);
                }
            }
        });
 
        return active;
    };
 
    /**
     * Function that takes a MM payload set as input that *includes* an entry of
     * preferences in a hierarchical format, as well as a strategy for selecting solutions
     * and a set of transformations rules between ontologies.
     *
     * @param data {Object} a match maker input payload that includes a translation of the
     *     preferences in an hierarchical ontology, keyed by 'hierarchicalPrefs'.
     * @param strategy {Function} the strategy to use to select which solutions should be configured and
     *     and launched on the system
     * @param transformSpec {Object} Transformation rules FROM the format used in the input paths of the
     *     solutions registry capability transformations TO the format in which the
     *     settings of hierarchicalPrefs in the data argument are given
     * @return {Object} An object keyed by contexts and where the values are arrays of solutions
     *     to launch in that context
     */
    gpii.matchMakerFramework.utils.disposeSolutions = function (data, strategy, transformSpec, ontologyMetadata) {
        var solrecs = gpii.matchMakerFramework.utils.expandSolutions(data.solutionsRegistryEntries, data.solutionCapabilities, transformSpec);
        var togo = {};
        // calculate match for each of the contexts
        fluid.each(data.hierarchicalPrefs.contexts, function (context, contextId) {
            var tmpSolrecs = fluid.copy(solrecs);
            // add implicit priorities based on which applications the user has application
            // specific settings for
            gpii.matchMakerFramework.utils.addPriorityFromApplicationSettings(context.preferences, tmpSolrecs);
 
            // add users explicit application priorities to the solrecs object
            gpii.matchMakerFramework.utils.parsePriorities(context, tmpSolrecs);
 
            var leaves = gpii.matchMakerFramework.utils.computeLeaves(context.preferences);
            var disposed = strategy(leaves, tmpSolrecs, data, contextId, ontologyMetadata);
            togo[contextId] = {};
            fluid.each(disposed, function (solrec, solid) {
                if (solrec.disposition === "accept") { // only output accepted solutions
                    togo[contextId][solid] = solrec.active; // true if it should be running
                }
            });
        });
        return togo;
    };
 
    // true if one of the values matches across the two arrays (ignoring the indexing)
    gpii.matchMakerFramework.utils.containsSameValue = function (arr1, arr2) {
        var obj2 = fluid.arrayToHash(arr2);
        // find match across arrays or set to false
        var found = fluid.find(arr1, function (v) {
            return obj2[v];
        }, false);
        return found;
    };
 
    /**
     * Calculate dispositions based on priorities while taking solution types into account.
     *
     * NOTE: this function will modify the solrecs object by adding, changing or removing the `disposition`,
     * `dispositionReason` and `priority` properties of a solrec[solution] entry.
     *
     * @param solrecs {Object}: a map of solution information, keyed by solution ids. This object should
     *     have a format identical to the output of the gpii.matchMakerFramework.utils.expandSolutions
     *     function. Each entry in this object will potentially be modified by the
     *     modification/addition/deletion of the disposition, priority and/or dispositionReason.
     * @param data {Object}: contains information about the type each solution is. More precisely,
     *     the value for the key `solutionTypeMapping` is a map of <solutionType name>: <array of
     *     solutionsIds of that type> pairs. The second key, `solutionTypes` is a map of <solutionIds>
     *     with <solution types> as values.
     */
    gpii.matchMakerFramework.utils.disposeFromPriority = function (solrecs, data, contextId) {
        // sort into prioritized map, eg: { 1024: [sola, solb], 200 [solc] }
        var prioritiesMap = {};
        fluid.each(solrecs, function (sol) {
            if (sol.priority) {
                fluid.set(prioritiesMap, [sol.priority, sol.index], true);
            }
        });
        // sort priority entries desc
        var priorities = Object.keys(prioritiesMap).sort(function (a, b) { return b - a; });
        // for each priority bucket:
        for (var i = 0; i < priorities.length; i++) {
            var priority = priorities[i];
            var sols = prioritiesMap[priority];
 
            // for each solution as sol
            for (var solutionId in sols) {
                var tied = [];
                var solutionType = data.solutionTypes[solutionId];
                // if a disposition is already decided for this solution, or if priority has been
                // removed (in case of ties), ignore it.
                if (solrecs[solutionId].disposition || !solrecs[solutionId].priority) {
                    continue;
                }
                // check if there are any similar typed solution with same priority:
                // for each remaining solution as rsol
                for (var otherId in sols) {
                    // if a disposition is already decided for this solution, or if priority has been
                    // removed (in case of ties), ignore it.
                    if (otherId === solutionId || solrecs[otherId].disposition || !solrecs[otherId].priority) {
                        continue;
                    }
                    // if solutions are of equal type:
                    if (gpii.matchMakerFramework.utils.containsSameValue(solutionType, data.solutionTypes[otherId])) {
                        // since we tie with another solution, resolve by other disposal means
                        tied.push(otherId);
                    }
                }
                // before accepting a solution, make sure all solutions of that type are marked reject
                gpii.matchMakerFramework.utils.rejectFromTypes(data.solutionTypes[solutionId],
                        data.solutionTypeMapping, solrecs,
                        "Another solution of same type with higher priority was found.");
 
                // if no ties, mark the current solution as "accept"
                if (tied.length === 0) {
                    solrecs[solutionId].disposition = "accept";
                    var prefActive = gpii.matchMakerFramework.utils.getActiveValueFromEnabledTerms(data.specialPreferences[contextId] || {},
                                                                                                data.specialCapabilities[solutionId],
                                                                                                data.solutionsRegistryEntries[solutionId],
                                                                                                solutionId);
                    solrecs[solutionId].active = (prefActive !== undefined) ? prefActive : true;
                    solrecs[solutionId].dispositionReason = "Has a higher priority (" + priority +
                        ") than any solution of the same type";
                } else {
                    // if there are ties, we "unreject" all of them, removing their disposition completely
                    // so they can be tiebreaked by other disposal means (such as via the canopy)
                    tied.push(solutionId);
                    gpii.matchMakerFramework.utils.removePriorityTies(tied, solrecs);
                }
            }
        }
    };
 
    /**
     * Remove priority and dispositions from tied solutions.
     * Given a list of tied solutionID and solution records, it modifies the solution
     * records by removing all priorities, dispositions and dispositionsReasons from the tied solutions.
     *
     * NOTE: this function will modify the solrecs object
     *
     * @param tied {Array} An array of solutionIds of tied solutions for which the disposition and
     *     priority information should be removed.
     * @param solrecs {Object}: a map of solution information, keyed by solution ids. This object should
     *     have a format identical to the output of the gpii.matchMakerFramework.utils.expandSolutions
     *     function, but might contain priority and disposition entries for each solution.
     *     Each tied entry in this object will be modified by this function
     */
    gpii.matchMakerFramework.utils.removePriorityTies = function (tied, solrecs) {
        fluid.each(tied, function (tiedSolutionId) {
            delete solrecs[tiedSolutionId].priority;
            delete solrecs[tiedSolutionId].disposition;
            delete solrecs[tiedSolutionId].dispositionReason;
            delete solrecs[tiedSolutionId].active;
        });
    };
 
    /**
     * Rejects all solutions of a given type. This is useful for ensuring that a user does not
     * get eg. multiple versions of screenReader launched. The "solution type" is the apptology
     * type as defined in the apptology ontology - see description in "%gpii-universal/documentation/Apptology.md"
     *
     * NOTE: this function will modify the solrecs object
     *
     * @param types {Array} An array of solution types
     * @param solutionTypeMapping {Object} A hash of solutionTypes with values being arrays of solutionIds
     *     of solutions that are of that type.
     * @param solrecs {Object}: a map of solution information, keyed by solution ids. This object should
     *     have a format identical to the output of the gpii.matchMakerFramework.utils.expandSolutions
     *     function. This object will be modified in the following way: If a solution is rejected
     *     based on its type by this function, that solution entry will have a `disposition: reject`
     *     and dispositionReason added to it.
     * @param disposeReason {String}: The reason to record for rejecting this solution. If this parameter
     *     is not provided, it will default to "Solution rejected due to its type of <type>"
     */
    gpii.matchMakerFramework.utils.rejectFromTypes = function (types, solutionTypeMapping, solrecs, disposeReason) {
        fluid.each(types, function (type) {
            for (var solutionId in solutionTypeMapping[type]) {
                var sol = solrecs[solutionId];
                if (!sol.disposition) {
                    sol.disposition = "accept";
                    sol.active = false;
                    sol.dispositionReason = disposeReason || "Solution accepted but deactivated due to its type of " + type;
                }
            }
        });
    };
 
    /**
     * Scans the metadata block for application priorities, and for each found, the priority is added
     * to the solrecs object.
     *
     * Given the context section of an NP set, the function will search the metadata section for
     * application priorities. If this is found, the entry for that solution in the solrec object
     * will be modified by the addition of a `priority` key with the value of the user priority.
     *
     * NOTE: this function will modify the solrecs object
     *
     * @param context {Object} the contextual portion of an NP set - i.e. the part of the NP set that is
     *     inside a single context (the value for the context name key)
     * @param solrecs {Object}: a map of solution information, keyed by solution ids. This object should
     *     have a format identical to the output of the `gpii.matchMakerFramework.utils.expandSolutions`
     *     function. For each solution for which the user has an application priority, this solutions'
     *     entry in solrecs will be modified by the addition of a `priority` key.
     */
    gpii.matchMakerFramework.utils.parsePriorities = function (context, solrecs) {
        // for each entry in the metadata block:
        fluid.each(context.metadata, function (metadata) {
            Eif (metadata.type === "priority") {
                fluid.each(metadata.scope, function (applicationId) {
                    // set the priority of the application if it's part of our solrecs list:
                    var solrec = solrecs[gpii.matchMakerFramework.utils.applicationIdFromTerm(applicationId)];
                    Eif (solrec) {
                        solrec.priority = metadata.value;
                    }
                });
            }
        });
    };
 
    gpii.matchMakerFramework.utils.addPriorityFromApplicationSettings = function (preferences, solrecs) {
        fluid.each(preferences.applications, function (value, applicationId) {
            var sol = solrecs[applicationId];
            // If solution is available on the system, and doesn't already have higher priority
            if (sol && (!sol.priority || sol.priority < gpii.matchMakerFramework.APP_SETTING_PRIORITY)) {
                sol.priority = gpii.matchMakerFramework.APP_SETTING_PRIORITY;
            }
        });
    };
 
    /**
     * Filters preferences to contain only common terms and application specific settings for the solutionId
     */
    gpii.matchMakerFramework.utils.filterPreferencesForSolution = function (solutionId, allPreferences, solutionEntry) {
        var filtered = fluid.copy(allPreferences);
 
        var applicationString = "http://registry.gpii.net/applications/" + solutionId;
 
        // find supported common terms:
        var supportedCommonArr = gpii.matchMakerFramework.utils.computeCapabilitiesFromSolution(solutionEntry);
        var supportedCommon = {}; // create object of keys that are unescaped common term URIs and values of true
        fluid.each(supportedCommonArr, function (common) {
            fluid.set(supportedCommon, common, true, fluid.model.escapedSetConfig);
        });
 
        // move any common terms from the application block to the outer level:
        if (filtered[applicationString]) { // application block for this solution
            fluid.each(filtered[applicationString], function (value, preference) {
                // move all common terms outside application block:
                if (gpii.matchMakerFramework.utils.isCommonTerm(preference)) {
                    filtered[preference] = value;
                    delete filtered[applicationString][preference];
                }
            });
        }
 
        // top level: filter everything that is not the application block and supported common terms
        return fluid.remove_if(filtered, function (value, preference) {
            // Keep preference if it is a supported common term
            if (gpii.matchMakerFramework.utils.isCommonTerm(preference) && supportedCommon[preference] === true) {
                return false;
            }
            // Also leave the applicaiton specific block
            if (preference.startsWith(applicationString) === true) {
                return false;
            }
 
            return true;
        });
    };
 
    /**
     * Function to build the payload required to be the output from the matchmaker framework
     *
     * @param fullModel {Object} The full input sent to the MM
     * @param disposed {Object} Object with keys of context-ids. Each value should be an array listing
     *     the disposed solutions
     * @return {Object} The data arranged to be compatible with the required MM format
     */
    gpii.matchMakerFramework.utils.buildReturnPayload = function (fullModel, disposed) {
        var togo = {
            inferredConfiguration: {}
        };
 
        fluid.each(disposed, function (solArray, contextId) {
            togo.inferredConfiguration[contextId] = {
                applications: {}
            };
            var appBlock = togo.inferredConfiguration[contextId].applications;
            fluid.each(solArray, function (active, solutionId) {
                var filteredSettings = gpii.matchMakerFramework.utils.filterPreferencesForSolution(solutionId, fullModel.preferences.contexts[contextId].preferences, fullModel.solutionsRegistryEntries[solutionId]);
                appBlock[solutionId] = {
                    active: active,
                    settings: filteredSettings
                };
                // TODO: add metadata sections
            });
 
            // add conditions if they exist:
            if (fullModel.preferences.contexts[contextId].conditions) {
                togo.inferredConfiguration[contextId].conditions = fullModel.preferences.contexts[contextId].conditions;
            }
        });
        return togo;
    };
 
    /**
     * Merges a set of common term preferences with an already existing preferences set. This is
     * used when merging inferred common terms from the MM input payload with the already existing
     * common terms of the NP set. This happens for all the context blocks (for which inferred
     * common terms exist). Existing common terms take priority over the inferred terms
     *
     * @param preferences {Object} A needs and Preferences set (including the context blocks)
     * @param inferred {Object} Inferred common terms, as provided in the MM input
     * @return {Object} A copy of the preferences object with the inferred common terms merged in
     */
    gpii.matchMakerFramework.utils.addInferredCommonTermsToPreferences = function (preferences, inferred) {
        var togo = fluid.copy(preferences);
        fluid.each(inferred, function (context, contextId) {
            var tcont = togo.contexts[contextId];
            fluid.each(context, function (settings) {
                tcont.preferences = fluid.extend(true, settings, tcont.preferences);
            });
        });
        return togo;
    };
 
    /**
     * Simple function that takes a list of capabilities and extract all 'special' capabilities.
     * This is currently all terms ending with /enabled
     *
     * @param capabilities {Array} an array of term/capabilities
     * @return {Array} an array of all capabilities that are special (i.e. ends with /enabled)
     **/
    gpii.matchMakerFramework.utils.extractSpecialCapabilities = function (capabilities) {
        return fluid.remove_if(fluid.copy(capabilities), function (term) {
            return !term.endsWith("/enabled");
        });
    };
 
    /**
     * Adds information about the supported capabilities for each solution (in the flat format) and special capabilities.
     * Two things will be added to the payload:
     * (1) A list of inputPaths from the capabilitiesTransformations of the settingshandlers as well as the content of the solutions "capabiliites" entry.
     * (2) A list of special capabilities, meaning the (1) list run through the extractSpecialCapabilities function
     *
     * NOTE: This will modify the supplied payload
     *
     * @param payload {Object} An object with the format of a standard matchmaker input payload. At a very
     *     minimum this payload should have a `solutionsRegistryEntries` key with a hashmap of
     *     (solutionID => solution registry entry) pairs. Note that this object will be modified by
     *     addition of two toplevel keys: `solutionTypes` and `solutionTypeMapping`.
     */
    gpii.matchMakerFramework.utils.addCapabilitiesInformation = function (payload) {
        fluid.each(payload.solutionsRegistryEntries, function (solution, solutionId) {
            var capabilities = gpii.matchMakerFramework.utils.computeCapabilitiesFromSolution(solution);
            fluid.set(payload, [ "solutionCapabilities", solutionId ], capabilities);
            fluid.set(payload, [ "specialCapabilities", solutionId ], gpii.matchMakerFramework.utils.extractSpecialCapabilities(capabilities));
        });
    };
 
    /**
     * Adds information about the solutions types to the payload paramater, which should be in the
     * format of an input payload for matchmakers.
     *
     * Two keys are added to the given payload:
     * `solutionTypes` is a hash of solutionId->list of the solution types it is
     * `solutionTypeMapping` is a hash of solutionType->array of solutionIds of that type
     *
     * NOTE: this function will modify the supplied `payload`
     *
     * @param payload {Object} An object with the format of a standard matchmaker input payload. At a very
     *     minimum this payload should have a `solutionsRegistryEntries` key with the solution entries as well
     *     as a 'solutionCapabilities' key, which contains information about a solutions capabilities (i.e. via
     *     the addCapabilitiesInformation function).
     * @param transformSpec {Object} ontology transform spec translating from common terms into
     *     a solution type ontology.
     */
    gpii.matchMakerFramework.utils.addSolutionTypeInformation = function (payload, transformSpec) {
        fluid.each(payload.solutionCapabilities, function (capabilities, solutionId) {
            // first get an array of what solution types the current entry is:
            var solutionTypes = gpii.matchMakerFramework.utils.transformCapabilitiesToOntologizedLeaves(capabilities, transformSpec);
            fluid.set(payload, [ "solutionTypes", solutionId], solutionTypes);
            // now add solution ID to the return array in the appropriate places:
            for (var i in solutionTypes) {
                // add solution ID to the solution type
                fluid.set(payload, ["solutionTypeMapping", solutionTypes[i], solutionId], true);
            }
        });
    };
 
    gpii.matchMakerFramework.utils.isApplicationTerm = function (term) {
        return term.startsWith("http://registry.gpii.net/applications/");
    };
 
    gpii.matchMakerFramework.utils.isCommonTerm = function (term) {
        return term.startsWith("http://registry.gpii.net/common/");
    };
 
    gpii.matchMakerFramework.utils.applicationIdFromTerm = function (term) {
        return term.substring("http://registry.gpii.net/applications/".length);
    };
 
    gpii.matchMakerFramework.utils.makeApplicationTerm = function (applicationId) {
        return "http://registry.gpii.net/applications/" + applicationId;
    };
 
    gpii.matchMakerFramework.utils.inferCommonTermsFromApplicationsPrefs = function (prefsId, prefsBlock, flattenedSolutionsRegistry) {
        var togo = {};
        if (gpii.matchMakerFramework.utils.isApplicationTerm(prefsId)) {
            var solutionId = gpii.matchMakerFramework.utils.applicationIdFromTerm(prefsId);
            // add any common terms from the application block directly as inferred:
            togo[solutionId] = fluid.remove_if(fluid.copy(prefsBlock), function (val, key) {
                return (!gpii.matchMakerFramework.utils.isCommonTerm(key)); // keep if it's a common term
            });
            // transform the application specific settings and add them to inferred list
            if (solutionId in flattenedSolutionsRegistry) {
                var entry = flattenedSolutionsRegistry[solutionId];
                fluid.each(entry.settingsHandlers, function (handler) {
                    var inverseRules;
                    if (handler.inverseCapabilitiesTransformations !== undefined) {
                        // use explicit inverses if available
                        inverseRules = handler.inverseCapabilitiesTransformations;
                    } else {
                        // else fall back to using the framework's automatic inversion features
                        inverseRules = handler.capabilitiesTransformations !== undefined ?
                            fluid.model.transform.invertConfiguration(handler.capabilitiesTransformations) : {};
                    }
 
                    var transformed = fluid.model.transformWithRules(prefsBlock, inverseRules);
                    var out = {};
                    fluid.set(out, [solutionId], transformed);
                    fluid.extend(true, togo, out);
                });
            }
        }
        return togo;
    };
 
    /**
     * Given a preference set, return a nested structure of context->appliactionBlock->special setting->value
     * and context->special setting->value.
     *
     * This function will walk an NP set and look for any /enabled terms. Anything that is not an /enabled
     * term will not be kept. A structure if returned containing the contexts on the outer level. Each context
     * will have any non application specific /enabled terms, as well as any application block with its contained
     * /enabled terms.
     *
     * @preferences {Object} a preferences set
     * @return {Object} The NP set with only context names and /enabled terms
    */
    gpii.matchMakerFramework.utils.findSpecialPreferences = function (preferences) {
        return fluid.transform(fluid.copy(preferences.contexts), function (context) {
            var togo = {};
            fluid.each(context.preferences, function (prefsBlock, prefsId) {
                if (prefsId.endsWith("/enabled")) {
                    togo[prefsId] = prefsBlock;
                } else if (gpii.matchMakerFramework.utils.isApplicationTerm(prefsId)) {
                    var applicationId = gpii.matchMakerFramework.utils.applicationIdFromTerm(prefsId);
                    fluid.each(prefsBlock, function (appPrefVal, appPrefId) {
                        if (appPrefId.endsWith("/enabled")) {
                            fluid.set(togo, [ applicationId, appPrefId ], appPrefVal);
                        }
                    });
                }
            });
            return togo;
        });
    };
 
    /**
     * Converts application specific settings into common terms, keyed by application ids. Given a
     * set of preferences, for each application block in those preferences, the settings for which
     * inverse transformations exist will be transformed into common terms. All the common terms
     * that have successfully been inferred from an application will be written to a block keyed by
     * that application's ID.
     *
     * Note that we're fetching the solution registry for all platforms. The reason is that if the
     * user has e.g. application specific preferences for a Linux solution, we need that solution
     * registry entry to be able to infer common terms - even if the user is currently on a Windows
     * platform. We could consider loading specific application entries as needed - this is
     * described in GPII-2140.
     *
     * @param preferences {Object} - An NP set (including contexts, etc)
     * @param fullSolutionsRegistry {Object} - The solutionsRegistries, keyed by OS
     *
     * @return {Object} - Object whose keys are solution IDs and entries are common term
     *      preferences which have been transformed from application specific settings for that
     *      solution
     */
    gpii.matchMakerFramework.utils.inferCommonTerms = function (preferences, fullSolutionsRegistry) {
        var flattenedSolutionsRegistry = {};
        fluid.each(fullSolutionsRegistry, function (entry) {
            fluid.extend(flattenedSolutionsRegistry, entry);
        });
        var togo = {};
        fluid.each(preferences.contexts, function (context, contextId) {
            togo[contextId] = {};
            fluid.each(context.preferences, function (prefsBlock, prefsId) {
                var inferred = gpii.matchMakerFramework.utils.inferCommonTermsFromApplicationsPrefs(
                    prefsId, prefsBlock, flattenedSolutionsRegistry);
                fluid.extend(true, togo[contextId], inferred);
            });
        });
        return togo;
    };
 
    gpii.matchMakerFramework.utils.updateSingleInferredConfiguration = function (inferredConfiguration, context, pref, value, solutionId) {
        if (solutionId) {
            var path = [ context, "applications", solutionId, "settings", pref ];
            Eif (fluid.get(inferredConfiguration, path) !== undefined) {
                fluid.set(inferredConfiguration, path, value);
            }
        } else {
            // if solutionId is not provided, loop through all solutions and update the preference value
            // (if the preference is already set in the solution)
            fluid.each(inferredConfiguration[context].applications, function (sol) {
                if (sol.settings[pref] !== undefined) {
                    sol.settings[pref] = value;
                }
            });
        }
    };
 
    /**
     * Takes a set of preferences and runs through the inferredConfiguration, updating all instances
     * matching preferences/settings within the application with the new values from the preferences
     * set.
     *
     * This feature is required by the PCP to allow updating e.g. a top-level common term and
     * ensuring that the relevant applications are affected by it
     */
    gpii.matchMakerFramework.utils.updateInferredConfiguration = function (preferences, inferredConfiguration, solutionsRegistryEntries) {
        var inferred = fluid.copy(inferredConfiguration);
        fluid.each(preferences.contexts, function (contextBlock, contextName) {
            fluid.each(contextBlock.preferences, function (val, pref) {
                if (gpii.matchMakerFramework.utils.isCommonTerm(pref)) {
                    gpii.matchMakerFramework.utils.updateSingleInferredConfiguration(inferred, contextName, pref, val);
                } else Eif (gpii.matchMakerFramework.utils.isApplicationTerm(pref)) {
                    var solutionId = gpii.matchMakerFramework.utils.applicationIdFromTerm(pref);
                    fluid.each(val, function (solPrefVal, solPref) {
                        gpii.matchMakerFramework.utils.updateSingleInferredConfiguration(inferred, contextName, solPref, solPrefVal, solutionId);
                    });
                }
            });
            // get active value from */enabled preferences:
            fluid.each(inferred[contextName].applications, function (solutionBlock, solutionId) {
                var solutionCapabilities = fluid.get(solutionsRegistryEntries, [ solutionId, "capabilities" ]) || {};
                var active = gpii.matchMakerFramework.utils.getActiveValueFromEnabledTerms(contextBlock.preferences, solutionCapabilities,
                        solutionsRegistryEntries[solutionId], solutionId);
                if (active !== undefined) {
                    solutionBlock.active = active;
                }
            });
        });
        return inferred;
    };
 
    /**
     * Given an inferred configuration this function creates a listing of "allowed" preferences and settings,
     * meaning a list of settings and preferences present in the inferred configuration. Any common term
     * encountered in the inferred configuration is added to the list as top level keys with a value of true. Any application
     * specific term will be added under a top level key of: "http://registry.gpii.net/applications/<app-id>". The
     * resulting "allowed" list will be built based on preferences and settings from all the "contexts" in the
     * inferred configuration (i.e. all the contexts of the preferences set)
     */
    gpii.matchMakerFramework.utils.extractAllowedPreferences = function (inferredConfiguration) {
        var allowed = {};
        fluid.each(inferredConfiguration, function (context) {
            fluid.each(context.applications, function (app, appId) {
                allowed["http://registry.gpii.net/applications/" + appId] = {}; // mark the solution in allowed
                fluid.each(app.settings, function (val, term) {
                    if (term.startsWith("http://registry.gpii.net/applications/")) {
                        allowed[term] = val; // copy all application specific values to a flat application block key
                        return;
                    }
                    allowed[term] = true;
                });
            });
        });
        return allowed;
    };
 
    /**
     * Filter a preference set based on the preferences available in the inferred configuration. This is used to
     * ensure that no preferences are passed in the NP set that are not already given via the inferred configuration,
     * which is useful for the something like the untrusted flowmanager model.
     */
    gpii.matchMakerFramework.utils.filterPreferencesFromInferredConfig = function (preferences, inferredConfiguration) {
        // Get the list of allowed terms
        var allowed = gpii.matchMakerFramework.utils.extractAllowedPreferences(inferredConfiguration);
 
        var togo = fluid.censorKeys(preferences, ["contexts"]);
        togo.contexts = fluid.transform(fluid.copy(preferences).contexts, function (context) {
            context.preferences = fluid.remove_if(context.preferences, function (val, term) {
                // if it's an application block
                if (term.startsWith("http://registry.gpii.net/applications/")) {
                    if (allowed[term] === undefined) { // if the application is not in the allowed terms, remove it
                        return true;
                    }
 
                    fluid.remove_if(val, function (appVal, appTerm) {
                        // remove if not found as top level common term and it's not in the application specific allowed
                        // terms block
                        return (allowed[appTerm] !== true && (fluid.get(allowed, [ term, appTerm ]) === undefined));
                    });
                } else {
                    return allowed[term] !== true;
                }
            });
            return context;
        });
        return togo;
    };
 
    gpii.matchMakerFramework.utils.livenessOrdering = [
        "OSRestart",
        "manualRestart",
        "liveRestart",
        "live"
    ];
 
    /**
     * Given one or more solutions registry entries and optionally a term, this function will walk each
     * solution (and its settingshandlers) and find the lowest liveness for any of the solutions. If a term is
     * given, the liveliness reported is the lowest of those settingshandlers which supports that term
     * (decided via its capabilities and/or capabilitiesTransformations). The lowest or least
     * liveness is dictated by gpii.matchMakerFramework.utils.livenessOrdering, where a lower
     * index means less/lower liveness.
     *
     * @param solutions {Array or Object} A list of the solutions that should be search for support of the term
     * @param term {String} - optional. the term to find the liveness for
     * @return {String} returns the lowest/least liveness found by any solution provided that supports the term
     */
    gpii.matchMakerFramework.utils.getLeastLiveness = function (solutions, term) {
        var leastLiveness;
        fluid.each(solutions, function (solution) {
            fluid.each(solution.settingsHandlers, function (handler) {
                if (term !== undefined) {
                    // if term is defined, only check liveness of block if the term is within the capabilities
                    // of the block. If not, simply skip to next block
                    var capabilities = gpii.matchMakerFramework.utils.extractCapabilities(handler);
                    if (capabilities && capabilities.indexOf(fluid.pathUtil.composeSegments(term)) === -1) {
                        return;
                    }
                }
 
                // if the liveness of term in current solution is lower than any previously checked solutions
                var livenessOrder = gpii.matchMakerFramework.utils.livenessOrdering.indexOf(handler.liveness);
                if (leastLiveness === undefined || livenessOrder < leastLiveness) {
                    leastLiveness = livenessOrder;
                }
            });
        });
        return gpii.matchMakerFramework.utils.livenessOrdering[leastLiveness];
    };
})();