invoices and order lists are not stored in webroot
766496
private function getFile($filenameWithPath)
    {
        $explodedString = explode('\\', $filenameWithPath);
        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="' . $explodedString[count($explodedString) - 1] . '"');
        readfile(ROOT . $filenameWithPath);
        exit; // $this->autoRender = false; is not enough!
    }
1114733
function appendDebugNodes( &$root, &$resourceData )
    {
        $path = $resourceData['template-filename'];
        // Do not ouput debug on pagelayout templates to avoid trigering
        // browser quirks mode
        if ( isset( $root[1][0][2] ) && is_string( $root[1][0][2] ) && stripos( $root[1][0][2], '<!DOCTYPE' ) === 0 )
            return;
        $uri = $resourceData['uri'];
        $preText = "\n<!-- START: including template: $path ($uri) -->\n";
        if ( eZTemplate::isXHTMLCodeIncluded() )
            $preText .= "<p class=\"small\">$path</p><br/>\n";
        $postText = "\n<!-- STOP: including template: $path ($uri) -->\n";

        $preNode = eZTemplateNodeTool::createTextNode( $preText );
        $postNode = eZTemplateNodeTool::createTextNode( $postText );

        if ( is_array( $root[1] ) )
        {
            $root[1] = array_merge( array( $preNode ), $root[1] );
        }
        else
        {
            $root[1] = array( $preNode );
        }
        $root[1][] = $postNode;
    }
443860
def _file_lists(load, form):
    '''
    
    '''
    if 'env' in load:
        # "env" is not supported; Use "saltenv".
        load.pop('env')

    saltenv = load['saltenv']
    if saltenv not in __opts__['file_roots']:
        if '__env__' in __opts__['file_roots']:
            log.debug("salt environment '%s' maps to __env__ file_roots directory", saltenv)
            saltenv = '__env__'
        else:
            return []

    list_cachedir = os.path.join(__opts__['cachedir'], 'file_lists', 'roots')
    if not os.path.isdir(list_cachedir):
        try:
            os.makedirs(list_cachedir)
        except os.error:
            log.critical('Unable to make cachedir %s', list_cachedir)
            return []
    list_cache = os.path.join(list_cachedir, '{0}.p'.format(salt.utils.files.safe_filename_leaf(saltenv)))
    w_lock = os.path.join(list_cachedir, '.{0}.w'.format(salt.utils.files.safe_filename_leaf(saltenv)))
    cache_match, refresh_cache, save_cache = \
        salt.fileserver.check_file_list_cache(
            __opts__, form, list_cache, w_lock
        )
    if cache_match is not None:
        return cache_match
    if refresh_cache:
        ret = {
            'files': set(),
            'dirs': set(),
            'empty_dirs': set(),
            'links': {}
        }

        def _add_to(tgt, fs_root, parent_dir, items):
            '''
            Add the files to the target set
            '''
            def _translate_sep(path):
                '''
                Translate path separators for Windows masterless minions
                '''
                return path.replace('\\', '/') if os.path.sep == '\\' else path

            for item in items:
                abs_path = os.path.join(parent_dir, item)
                log.trace('roots: Processing %s', abs_path)
                is_link = salt.utils.path.islink(abs_path)
                log.trace(
                    'roots: %s is %sa link',
                    abs_path, 'not ' if not is_link else ''
                )
                if is_link and __opts__['fileserver_ignoresymlinks']:
                    continue
                rel_path = _translate_sep(os.path.relpath(abs_path, fs_root))
                log.trace('roots: %s relative path is %s', abs_path, rel_path)
                if salt.fileserver.is_file_ignored(__opts__, rel_path):
                    continue
                tgt.add(rel_path)
                try:
                    if not os.listdir(abs_path):
                        ret['empty_dirs'].add(rel_path)
                except Exception:
                    # Generic exception because running os.listdir() on a
                    # non-directory path raises an OSError on *NIX and a
                    # WindowsError on Windows.
                    pass
                if is_link:
                    link_dest = salt.utils.path.readlink(abs_path)
                    log.trace(
                        'roots: %s symlink destination is %s',
                        abs_path, link_dest
                    )
                    if salt.utils.platform.is_windows() \
                            and link_dest.startswith('\\\\'):
                        # Symlink points to a network path. Since you can't
                        # join UNC and non-UNC paths, just assume the original
                        # path.
                        log.trace(
                            'roots: %s is a UNC path, using %s instead',
                            link_dest, abs_path
                        )
                        link_dest = abs_path
                    if link_dest.startswith('..'):
                        joined = os.path.join(abs_path, link_dest)
                    else:
                        joined = os.path.join(
                            os.path.dirname(abs_path), link_dest
                        )
                    rel_dest = _translate_sep(
                        os.path.relpath(
                            os.path.realpath(os.path.normpath(joined)),
                            fs_root
                        )
                    )
                    log.trace(
                        'roots: %s relative path is %s',
                        abs_path, rel_dest
                    )
                    if not rel_dest.startswith('..'):
                        # Only count the link if it does not point
                        # outside of the root dir of the fileserver
                        # (i.e. the "path" variable)
                        ret['links'][rel_path] = link_dest

        for path in __opts__['file_roots'][saltenv]:
            for root, dirs, files in salt.utils.path.os_walk(
                    path,
                    followlinks=__opts__['fileserver_followsymlinks']):
                _add_to(ret['dirs'], path, root, dirs)
                _add_to(ret['files'], path, root, files)

        ret['files'] = sorted(ret['files'])
        ret['dirs'] = sorted(ret['dirs'])
        ret['empty_dirs'] = sorted(ret['empty_dirs'])

        if save_cache:
            try:
                salt.fileserver.write_file_list_cache(
                    __opts__, ret, list_cache, w_lock
                )
            except NameError:
                # Catch msgpack error in salt-ssh
                pass
        return ret.get(form, [])
    # Shouldn't get here, but if we do, this prevents a TypeError
    return []
