Пример #1
0
 private static function pushNotification($userKey, $message, $title = null, $url = null, $urltitle = null)
 {
     Logger::getLogger('MESSAGING')->debug('Pushover[pushNotification' . ']; $userKey=[' . $userKey . ']; $message=[' . $message . ']; $title=[' . $title . ']; $url=[' . $url . ']; $urltitle=[' . $urltitle . ']');
     $notification = new Pushover();
     $token = Config::get('applicationToken', 'msg_pushover');
     if (is_null($token)) {
         throw new Exception("Pushover - Application token not specified", 500);
     }
     if (is_null($userKey)) {
         throw new Exception("Pushover - User key not specified", 500);
     }
     $notification->setToken($token);
     $notification->setUser($userKey);
     $notification->setMessage($message);
     if (!is_null($title)) {
         $notification->setTitle($title);
     }
     $notification->setHtml(1);
     $notification->setUrl($url);
     $notification->setUrlTitle($urltitle);
     if (!$notification->send()) {
         Logger::getUserLogger()->error("Pushover - Error in sending a notification to '{$userKey}'");
     } else {
         Logger::getUserLogger()->notice("Pushover message sent.");
     }
 }
Пример #2
0
 /**
  * Constructor of Session class
  * private to prevent any outside instantiation of this object
  */
 private function __construct()
 {
     $this->logger = Logger::getLogger('FW');
     $this->database = Database::singleton();
     $conceptSession = Concept::getConceptByLabel('SESSION');
     // Also checks if 'SESSION' is defined as concept in Ampersand script
     $this->id = session_id();
     $this->sessionAtom = new Atom($this->id, $conceptSession);
     $this->logger->debug("Session id: {$this->id}");
     // Remove expired Ampersand sessions from __SessionTimeout__ and all concept tables and relations where it appears.
     $expiredSessionsAtoms = array_column((array) $this->database->Exe("SELECT SESSION FROM `__SessionTimeout__` WHERE `lastAccess` < " . (time() - Config::get('sessionExpirationTime'))), 'SESSION');
     foreach ($expiredSessionsAtoms as $expiredSessionAtom) {
         if ($expiredSessionAtom == $this->id) {
             // Notify user that session is expired when login functionality is enabled
             if (Config::get('loginEnabled')) {
                 Logger::getUserLogger()->warning("Your session has expired, please login again");
             }
             // 440 Login Timeout -> is redirected by frontend to login page
         }
         $this->destroyAmpersandSession($expiredSessionAtom);
     }
     // Create a new Ampersand session atom if not yet in SESSION table (browser started a new session or Ampersand session was expired)
     $sessionAtom = new Atom($this->id, $conceptSession);
     if (!$sessionAtom->atomExists()) {
         $sessionAtom->addAtom();
         $this->database->commitTransaction();
         //TODO: ook door Database->closeTransaction() laten doen, maar die verwijst terug naar Session class voor de checkrules. Oneindige loop
     }
     $this->database->Exe("INSERT INTO `__SessionTimeout__` (`SESSION`,`lastAccess`) VALUES ('" . $this->id . "', '" . time() . "') ON DUPLICATE KEY UPDATE `lastAccess` = '" . time() . "'");
     // Add public interfaces
     $this->accessibleInterfaces = InterfaceObject::getPublicInterfaces();
 }
Пример #3
0
 /**
  * Conjunct constructor
  * Private function to prevent outside instantiation of conjuncts. Use Conjunct::getConjunct($conjId)
  *
  * @param array $conjDef
  */
 private function __construct($conjDef)
 {
     $this->logger = Logger::getLogger('FW');
     $this->id = $conjDef['id'];
     $this->query = $conjDef['violationsSQL'];
     $this->invRuleNames = (array) $conjDef['invariantRuleNames'];
     $this->sigRuleNames = (array) $conjDef['signalRuleNames'];
 }
