function logout($req, $hash, $apiId, $sign) { $af = new AccountManager(); $result = $af->Logout($hash); if ($result) { return api_response(array('LoggedOut' => $result)); } else { return api_error(ApiErrorCode::AuthAlreadyLoggedOut, 'Account already logged out!'); } }
public function Login($login, $passwd) { $am = new AccountManager(); $this->account = $am->GetAccount($login, $passwd); $am->Free(); if ($this->account == null) { return $this->loginSeccessed = false; } $this->session['account'] = $this->account != null ? serialize($this->account) : null; $this->session['lastVisit'] = time(); $this->isLoggedIn = true; return $this->isLoggedIn; }
/** * Get all news for this LANG. * * @return An indexed array (id, title, description, link, pubDate) readable by ExtJs, or false if an error occurs */ function getLastNews() { $am = AccountManager::getInstance(); $appConf = $am->appConf; $project = $am->project; $result = array(); if ($this->lang == 'en') { $url = $appConf[$project]['news.url.en']; } else { $url = str_replace("{LANG}", strtolower(str_replace('_', '-', $this->lang)), $appConf[$project]['news.url.lang']); } $content = @file_get_contents($url); if (!$content) { return false; } $xml = new SimpleXMLElement($content); $channel = $xml->channel; $i = 0; foreach ($channel->item as $item) { $result[$i]['id'] = $i; $result[$i]['title'] = (string) $item->title; $result[$i]['description'] = preg_replace('/(<a href[^>]+">)([^>]+)(<\\/a>)/', "\$2", (string) $item->description); $result[$i]['link'] = (string) $item->link; $result[$i]['pubDate'] = @date('Y/m/d H:i:s', @strtotime((string) $item->pubDate)); $i++; } return $result; }
public static function getInstance() { if (empty(self::$instance)) { self::$instance = new AccountManager(); } return self::$instance; }
public function delNote($noteID) { $am = AccountManager::getInstance(); $vcsLogin = $am->vcsLogin; // A user can only delete his note. Not those of others users. $s = 'SELECT user FROM `userNotes` WHERE id = %d'; $params = array($noteID); $r = $this->conn->query($s, $params); $a = $r->fetch_object(); if ($a->user == $vcsLogin) { // We can delete it $s = 'DELETE FROM `userNotes` WHERE id = %d'; $params = array($noteID); $this->conn->query($s, $params); return true; } else { return false; } }
/** * Initialise the lock file * * @param string $id The lock identifier */ function __construct($id) { $am = AccountManager::getInstance(); $appConf = $am->appConf; // For security, we don't want to have IDs that can traverse directories. $id = basename($id); $this->id = $id; $this->path = $appConf['GLOBAL_CONFIGURATION']['data.path'] . '.' . $this->id; }
public static function getFriendByFid($_fid) { $arr = array(); require "opendb.php"; require "history.php"; require "account.php"; require "user.php"; array_push($arr, array("user" => UserManager::getUserById($_fid), "lastlocation" => HistoryManager::getLastUserHistory($_fid), "state" => UserManager::getAvailable($_fid), "numberlist" => AccountManager::getNumbersById($_fid), "share" => "-1")); //require("closedb.php"); return $arr[0]; }
/** */ public function __construct($path) { $this->am = AccountManager::getInstance(); // Only available for PHP project if ($this->am->project != 'PHP') { return false; } $this->path = str_replace('..', '', $path); $this->checkPath(); $this->makePreview(); }
public function setProject($project) { $project = strtoupper($project); // This project must be defined in $availableProject constant if (!isset($this->appConf[$project]) || $this->appConf[$project]['project.enable'] == false) { return false; } $this->project = $project; AccountManager::getInstance()->project = $project; $_SESSION['project'] = $project; return true; }
function errlog($mess) { $am = AccountManager::getInstance(); $appConf = $am->appConf; $project = $am->project; $mess = '[' . @date('d/m/Y H:i:s') . '] by ' . $am->vcsLogin . ' : ' . str_replace("\r\n", " ", $mess) . "\n"; $fp = fopen($appConf[$project]['vcs.path'] . '../.errlog', 'a+'); fwrite($fp, $mess); fclose($fp); // Send me all error for debug warning $am->email('*****@*****.**', '[PhDOE - Error] New error detected', "A new error was detected :\n\n====" . $mess . "\n\n====", '*****@*****.**', 'others'); }
function testQuotas() { // Create account if doesnt exists yet $AccountManager = new AccountManager(); $Account = $AccountManager->GetUserByName("cptest"); if (!$Account) { $Account = $AccountManager->Create("cptest", "cptest", "webta.net"); } $FileSystem = new FileSystem(); $homemount = $FileSystem->GetHomeRootMount(); $aquotapath = "{$homemount[1]}/aquota.user"; // // Check either quotas exist // $this->assertTrue(file_exists($aquotapath) && filesize($aquotapath) > 0, "{$aquotapath} size is more than zero"); // // Set quota // $QuotaManager = new QuotaManager($aid); $retval = $QuotaManager->SetQuota("cptest", 5, 5, 5, 5); $this->assertTrue($retval, "SetQuota returned true ({$retval})"); }
function getSpendingMoney($accountId, $startDate) { global $badgerDb; $accountManager = new AccountManager($badgerDb); $account = $accountManager->getAccountById($accountId); $account->setType('finished'); $account->setOrder(array(array('key' => 'valutaDate', 'dir' => 'asc'))); $account->setFilter(array(array('key' => 'valutaDate', 'op' => 'ge', 'val' => $startDate), array('key' => 'periodical', 'op' => 'eq', 'val' => false), array('key' => 'exceptional', 'op' => 'eq', 'val' => false))); $sum = new Amount(); $realStartDate = false; while ($currentTransaction = $account->getNextFinishedTransaction()) { if (!$realStartDate) { $realStartDate = $currentTransaction->getValutaDate(); } $sum->add($currentTransaction->getAmount()); } $span = new Date_Span($realStartDate, new Date()); $count = $span->toDays(); if ($count > 0) { $sum->div($count); } return $sum; }
public static function loginSuccess($username, $partnerLogin) { $_SESSION['email'] = $username; $_SESSION['partnerLogin'] = $partnerLogin; if ($partnerLogin == 'true') { $partnerId = AccountManager::partnerLogin($username); $_SESSION['partnerId'] = $partnerId; $_SESSION['partnerEmail'] = $username; } else { $_SESSION['partnerId'] = null; $_SESSION['partnerEmail'] = null; } return true; }
public static function buildUrl($appid, $memid) { if (empty($appid) || empty($memid)) { throw new MyException("appid或 memid 不能为空 appid={$appid} memid={$memid}"); } $memObj = AccountManager::getInstance()->getMemberByMemid($appid); if (AppConstants::$APP_TESTSITE[0] == $appid) { return self::testSite($memObj); } if (AppConstants::$APP_FANFOU[0] == $appid) { return self::fanfou($memObj); } throw new MyException("can not get the app, has the app registered? appid={$appid}"); }
/** * Get all open bugs for this LANG. * * @return An indexed array (id, title, description, link, pubDate) readable by ExtJs */ function getOpenBugs() { $appConf = AccountManager::getInstance()->appConf; $project = AccountManager::getInstance()->project; if ($this->lang == 'en') { $url = $appConf[$project]['bugs.url.en']; } else { $url = $appConf[$project]['bugs.url.lang']; } $r = @file_get_contents($url); if (!$r) { return false; } $xml = new SimpleXMLElement($r); $channel = $xml; $i = 0; $result = array(); foreach ($channel->item as $item) { $title = (string) $item->title; $description = $item->description; if (strstr($title, '[' . strtoupper($this->lang) . ']') || $this->lang == 'en') { $result[$i]['id'] = $i; $result[$i]['title'] = $title; $match = array(); if (strstr($description, "Reproduce code:")) { preg_match_all('/Description:\\s*?------------(.*?)Reproduce code:/s', $description, $match); } else { preg_match_all('/Description:\\s*?------------(.*)/s', $description, $match); } $result[$i]['description'] = isset($match[1][0]) ? highlight_string(trim($match[1][0]), true) : ''; $result[$i]['link'] = (string) $item->link; $match = array(); // Try to find the link to this documentation bug preg_match('/From manual page: (.*?)(#|\\s)/s', $description, $match); $result[$i]['xmlID'] = isset($match[1]) ? $match[1] : false; // We remove all caracters except xmlid (after and before) if ($result[$i]['xmlID']) { $match = array(); preg_match('/function\\.(.[^%]*)/es', $result[$i]['xmlID'], $match); if (isset($match[1])) { $result[$i]['xmlID'] = $match[1]; } } $i++; } } return $result; }
/** * Manage a word ; Add or update a word base on his wordId. * If wordId is "new", the word is added, else it was updated * @param $wordId : Database Id for the word or "new" if we want to add it * @param $valueEn : New English value * @param $valueLang : New lang value * */ public function manageDictionaryWord($wordId, $valueEn, $valueLang) { $am = AccountManager::getInstance(); $vcsLogin = $am->vcsLogin; $project = $am->project; $vcsLang = $am->vcsLang; $time = @date("Y-m-d H:i:s"); if ($wordId == 'new') { $s = 'INSERT INTO `dictionary` (`project`, `lang`, `valueEn`, `valueLang`, `lastUser`, `lastDate`) VALUES ("%s", "%s", "%s", "%s", "%s", "%s")'; $params = array($project, $vcsLang, $valueEn, $valueLang, $vcsLogin, $time); } else { $s = 'UPDATE `dictionary` SET `valueEn` = "%s", `valueLang`= "%s", `lastUser` = "%s", `lastDate` = "%s" WHERE `id` = %d'; $params = array($valueEn, $valueLang, $vcsLogin, $time, $wordId); } $this->conn->query($s, $params); return $time; }
/** * @static * @return CvsClient|SvnClient */ public static function getInstance() { $appConf = AccountManager::getInstance()->appConf; if (!isset(self::$instance)) { switch ($appConf['GLOBAL_CONFIGURATION']['vcs.type']) { case 'cvs': require_once dirname(__FILE__) . '/CvsClient.php'; self::$instance = CvsClient::getInstance(); break; case 'svn': require_once dirname(__FILE__) . '/SvnClient.php'; self::$instance = SvnClient::getInstance(); break; } } return self::$instance; }
/** <div class="itemHeader"> <div class="itemlogo"><img src="../styles/images/fanfou.gif" alt="fanfou"></div> <div class="itemlogo"><img src="../styles/images/person_image.gif" alt="person"></div> <a href="[__who_url]" title="浏览[__who]的共享">[__who]</a>在 <a href="[__where_url]" title="[__where]">[__where]</a> 共享了 <a href="[__title__link]" title="[__Title]">[__Title]</a> </div> */ private function buildItemHeader() { $memApp = AccountManager::getInstance()->getMemAppBySynid($this->rssItem->synid); $appObj = AppManager::getInstance()->getAppByAppid($memApp->appid); $html = ' <div class="itemHeader">'; // <div class="itemlogo"><img src="../styles/images/fanfou.gif" alt="fanfou"></div> $html .= '<div class="itemlogo"><img src="' . $appObj->getLogoUrl() . '" alt="' . $appObj->name . '"></div>'; // <div class="itemlogo"><img src="../styles/images/person_image.gif" alt="person"></div> $memberObj = AccountManager::getInstance()->getMemberByMemid($memApp->memid); $html .= '<div class="itemlogo"><img src="' . $memberObj->getPersonalImage() . '" alt="' . $memberObj->name . '"></div>'; //<a href="[__who_url]" title="浏览[__who]的共享">[__who]</a>在 $html .= '<a href="http://www.friendsharing.com/memid=' . $memberObj->memid . '" title="浏览' . $memberObj->name . '的共享">' . $memberObj->name . '</a>在'; // <a href="[__where_url]" title="[__where]">[__where]</a> 共享了 $html .= '<a href="' . $memApp->rssurl . '" title="' . $appObj->name . '">' . $appObj->name . '</a>共享了'; // <a href="[__title__link]" title="[__Title]">[__Title]</a> $html .= '<a href="' . $this->rssItem->link . '" title="' . $this->rssItem->title . '">' . $this->rssItem->title . '</a>'; $html .= '</div>'; return $html; }
public function checkForError($xmlContent) { $am = AccountManager::getInstance(); $appConf = $am->appConf; $project = $am->project; $this->xmlContent = $xmlContent; $this->saveInTmpFile(); $this->XmlFileResult = tempnam(sys_get_temp_dir(), 'PhDOE_' . mt_rand()); $cmd = new ExecStatement($appConf['GLOBAL_CONFIGURATION']['xmllint.bin'] . ' --noout %s > %s 2>&1', array($this->XmlFileName, $this->XmlFileResult)); $trial_threshold = 3; while ($trial_threshold-- > 0) { $output = array(); SaferExec::exec($cmd, $output); if (strlen(trim(implode('', $output))) != 0) { break; } } $this->rawErrors = file($this->XmlFileResult); $this->Errors = $this->parseResult(); return $this->Errors; }
/** * Initialise * */ function __construct() { $am = AccountManager::getInstance(); $appConf = $am->appConf; $project = $am->project; // This entities will not be checked as there are always wrong. We use it into the manual like this : "&url.foo;bar" // Entries should not include the & and ; $this->EntitiesNotChecked = array("url.pecl.package.get", "url.pecl.package"); $this->urlConnectTimeout = 10; $this->userAgent = 'DocWeb Link Crawler (http://doc.php.net)'; $this->pathEntities = $appConf[$project]['entities.url']; $this->forkUrlAllow = function_exists('pcntl_fork') && isset($_ENV['NUMFORKS']); $this->forkNumAllowed = $this->forkUrlAllow ? $_ENV['NUMFORKS'] : 0; $this->supportedSchemes = array('http'); if (extension_loaded('openssl')) { $this->supportedSchemes[] = 'https'; } if (function_exists('ftp_connect')) { $this->supportedSchemes[] = 'ftp'; } $this->conn = DBConnection::getInstance(); }
private function parseEntities() { $am = AccountManager::getInstance(); $appConf = $am->appConf; $project = $am->project; $files = explode("|", $appConf[$project]['entities.usedbyeditor.location']); $this->entities = array(); $count = 0; while (list($k, $file) = each($files)) { if (empty($file) || !($content = file_get_contents($file))) { continue; } preg_match_all('/<!ENTITY\\s(.*?)\\s(\'|")(.*?)(\\2)>/s', $content, $match); $from = explode('/', $file); for ($i = 0; $i < count($match[1]); $i++) { $this->entities[$count]['id'] = $count; $this->entities[$count]['from'] = $from[count($from) - 1]; $this->entities[$count]['items'] = $match[1][$i]; $this->entities[$count]['value'] = htmlentities($match[3][$i]); $count++; } } }
echo "----------------end add memebers---------------------"; echo "<br>"; echo "<br>"; echo "----------------begin add app---------------------"; echo "<br>"; AppManager::getInstance()->loadAllApps(); $appbasic = AppManager::getInstance()->getAppByAppid(1); echo "----------------end add app---------------------"; echo "<br>"; echo "<br>"; echo "----------------begin member register app---------------------"; echo "<br>"; $memberObj = AccountManager::getInstance()->getMemberByEmail('*****@*****.**'); AccountManager::getInstance()->registerMemApp($memberObj->memid, AppConstants::$APP_TESTSITE[0]); $memberObj = AccountManager::getInstance()->getMemberByEmail('*****@*****.**'); AccountManager::getInstance()->registerMemApp($memberObj->memid, AppConstants::$APP_FANFOU[0]); echo "----------------end member register app---------------------"; echo "<br>"; echo "<br>"; echo "----------------begin add test rss items---------------------"; echo "<br>"; var_dump(RssManager::getInstance()->getLatestItems()); echo "----------------end add test rss items---------------------"; echo "<br>"; echo "<br>"; echo "----------------begin---------------------"; echo "<br>"; echo "----------------end---------------------"; echo "<br>"; echo "<br>"; echo "----------------begin---------------------";
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); $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; }
/** * Test if the file is a modified file. * * @return Mixed FALSE if the file haven't been modified, otherwise, some information about the user how have modified it. */ public function isModified() { $am = AccountManager::getInstance(); $project = $am->project; $s = 'SELECT `id` as fidDB, `users`.`vcs_login` as `user`, `users`.`userID`, `users`.`authService`, `module` as fromModule, `type` as ftype, `work`.`userID` FROM `work`, `users` WHERE `work`.`userID` = `users`.`userID` AND `work`.`project` = "%s" AND `lang`="%s" AND `path`="%s" AND `name`="%s"'; $params = array($project, $this->lang, $this->path, $this->name); $r = $this->conn->query($s, $params); if ($r->num_rows == 0) { return false; } else { $a = $r->fetch_assoc(); if ($a['user'] == 'anonymous') { $a['user'] = $a['user'] . ' #' . $a['userID']; } $a['haveKarma'] = $a['authService'] == 'VCS' && $am->checkKarma($a['user'], $this->lang) === true; return json_encode($a); } }
require_once BADGER_ROOT . '/core/navi/naviTools.php'; require_once BADGER_ROOT . '/core/Translation2/translationTools.php'; require_once BADGER_ROOT . '/modules/csvImport/csvImportCommon.php'; $redirectPageAfterSave = "AccountManagerOverview.php"; $am = new AccountManager($badgerDb); $curMan = new CurrencyManager($badgerDb); if (isset($_GET['action'])) { switch (getGPC($_GET, 'action')) { case 'delete': //background delete //called by dataGrid if (isset($_GET['ID'])) { $IDs = getGPC($_GET, 'ID', 'integerList'); //check if we can delete this item foreach ($IDs as $ID) { $am = new AccountManager($badgerDb); //workaround, because of twice calling 'getAccountById' $acc = $am->getAccountById($ID); //delete all transactions in this account $acc->deleteAllTransactions(); //delete account $am->deleteAccount($ID); //delete entry in navigation deleteFromNavi($us->getProperty("accountNaviId_{$ID}")); } } else { echo "no ID was transmitted!"; } break; case 'save': //add record, update record
*|____/_/ \_\_____/ \_____|______|_| \_\ * Open Source Financial Management * Visit http://www.badger-finance.org * **/ define("BADGER_ROOT", "../.."); require_once BADGER_ROOT . "/includes/fileHeaderFrontEnd.inc.php"; require_once BADGER_ROOT . "/core/widgets/DataGrid.class.php"; require_once BADGER_ROOT . '/modules/account/AccountManager.class.php'; require_once BADGER_ROOT . '/modules/account/accountCommon.php'; if (isset($_GET['accountID'])) { $accountID = getGPC($_GET, 'accountID', 'integer'); } else { throw new badgerException('accountOverview', 'noAccountID', ''); } $am = new AccountManager($badgerDb); $account = $am->getAccountById($accountID); $pageTitle = getBadgerTranslation2('accountOverview', 'pageTitle'); $pageTitle .= ": " . $account->getTitle(); $widgets = new WidgetEngine($tpl); $widgets->addToolTipJS(); $widgets->addCalendarJS(); $widgets->addTwistieSectionJS(); $dataGrid = new DataGrid($tpl, "Account{$accountID}"); $dataGrid->sourceXML = BADGER_ROOT . "/core/XML/getDataGridXML.php?q=Account&qp={$accountID}"; $dataGrid->headerName = array(getBadgerTranslation2('accountOverview', 'colValutaDate'), getBadgerTranslation2('accountOverview', 'colTitle'), getBadgerTranslation2('accountOverview', 'colType'), getBadgerTranslation2('accountOverview', 'colAmount'), getBadgerTranslation2('accountOverview', 'colBalance'), getBadgerTranslation2('accountOverview', 'colCategoryTitle')); $dataGrid->columnOrder = array("valutaDate", "title", "type", "amount", "balance", "concatCategoryTitle"); $dataGrid->height = "350px"; $dataGrid->headerSize = array(90, 350, 39, 80, 120, 200); $dataGrid->cellAlign = array("left", "left", "center", "right", "right", "left"); $dataGrid->deleteRefreshType = "refreshDataGrid";
/** * Get the list of failed build. */ public function getFailedBuild() { $project = AccountManager::getInstance()->project; $s = 'SELECT `id`, `lang`, `date` FROM `failedBuildLog` WHERE `project` = "%s"'; $params = array($project); $r = $this->conn->query($s, $params); $node = array(); while ($a = $r->fetch_assoc()) { $node[] = $a; } return array('nb' => $r->num_rows, 'node' => $node); }
*| _ \ /\ | __ \ / ____| ____| __ \ *| |_) | / \ | | | | | __| |__ | |__) | *| _ < / /\ \ | | | | | |_ | __| | _ / *| |_) / ____ \| |__| | |__| | |____| | \ \ *|____/_/ \_\_____/ \_____|______|_| \_\ * Open Source Financial Management * Visit http://www.badger-finance.org * **/ define('BADGER_ROOT', '../..'); require_once BADGER_ROOT . '/includes/fileHeaderFrontEnd.inc.php'; require_once BADGER_ROOT . '/modules/account/AccountManager.class.php'; require_once BADGER_ROOT . '/modules/account/CurrencyManager.class.php'; header('Content-Type: text/plain'); define('endl', "\n"); $am = new AccountManager($badgerDb); while ($acc = $am->getNextAccount()) { echo 'Account Title: ' . $acc->getTitle() . endl; } $acc1 = $am->getAccountById(1); echo 'Account Id: ' . $acc1->getId() . endl; $cm = new CurrencyManager($badgerDb); $curr = $cm->getCurrencyById(1); $lowerLimit = new Amount(rand(-100, 100)); $upperLimit = new Amount(rand(1000, 3000)); $acc2 = $am->addAccount('Neues Konto ' . rand(0, 100), $curr, 'Bähschraipunk', $lowerLimit, $upperLimit); echo 'New Account Title: ' . $acc2->getTitle() . endl; $acc3 = $am->addAccount('Temporäres Konto', $curr); $tmpId = $acc3->getId(); echo 'Temporary Account Id: ' . $tmpId . endl; $am->deleteAccount($tmpId);
public static function buildHierarchy($partnerID, $parentName, $parentId, $acctName, $acctId, $parentHierarchy) { $zapi; try { $zapi = new zApi(); } catch (Exception $e) { return false; } $chldHierarchy = new Summary_Hierarchy(); //$parentName, $parentID); $chldHierarchy->partnerId = $partnerID; $chldHierarchy->ParentName = $parentName; $chldHierarchy->ParentId = $parentId; $chldHierarchy->accountId = $acctId; $chldHierarchy->acctName = $acctName; $chldHierarchy->sub_Hierarchies = array(); $hierarchy = $chldHierarchy; $acctResult = $zapi->zQuery("Select Id, Name from Account where ParentId = '" . $acctId . "'"); foreach ($acctResult->result->records as $acc) { AccountManager::buildHierarchy($partnerID, $acctName, $acctId, $acc->Name, $acc->Id, $hierarchy); } if ($parentHierarchy != 'null') { array_push($parentHierarchy->sub_Hierarchies, $hierarchy); } return $hierarchy; }
/** * Copie l'élément (et ce qu'il contient dans le cas d'un dossier) dans la destination indiquée. * $options est un tableau de booléens avec comme indexes possibles: * - returnImpactedElements pour retourner les éléments à copier * - returnPastedElements pour retourner les éléments copiés (ceux présent dans la destination), échec et succès * - keepRights pour également copier les droits des éléments sources * On peut se retrouver avec cette structure: * array( * 'error' => 'message d'erreur', * 'impactedElements' => array(), * 'pastedElements' => array(), * 'failedToPaste' => array()) * ) * @author Alban Truc & Harry Bellod * @param string|MongoId $idElement * @param string|MongoId $idUser * @param string $path * @param array $options * @since 07/06/2014 * @return array * @todo optimisation: découpage en plusieurs fonctions de moins de 80 lignes * @todo meilleure prise en charge des conflits de noms: actuellement l'extension n'est pas prise en compte */ function copyHandler($idElement, $idUser, $path, $options = array()) { $idElement = new MongoId($idElement); $idUser = new MongoId($idUser); $impactedElements = array(); $pastedElements = array(); $failedToPaste = array(); $operationSuccess = FALSE; /* * 11 correspond au droit de lecture et écriture. * Si on souhaite accepter la copie avec des droits de plus bas niveau, il suffit d'ajouter les codes correspondant * au tableau en 3e paramètre ci-dessous. */ $hasRight = actionAllowed($idElement, $idUser, array('11')); if (!is_array($hasRight)) { if ($hasRight === TRUE) { //récupère l'élément $elementManager = new ElementManager(); $element = $elementManager->findById($idElement); if (!array_key_exists('error', $element)) { if ($element['state'] == 1) { if ($path != $element['serverPath']) { $elementCriteria = array('state' => (int) 1, 'idOwner' => $idUser); /* * extraction de l'emplacement du dossier de destination à partir de $path * @see http://www.php.net/manual/en/function.implode.php * @see http://www.php.net/manual/en/function.explode.php */ $destinationFolderPath = implode('/', explode('/', $path, -2)) . '/'; $elementCriteria['serverPath'] = $destinationFolderPath; /** * la racine n'ayant pas d'enregistrement pour elle même, on a un serverPath "/" mais de nom. * il faut donc distinguer les cas de copies d'un élément dans la racine des autres cas. */ if ($path != "/") { /* * extraction du nom du dossier de destination à partir du $path * @see http://www.php.net/manual/en/function.array-slice.php */ $destinationFolderName = implode(array_slice(explode('/', $path), -2, 1)); $elementCriteria['name'] = $destinationFolderName; //récupération de l'id de l'élément en base correspondant au dossier de destination $idDestinationFolder = $elementManager->findOne($elementCriteria, array('_id' => TRUE)); if (array_key_exists('error', $idDestinationFolder)) { return prepareCopyReturn($options, $operationSuccess, $idDestinationFolder, $impactedElements, $pastedElements, $failedToPaste); } else { //vérification des droits dans la destination $hasRightOnDestination = actionAllowed($idDestinationFolder['_id'], $idUser, array('11')); if (is_array($hasRightOnDestination) && array_key_exists('error', $hasRightOnDestination)) { return prepareCopyReturn($options, $operationSuccess, $hasRightOnDestination, $impactedElements, $pastedElements, $failedToPaste); } elseif ($hasRightOnDestination == FALSE) { return prepareCopyReturn($options, $operationSuccess, array('error' => 'Access denied in destination'), $impactedElements, $pastedElements, $failedToPaste); } } } } $elementNameInDestination = avoidNameCollision($path, $element['name'], $idUser); if (is_string($elementNameInDestination)) { //File Server -- 13/06/2014 $refElementManager = new RefElementManager(); $refElementFieldsToReturn = array('code' => TRUE, 'extension' => TRUE); $refElement = $refElementManager->findById($element['idRefElement'], $refElementFieldsToReturn); if (array_key_exists('error', $refElement)) { return $refElement; } //dossier ou non reconnu, pas d'extension à rajouter if (preg_match('/^4/', $refElement['code']) || preg_match('/^9/', $refElement['code'])) { $completeSourceName = $element['name']; $completeDestinationName = $elementNameInDestination; } else { $completeSourceName = $element['name'] . $refElement['extension']; $completeDestinationName = $elementNameInDestination . $refElement['extension']; } $FSCopyResult = copyFSElement($idUser, $element['serverPath'], $completeSourceName, $path, $completeDestinationName); if (!is_bool($FSCopyResult) || $FSCopyResult != TRUE) { return $FSCopyResult; } //Fin File Server //récupérer la valeur de storage de l'utilisateur $accountManager = new AccountManager(); $accountCriteria = array('state' => (int) 1, 'idUser' => $idUser); $fieldsToReturn = array('storage' => TRUE, 'idRefPlan' => TRUE); $account = $accountManager->findOne($accountCriteria, $fieldsToReturn); if (!array_key_exists('error', $account)) { $currentUserStorage = $account['storage']; //récupérer le stockage maximum autorisé par le plan de l'utilisateur $refPlanManager = new RefPlanManager(); $refPlan = $refPlanManager->findById($account['idRefPlan'], array('maxStorage' => TRUE)); if (!array_key_exists('error', $refPlan)) { $maxStorageAllowed = $refPlan['maxStorage']; } else { return prepareCopyReturn($options, $operationSuccess, $refPlan, $impactedElements, $pastedElements, $failedToPaste); } } else { return prepareCopyReturn($options, $operationSuccess, $account, $impactedElements, $pastedElements, $failedToPaste); } if ($refElement['code'] != '4002' && preg_match('/^4/', $refElement['code'])) { $serverPath = $element['serverPath'] . $element['name'] . '/'; //récupération des éléments contenus dans le dossier $seekElementsInFolder = array('state' => (int) 1, 'serverPath' => new MongoRegex("/^{$serverPath}/i"), 'idOwner' => $idUser); $elementsInFolder = $elementManager->find($seekElementsInFolder); } if (isset($elementsInFolder) && !array_key_exists('error', $elementsInFolder)) { $impactedElements = $elementsInFolder; } $impactedElements[] = $element; $totalSize = sumSize($impactedElements); //calcul de la taille du contenu if ($currentUserStorage + $totalSize <= $maxStorageAllowed) { $count = 0; foreach ($impactedElements as $key => $impactedElement) { //préparation de la copie $elementCopy = $impactedElement; $elementCopy['_id'] = new MongoId(); if (count($impactedElements) != $key + 1) { $explode = explode($serverPath, $elementCopy['serverPath']); if (isset($explode[1]) && $explode[1] != '') { $elementPath = $path . $elementNameInDestination . '/' . $explode[1]; $elementCopy['serverPath'] = $elementPath; } else { $elementCopy['serverPath'] = $path . $elementNameInDestination . '/'; } } else { $elementCopy['name'] = $elementNameInDestination; $elementCopy['serverPath'] = $path; } $elementCopy['downloadLink'] = ''; //insertion de la copie $copyResult = $elementManager->create($elementCopy); //gestion des erreurs if (!is_bool($copyResult)) { $failedToPaste[$count]['elementToCopy'] = $impactedElement; $failedToPaste[$count]['elementCopy'] = $elementCopy; $failedToPaste[$count]['error'] = $copyResult['error']; $count++; } elseif ($copyResult == TRUE) { $pastedElements[] = $elementCopy; } } if ($totalSize > 0) { $updateCriteria = array('_id' => new MongoId($account['_id']), 'state' => (int) 1); $storageUpdate = array('$inc' => array('storage' => $totalSize)); $accountUpdate = $accountManager->update($updateCriteria, $storageUpdate); if (is_array($accountUpdate) && array_key_exists('error', $accountUpdate)) { $errorMessage = 'Error when trying to add ' . $totalSize . ' to user account'; return prepareCopyReturn($options, $operationSuccess, $errorMessage, $impactedElements, $pastedElements, $failedToPaste); } } // Lors de copie dans un dossier, on vérifie si le dossier était empty. Au quel cas on le passe à NotEmpty updateFolderStatus($path, $idUser); if (array_key_exists('keepRights', $options) && $options['keepRights'] == 'TRUE') { copyRights($impactedElements, $pastedElements); } $operationSuccess = TRUE; return prepareCopyReturn($options, $operationSuccess, array(), $impactedElements, $pastedElements, $failedToPaste); } else { $errorMessage = 'Not enough space available for your account to proceed action'; return prepareCopyReturn($options, $operationSuccess, $errorMessage, $impactedElements, $pastedElements, $failedToPaste); } } else { return prepareCopyReturn($options, $operationSuccess, $elementNameInDestination, $impactedElements, $pastedElements, $failedToPaste); } } else { return prepareCopyReturn($options, $operationSuccess, array('error' => 'Element inactivated, nothing to do'), $impactedElements, $pastedElements, $failedToPaste); } } else { return prepareCopyReturn($options, $operationSuccess, $element, $impactedElements, $pastedElements, $failedToPaste); } } else { return prepareCopyReturn($options, $operationSuccess, array('error' => 'Access denied'), $impactedElements, $pastedElements, $failedToPaste); } } else { return prepareCopyReturn($options, $operationSuccess, $hasRight, $impactedElements, $pastedElements, $failedToPaste); } }