/**
  * Returns all fields in an array.
  * 
  * The result has the following form:
  * array (
  *   array (
  *     'field name 0' => 'value of field 0',
  *     'field name 1' => 'value of field 1'
  *   )
  * );
  * 
  * The inner array is repeated for each row.
  * The fields need to be in the order returned by @link getFieldNames().
  * 
  * @return array A list of all fields.
  */
 public function getAll()
 {
     global $badgerDb;
     $us = new UserSettings($badgerDb);
     $tpl = new TemplateEngine($us, BADGER_ROOT);
     $widgets = new WidgetEngine($tpl);
     $currentLanguage = $us->getProperty('badgerLanguage');
     $result = array();
     switch ($this->type) {
         case 'transaction':
             $this->fetchTransactions();
             $sum = new Amount();
             foreach ($this->finishedTransactions as $currentTransaction) {
                 $sum->add($currentTransaction->getAmount());
                 $classAmount = $currentTransaction->getAmount()->compare(0) >= 0 ? 'dgPositiveAmount' : 'dgNegativeAmount';
                 $classSum = $sum->compare(0) >= 0 ? 'dgPositiveAmount' : 'dgNegativeAmount';
                 $result[] = array('transactionId' => $currentTransaction->getId(), 'type' => $widgets->addImage($currentTransaction->getType() == 'FinishedTransaction' ? 'Account/finished_transaction.png' : 'Account/planned_transaction.png', 'title="' . getBadgerTranslation2('Account', $currentTransaction->getType()) . '"'), 'title' => $currentTransaction->getTitle(), 'description' => $currentTransaction->getDescription(), 'valutaDate' => ($tmp = $currentTransaction->getValutaDate()) ? $tmp->getFormatted() : '', 'amount' => "<span class='{$classAmount}'>" . $currentTransaction->getAmount()->getFormatted() . '</span>', 'outsideCapital' => is_null($tmp = $currentTransaction->getOutsideCapital()) ? '' : $tmp, 'transactionPartner' => $currentTransaction->getTransactionPartner(), 'categoryId' => ($tmp = $currentTransaction->getCategory()) ? $tmp->getId() : '', 'categoryTitle' => ($tmp = $currentTransaction->getCategory()) ? $tmp->getTitle() : '', 'sum' => "<span class='{$classSum}'>" . $sum->getFormatted() . '</span>');
             }
             break;
         case 'finished':
             while ($this->fetchNextFinishedTransaction()) {
             }
             foreach ($this->finishedTransactions as $currentTransaction) {
                 $classAmount = $currentTransaction->getAmount()->compare(0) >= 0 ? 'dgPositiveAmount' : 'dgNegativeAmount';
                 $result[] = array('finishedTransactionId' => $currentTransaction->getId(), 'title' => $currentTransaction->getTitle(), 'description' => $currentTransaction->getDescription(), 'valutaDate' => ($tmp = $currentTransaction->getValutaDate()) ? $tmp->getFormatted() : '', 'amount' => "<span class='{$classAmount}'>" . $currentTransaction->getAmount()->getFormatted() . '</span>', 'outsideCapital' => is_null($tmp = $currentTransaction->getOutsideCapital()) ? '' : $tmp, 'transactionPartner' => $currentTransaction->getTransactionPartner(), 'categoryId' => ($tmp = $currentTransaction->getCategory()) ? $tmp->getId() : '', 'categoryTitle' => ($tmp = $currentTransaction->getCategory()) ? $tmp->getTitle() : '', 'exceptional' => is_null($tmp = $currentTransaction->getExceptional()) ? '' : $tmp, 'periodical' => is_null($tmp = $currentTransaction->getPeriodical()) ? '' : $tmp);
             }
             break;
         case 'planned':
             while ($this->fetchNextPlannedTransaction()) {
             }
             foreach ($this->plannedTransactions as $currentTransaction) {
                 $classAmount = $currentTransaction->getAmount()->compare(0) >= 0 ? 'dgPositiveAmount' : 'dgNegativeAmount';
                 $result[] = array('plannedTransactionId' => 'p' . $currentTransaction->getId() . '_X', 'title' => $currentTransaction->getTitle(), 'description' => $currentTransaction->getDescription(), 'amount' => "<span class='{$classAmount}'>" . $currentTransaction->getAmount()->getFormatted() . '</span>', 'outsideCapital' => is_null($tmp = $currentTransaction->getOutsideCapital()) ? '' : $tmp, 'transactionPartner' => $currentTransaction->getTransactionPartner(), 'beginDate' => $currentTransaction->getBeginDate()->getFormatted(), 'endDate' => ($tmp = $currentTransaction->getEndDate()) ? $tmp->getFormatted() : '', 'repeatUnit' => getBadgerTranslation2('Account', $currentTransaction->getRepeatUnit()), 'repeatFrequency' => $currentTransaction->getRepeatFrequency(), 'categoryId' => ($tmp = $currentTransaction->getCategory()) ? $tmp->getId() : '', 'categoryTitle' => ($tmp = $currentTransaction->getCategory()) ? $tmp->getTitle() : '');
             }
             break;
     }
     return $result;
 }