Пример #4
0
 public static function addHook($hookpoint, $hook)
 {
     self::$hooks[$hookpoint][] = $hook;
     if ($hook['class']) {
         $log = $hook['class'] . '::';
     }
     $log .= $hook['function'] . '(';
     $log .= implode(', ', $hook['params']) . ')';
     Logger::getLogger('HOOKS')->debug("Hook '{$log}' added to '{$hookpoint}'");
 }
Пример #5
0
 private static function pushNotification($userKey, $message, $title = null, $url = null, $urltitle = null)
 {
     Logger::getLogger('MESSAGING')->debug('Pushalot - $userKey=[' . $userKey . ']; $message=[' . $message . ']; $title=[' . $title . ']; $url=[' . $url . ']; $urltitle=[' . $urltitle . ']');
     if (is_null($userKey)) {
         throw new Exception("Pushalot - User/API key not specified", 500);
     }
     $notification = new Pushalot($userKey);
     //$pushalot->setProxy('http://localhost:12345','user:pass');
     $success = $notification->sendMessage(array('Title' => $title, 'Body' => $message, 'IsImportant' => true, 'IsSilent' => false, 'Image' => 'http://wiki.tarski.nl/skins/common/images/AmpersandLogo.png', 'Source' => 'Ampersand prototype'));
     if (!$success) {
         Logger::getUserLogger()->error("Pushalot error '{$notification->getError}()' sending notification to '{$userKey}'");
     } else {
         Logger::getUserLogger()->notice("Pushalot message sent.");
     }
 }
