/** * * @param array $lines */ private function ParseLines($lines) { $relations = $concept = $separator = $flipped = array(); foreach ($lines as $linenr => $line) { $totalcolumns = count($line); // First line specifies relation names if ($linenr == 0) { for ($col = 0; $col < $totalcolumns; $col++) { $relations[$col] = trim($line[$col]); // No leading/trailing spaces around relation names. } // Second line specifies concepts (and optionally: separators) } elseif ($linenr == 1) { // In the Haskell importer, separators are the last character before the ']' if the concept is surrounded by such block quotes. Alternatively, you could specify a separator following such block-quotes, allowing for multiple-character separators. for ($col = 0; $col < $totalcolumns; $col++) { $cellvalue = trim($line[$col]); // No leading/trailing spaces around cell values in second line if ($cellvalue == '') { $concept[$col] = null; // The cell contains either 'Concept' or '[Conceptx]' where x is a separator character (e.g. ';', ',', ...) } elseif (substr($cellvalue, 0, 1) == '[' && substr($cellvalue, -1) == ']') { if ($col == 0) { throw new Exception("Seperator character not allowed for first column of excel import. Specified '{$line[$col]}'", 500); } $concept[$col] = Concept::getConceptByLabel(substr($cellvalue, 1, -2)); $separator[$col] = substr($cellvalue, -2, 1); } else { $concept[$col] = Concept::getConceptByLabel($cellvalue); $separator[$col] = false; } // Determine relations for all cols except col 0 if ($col > 0) { if ($relations[$col] == '' || $concept[$col] == '') { $relations[$col] = null; } elseif (substr($relations[$col], -1) == '~') { // Relation is flipped is last character is a tilde (~) $relations[$col] = Relation::getRelation(substr($relations[$col], 0, -1), $concept[$col], $concept[0]); $flipped[$col] = true; } else { $relations[$col] = Relation::getRelation($relations[$col], $concept[0], $concept[$col]); $flipped[$col] = false; } } } // All other lines specify atoms } else { $line[0] = trim($line[0]); // Trim cell content (= dirty identifier) // Determine left atom (column 0) of line if ($line[0] == '') { continue; } elseif ($line[0] == '_NEW') { $leftAtom = $concept[0]->createNewAtom(); } else { $leftAtom = new Atom($line[0], $concept[0]); } // Insert $leftAtom into the DB if it does not yet exist $leftAtom->addAtom(); // Process other columns of line for ($col = 1; $col < $totalcolumns; $col++) { if (is_null($concept[$col])) { continue; } // If no concept is specified, the cell is skipped if (is_null($relations[$col])) { continue; } // If no relation is specified, the cell is skipped // Determine right atom(s) $rightAtoms = array(); $cell = trim($line[$col]); // Start of check for multiple atoms in single cell if ($cell == '') { continue; } elseif ($cell == '_NEW') { $rightAtoms[] = $leftAtom; } elseif ($separator[$col]) { $atomsIds = explode($separator[$col], $cell); // atomnames may have surrounding whitespace foreach ($atomsIds as $atomId) { $rightAtoms[] = new Atom(trim($atomId), $concept[$col]); } } else { $rightAtoms[] = new Atom($line[$col], $concept[$col]); // DO NOT TRIM THIS CELL CONTENTS as it contains an atom that may need leading/trailing spaces } foreach ($rightAtoms as $rightAtom) { $relations[$col]->addLink($leftAtom, $rightAtom, $flipped[$col], 'ExcelImport'); } } } } }
}); // Output $output = new OutputCSV(); $output->addColumns(array_keys($content[0])); foreach ($content as $row) { $output->addRow($row); } $output->render('conj-performance-report.csv'); // print json_encode($content, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); }); $app->get('/admin/report/relations', function () use($app) { if (Config::get('productionEnv')) { throw new Exception("Reports are not allowed in production environment", 403); } $content = array(); foreach (Relation::getAllRelations() as $relation) { $relArr = array(); $relArr['signature'] = $relation->signature; $relArr['constraints'] .= $relation->isUni ? "[UNI]" : ""; $relArr['constraints'] .= $relation->isTot ? "[TOT]" : ""; $relArr['constraints'] .= $relation->isInj ? "[INJ]" : ""; $relArr['constraints'] .= $relation->isSur ? "[SUR]" : ""; if (empty($relArr['constraints'])) { $relArr['constraints'] = "no constraints"; } $relArr['affectedConjuncts'] = array(); foreach ($relation->affectedConjuncts as $conjunct) { $relArr['affectedConjuncts'][$conjunct->id] = array(); foreach ($conjunct->invRuleNames as $ruleName) { $relArr['affectedConjuncts'][$conjunct->id]['invRules'][] = $ruleName; }
/** * Function to create a new Atom at the given interface. * @param array $data * @param array $options * @throws Exception * @return mixed */ public function create($data, $options = array()) { $this->logger->debug("create() called on {$this->path}"); // CRUD check if (!$this->crudC) { throw new Exception("Create not allowed for '{$this->path}'", 405); } if (!$this->tgtConcept->isObject) { throw new Exception("Cannot create non-object '{$this->tgtConcept}' in '{$this->path}'. Use PATCH add operation instead", 405); } if ($this->isRef()) { throw new Exception("Cannot create on reference interface in '{$this->path}'. See #498", 501); } // Handle options if (isset($options['requestType'])) { $this->database->setRequestType($options['requestType']); } // Perform create $newAtom = $this->tgtConcept->createNewAtom(); // Special case for CREATE in I[Concept] interfaces if ($this->srcAtom->id === '_NEW') { $this->srcAtom->setId($newAtom->id); $this->path = str_replace('_NEW', $newAtom->getJsonRepresentation(), $this->path); } // If interface expression is a relation, also add tuple(this, newAtom) in this relation if ($this->relation) { $this->relation()->addLink($this->srcAtom, $newAtom, $this->relationIsFlipped); } else { $newAtom->addAtom(); } // Walk to new atom $newAtom = $this->atom($newAtom->id); // Set requested state (using patches) $patches = is_array($data) ? $data['patches'] : array(); $newAtom->doPatches($patches); // Special case for file upload. TODO: make extension with hooks if ($this->tgtConcept->isFileObject()) { $conceptFilePath = Concept::getConceptByLabel('FilePath'); $conceptFileName = Concept::getConceptByLabel('FileName'); if (is_uploaded_file($_FILES['file']['tmp_name'])) { $tmp_name = $_FILES['file']['tmp_name']; $new_name = time() . '_' . $_FILES['file']['name']; $absolutePath = Config::get('absolutePath') . Config::get('uploadPath') . $new_name; $relativePath = Config::get('uploadPath') . $new_name; $result = move_uploaded_file($tmp_name, $absolutePath); if ($result) { Logger::getUserLogger()->notice("File '{$new_name}' uploaded"); } else { throw new Exception("Error in file upload", 500); } // Populate filePath and originalFileName relations in database $relFilePath = Relation::getRelation('filePath', $newAtom->concept, $conceptFilePath); $relOriginalFileName = Relation::getRelation('originalFileName', $newAtom->concept, $conceptFileName); $relFilePath->addLink($newAtom, new Atom($relativePath, $conceptFilePath)); $relOriginalFileName->addLink($newAtom, new Atom($_FILES['file']['name'], $conceptFileName)); } else { throw new Exception("No file uploaded", 500); } } // Close transaction $this->database->closeTransaction($newAtom->concept . ' created', null, $newAtom); // temp store content of $newAtom (also when not crudR) // Return atom content (can be null) return $newAtom->getStoredContent(); }
private function login($email) { if (empty($email)) { throw new Exception("No emailaddress provided to login", 500); } $session = Session::singleton(); $db = Database::singleton(); $conceptUserID = Concept::getConceptByLabel('UserID'); $conceptDomain = Concept::getConceptByLabel('Domain'); $conceptDateTime = Concept::getConceptByLabel('DateTime'); $conceptOrg = Concept::getConceptByLabel('Organization'); $conceptAccount = Concept::getConceptByLabel('Account'); $conceptSession = Concept::getConceptByLabel('SESSION'); // Set sessionUser $atom = new Atom($email, $conceptUserID); $accounts = $atom->ifc('AccountForUserid')->getTgtAtoms(); // create new user if (empty($accounts)) { $newAccount = Concept::getConceptByLabel('Account')->createNewAtom(); // Save email as accUserid $relAccUserid = Relation::getRelation('accUserid', $newAccount->concept, $conceptUserID); $relAccUserid->addLink($newAccount, new Atom($email, $conceptUserID), false, 'OAuthLoginExtension'); // If possible, add account to organization(s) based on domain name $domain = explode('@', $email)[1]; $atom = new Atom($domain, $conceptDomain); $orgs = $atom->ifc('DomainOrgs')->getTgtAtoms(); $relAccOrg = Relation::getRelation('accOrg', $newAccount->concept, $conceptOrg); foreach ($orgs as $org) { $relAccOrg->addLink($newAccount, $org, false, 'OAuthLoginExtension'); } // Account created, add to $accounts list (used lateron) $accounts[] = $newAccount; } if (count($accounts) > 1) { throw new Exception("Multiple users registered with email {$email}", 401); } $relSessionAccount = Relation::getRelation('sessionAccount', $conceptSession, $conceptAccount); $relAccMostRecentLogin = Relation::getRelation('accMostRecentLogin', $conceptAccount, $conceptDateTime); $relAccLoginTimestamps = Relation::getRelation('accLoginTimestamps', $conceptAccount, $conceptDateTime); foreach ($accounts as $account) { // Set sessionAccount $relSessionAccount->addLink($session->sessionAtom, $account, false, 'OAuthLoginExtension'); // Timestamps $ts = new Atom(date(DATE_ISO8601), $conceptDateTime); $relAccMostRecentLogin->addLink($account, $ts, false, 'OAuthLoginExtension'); $relAccLoginTimestamps->addLink($account, $ts, false, 'OAuthLoginExtension'); } $db->closeTransaction('Login successfull', true); }
function OverwritePopulation($rArray, $relationName, $conceptName) { try { $database = Database::singleton(); $concept = Concept::getConceptByLabel($conceptName); $relation = Relation::getRelation($relationName, $concept, $concept); $relationTable = $relation->getMysqlTable(); $srcCol = $relationTable->srcCol(); $tgtCol = $relationTable->tgtCol(); $query = "DELETE FROM `{$relationTable->name}`"; // Do not use TRUNCATE statement, this causes an implicit commit $database->Exe($query); foreach ($rArray as $src => $tgtArray) { foreach ($tgtArray as $tgt => $bool) { if ($bool) { $query = "INSERT INTO `{$relationTable->name}` (`{$srcCol->name}`, `{$tgtCol->name}`) VALUES ('{$src}','{$tgt}')"; $database->Exe($query); } } } } catch (Exception $e) { throw new Exception('OverwritePopulation: ' . $e->getMessage(), 500); } }
/** * Remove all occurrences of $atom in the database (all concept tables and all relation tables) * In tables where the atom may not be null, the entire row is removed. * TODO: If all relation fields in a wide table are null, the entire row could be deleted, but this doesn't happen now. As a result, relation queries may return some nulls, but these are filtered out anyway. * @param \Ampersand\Core\Atom $atom * @return void */ function deleteAtom($atom) { $this->logger->debug("deleteAtom({$atom->__toString()})"); // This function is under control of transaction check! if (!isset($this->transaction)) { $this->startTransaction(); } $concept = $atom->concept; // Delete atom from concept table $conceptTable = $concept->getConceptTableInfo(); $query = "DELETE FROM `{$conceptTable->name}` WHERE `{$conceptTable->getFirstCol()->name}` = '{$atom->idEsc}' LIMIT 1"; $this->Exe($query); // Check if query resulted in an affected row $this->checkForAffectedRows(); $this->addAffectedConcept($concept); // add concept to affected concepts. Needed for conjunct evaluation. // Delete atom from relation tables where atom is mentioned as src or tgt atom foreach (Relation::getAllRelations() as $relation) { $tableName = $relation->getMysqlTable()->name; $cols = array(); if ($relation->srcConcept->inSameClassificationTree($concept)) { $cols[] = $relation->getMysqlTable()->srcCol(); } if ($relation->tgtConcept->inSameClassificationTree($concept)) { $cols[] = $relation->getMysqlTable()->tgtCol(); } foreach ($cols as $col) { // If n-n table, remove row if (is_null($relation->getMysqlTable()->tableOf)) { $query = "DELETE FROM `{$tableName}` WHERE `{$col->name}` = '{$atom->idEsc}'"; } elseif ($col->null) { $query = "UPDATE `{$tableName}` SET `{$col->name}` = NULL WHERE `{$col->name}` = '{$atom->idEsc}'"; } else { $query = "DELETE FROM `{$tableName}` WHERE `{$col->name}` = '{$atom->idEsc}'"; } $this->Exe($query); $this->addAffectedRelations($relation); } } $this->logger->debug("Atom '{$atom->__toString()}' (and all related links) deleted in database"); Hooks::callHooks('postDatabaseDeleteAtom', get_defined_vars()); }
function DelPair($relationName, $srcConceptName, $srcAtom, $tgtConceptName, $tgtAtom) { Logger::getLogger('EXECENGINE')->info("DelPair({$relationName},{$srcConceptName},{$srcAtom},{$tgtConceptName},{$tgtAtom})"); if (func_num_args() != 5) { throw new Exception("Wrong number of arguments supplied for function DelPair(): " . func_num_args() . " arguments", 500); } try { // Check if relation signature exists: $relationName[$srcConceptName*$tgtConceptName] $srcConcept = Concept::getConceptByLabel($srcConceptName); $tgtConcept = Concept::getConceptByLabel($tgtConceptName); $relation = Relation::getRelation($relationName, $srcConcept, $tgtConcept); if ($srcAtom == "NULL" or $tgtAtom == "NULL") { throw new Exception("Use of keyword NULL is deprecated, use '_NEW'", 500); } // if either srcAtomIdStr or tgtAtom is not provided by the pairview function (i.e. value set to '_NULL'): skip the insPair if ($srcAtom == '_NULL' or $tgtAtom == '_NULL') { Logger::getLogger('EXECENGINE')->debug("DelPair ignored because src and/or tgt atom is _NULL"); return; } $srcAtoms = explode('_AND', $srcAtom); $tgtAtoms = explode('_AND', $tgtAtom); if (count($srcAtoms) > 1) { throw new Exception('DelPair function call has more than one src atom', 501); } // 501: Not implemented if (count($tgtAtoms) > 1) { throw new Exception('DelPair function call has more than one tgt atom', 501); } // 501: Not implemented foreach ($srcAtoms as $a) { $src = new Atom($a, $srcConcept); foreach ($tgtAtoms as $b) { $tgt = new Atom($b, $tgtConcept); $relation->deleteLink($src, $tgt, false, 'ExecEngine'); } } Logger::getLogger('EXECENGINE')->debug("Tuple ('{$srcAtom}', '{$tgtAtom}') deleted from '{$relation->__toString()}'"); } catch (Exception $e) { Logger::getUserLogger()->error('DelPair: ' . $e->getMessage()); } }