function importMatching($importedTransaction, $accountId)
{
    global $us;
    global $badgerDb;
    static $dateDelta = null;
    static $amountDelta = null;
    static $textSimilarity = null;
    static $categories = null;
    if (is_null($dateDelta)) {
        try {
            $dateDelta = $us->getProperty('matchingDateDelta');
        } catch (BadgerException $ex) {
            $dateDelta = 5;
        }
        try {
            $amountDelta = $us->getProperty('matchingAmountDelta');
        } catch (BadgerException $ex) {
            $amountDelta = 0.1;
        }
        try {
            $textSimilarity = $us->getProperty('matchingTextSimilarity');
        } catch (BadgerException $ex) {
            $textSimilarity = 0.25;
        }
        $categoryManager = new CategoryManager($badgerDb);
        while ($currentCategory = $categoryManager->getNextCategory()) {
            $categories[$currentCategory->getId()] = preg_split('/[\\n]+/', $currentCategory->getKeywords(), -1, PREG_SPLIT_NO_EMPTY);
        }
    }
    if (!$importedTransaction['valutaDate']) {
        return $importedTransaction;
    }
    $minDate = new Date($importedTransaction['valutaDate']);
    $minDate->subtractSeconds($dateDelta * 24 * 60 * 60);
    $maxDate = new Date($importedTransaction['valutaDate']);
    $maxDate->addSeconds($dateDelta * 24 * 60 * 60);
    if (!$importedTransaction['amount']) {
        return $importedTransaction;
    }
    $minAmount = new Amount($importedTransaction['amount']);
    $minAmount->mul(1 - $amountDelta);
    $maxAmount = new Amount($importedTransaction['amount']);
    $maxAmount->mul(1 + $amountDelta);
    $accountManager = new AccountManager($badgerDb);
    $account = $accountManager->getAccountById($accountId);
    if ($minAmount->compare(0) < 0) {
        $tmpAmount = $maxAmount;
        $maxAmount = $minAmount;
        $minAmount = $tmpAmount;
        unset($tmpAmount);
    }
    $account->setFilter(array(array('key' => 'valutaDate', 'op' => 'ge', 'val' => $minDate), array('key' => 'valutaDate', 'op' => 'le', 'val' => $maxDate), array('key' => 'amount', 'op' => 'ge', 'val' => $minAmount), array('key' => 'amount', 'op' => 'le', 'val' => $maxAmount)));
    $similarTransactions = array();
    while ($currentTransaction = $account->getNextTransaction()) {
        $titleSimilarity = getSimilarity($importedTransaction['title'], $currentTransaction->getTitle(), $textSimilarity);
        $descriptionSimilarity = getSimilarity($importedTransaction['description'], $currentTransaction->getDescription(), $textSimilarity);
        $transactionPartnerSimilarity = getSimilarity($importedTransaction['transactionPartner'], $currentTransaction->getTransactionPartner(), $textSimilarity);
        $currDate = $currentTransaction->getValutaDate();
        $impDate = $importedTransaction['valutaDate'];
        $dateSimilarity = 1 - abs(Date_Calc::dateDiff($currDate->getDay(), $currDate->getMonth(), $currDate->getYear(), $impDate->getDay(), $impDate->getMonth(), $impDate->getYear())) / $dateDelta;
        $cmpAmount = new Amount($currentTransaction->getAmount());
        $impAmount = new Amount($importedTransaction['amount']);
        $cmpAmount->sub($impAmount);
        $cmpAmount->abs();
        $impAmount->mul($amountDelta);
        $impAmount->abs();
        $amountSimilarity = 1 - $cmpAmount->div($impAmount)->get();
        $currentTextSimilarity = ($titleSimilarity + $descriptionSimilarity + $transactionPartnerSimilarity) / 3;
        if ($currentTextSimilarity >= $textSimilarity) {
            $overallSimilarity = ($titleSimilarity + $descriptionSimilarity + $transactionPartnerSimilarity + $dateSimilarity + $amountSimilarity) / 5;
            //$similarTransactions["$overallSimilarity t:$titleSimilarity d:$descriptionSimilarity tp:$transactionPartnerSimilarity vd:$dateSimilarity a:$amountSimilarity"] = $currentTransaction;
            $similarTransactions["{$overallSimilarity}"] = $currentTransaction;
        }
    }
    krsort($similarTransactions);
    if (count($similarTransactions)) {
        $importedTransaction['similarTransactions'] = $similarTransactions;
        return $importedTransaction;
    }
    if ($importedTransaction['categoryId']) {
        return $importedTransaction;
    }
    $transactionStrings = array($importedTransaction['title'], $importedTransaction['description'], $importedTransaction['transactionPartner']);
    foreach ($transactionStrings as $currentTransactionString) {
        foreach ($categories as $currentCategoryId => $keywords) {
            foreach ($keywords as $keyword) {
                if (stripos($currentTransactionString, trim($keyword)) !== false) {
                    $importedTransaction['categoryId'] = $currentCategoryId;
                    break 3;
                }
                //if keyword found
            }
            //foreach keywords
        }
        //foreach categories
    }
    //foreach transactionStrings
    return $importedTransaction;
}
        if ($i > MAX_CATEGORIES) {
            $other->add($currentAmount);
            unset($amounts[$currentId]);
            unset($labels[$currentId]);
        }
    }
}
$total = new Amount(0);
$total->add($other);
foreach ($amounts as $currentAmount) {
    $total->add($currentAmount);
}
foreach ($amounts as $currentId => $currentAmount) {
    $percentage = new Amount($currentAmount);
    $percentage->div($total);
    if ($percentage->compare(MIN_PERCENTAGE) < 0) {
        $other->add($currentAmount);
        unset($amounts[$currentId]);
        unset($labels[$currentId]);
    }
}
if ($other->compare(0) != 0) {
    $amounts['other'] = $other;
    $labels['other'] = getBadgerTranslation2('statistics2', 'miscCategories');
}
$data = array();
$dataNames = array();
foreach ($amounts as $currentAmount) {
    $data[] = $currentAmount->mul($type == 'i' ? 1 : -1)->get();
    $dataNames[] = $currentAmount->getFormatted();
}
function getAllTransactions(&$finishedTransactions, $selectedFields, $order, $upperLimit, $lowerLimit)
{
    $result = array();
    $currResultIndex = 0;
    $sum = new Amount();
    $now = new Date();
    $now->setHour(0);
    $now->setMinute(0);
    $now->setSecond(0);
    if (isset($order[0]) && $order[0]['key'] == 'valutaDate') {
        $firstOrderValutaDate = true;
        $orderCompareNumber = $order[0]['dir'] == 'asc' ? -1 : 1;
    } else {
        $firstOrderValutaDate = false;
    }
    $todayMarkerSet = false;
    foreach ($finishedTransactions as $currentTransaction) {
        $sum->add($currentTransaction->getAmount());
        $classAmount = $currentTransaction->getAmount()->compare(0) >= 0 ? 'dgPositiveAmount' : 'dgNegativeAmount';
        if ($sum->compare(0) >= 0) {
            if ($upperLimit && $sum->compare($upperLimit) > 0) {
                $classSum = 'dgOverMaxAmount';
            } else {
                $classSum = 'dgPositiveAmount';
            }
        } else {
            if ($lowerLimit && $sum->compare($lowerLimit) < 0) {
                $classSum = 'dgUnderMinAmount';
            } else {
                $classSum = 'dgNegativeAmount';
            }
        }
        $balance = $currentTransaction->getBalance();
        if ($balance->compare(0) >= 0) {
            if ($upperLimit && $balance->compare($upperLimit) > 0) {
                $classBalance = 'dgOverMaxAmount';
            } else {
                $classBalance = 'dgPositiveAmount';
            }
        } else {
            if ($lowerLimit && $balance->compare($lowerLimit) < 0) {
                $classBalance = 'dgUnderMinAmount';
            } else {
                $classBalance = 'dgNegativeAmount';
            }
        }
        $category = $currentTransaction->getCategory();
        if (!is_null($category)) {
            $parentCategory = $category->getParent();
        } else {
            $parentCategory = null;
        }
        if ($parentCategory) {
            $concatCategoryTitle = $parentCategory->getTitle() . ' - ';
        } else {
            $concatCategoryTitle = '';
        }
        if ($category) {
            $concatCategoryTitle .= $category->getTitle();
        }
        if ($currentTransaction->getType() == 'FinishedTransaction' || $currentTransaction->getType() == 'FinishedTransferalTransaction') {
            $id = $currentTransaction->getId();
        } else {
            $id = 'p' . $currentTransaction->getPlannedTransaction()->getId() . '_' . $currentTransaction->getId();
        }
        switch ($currentTransaction->getType()) {
            case 'FinishedTransaction':
                $typeImg = 'Account/finished_transaction.png';
                $typeText = getBadgerTranslation2('Account', 'FinishedTransaction');
                break;
            case 'FinishedTransferalTransaction':
                if ($currentTransaction->getTransferalSource()) {
                    $typeImg = 'Account/finished_transferal_source_transaction.png';
                    $typeText = getBadgerTranslation2('Account', 'FinishedTransferalSourceTransaction');
                } else {
                    $typeImg = 'Account/finished_transferal_target_transaction.png';
                    $typeText = getBadgerTranslation2('Account', 'FinishedTransferalTargetTransaction');
                }
                break;
            case 'PlannedTransaction':
                $typeImg = 'Account/planned_transaction.png';
                $typeText = getBadgerTranslation2('Account', 'PlannedTransaction');
                break;
            case 'PlannedTransferalTransaction':
                if ($currentTransaction->getTransferalSource()) {
                    $typeImg = 'Account/planned_transferal_source_transaction.png';
                    $typeText = getBadgerTranslation2('Account', 'PlannedTransferalSourceTransaction');
                } else {
                    $typeImg = 'Account/planned_transferal_target_transaction.png';
                    $typeText = getBadgerTranslation2('Account', 'PlannedTransferalTargetTransaction');
                }
                break;
        }
        $result[$currResultIndex] = array();
        if ($firstOrderValutaDate && $todayMarkerSet === false && !is_null($currentTransaction->getValutaDate()) && Date::compare($now, $currentTransaction->getValutaDate()) == $orderCompareNumber) {
            $result[$currResultIndex]['transactionId'] = array('marker' => 'today', 'content' => $id);
            $todayMarkerSet = true;
        } else {
            $result[$currResultIndex]['transactionId'] = $id;
        }
        foreach ($selectedFields as $selectedField) {
            switch ($selectedField) {
                case 'type':
                    $result[$currResultIndex]['type'] = array('img' => getRelativeTplPath($typeImg), 'title' => $typeText);
                    break;
                case 'title':
                    $result[$currResultIndex]['title'] = $currentTransaction->getTitle();
                    break;
                case 'description':
                    $result[$currResultIndex]['description'] = $currentTransaction->getDescription();
                    break;
                case 'valutaDate':
                    $result[$currResultIndex]['valutaDate'] = ($tmp = $currentTransaction->getValutaDate()) ? $tmp->getFormatted() : '';
                    break;
                case 'amount':
                    $result[$currResultIndex]['amount'] = array('class' => $classAmount, 'content' => $currentTransaction->getAmount()->getFormatted());
                    break;
                case 'outsideCapital':
                    $result[$currResultIndex]['outsideCapital'] = is_null($tmp = $currentTransaction->getOutsideCapital()) ? '' : $tmp;
                    break;
                case 'transactionPartner':
                    $result[$currResultIndex]['transactionPartner'] = $currentTransaction->getTransactionPartner();
                    break;
                case 'categoryId':
                    $result[$currResultIndex]['categoryId'] = $category ? $category->getId() : '';
                    break;
                case 'categoryTitle':
                    $result[$currResultIndex]['categoryTitle'] = $category ? $category->getTitle() : '';
                    break;
                case 'parentCategoryId':
                    $result[$currResultIndex]['parentCategoryId'] = $parentCategory ? $parentCategory->getId() : '';
                    break;
                case 'parentCategoryTitle':
                    $result[$currResultIndex]['parentCategoryTitle'] = $parentCategory ? $parentCategory->getTitle() : '';
                    break;
                case 'concatCategoryTitle':
                    $result[$currResultIndex]['concatCategoryTitle'] = $concatCategoryTitle;
                    break;
                case 'sum':
                    $result[$currResultIndex]['sum'] = array('class' => $classSum, 'content' => $sum->getFormatted());
                    break;
                case 'balance':
                    $result[$currResultIndex]['balance'] = array('class' => $classBalance, 'content' => $currentTransaction->getBalance()->getFormatted());
                    break;
                case 'plannedTransactionId':
                    $result[$currResultIndex]['plannedTransactionId'] = is_null($tmp = $currentTransaction->getPlannedTransaction()) ? '' : $tmp->getId();
                    break;
                case 'exceptional':
                    $result[$currResultIndex]['exceptional'] = is_null($tmp = $currentTransaction->getExceptional()) ? '' : $tmp;
                    break;
                case 'periodical':
                    $result[$currResultIndex]['periodical'] = is_null($tmp = $currentTransaction->getPeriodical()) ? '' : $tmp;
                    break;
                case 'accountTitle':
                    $result[$currResultIndex]['accountTitle'] = $currentTransaction->getAccount()->getTitle();
                    break;
            }
            //switch
        }
        //foreach selectedFields
        $currResultIndex++;
    }
    //foreach finishedTransactions
    return $result;
}