Пример #6
0
function TransitiveClosure($r, $C, $rCopy, $rPlus)
{
    if (func_num_args() != 4) {
        throw new Exception("Wrong number of arguments supplied for function TransitiveClosure(): " . func_num_args() . " arguments", 500);
    }
    Logger::getLogger('EXECENGINE')->debug("Exeucte TransitiveClosure({$r},{$C},{$rCopy},{$rPlus})");
    $warshallRunCount = $GLOBALS['ext']['ExecEngine']['functions']['warshall']['runCount'];
    $execEngineRunCount = ExecEngine::$runCount;
    if ($GLOBALS['ext']['ExecEngine']['functions']['warshall']['warshallRuleChecked'][$r]) {
        if ($warshallRunCount == $execEngineRunCount) {
            Logger::getLogger('EXECENGINE')->debug("Skipping TransitiveClosure({$r},{$C},{$rCopy},{$rPlus})");
            return;
            // this is the case if we have executed this function already in this transaction
        }
    }
    $GLOBALS['ext']['ExecEngine']['functions']['warshall']['warshallRuleChecked'][$r] = true;
    $GLOBALS['ext']['ExecEngine']['functions']['warshall']['runCount'] = ExecEngine::$runCount;
    // Compute transitive closure following Warshall's algorithm
    $closure = RetrievePopulation($r, $C);
    // get adjacency matrix
    OverwritePopulation($closure, $rCopy, $C);
    // store it in the 'rCopy' relation
    // Get all unique atoms from this population
    $atoms = array_keys($closure);
    // 'Src' (left) atoms of pairs in $closure
    foreach ($closure as $tgtAtomsList) {
        // Loop to add 'Tgt' atoms that not yet exist
        $tgtAtoms = array_keys($tgtAtomsList);
        foreach ($tgtAtoms as $tgtAtom) {
            if (!in_array($tgtAtom, $atoms)) {
                $atoms[] = $tgtAtom;
            }
        }
    }
    foreach ($atoms as $k) {
        foreach ($atoms as $i) {
            if ($closure[$i][$k]) {
                foreach ($atoms as $j) {
                    $closure[$i][$j] = $closure[$i][$j] || $closure[$k][$j];
                }
            }
        }
    }
    OverwritePopulation($closure, $rPlus, $C);
}
Пример #7
0
function RerunExecEngine($logText = 'run ExecEngine again after completion')
{
    Logger::getLogger('EXECENGINE')->debug("Rerun: {$logText}");
    ExecEngine::$doRun = true;
    return true;
}
Пример #8
0
    }
}
NewResponse::addResponseCode(440, "Login Timeout");
// Create and configure Slim app (version 2.x)
$app = new \Slim\Slim(array('debug' => Config::get('debugMode')));
$app->add(new \Slim\Middleware\ContentTypes());
$app->response->headers->set('Content-Type', 'application/json');
// Error handler
$app->error(function (Exception $e) use($app) {
    $app->response->setStatus($e->getCode());
    try {
        Logger::getLogger("API")->error($e->getMessage());
        $notifications = Notifications::getAll();
        print json_encode(array('error' => $e->getCode(), 'msg' => $e->getMessage(), 'notifications' => $notifications));
    } catch (Exception $b) {
        Logger::getLogger("API")->error($b->getMessage());
        print json_encode(array('error' => $b->getCode(), 'msg' => $b->getMessage(), 'notifications' => array()));
    }
});
// Not found handler
$app->notFound(function () use($app) {
    $app->response->setStatus(404);
    print json_encode(array('error' => 404, 'msg' => "API call not found: {$app->request->getMethod()} {$app->request->getUrl()}{$app->request->getPath()}"));
});
include __DIR__ . '/resources.php';
// API calls starting with '/resources/'
include __DIR__ . '/admin.php';
// API calls starting with '/admin/'
include __DIR__ . '/sessions.php';
// API calls starting with '/sessions/'
include __DIR__ . '/interfaces.php';
Пример #9
0
 /**
  * Rule constructor
  * Private function to prevent outside instantiation. Use Rule::getRule($ruleName)
  *
  * @param array $ruleDef
  * @param boolean $type
  */
 private function __construct($ruleDef, $type = null)
 {
     $this->logger = Logger::getLogger('FW');
     $this->id = $ruleDef['name'];
     $this->origin = $ruleDef['origin'];
     $this->ruleAdl = $ruleDef['ruleAdl'];
     $this->srcConcept = Concept::getConcept($ruleDef['srcConceptId']);
     $this->tgtConcept = Concept::getConcept($ruleDef['tgtConceptId']);
     $this->meaning = $ruleDef['meaning'];
     $this->message = $ruleDef['message'];
     // Conjuncts
     foreach ($ruleDef['conjunctIds'] as $conjId) {
         $this->conjuncts[] = Conjunct::getConjunct($conjId);
     }
     $this->violationSegments = (array) $ruleDef['pairView'];
     switch ($type) {
         case 'sig':
             $this->isSignal = true;
             break;
         case 'inv':
             $this->isInvariant = true;
             break;
         case null:
             break;
         default:
             throw new Exception("Unknown/unsupported rule type. Allowed types are signal or invariant", 500);
     }
 }
Пример #10
0
 /**
  * Constructor
  */
 function __construct()
 {
     $this->logger = Logger::getLogger('EXCELIMPORT');
 }