954823
function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) {
                // Make all paths absolute/normalized if they are not already
                rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); });
                // Determine the path to the directory containing the script relative to the root directory it is contained within
                var relativeDirectory;
                for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) {
                    var rootDirectory = rootDirs_1[_i];
                    if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) {
                        relativeDirectory = scriptPath.substr(rootDirectory.length);
                        break;
                    }
                }
                // Now find a path for each potential directory that is to be merged with the one containing the script
                return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }));
            }
1271244
public function index()
    {
        if (!userHasPermission('admin:invoice:payment:view')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        //  Set method info
        $this->data['page']->title = 'Manage Payments';

        // --------------------------------------------------------------------------

        $oInput         = Factory::service('Input');
        $oDriverService = Factory::service('PaymentDriver', 'nails/module-invoice');
        $oPaymentModel  = Factory::model('Payment', 'nails/module-invoice');
        $oInvoiceModel  = Factory::model('Invoice', 'nails/module-invoice');

        // --------------------------------------------------------------------------

        $sTableAlias = $oPaymentModel->getTableAlias();

        //  Get pagination and search/sort variables
        $iPage      = $oInput->get('page') ? $oInput->get('page') : 0;
        $iPerPage   = $oInput->get('perPage') ? $oInput->get('perPage') : 50;
        $sSortOn    = $oInput->get('sortOn') ? $oInput->get('sortOn') : $sTableAlias . '.created';
        $sSortOrder = $oInput->get('sortOrder') ? $oInput->get('sortOrder') : 'desc';
        $sKeywords  = $oInput->get('keywords') ? $oInput->get('keywords') : '';

        // --------------------------------------------------------------------------

        //  Define the sortable columns
        $sortColumns = [
            $sTableAlias . '.created'    => 'Received Date',
            $sTableAlias . '.driver'     => 'Payment Gateway',
            $sTableAlias . '.invoice_id' => 'Invoice ID',
            $sTableAlias . '.txn_id'     => 'Transaction ID',
            $sTableAlias . '.amount'     => 'Amount',
            $sTableAlias . '.currency'   => 'Currency',
        ];

        // --------------------------------------------------------------------------

        //  Define the filters
        $aCbFilters = [];
        $aOptions   = [];
        $aDrivers   = $oDriverService->getAll();

        foreach ($aDrivers as $sSlug => $oDriver) {
            $aOptions[] = [
                $oDriver->name,
                $sSlug,
                true,
            ];
        }

        $aCbFilters[] = Helper::searchFilterObject(
            $sTableAlias . '.driver',
            'Gateway',
            $aOptions
        );

        $aCbFilters[] = Helper::searchFilterObject(
            $sTableAlias . '.status',
            'Status',
            $oPaymentModel->getStatusesHuman()
        );

        // --------------------------------------------------------------------------

        //  Define the $aData variable for the queries
        $aData = [
            'sort'      => [
                [$sSortOn, $sSortOrder],
            ],
            'keywords'  => $sKeywords,
            'cbFilters' => $aCbFilters,
        ];

        //  Get the items for the page
        $totalRows                   = $oPaymentModel->countAll($aData);
        $this->data['payments']      = $oPaymentModel->getAll($iPage, $iPerPage, $aData);
        $this->data['invoiceStates'] = $oInvoiceModel->getStates();

        //  Set Search and Pagination objects for the view
        $this->data['search']     = Helper::searchObject(true, $sortColumns, $sSortOn, $sSortOrder, $iPerPage, $sKeywords, $aCbFilters);
        $this->data['pagination'] = Helper::paginationObject($iPage, $iPerPage, $totalRows);

        // --------------------------------------------------------------------------

        //  Add a header button
        if (userHasPermission('admin:invoice:invoice:create')) {
            Helper::addHeaderButton(
                'admin/invoice/invoice/create',
                'Create Invoice'
            );
        }

        // --------------------------------------------------------------------------

        Helper::loadView('index');
    }
775599
private AFTPClient actionListDir() throws PageException, IOException {
	required("name", name);
	required("directory", directory);

	AFTPClient client = getClient();
	FTPFile[] files = client.listFiles(directory);
	if (files == null) files = new FTPFile[0];

	pageContext.setVariable(name, toQuery(files, "ftp", directory, client.getRemoteAddress().getHostName()));
	writeCfftp(client);
	return client;
    }
1259596
function iniDOMTree( $filename, $siteAccess, &$blockArray, $remoteIDArray )
    {
        if ( !$filename || !$siteAccess || !$blockArray )
        {
            return false;
        }

        $iniNode = eZDOMDocument::createElementNode( 'ini-addon', array( 'site-access' => $siteAccess,
                                                                          'filename' => $filename ) );

        $blocksNode = eZDOMDocument::createElementNode( 'blocks' );
        $iniNode->appendChild( $blocksNode );
        foreach( array_keys( $blockArray ) as $blockName )
        {
            $block =& $blockArray[$blockName];
            unset( $blockNode );
            $blockNode = eZDOMDocument::createElementNode( 'block', array( 'name' => $blockName ) );
            $blocksNode->appendChild( $blockNode );

            foreach( array_keys( $block ) as $blockVariable )
            {
                $variableValue =& $block[$blockVariable];
                unset( $variableNode );
                $variableNode = eZDomDocument::createElementNode( 'block-variable', array( 'name' => $blockVariable ) );
                $blockNode->appendChild( $variableNode );

                if ( is_array( $variableValue ) )
                {
                    foreach( array_keys( $variableValue) as $valueName )
                    {
                        $value = $variableValue[$valueName];
                        unset( $valueNode );
                        $valueNode = eZDomDocument::createElementNode( 'value', array( 'name' => $valueName ) );
                        $variableNode->appendChild( $valueNode );
                        $remoteID = false;
                        if ( is_int( $value ) )
                        {
                            if ( strpos( $valueName, 'class' ) !== false )
                            {
                                $value = $remoteIDArray['class'][(string)$value];
                                $remoteID = 'class';
                            }
                            else if( strpos( $valueName, 'node' ) !== false )
                            {
                                $value = $remoteIDArray['node'][(string)$value];
                                $remoteID = 'node';
                            }
                            else if ( strpos( $valueName, 'object' ) !== false )
                            {
                                $value = $remoteIDArray['class'][(string)$value];
                                $remoteID = 'object';
                            }
                            else
                            {
                                eZDebug::writeNotice( 'Could not interpret ' . $valueName . ': ' . $value, __METHOD__ );
                            }
                        }
                        if ( $remoteID )
                        {
                            $valueNode->appendAttribute( eZDomDocument::createAttributeNode( 'remote-id', $remoteID ) );
                        }
                        $valueNode->appendChild( eZDomDocument::createTextNode( $value ) );
                    }
                }
                else
                {
                    $remoteID = false;
                    if ( is_int( $variableValue ) )
                    {
                        if ( strpos( $blockVariable, 'class' ) !== false )
                        {
                            $variableValue = $remoteIDArray['class'][(string)$value];
                            $remoteID = 'class';
                        }
                        else if( strpos( $blockVariable, 'node' ) !== false )
                        {
                            $variableValue = $remoteIDArray['node'][(string)$value];
                            $remoteID = 'node';
                        }
                        else if ( strpos( $blockVariable, 'object' ) !== false )
                        {
                            $variableValue = $remoteIDArray['class'][(string)$value];
                            $remoteID = 'object';
                        }
                        else
                        {
                            eZDebug::writeNotice( 'Could not interpret ' . $blockVariable . ': ' . $variableValue, __METHOD__ );
                        }
                    }
                    unset( $valueNode );
                    $valueNode = eZDomDocument::createElementNode( 'value' );
                    $variableNode->appendChild( $valueNode );
                    if ( $remoteID )
                    {
                        $valueNode->appendAttribute( eZDomDocument::createAttributeNode( 'remote-id', $remoteID ) );
                    }
                    $valueNode->appendChild( eZDomDocument::createTextNode( $variableValue ) );
                }
            }
        }
        return $iniNode;
    }
98574
private static void addOrderPossiblyNested(CriteriaQuery query,
                                               From queryRoot,
                                               CriteriaBuilder criteriaBuilder,
                                               PersistentEntity entity,
                                               String sort,
                                               String order,
                                               boolean ignoreCase) {
        int firstDotPos = sort.indexOf(".");
        if (firstDotPos == -1) {
            addOrder(entity, query, queryRoot, criteriaBuilder, sort, order, ignoreCase);
        } else { // nested property
            String sortHead = sort.substring(0, firstDotPos);
            String sortTail = sort.substring(firstDotPos + 1);
            PersistentProperty property = entity.getPropertyByName(sortHead);
            if (property instanceof Embedded) {
                // embedded objects cannot reference entities (at time of writing), so no more recursion needed
                addOrder(entity, query, queryRoot, criteriaBuilder, sort, order, ignoreCase);
            } else if (property instanceof Association) {
                Association a = (Association) property;
                final Join join = queryRoot.join(sortHead);
                PersistentEntity associatedEntity = a.getAssociatedEntity();
                Class<?> propertyTargetClass = associatedEntity.getJavaClass();
                addOrderPossiblyNested(query, join, criteriaBuilder, associatedEntity, sortTail, order, ignoreCase); // Recurse on nested sort
            }
        }
    }
287824
function resolveInRoot(root) {
    var input, result;
    var args = Array.prototype.slice.call(arguments, 1);

    input = args
        .reduce(function(current, p) {
            // Handle path relative to book root ("/README.md")
            if (p[0] == '/' || p[0] == '\\') return p.slice(1);

            return current? path.join(current, p) : path.normalize(p);
        }, '');

    result = path.resolve(root, input);

    if (!isInRoot(root, result)) {
        throw new error.FileOutOfScopeError({
            filename: result,
            root: root
        });
    }

    return result;
}
689632
function(items, userData) {

		var selfHostingConfig = this._siteClient.getSelfHostingConfig();

		var self = this;
		var dialog = new ConvertToSelfHostingDialog({
			serviceRegistry: this.serviceRegistry,
			fileClient: this.fileClient,
			siteClient: this._siteClient,
			selfHostingConfig: selfHostingConfig,
			func: function(folderInfos) {
				var folderLocations = folderInfos.map(function(folderInfo) {
					return folderInfo.folder.Location;
				});
				self._siteClient.convertToSelfHosting(self.getSiteConfiguration(), folderLocations).then(
					function(updatedSite) {
						self.mappings.deleteAllMappings();
						self.mappings.addMappings(updatedSite.Mappings);
						self.save();
					});
			}
		});
		dialog.show();
	}
850876
def cli(env, identifier, details):
    """"""

    manager = AccountManager(env.client)
    top_items = manager.get_billing_items(identifier)

    title = "Invoice %s" % identifier
    table = formatting.Table(["Item Id", "Category", "Description", "Single",
                              "Monthly", "Create Date", "Location"], title=title)
    table.align['category'] = 'l'
    table.align['description'] = 'l'
    for item in top_items:
        fqdn = "%s.%s" % (item.get('hostName', ''), item.get('domainName', ''))
        # category id=2046, ram_usage doesn't have a name...
        category = utils.lookup(item, 'category', 'name') or item.get('categoryCode')
        description = nice_string(item.get('description'))
        if fqdn != '.':
            description = "%s (%s)" % (item.get('description'), fqdn)
        table.add_row([
            item.get('id'),
            category,
            nice_string(description),
            "$%.2f" % float(item.get('oneTimeAfterTaxAmount')),
            "$%.2f" % float(item.get('recurringAfterTaxAmount')),
            utils.clean_time(item.get('createDate'), out_format="%Y-%m-%d"),
            utils.lookup(item, 'location', 'name')
        ])
        if details:
            for child in item.get('children', []):
                table.add_row([
                    '>>>',
                    utils.lookup(child, 'category', 'name'),
                    nice_string(child.get('description')),
                    "$%.2f" % float(child.get('oneTimeAfterTaxAmount')),
                    "$%.2f" % float(child.get('recurringAfterTaxAmount')),
                    '---',
                    '---'
                ])

    env.fout(table)
614048
public function listDocumentRootReplaced()
    {
        if ($this->pathNameRecord == 'none') {
            throw new \LogicException(
                'Can\'t listDocumentRootReplaced() ' . (!$this->dirs ? 'filenames' : 'dirnames')
                . ' when items\' paths aren\'t recorded'
                . (!$this->requireUnique || !$this->itemValue ? '.' :
                    (', incompatible when both requireUnique is \'on\' and itemValue function defined.')
                )
            );
        }
        $utils = Utils::getInstance();
        $list = $this->getArrayCopy();
        if ($this->pathNameRecord == 'key') {
            $list = array_keys($list);
        }
        foreach ($list as &$pathname) {
            $pathname = $utils->pathReplaceDocumentRoot($pathname, Utils::DOCUMENT_ROOT_REPLACER, true);
        }
        unset($pathname);
        return $list;
    }
492191
public function index()
    {
        if (!userHasPermission('admin:invoice:settings:*')) {
            unauthorised();
        }

        $oInput                = Factory::service('Input');
        $oDb                   = Factory::service('Database');
        $oAppSettingService    = Factory::service('AppSetting');
        $oPaymentDriverService = Factory::service('PaymentDriver', 'nails/module-invoice');
        $oInvoiceSkinService   = Factory::service('InvoiceSkin', 'nails/module-invoice');

        //  Process POST
        if ($oInput->post()) {

            //  Settings keys
            $sKeyPaymentDriver = $oPaymentDriverService->getSettingKey();
            $sKeyInvoiceSkin   = $oInvoiceSkinService->getSettingKey();

            //  Validation
            $oFormValidation = Factory::service('FormValidation');

            $oFormValidation->set_rules('business_name', '', '');
            $oFormValidation->set_rules('business_address', '', '');
            $oFormValidation->set_rules('business_phone', '', '');
            $oFormValidation->set_rules('business_email', '', 'valid_email');
            $oFormValidation->set_rules('business_vat_number', '', '');
            $oFormValidation->set_rules('business_', '', '');
            $oFormValidation->set_rules('default_additional_text', '', '');
            $oFormValidation->set_rules('default_payment_terms', '', '');
            $oFormValidation->set_rules('saved_cards_enabled', '', '');
            $oFormValidation->set_rules('saved_addresses_enabled', '', '');
            $oFormValidation->set_rules($sKeyPaymentDriver, '', '');
            $oFormValidation->set_rules($sKeyInvoiceSkin, '', '');

            $oFormValidation->set_message('valid_email', lang('fv_valid_email'));

            if ($oFormValidation->run()) {

                try {

                    $aSettings = [
                        'business_name'           => trim(strip_tags($oInput->post('business_name'))),
                        'business_address'        => trim(strip_tags($oInput->post('business_address'))),
                        'business_phone'          => trim(strip_tags($oInput->post('business_phone'))),
                        'business_email'          => trim(strip_tags($oInput->post('business_email'))),
                        'business_vat_number'     => trim(strip_tags($oInput->post('business_vat_number'))),
                        'default_additional_text' => trim(strip_tags($oInput->post('default_additional_text'))),
                        'default_payment_terms'   => (int) $oInput->post('default_payment_terms'),
                        'saved_cards_enabled'     => (bool) $oInput->post('saved_cards_enabled'),
                        'saved_addresses_enabled' => (bool) $oInput->post('saved_addresses_enabled'),
                    ];

                    $oDb->trans_begin();

                    //  Normal settings
                    if (!$oAppSettingService->set($aSettings, 'nails/module-invoice')) {
                        throw new NailsException($oAppSettingService->lastError(), 1);
                    }

                    //  Drivers & Skins
                    $oPaymentDriverService->saveEnabled($oInput->post($sKeyPaymentDriver));
                    $oInvoiceSkinService->saveEnabled($oInput->post($sKeyInvoiceSkin));

                    $oDb->trans_commit();
                    $this->data['success'] = 'Invoice &amp; Payment settings were saved.';

                } catch (\Exception $e) {
                    $oDb->trans_rollback();
                    $this->data['error'] = 'There was a problem saving settings. ' . $e->getMessage();
                }

            } else {
                $this->data['error'] = lang('fv_there_were_errors');
            }
        }

        // --------------------------------------------------------------------------

        //  Get data
        $this->data['settings'] = appSetting(null, 'nails/module-invoice', true);

        Helper::loadView('index');
    }
1007751
def get_list(
        self,
        search='',
        start=0,
        limit=0,
        order_by='',
        order_by_dir='ASC',
        published_only=False,
        minimal=False
    ):
        

        parameters = {}
        args = ['search', 'start', 'limit', 'minimal']
        for arg in args:
            if arg in locals() and locals()[arg]:
                parameters[arg] = locals()[arg]
        if order_by:
            parameters['orderBy'] = order_by
        if order_by_dir:
            parameters['orderByDir'] = order_by_dir
        if published_only:
            parameters['publishedOnly'] = 'true'
        response = self._client.session.get(
            self.endpoint_url, params=parameters
        )
        return self.process_response(response)
490747
public function index()
    {
        if (!userHasPermission('admin:invoice:invoice:manage')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        //  Are we dealing with a filtered view?
        $oInput         = Factory::service('Input');
        $oCustomerModel = Factory::model('Customer', 'nails/module-invoice');
        $iCustomerId    = $oInput->get('customer_id');

        if ($iCustomerId) {
            $oCustomer = $oCustomerModel->getbyId($iCustomerId);
        }

        // --------------------------------------------------------------------------

        //  Set method info
        $this->data['page']->title = empty($oCustomer) ? 'Manage Invoices' : possessive($oCustomer->label) . ' invoices';

        // --------------------------------------------------------------------------

        $sTableAlias = $this->oInvoiceModel->getTableAlias();

        //  Get pagination and search/sort variables
        $iPage      = $oInput->get('page') ? $oInput->get('page') : 0;
        $iPerPage   = $oInput->get('perPage') ? $oInput->get('perPage') : 50;
        $sSortOn    = $oInput->get('sortOn') ? $oInput->get('sortOn') : $sTableAlias . '.created';
        $sSortOrder = $oInput->get('sortOrder') ? $oInput->get('sortOrder') : 'desc';
        $sKeywords  = $oInput->get('keywords') ? $oInput->get('keywords') : '';

        // --------------------------------------------------------------------------

        //  Define the sortable columns
        $aSortColumns = [
            $sTableAlias . '.created'  => 'Created Date',
            $sTableAlias . '.modified' => 'Modified Date',
            $sTableAlias . '.state'    => 'Invoice State',
        ];

        // --------------------------------------------------------------------------

        //  Define the filters
        $aCbFilters = [];

        //  States
        $aStateOptions = [];
        $aStates       = $this->oInvoiceModel->getStates();

        foreach ($aStates as $sState => $sLabel) {
            $aStateOptions[] = [
                $sLabel,
                $sState,
                true,
            ];
        }

        $aCbFilters[] = Helper::searchFilterObject(
            $sTableAlias . '.state',
            'State',
            $aStateOptions
        );

        //  Currencies
        $oCurrency        = Factory::service('Currency', 'nails/module-currency');
        $aCurrencyOptions = [];
        $aCurrencies      = $oCurrency->getAllEnabled();

        foreach ($aCurrencies as $oCurrency) {
            $aCurrencyOptions[] = [
                $oCurrency->code,
                $oCurrency->code,
                true,
            ];
        }

        $aCbFilters[] = Helper::searchFilterObject(
            $sTableAlias . '.currency',
            'Currency',
            $aCurrencyOptions
        );

        // --------------------------------------------------------------------------

        //  Define the $aData variable for the queries
        $aData = [
            'where'     => array_filter([
                !empty($oCustomer) ? ['customer_id', $oCustomer->id] : null,
            ]),
            'sort'      => [
                [$sSortOn, $sSortOrder],
            ],
            'expand'    => ['customer', 'payments'],
            'keywords'  => $sKeywords,
            'cbFilters' => $aCbFilters,
        ];

        //  Get the items for the page
        $iTotalRows             = $this->oInvoiceModel->countAll($aData);
        $this->data['invoices'] = $this->oInvoiceModel->getAll($iPage, $iPerPage, $aData);

        //  Set Search and Pagination objects for the view
        $this->data['search']     = Helper::searchObject(true, $aSortColumns, $sSortOn, $sSortOrder, $iPerPage, $sKeywords, $aCbFilters);
        $this->data['pagination'] = Helper::paginationObject($iPage, $iPerPage, $iTotalRows);

        //  Add a header button
        if (userHasPermission('admin:invoice:invoice:create')) {
            Helper::addHeaderButton(
                'admin/invoice/invoice/create',
                'Create Invoice'
            );
        }

        // --------------------------------------------------------------------------

        Helper::loadView('index');
    }
323444
function getDirectories (basePath, includeFiles, userSuppliedFilterFn) {

  var items;
  try {
    items = fs.readdirSync(basePath);
  }
  catch (err) {

    // probably a file not a dir, but let's check error message to be sure
    if (includeFiles && String(err.stack).match(/ENOTDIR/)) {
      return [ basePath ];
    }

    // something is wrong, perhaps directory read permissions problem
    // maybe throw err instead
    console.error(err.stack);
    return [];
  }

  return items.filter(function (file) {

    var absPath = path.join(basePath, file);

    var stats = fs.lstatSync(absPath);
    if (stats.isSymbolicLink()) {
      return false;
    }

    var isDir = includeFiles ? true : stats.isDirectory();
    var isNotDotFile = path.basename(file).indexOf('.') !== 0;
    return isDir && isNotDotFile && (userSuppliedFilterFn || allOK)(absPath);

  })
  .map(function (item) {
    // return path.join(basePath, item);
    return item;
  })
  .sort();
}
777278
def create_invoices(invoices)
      b = Builder::XmlMarkup.new
      request_xml = b.Invoices {
        invoices.each do | invoice |
          invoice.to_xml(b)
        end
      }

      response_xml = http_put(@client, "#{@xero_url}/Invoices?SummarizeErrors=false", request_xml, {})

      response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/invoices'})
      response.invoices.each_with_index do | response_invoice, index |
        invoices[index].invoice_id = response_invoice.invoice_id if response_invoice && response_invoice.invoice_id
      end
      response
    end