Пример #11
0
 /**
  * InterfaceObject constructor
  * @param array $ifcDef Interface object definition as provided by Ampersand generator
  * @param string $pathEntry
  * @param boolean $rootIfc Specifies if this interface object is a toplevel interface (true) or subinterface (false)
  */
 public function __construct($ifcDef, $pathEntry = null, $rootIfc = false)
 {
     $this->database = Database::singleton();
     $this->logger = Logger::getLogger('FW');
     $this->isRoot = $rootIfc;
     // Set attributes from $ifcDef
     $this->id = $ifcDef['id'];
     $this->label = $ifcDef['label'];
     $this->view = is_null($ifcDef['viewId']) ? null : View::getView($ifcDef['viewId']);
     $this->path = is_null($pathEntry) ? $this->id : "{$pathEntry}/{$this->id}";
     // Information about the (editable) relation if applicable
     $this->relation = is_null($ifcDef['relation']) ? null : Relation::getRelation($ifcDef['relation']);
     $this->relationIsFlipped = $ifcDef['relationIsFlipped'];
     // Interface expression information
     $this->srcConcept = Concept::getConcept($ifcDef['expr']['srcConceptId']);
     $this->tgtConcept = Concept::getConcept($ifcDef['expr']['tgtConceptId']);
     $this->isUni = $ifcDef['expr']['isUni'];
     $this->isTot = $ifcDef['expr']['isTot'];
     $this->isIdent = $ifcDef['expr']['isIdent'];
     $this->query = $ifcDef['expr']['query'];
     // CRUD rights
     $this->crudC = $ifcDef['crud']['create'];
     $this->crudR = $ifcDef['crud']['read'];
     $this->crudU = $ifcDef['crud']['update'];
     $this->crudD = $ifcDef['crud']['delete'];
     if ($this->crudU && $this->tgtConcept->isObject) {
         $this->editableConcepts[] = $this->tgtConcept;
     }
     // Interface expression must equal (editable) relation when crudU is specified
     if ($this->crudU && is_null($this->relation)) {
         $this->logger->warning("Update rights (crUd) specified while interface expression is not an editable relation for (sub)interface: {$this->path}");
     }
     // Check for unsupported patchReplace functionality due to missing 'old value'. Related with issue #318
     if (!is_null($this->relation) && $this->crudU && !$this->tgtConcept->isObject && $this->isUni) {
         // Only applies to editable relations
         // Only applies to crudU, because issue is with patchReplace, not with add/remove
         // Only applies to scalar, because objects don't use patchReplace, but Remove and Add
         // Only if interface expression (not! the relation) is univalent, because else a add/remove option is used in the UI
         if (!$this->relationIsFlipped && $this->relation->getMysqlTable()->tableOf == 'tgt' || $this->relationIsFlipped && $this->relation->getMysqlTable()->tableOf == 'src') {
             $this->logger->warning("Unsupported edit functionality due to combination of factors for (sub)interface: '{$this->path}' - {$this->relation->__toString()}" . ($this->relationIsFlipped ? '~' : '') . " administrated in table of '{$this->relation->getMysqlTable()->tableOf}'");
         }
     }
     // Subinterfacing
     if (!is_null($ifcDef['subinterfaces'])) {
         // Subinterfacing is not supported/possible for tgt concepts with a scalar representation type (i.e. non-objects)
         if (!$this->tgtConcept->isObject) {
             throw new Exception("Subinterfacing is not supported for concepts with a scalar representation type (i.e. non-objects). (Sub)Interface '{$this->path}' with target {$this->tgtConcept->__toString()} (type:{$this->tgtConcept->type}) has subinterfaces specified", 501);
         }
         // Reference to top level interface
         $this->refInterfaceId = $ifcDef['subinterfaces']['refSubInterfaceId'];
         $this->isLinkTo = $ifcDef['subinterfaces']['refIsLinTo'];
         // Inline subinterface definitions
         foreach ((array) $ifcDef['subinterfaces']['ifcObjects'] as $subIfcDef) {
             $ifc = new InterfaceObject($subIfcDef, $this->path);
             $this->subInterfaces[$ifc->id] = $ifc;
             $this->editableConcepts = array_merge($this->editableConcepts, $ifc->editableConcepts);
         }
     }
 }
Пример #12
0
 /**
  * Concept constructor
  * Private function to prevent outside instantiation of concepts. Use Concept::getConcept($conceptName)
  * 
  * @param array $conceptDef
  */
 private function __construct($conceptDef)
 {
     $this->database = Database::singleton();
     $this->logger = Logger::getLogger('FW');
     $this->def = $conceptDef;
     $this->name = $conceptDef['id'];
     $this->label = $conceptDef['label'];
     $this->type = $conceptDef['type'];
     $this->isObject = $this->type == "OBJECT" ? true : false;
     $this->affectedConjunctIds = (array) $conceptDef['affectedConjuncts'];
     foreach ($this->affectedConjunctIds as $conjId) {
         $conj = Conjunct::getConjunct($conjId);
         if ($conj->isSigConj()) {
             $this->affectedSigConjuncts[] = $conj;
         }
         if ($conj->isInvConj()) {
             $this->affectedInvConjuncts[] = $conj;
         }
         // if (!$conj->isSigConj() && !$conj->isInvConj()) $this->logger->warning("Affected conjunct '{$conj->id}' (specified for concept '[{$this->name}]') is not part of an invariant or signal rule");
     }
     $this->specializations = (array) $conceptDef['specializations'];
     $this->generalizations = (array) $conceptDef['generalizations'];
     $this->interfaceIds = (array) $conceptDef['interfaces'];
     $this->largestConceptId = $conceptDef['largestConcept'];
     if (!is_null($conceptDef['defaultViewId'])) {
         $this->defaultView = View::getView($conceptDef['defaultViewId']);
     }
     $this->mysqlConceptTable = new DatabaseTable($conceptDef['conceptTable']['name']);
     foreach ($conceptDef['conceptTable']['cols'] as $colName) {
         $this->mysqlConceptTable->addCol(new DatabaseTableCol($colName));
     }
 }
Пример #13
0
 private static function pushNotification($SMSAddr, $message, $title = null, $url = null, $urltitle = null)
 {
     Logger::getLogger('MESSAGING')->debug('UNTESTED !!! SMS[pushNotification' . ']; $SMSAddr=[' . $SMSAddr . ']; $message=[' . $message . ']; $title=[' . $title . ']; $url=[' . $url . ']; $urltitle=[' . $urltitle . ']');
     /* Config params for SendSMS function of ExecEngine (using MessageBird.com)
      * Set the sender, could be a number (16 numbers) or letters (11 characters)
      * 
      */
     // Copy the following line to localSettings.php and provide settings
     // Config::set('sendSMSConfig', 'execEngine', array('username' => '', 'password' => '', 'sender' => ''));
     $config = Config::get('sendSMSConfig', 'msg_SMS');
     $username = $config['username'];
     $password = $config['password'];
     $sender = $config['sender'];
     Logger::getLogger('MESSAGING')->debug('Username = '******'31600000000');
     // Set an reference, optional
     // $sms->setReference('123456789');
     // Set a schedule date-time, optional
     // $sms->setTimestamp('2014-01-01 10:02');
     // Replace non GSM-7 characters by appropriate valid GSM-7 characters
     // $sms->setReplacechars(false);
     // If you want a dlr notification of the message send to another url then that you have set on the web site, you can use this parameter. Don't forget to set a reference!
     // $sms->setDlrUrl('http://www.example.com/dlr_url.php');
     // If $test is TRUE, then the message is not actually sent or scheduled, and there will be no credits deducted.
     Logger::getLogger('MESSAGING')->debug("SMS testing is set to TRUE (messages are not actually sent)");
     $sms->setTest(true);
     // Send the message to the destination(s)
     $sms->sendSms($message);
     if ($sms->getResponseCode() == "01") {
         Logger::getUserLogger()->notice("SMS message sent.");
     } else {
         Logger::getUserLogger()->error('SMS error: ' . $sms->getResponseMessage());
     }
     Logger::getLogger('MESSAGING')->debug("SMS Response: " . $sms->getResponseMessage());
     Logger::getLogger('MESSAGING')->debug("SMS Balance: " . $sms->getCreditBalance());
 }
Пример #14
0
 public function __construct()
 {
     $this->logger = Logger::getLogger('FW');
     $this->logger->debug("## BUILD ANGULAR APP ##################################################");
     $this->buildHtml();
 }
Пример #15
0
 /**
  * Relation constructor
  * Private function to prevent outside instantiation of Relations. Use Relation::getRelation($relationSignature)
  *
  * @param array $relationDef
  */
 public function __construct($relationDef)
 {
     $this->db = Database::singleton();
     $this->logger = Logger::getLogger('FW');
     $this->name = $relationDef['name'];
     $this->srcConcept = Concept::getConcept($relationDef['srcConceptId']);
     $this->tgtConcept = Concept::getConcept($relationDef['tgtConceptId']);
     $this->signature = $relationDef['signature'];
     $this->isUni = $relationDef['uni'];
     $this->isTot = $relationDef['tot'];
     $this->isInj = $relationDef['inj'];
     $this->isSur = $relationDef['sur'];
     $this->isProp = $relationDef['prop'];
     foreach ((array) $relationDef['affectedConjuncts'] as $conjId) {
         $conj = Conjunct::getConjunct($conjId);
         $this->affectedConjuncts[] = $conj;
         if ($conj->isSigConj()) {
             $this->affectedSigConjuncts[] = $conj;
         }
         if ($conj->isInvConj()) {
             $this->affectedInvConjuncts[] = $conj;
         }
         // if (!$conj->isSigConj() && !$conj->isInvConj()) $this->logger->warning("Affected conjunct '{$conj->id}' (specified for relation '{$this->__toString()}') is not part of an invariant or signal rule");
     }
     // Specify mysql table information
     $this->mysqlTable = new RelationTable($relationDef['mysqlTable']['name'], $relationDef['mysqlTable']['tableOf']);
     $srcCol = $relationDef['mysqlTable']['srcCol'];
     $tgtCol = $relationDef['mysqlTable']['tgtCol'];
     $this->mysqlTable->addSrcCol(new DatabaseTableCol($srcCol['name'], $srcCol['null'], $srcCol['unique']));
     $this->mysqlTable->addTgtCol(new DatabaseTableCol($tgtCol['name'], $tgtCol['null'], $tgtCol['unique']));
 }
Пример #16
0
 private static function pushNotification($emailAddr, $message, $title = null, $url = null, $urltitle = null)
 {
     Logger::getLogger('MESSAGING')->debug('Email[pushNotification' . ']; $emailAddr=[' . $emailAddr . ']; $message=[' . $message . ']; $title=[' . $title . ']; $url=[' . $url . ']; $urltitle=[' . $urltitle . ']');
     // adapted from http://phpmailer.worxware.com/?pg=examplebgmail
     $config = Config::get('sendEmailConfig', 'msg_email');
     $from = $config['from'];
     $username = $config['username'];
     $password = $config['password'];
     Logger::getLogger('MESSAGING')->debug('Email.php - Username = '******'smtp.gmail.com';
     // Specify main and backup server
     $mail->SMTPSecure = 'ssl';
     // Enable encryption, 'ssl' also accepted
     $mail->Port = 465;
     $mail->SMTPAuth = true;
     // Enable SMTP authentication
     $mail->Username = $username;
     // SMTP username (for GMAIL)
     $mail->Password = $password;
     // SMTP password
     $mail->From = $from;
     $mail->FromName = 'Ampersand Prototype';
     $mail->AddAddress($emailAddr);
     // Add a recipient, e.g. $to = '*****@*****.**', 'Rieks Joosten'
     $mail->Subject = $title;
     //      $message = $message . 'optional URL';
     if ($url != '_NULL' && $url != '') {
         $mail->IsHTML(true);
         // make sure we send in HTML
         if ($urltitle != '_NULL' && $urltitle != '') {
             $message = '<p>' . $message . '</p><p><a href=' . $url . '>' . $urltitle . '</a></p>';
         } else {
             $message = $message . '<a' . $urltitle . '</a>';
         }
         Logger::getLogger('MESSAGING')->debug('Email message refactored to: [' . $message . ']');
     }
     $mail->Body = $message;
     $mail->WordWrap = 50;
     // Set word wrap to 50 characters
     if (!$mail->Send()) {
         Logger::getUserLogger()->error('Mailer Error: ' . $mail->ErrorInfo);
     } else {
         Logger::getUserLogger()->notice("Email message sent.");
     }
 }
Пример #17
0
function LogViolation($srcAtom, $tgtAtom)
{
    Logger::getLogger('EXECENGINE')->debug("Violation: ({$srcAtom},{$tgtAtom})");
}
Пример #18
0
function ClearConcept($concept, $atom)
{
    Logger::getLogger('EXECENGINE')->info("ClearConcept({$concept},{$atom})");
    if (func_num_args() != 2) {
        throw new Exception("Wrong number of arguments supplied for function ClearConcept(): " . func_num_args() . " arguments", 500);
    }
    try {
        $database = Database::singleton();
        $atom = new Atom($atom, Concept::getConceptByLabel($concept));
        $database->atomClearConcept($atom);
        Logger::getLogger('EXECENGINE')->debug("Atom '{$atom->__toString()}' removed as member from concept '{$concept}'");
    } catch (Exception $e) {
        Logger::getUserLogger()->error('ClearConcept: ' . $e->getMessage());
    }
}
Пример #19
0
 /**
  * Function to create new database. Drops database (and loose all data) if already exists
  * @throws Exception
  * @return void
  */
 public static function createDB()
 {
     try {
         $logger = Logger::getLogger('DATABASE');
         $DB_host = Config::get('dbHost', 'mysqlDatabase');
         $DB_user = Config::get('dbUser', 'mysqlDatabase');
         $DB_pass = Config::get('dbPassword', 'mysqlDatabase');
         $DB_name = Config::get('dbName', 'mysqlDatabase');
         // Enable mysqli errors to be thrown as Exceptions
         mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
         $db_link = mysqli_init();
         // Connect to MYSQL database
         $logger->info("Connecting to host: '{$DB_host}'");
         $db_link->real_connect($DB_host, $DB_user, $DB_pass);
         // Set sql_mode to ANSI
         $logger->info("Setting session sql_mode to 'ANSI,TRADITIONAL'");
         $db_link->query("SET SESSION sql_mode = 'ANSI,TRADITIONAL'");
         // Drop database
         $logger->info("Drop database if exists: '{$DB_name}'");
         $db_link->query("DROP DATABASE IF EXISTS {$DB_name}");
         // Create new database
         $logger->info("Create new database: '{$DB_name}'");
         $db_link->query("CREATE DATABASE {$DB_name} DEFAULT CHARACTER SET UTF8");
     } catch (Exception $e) {
         // Convert mysqli_sql_exceptions into 500 errors
         throw new Exception($e->getMessage(), 500);
     }
 }
Пример #20
0
 /**
  * 
  * @return Violation[]
  */
 public static function getSignalViolationsFromDB()
 {
     $logger = Logger::getLogger('FW');
     $session = Session::singleton();
     $dbsignalTableName = Config::get('dbsignalTableName', 'mysqlDatabase');
     $conjuncts = array();
     $conjunctRuleMap = array();
     foreach ($session->rulesToMaintain as $rule) {
         foreach ($rule->conjuncts as $conjunct) {
             $conjunctRuleMap[$conjunct->id][] = $rule;
         }
         $conjuncts = array_merge($conjuncts, $rule->conjuncts);
     }
     $conjuncts = array_unique($conjuncts);
     // remove duplicates
     $violations = array();
     if (count($conjuncts) > 0) {
         $q = implode(',', array_map(function ($conj) {
             return "'{$conj->id}'";
         }, $conjuncts));
         // returns string "<conjId1>,<conjId2>,<etc>"
         $query = "SELECT * FROM `{$dbsignalTableName}` WHERE `conjId` IN ({$q})";
         $result = $session->database->Exe($query);
         // array(array('conjId' => '<conjId>', 'src' => '<srcAtomId>', 'tgt' => '<tgtAtomId>'))
         foreach ($result as $row) {
             foreach ($conjunctRuleMap[$row['conjId']] as $rule) {
                 $violations[] = new Violation($rule, $row['src'], $row['tgt']);
             }
         }
     } else {
         $logger->debug("No conjuncts to check (it can be that this role does not maintain any rule)");
     }
     return $violations;
 }
Пример #21
0
 /**
  * 
  * @param Rule\Violation $violation
  */
 public static function addSignal($violation)
 {
     $ruleHash = hash('md5', $violation->rule->id);
     self::$signals[$ruleHash]['ruleMessage'] = $violation->rule->getViolationMessage();
     self::$signals[$ruleHash]['tuples'][] = array('violationMessage' => $violationMessage = $violation->getViolationMessage(), 'links' => $violation->getLinks());
     Logger::getLogger('SIGNAL')->info("'{$violationMessage}' RULE: '{$violation->rule->__toString()}'");
 }
Пример #22
0
 /**
  * Atom constructor
  * @param string $atomId
  * @param Concept $concept
  * @param InterfaceObject $ifc
  * @param array $qData the row data (from database query) from which this atom is created
  * @return void
  */
 public function __construct($atomId, Concept $concept, InterfaceObject $ifc = null, array $qData = null)
 {
     $this->database = Database::singleton();
     $this->logger = Logger::getLogger('FW');
     $this->concept = $concept;
     $this->parentIfc = $ifc;
     $this->qData = $qData;
     $this->setId($atomId);
     // JSON-LD attributes
     $this->url = Config::get('serverURL') . Config::get('apiPath') . '/resource/' . $this->concept->name . '/' . $this->getJsonRepresentation();
 }
Пример #23
0
function datimeGT($gtRelation, $DateConcept, $srcAtom, $tgtAtom)
{
    Logger::getLogger('EXECENGINE')->debug("datimeGT({$gtRelation},{$DateConcept},{$srcAtom},{$tgtAtom})");
    if (($dt1 = strtotime($srcAtom)) === false) {
        Logger::getUserLogger()->error("datimeGT: Illegal date {$dt1} specified in srcAtom (3rd arg): {$srcAtom}");
    }
    if (($dt2 = strtotime($tgtAtom)) === false) {
        Logger::getUserLogger()->error("datimeGT: Illegal date {$dt2} specified in tgtAtom (4th arg): {$tgtAtom}");
    }
    if ($dt1 == $dt2) {
        return;
    }
    if ($dt1 > $dt2) {
        InsPair($gtRelation, $DateConcept, $srcAtom, $DateConcept, $tgtAtom);
    } else {
        InsPair($gtRelation, $DateConcept, $tgtAtom, $DateConcept, $srcAtom);
    }
}
Пример #24
0
 /**
  * 
  * @param Violation[] $violations
  * @throws Exception
  * @return void
  */
 public static function fixViolations($violations)
 {
     $logger = Logger::getLogger('EXECENGINE');
     $total = count($violations);
     foreach ($violations as $key => $violation) {
         $num = $key + 1;
         $logger->info("Fixing violation {$num}/{$total}: ({$violation->src},{$violation->tgt})");
         $violation = new ExecEngineViolation($violation->rule, $violation->src->id, $violation->tgt->id);
         $theMessage = $violation->getViolationMessage();
         // Determine actions/functions to be taken
         $functionsToBeCalled = explode('{EX}', $theMessage);
         // Execute actions/functions
         foreach ($functionsToBeCalled as $functionToBeCalled) {
             if (empty($functionToBeCalled)) {
                 continue;
             }
             // skips to the next iteration if $functionToBeCalled is empty. This is the case when violation text starts with delimiter {EX}
             // Determine delimiter
             if (substr($functionToBeCalled, 0, 2) == '_;') {
                 $delimiter = '_;';
                 $functionToBeCalled = substr($functionToBeCalled, 2);
             } else {
                 $delimiter = ';';
             }
             $params = explode($delimiter, $functionToBeCalled);
             // Split off variables
             //$params = array_map('trim', $params); // Trim all params // Commented out, because atoms can have spaces in them
             $params = array_map('phpArgumentInterpreter', $params);
             // Evaluate phpArguments, using phpArgumentInterpreter function
             $function = trim(array_shift($params));
             // First parameter is function name
             $classMethod = (array) explode('::', $function);
             if (function_exists($function) || method_exists($classMethod[0], $classMethod[1])) {
                 call_user_func_array($function, $params);
             } else {
                 throw new Exception("Function '{$function}' does not exists. Create function with {count({$params})} parameters", 500);
             }
         }
     }
 }