Exemplo n.º 1
0
 public function run()
 {
     //set_error_handler(array('\Slim\Slim', 'handleErrors'));
     //Fetch status, header, and body
     list($status, $headers, $body) = $this->response->finalize();
     // Serialize cookies (with optional encryption)
     \Slim\Http\Util::serializeCookies($headers, $this->response->cookies, $this->settings);
     //Send headers
     if (headers_sent() === false) {
         //Send status
         if (strpos(PHP_SAPI, 'cgi') === 0) {
             header(sprintf('Status: %s', \Slim\Http\Response::getMessageForCode($status)));
         } else {
             header(sprintf('HTTP/%s %s', Config::get('http.version'), \Slim\Http\Response::getMessageForCode($status)));
         }
         //Send headers
         foreach ($headers as $name => $value) {
             $hValues = explode("\n", $value);
             foreach ($hValues as $hVal) {
                 header("{$name}: {$hVal}", false);
             }
         }
     }
     //Send body, but only if it isn't a HEAD request
     if (!$this->request->isHead()) {
         echo $body;
     }
 }
Exemplo n.º 2
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.");
     }
 }
Exemplo n.º 3
0
 private static function getTwig()
 {
     if (!self::$twig) {
         Twig_Autoloader::register();
         $cache = Config::get('cache') ? __DIR__ . '/../../../../' . Config::get('cache') . '/' : false;
         $loader = new Twig_Loader_Filesystem(__DIR__ . '/../../../../' . Config::get('views') . '/');
         self::$twig = new Twig_Environment($loader, array('cache' => $cache, 'debug' => Config::get('debug')));
     }
     return self::$twig;
 }
Exemplo n.º 4
0
 public static function getTwig()
 {
     if (!self::$twig) {
         \Twig_Autoloader::register();
         $cache = Config::get('cache') ? Config::get('cache') . '/' : false;
         $loader = new \Twig_Loader_Filesystem(Config::get('views') . '/');
         $twig = new \Twig_Environment($loader, array('cache' => $cache, 'debug' => Config::get('debug')));
         // Add globals
         $twig->addGlobal('session', Session::getInstance());
         $twig->addGlobal('url', new URL());
         self::$twig = $twig;
     }
     return self::$twig;
 }
Exemplo n.º 5
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.");
     }
 }
Exemplo n.º 6
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());
 }
Exemplo n.º 7
0
 public static function pushNotificationOnCommit($userKeys, $message, $title = null, $url = null, $urltitle = null)
 {
     Logger::getLogger('MESSAGING')->debug('Pushalot[pushNotificationOnCommit' . ']; $userKeys=[' . $userKeys . ']; $message=[' . $message . ']; $title=[' . $title . ']; $url=[' . $url . ']; $urltitle=[' . $urltitle . ']');
     foreach ($userKeys as $userKey) {
         if (!is_null($userKey)) {
             self::$notifications[] = array('userKey' => $userKey, 'message' => $message, 'title' => $title, 'url' => $url, 'urltitle' => $urltitle);
         }
     }
     // Send same notification to users in 'alwaysNotifyUsers' config
     foreach ((array) Config::get('alwaysNotifyUsers', 'msg_pushalot') as $notifyUser) {
         if (!in_array($notifyUser, $userKeys)) {
             // prevent duplicate notifications
             if ($notifyUser != '') {
                 self::$notifications[] = array('userKey' => $notifyUser, 'message' => $message, 'title' => $title, 'url' => $url, 'urltitle' => $urltitle);
             }
             // Disregard a possibly empty setting from localSettings.php
         }
     }
 }
Exemplo n.º 8
0
 public static function run($allRules = false)
 {
     $database = Database::singleton();
     $logger = Logger::getLogger('EXECENGINE');
     $logger->info("ExecEngine run started");
     // Load the execEngine functions (security hazard :P)
     $files = getDirectoryList(__DIR__ . '/functions');
     foreach ($files as $file) {
         if (substr($file, -3) !== 'php') {
             continue;
         }
         require_once $path = __DIR__ . '/functions/' . $file;
         $logger->debug("Included file: {$path}");
     }
     self::$roleName = Config::get('execEngineRoleName', 'execEngine');
     try {
         $role = Role::getRoleByName(self::$roleName);
     } catch (Exception $e) {
         $logger->warning("ExecEngine extension included but role '" . self::$roleName . "' not used/defined in &-script.");
         self::$doRun = false;
         // prevent exec engine execution
     }
     $maxRunCount = Config::get('maxRunCount', 'execEngine');
     self::$runCount = 0;
     self::$autoRerun = Config::get('autoRerun', 'execEngine');
     // Get all rules that are maintained by the ExecEngine
     $rulesThatHaveViolations = array();
     while (self::$doRun) {
         self::$doRun = false;
         self::$runCount++;
         // Prevent infinite loop in ExecEngine reruns
         if (self::$runCount > $maxRunCount) {
             Logger::getUserLogger()->error('Maximum reruns exceeded for ExecEngine (rules with violations:' . implode(', ', $rulesThatHaveViolations) . ')');
             break;
         }
         $logger->notice("ExecEngine run #" . self::$runCount . " (auto rerun: " . var_export(self::$autoRerun, true) . ") for role '{$role->label}'");
         // Determine affected rules that must be checked by the exec engine
         $affectedConjuncts = RuleEngine::getAffectedConjuncts($database->getAffectedConcepts(), $database->getAffectedRelations(), 'sig');
         $affectedRules = array();
         foreach ($affectedConjuncts as $conjunct) {
             $affectedRules = array_merge($affectedRules, $conjunct->sigRuleNames);
         }
         // Check rules
         $rulesThatHaveViolations = array();
         foreach ($role->maintains() as $ruleName) {
             if (!in_array($ruleName, $affectedRules) && !$allRules) {
                 continue;
             }
             // skip this rule
             $rule = Rule::getRule($ruleName);
             $violations = $rule->getViolations(false);
             if (count($violations)) {
                 $rulesThatHaveViolations[] = $rule->id;
                 // Fix violations for every rule
                 $logger->notice("ExecEngine fixing " . count($violations) . " violations for rule '{$rule->id}'");
                 self::fixViolations($violations);
                 // Conjunct violations are not cached, because they are fixed by the ExecEngine
                 $logger->debug("Fixed " . count($violations) . " violations for rule '{$rule->__toString()}'");
                 // If $autoRerun, set $doRun to true because violations have been fixed (this may fire other execEngine rules)
                 if (self::$autoRerun) {
                     self::$doRun = true;
                 }
             }
         }
     }
     $logger->info("ExecEngine run completed");
 }
Exemplo n.º 9
0
 /**
  * Import all rule definitions from json file and create and save Rule objects
  * @return void
  */
 private static function setAllRules()
 {
     self::$allRules = array();
     // import json file
     $file = file_get_contents(Config::get('pathToGeneratedFiles') . 'rules.json');
     $allRuleDefs = (array) json_decode($file, true);
     // Signal rules
     foreach ($allRuleDefs['signals'] as $ruleDef) {
         $rule = new Rule($ruleDef, 'sig');
         self::$allRules[$rule->id] = $rule;
     }
     // Invariant rules
     foreach ($allRuleDefs['invariants'] as $ruleDef) {
         $rule = new Rule($ruleDef, 'inv');
         self::$allRules[$rule->id] = $rule;
     }
 }
Exemplo n.º 10
0
use Ampersand\Config;
use Ampersand\Log\Logger;
use Ampersand\Log\Notifications;
require_once __DIR__ . '/../../src/bootstrap.php';
// Code to add special http response codes that are not supported by Slim
class NewResponse extends \Slim\Http\Response
{
    public static function addResponseCode($code, $message)
    {
        parent::$messages[$code] = "{$code} {$message}";
    }
}
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
Exemplo n.º 11
0
use Exception;
use Ampersand\AngularApp;
use Ampersand\Core\Atom;
use Ampersand\Core\Concept;
use Ampersand\Config;
use Ampersand\Interfacing\InterfaceObject;
use Ampersand\Core\Relation;
use Ampersand\Log\Logger;
use PHPExcel_Cell;
use PHPExcel_Shared_Date;
use PHPExcel_IOFactory;
require_once __DIR__ . '/lib/Classes/PHPExcel.php';
// UI
AngularApp::addMenuItem('ext', 'extensions/ExcelImport/ui/views/MenuItem.html', function ($session) {
    $roles = Config::get('allowedRolesForExcelImport', 'excelImport');
    return !empty(array_intersect($session->getActiveRoles(), (array) $roles)) || is_null($roles);
});
AngularApp::addCSS('extensions/ExcelImport/ui/css/style.css');
AngularApp::addJS('extensions/ExcelImport/ui/js/ExcelImport.js');
// API
$GLOBALS['api']['files'][] = __DIR__ . DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . 'import.php';
// Config
Config::set('allowedMimeTypes', 'excelImport', array('application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/excel'));
class ExcelImport
{
    /**
     * 
     * @var string
     */
    public $file;
Exemplo n.º 12
0
<?php

use Ampersand\Session;
use Ampersand\Config;
use Ampersand\Log\Notifications;
use Ampersand\Core\Atom;
use Ampersand\Core\Concept;
use Ampersand\Extension\OAuthLogin\OAuthLoginController;
global $app;
// Path to API is 'api/v1/oauthlogin/login'
$app->get('/oauthlogin/login', function () use($app) {
    Session::singleton();
    $idps = array();
    $identityProviders = Config::get('identityProviders', 'OAuthLogin');
    if (is_null($identityProviders)) {
        throw new Exception("No identity providers specified for OAuthLogin extension", 500);
    }
    foreach ($identityProviders as $idpSettings) {
        $auth_url = array('auth_base' => $idpSettings['authBase'], 'arguments' => array('client_id' => $idpSettings['clientId'], 'response_type' => 'code', 'redirect_uri' => $idpSettings['redirectUrl'], 'scope' => $idpSettings['scope'], 'state' => $idpSettings['state']));
        $url = $auth_url['auth_base'] . '?' . http_build_query($auth_url['arguments']);
        $idps[] = array('name' => $idpSettings['name'], 'loginUrl' => $url, 'logo' => $idpSettings['logoUrl']);
    }
    // Return
    $result = array('identityProviders' => $idps, 'notifications' => Notifications::getAll());
    print json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
});
// Path to API is 'api/v1/oauthlogin/logout'
$app->get('/oauthlogin/logout', function () use($app) {
    $session = Session::singleton();
    $session->sessionAtom->deleteAtom();
    $session->database->closeTransaction('Logout successfull', true);
Exemplo n.º 13
0
 public static function callback($code, $idp)
 {
     $identityProviders = Config::get('identityProviders', 'OAuthLogin');
     if (empty($code)) {
         throw new Exception("Oops. Someting went wrong during login. Please try again", 401);
     }
     if (!isset($identityProviders[$idp])) {
         throw new Exception("Unknown identity provider", 500);
     }
     $client_id = $identityProviders[$idp]['clientId'];
     $client_secret = $identityProviders[$idp]['clientSecret'];
     $redirect_uri = $identityProviders[$idp]['redirectUrl'];
     $token_url = $identityProviders[$idp]['tokenUrl'];
     $api_url = $identityProviders[$idp]['apiUrl'];
     // instantiate authController
     $authController = new OAuthLoginController($client_id, $client_secret, $redirect_uri, $token_url);
     // request token
     if ($authController->requestToken($code)) {
         // request data
         if ($authController->requestData($api_url)) {
             // Get email here
             $email = null;
             switch ($idp) {
                 case 'linkedin':
                     // Linkedin provides primary emailaddress only. This is always a verified address.
                     $email = $authController->getData()->emailAddress;
                     break;
                 case 'google':
                     $email = $authController->getData()->email;
                     if (!$authController->getData()->verified_email) {
                         throw new Exception("Google emailaddress is not verified", 500);
                     }
                     break;
                 case 'github':
                     foreach ($authController->getData() as $data) {
                         if ($data->primary && $data->verified) {
                             $email = $data->email;
                         }
                     }
                     if (is_null($email)) {
                         throw new Exception("Github primary emailaddress is not verified", 500);
                     }
                     break;
                 default:
                     throw new Exception("Unknown identity provider", 500);
                     break;
             }
             $authController->login($email);
         }
     }
     header('Location: ' . Config::get('redirectAfterLogin', 'OAuthLogin'));
     exit;
 }
Exemplo n.º 14
0
 /**
  * Import all interface object definitions from json file and create and save InterfaceObject objects
  * @return void
  */
 private static function setAllInterfaces()
 {
     self::$allInterfaces = array();
     // import json file
     $file = file_get_contents(Config::get('pathToGeneratedFiles') . 'interfaces.json');
     $allInterfaceDefs = (array) json_decode($file, true);
     foreach ($allInterfaceDefs as $ifcDef) {
         $ifc = new InterfaceObject($ifcDef['ifcObject'], null, true);
         // Set additional information about this toplevel interface object
         $ifc->ifcRoleNames = $ifcDef['interfaceRoles'];
         self::$allInterfaces[$ifc->id] = $ifc;
     }
 }
Exemplo n.º 15
0
 /**
  * Determine is there is a loggedin user (account)
  * @return boolean
  */
 public function sessionUserLoggedIn()
 {
     if (!Config::get('loginEnabled')) {
         return false;
     } elseif ($this->getSessionAccount() !== false) {
         return true;
     } else {
         return false;
     }
 }
Exemplo n.º 16
0
 /**
  * Import all concept definitions from json file and create and save Concept objects
  * @return void
  */
 private static function setAllConcepts()
 {
     self::$allConcepts = array();
     // import json file
     $file = file_get_contents(Config::get('pathToGeneratedFiles') . 'concepts.json');
     $allConceptDefs = (array) json_decode($file, true);
     foreach ($allConceptDefs as $conceptDef) {
         self::$allConcepts[$conceptDef['id']] = new Concept($conceptDef);
     }
 }
Exemplo n.º 17
0
 public static function getDefaultSettings()
 {
     return array('switchShowSignals' => Config::get('defaultShowSignals', 'notifications'), 'switchShowInfos' => Config::get('defaultShowInfos', 'notifications'), 'switchShowSuccesses' => Config::get('defaultShowSuccesses', 'notifications'), 'switchAutoHideSuccesses' => Config::get('defaultAutoHideSuccesses', 'notifications'), 'switchShowErrors' => Config::get('defaultShowErrors', 'notifications'), 'switchShowWarnings' => Config::get('defaultShowWarnings', 'notifications'), 'switchShowInvariants' => Config::get('defaultShowInvariants', 'notifications'));
 }
Exemplo n.º 18
0
    Config::set('ignoreInvariantViolations', 'transactions', false);
    // for debugging can be set to true (transactions will be committed regardless off invariant violations)
    Config::set('interfaceAutoCommitChanges', 'transactions', true);
    // specifies whether changes in an interface are automatically commited when allowed (all invariants hold)
    Config::set('interfaceAutoSaveChanges', 'transactions', true);
    // specifies whether changes in interface are directly communicated (saved) to server
    Config::set('interfaceCacheGetCalls', 'transactions', false);
    // specifies whether GET calls should be cached by the frontend (e.g. angular) application
    // Default CRUD rights for interfaces
    Config::set('defaultCrudC', 'transactions', true);
    Config::set('defaultCrudR', 'transactions', true);
    Config::set('defaultCrudU', 'transactions', true);
    Config::set('defaultCrudD', 'transactions', true);
    // Default notification settings
    Config::set('defaultShowSignals', 'notifications', true);
    Config::set('defaultShowInfos', 'notifications', true);
    Config::set('defaultShowWarnings', 'notifications', true);
    Config::set('defaultShowSuccesses', 'notifications', true);
    Config::set('defaultAutoHideSuccesses', 'notifications', true);
    Config::set('defaultShowErrors', 'notifications', true);
    Config::set('defaultShowInvariants', 'notifications', true);
    // Navigation menu settings
    AngularApp::addMenuItem('refresh', 'app/views/menu/installer.html', function ($session) {
        return !Config::get('productionEnv');
    });
    AngularApp::addMenuItem('refresh', 'app/views/menu/checkAllRules.html', function ($session) {
        return !Config::get('productionEnv');
    });
} catch (Exception $e) {
    throw $e;
}
Exemplo n.º 19
0
 public function buildHtml()
 {
     $this->addHtmlLine("<!doctype html>");
     $this->addHtmlLine('<html ng-app="AmpersandApp">');
     $this->addHtmlLine('<head>');
     $this->addHtmlLine('<title>' . Config::get('contextName') . '</title>');
     // Meta tags
     $this->addHtmlLine('<meta name="viewport" content="width=device-width, initial-scale=1.0"/>');
     $this->addHtmlLine('<meta charset="UTF-8">');
     $this->addHtmlLine('<meta http-equiv="Expires" content="0"/>');
     $this->addHtmlLine('<meta http-equiv="Cache-Control" content="no-store"/>');
     // initSessionId
     $this->addHtmlLine('<script type="text/javascript">var initSessionId = \'' . session_id() . '\';</script>');
     // JQuery
     $this->addHtmlLine('<script src="app/lib/jquery/jquery-1.11.0.min.js"></script>');
     $this->addHtmlLine('<script src="app/lib/jquery/jquery-migrate-1.2.1.js"></script>');
     $this->addHtmlLine('<script src="app/lib/jquery/jquery-ui-1.10.4.custom.js"></script>');
     // Bootstrap (requires Jquery, loaded above)
     $this->addHtmlLine('<link href="app/lib/bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet" media="screen">');
     // load boostrap.css before app specific css files that overwrite bootstrap.css
     $this->addHtmlLine('<script src="app/lib/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>');
     /*
      ********** Angular *********************************
      *
      */
     $this->addHtmlLine('<script src="app/lib/angular/angular.min.js"></script>');
     $this->addHtmlLine('<script src="app/lib/angular/angular-resource.min.js"></script>');
     $this->addHtmlLine('<script src="app/lib/angular/angular-route.min.js"></script>');
     $this->addHtmlLine('<script src="app/lib/angular/angular-sanitize.min.js"></script>');
     /* Third party directives/libraries for angular */
     // angular-ui-switch
     $this->addHtmlLine('<script src="app/lib/angular/angular-ui-switch/angular-ui-switch-adapted.js"></script>');
     $this->addHtmlLine('<link href="app/lib/angular/angular-ui-switch/angular-ui-switch.css" rel="stylesheet" media="screen" type="text/css">');
     // angular-busy
     $this->addHtmlLine('<script src="app/lib/angular/angular-busy/angular-busy.min.js"></script>');
     $this->addHtmlLine('<link href="app/lib/angular/angular-busy/angular-busy.min.css" rel="stylesheet" media="screen" type="text/css">');
     // si-table
     $this->addHtmlLine('<script src="app/lib/angular/si-table/si-table.js"></script>');
     // angular-code-mirror
     $this->addHtmlLine('<script src="app/lib/angular/angular-code-mirror/angular-code-mirror.min.js"></script>');
     $this->addHtmlLine('<link href="app/lib/angular/angular-code-mirror/angular-code-mirror.css" rel="stylesheet" media="screen" type="text/css">');
     // ng-storage
     $this->addHtmlLine('<script src="app/lib/angular/angular-ng-storage/ngStorage.min.js"></script>');
     // angular-file-upload
     $this->addHtmlLine('<script src="app/lib/angular/angular-file-upload/angular-file-upload.min.js"></script>');
     // angular-grid
     $this->addHtmlLine('<script src="app/lib/angular/angular-grid/ag-grid.min.js"></script>');
     $this->addHtmlLine('<link href="app/lib/angular/angular-grid/ag-grid.min.css" rel="stylesheet" media="screen" type="text/css">');
     $this->addHtmlLine('<link href="app/lib/angular/angular-grid/theme-dark.min.css" rel="stylesheet" media="screen" type="text/css">');
     $this->addHtmlLine('<link href="app/lib/angular/angular-grid/theme-fresh.min.css" rel="stylesheet" media="screen" type="text/css">');
     // Restangular (with depency for lodash)
     $this->addHtmlLine('<script src="app/lib/restangular/restangular.min.js"></script>');
     $this->addHtmlLine('<script src="app/lib/restangular/lodash.min.js"></script>');
     // jquery UI & bootstrap in native AngularJS
     $this->addHtmlLine('<script src="app/lib/ui-bootstrap/ui-bootstrap-tpls-0.14.3.min.js"></script>');
     // datetimepicker
     $this->addHtmlLine('<script src="app/lib/ui-bootstrap/datetimepicker/datetimepicker.js"></script>');
     $this->addHtmlLine('<link href="app/lib/ui-bootstrap/datetimepicker/datetimepicker.css" rel="stylesheet" media="screen" type="text/css">');
     // markdown support
     $this->addHtmlLine('<script src="app/lib/marked/lib/marked.js"></script>');
     $this->addHtmlLine('<script src="app/lib/angular-marked/dist/angular-marked.js"></script>');
     /*
      ********** CSS *********************************
      *
      */
     // CSS files from app directory
     $files = getDirectoryList(Config::get('pathToAppFolder') . 'css');
     $cssFiles = array();
     foreach ((array) $files as $file) {
         if (substr($file, -3) !== 'css') {
             continue;
         }
         if ($file == 'ampersand.css') {
             array_unshift($cssFiles, 'app/css/' . $file);
         } else {
             $cssFiles[] = 'app/css/' . $file;
         }
     }
     // Add css files to html output
     foreach ($cssFiles as $file) {
         $this->addHtmlLine('<link href="' . $file . '" rel="stylesheet" media="screen" type="text/css">');
     }
     // Other css files (from extensions)
     foreach (AngularApp::$cssFiles as $file) {
         $this->addHtmlLine('<link href="' . $file . '" rel="stylesheet" media="screen" type="text/css">');
     }
     /*
      ********** App specific javascript ***************
      *
      */
     // AmpersandApp
     $this->addHtmlLine('<script src="app/AmpersandApp.js"></script>');
     $this->addHtmlLine('<script src="app/RouteProvider.js"></script>');
     // AngularApp controler files (both static and generated)
     $files = getDirectoryList(Config::get('pathToAppFolder') . 'controllers');
     foreach ((array) $files as $file) {
         if (substr($file, -2) !== 'js') {
             continue;
         }
         $this->addHtmlLine('<script src="app/controllers/' . $file . '"></script>');
     }
     // Javascript files
     $files = getDirectoryList(Config::get('pathToAppFolder') . 'js');
     foreach ((array) $files as $file) {
         if (substr($file, -2) !== 'js') {
             continue;
         }
         $this->addHtmlLine('<script src="app/js/' . $file . '"></script>');
     }
     // Add js files to html output
     foreach (AngularApp::$jsFiles as $file) {
         $this->addHtmlLine('<script src="' . $file . '"></script>');
     }
     $this->addHtmlLine('</head>');
     $this->addHtmlLine('<body>');
     $this->addHtmlLine(file_get_contents(Config::get('pathToAppFolder') . 'AmpersandApp.html'));
     $this->addHtmlLine('</body>');
     $this->addHtmlLine('</html>');
 }
Exemplo n.º 20
0
<?php

use Ampersand\Session;
use Ampersand\AngularApp;
use Ampersand\Log\Notifications;
use Ampersand\Config;
use Ampersand\Rule\RuleEngine;
global $app;
$app->get('/sessions/:sessionId/navbar', function ($sessionId) use($app) {
    $session = Session::singleton();
    $roleIds = $app->request->params('roleIds');
    $session->activateRoles($roleIds);
    foreach (RuleEngine::getSignalViolationsFromDB() as $violation) {
        Notifications::addSignal($violation);
    }
    $content = array('top' => AngularApp::getNavBarIfcs('top'), 'new' => AngularApp::getNavBarIfcs('new'), 'refreshMenu' => AngularApp::getMenuItems('refresh'), 'extMenu' => AngularApp::getMenuItems('ext'), 'roleMenu' => AngularApp::getMenuItems('role'), 'defaultSettings' => array('notifications' => Notifications::getDefaultSettings(), 'switchAutoCommit' => Config::get('interfaceAutoCommitChanges', 'transactions'), 'cacheGetCalls' => Config::get('interfaceCacheGetCalls', 'transactions'), 'switchAutoSave' => Config::get('interfaceAutoSaveChanges', 'transactions')), 'notifications' => Notifications::getAll(), 'session' => array('id' => $session->id, 'loggedIn' => $session->sessionUserLoggedIn()), 'sessionRoles' => array_values($session->getSessionRoles()), 'sessionVars' => $session->getSessionVars());
    print json_encode($content, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
});
$app->get('/sessions/:sessionId/notifications', function ($sessionId) use($app) {
    $session = Session::singleton();
    $roleIds = $app->request->params('roleIds');
    $session->activateRoles($roleIds);
    foreach (RuleEngine::getSignalViolationsFromDB() as $violation) {
        Notifications::addSignal($violation);
    }
    $content = Notifications::getAll();
    print json_encode($content, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
});
$app->delete('/sessions/:sessionId', function ($sessionId) use($app) {
    $session = Session::singleton();
    // Checks
Exemplo n.º 21
0
 /**
  * Import all role definitions from json file and create and save Role objects
  * @return void
  */
 private static function setAllRoles()
 {
     self::$allRoles = array();
     // import json file
     $file = file_get_contents(Config::get('pathToGeneratedFiles') . 'roles.json');
     $allRoleDefs = (array) json_decode($file, true);
     foreach ($allRoleDefs as $roleDef) {
         self::$allRoles[$roleDef['name']] = new Role($roleDef);
     }
 }
Exemplo n.º 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();
 }
Exemplo n.º 23
0
 /**
  * Check if insert/update/delete function resulted in updated record(s). If not, report warning (or throw exception) to indicate that something is going wrong
  * @throws Exception when no records are affected and application is not in production mode
  * @return void
  */
 private function checkForAffectedRows()
 {
     if ($this->db_link->affected_rows == 0) {
         if (Config::get('productionEnv')) {
             $this->logger->warning("Oops.. something went wrong: No recors affected in database");
         } else {
             throw new Exception("Oops.. something went wrong: No records affected in database", 500);
         }
     }
 }
Exemplo n.º 24
0
    $content = array();
    foreach (Conjunct::getAllConjuncts() as $conj) {
        if ($conj->isInvConj()) {
            $content['invConjuncts'][] = $conj->__toString();
        }
        if ($conj->isSigConj()) {
            $content['sigConjuncts'][] = $conj->__toString();
        }
        if (!$conj->isInvConj() && !$conj->isSigConj()) {
            $content['unused'][] = $conj->__toString();
        }
    }
    print json_encode($content, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
});
$app->get('/admin/report/interfaces', function () use($app) {
    if (Config::get('productionEnv')) {
        throw new Exception("Reports are not allowed in production environment", 403);
    }
    $arr = array();
    foreach (InterfaceObject::getAllInterfaces() as $key => $ifc) {
        $arr = array_merge($arr, $ifc->getInterfaceFlattened());
    }
    $content = array_map(function (InterfaceObject $ifc) {
        return array('path' => $ifc->path, 'label' => $ifc->label, 'crudC' => $ifc->crudC, 'crudR' => $ifc->crudR, 'crudU' => $ifc->crudU, 'crudD' => $ifc->crudD, 'src' => $ifc->srcConcept->name, 'tgt' => $ifc->tgtConcept->name, 'view' => $ifc->view->label, 'relation' => $ifc->relation->signature, 'flipped' => $ifc->relationIsFlipped, 'ref' => $ifc->refInterfaceId, 'root' => $ifc->isRoot(), 'public' => $ifc->isPublic(), 'roles' => implode(',', $ifc->ifcRoleNames));
    }, $arr);
    // Output
    $output = new OutputCSV();
    $output->addColumns(array_keys($content[0]));
    foreach ($content as $row) {
        $output->addRow($row);
    }
Exemplo n.º 25
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;
 }
Exemplo n.º 26
0
 /**
  * Import all view definitions from json file and create and save View objects 
  * @return void
  */
 private static function setAllViews()
 {
     self::$allViews = array();
     // import json file
     $file = file_get_contents(Config::get('pathToGeneratedFiles') . 'views.json');
     $allViewDefs = (array) json_decode($file, true);
     foreach ($allViewDefs as $viewDef) {
         self::$allViews[$viewDef['label']] = new View($viewDef);
     }
 }
Exemplo n.º 27
0
<?php

use Ampersand\Config;
use Ampersand\Extension\ExecEngine\ExecEngine;
use Ampersand\Log\Notifications;
use Ampersand\Session;
global $app;
// Path to API is 'api/v1/execengine/import'
$app->get('/execengine/run', function () use($app) {
    $session = Session::singleton();
    $roleIds = $app->request->params('roleIds');
    $session->activateRoles($roleIds);
    // Check sessionRoles if allowedRolesForRunFunction is specified
    $allowedRoles = Config::get('allowedRolesForRunFunction', 'execEngine');
    if (!is_null($allowedRoles)) {
        $ok = false;
        foreach ($session->getSessionRoles() as $role) {
            if (in_array($role->label, $allowedRoles)) {
                $ok = true;
            }
        }
        if (!$ok) {
            throw new Exception("You do not have access to run the exec engine", 401);
        }
    }
    ExecEngine::run(true);
    $session->database->closeTransaction('Run completed', true);
    $result = array('notifications' => Notifications::getAll());
    print json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
});
Exemplo n.º 28
0
 /**
  * Import all Relation definitions from json file and create and save Relation objects
  * @return void
  */
 private static function setAllRelations()
 {
     self::$allRelations = array();
     // import json file
     $file = file_get_contents(Config::get('pathToGeneratedFiles') . 'relations.json');
     $allRelationDefs = (array) json_decode($file, true);
     foreach ($allRelationDefs as $relationDef) {
         $relation = new Relation($relationDef);
         self::$allRelations[$relation->signature] = $relation;
     }
 }
Exemplo n.º 29
0
date_default_timezone_set('Europe/Amsterdam');
/**************************************************************************************************
 * LOGGING functionality
 *************************************************************************************************/
error_reporting(E_ALL & ~E_NOTICE);
ini_set("display_errors", true);
/**************************************************************************************************
 * Execution time limit is set to a default of 30 seconds. Use 0 to have no time limit. (not advised)
 *************************************************************************************************/
set_time_limit(30);
//Config::set('debugMode', 'global', true); // default = false
// Log file handler
$fileHandler = new \Monolog\Handler\RotatingFileHandler(__DIR__ . '/log/error.log', 0, \Monolog\Logger::WARNING);
//$fileHandler->pushProcessor(new \Monolog\Processor\WebProcessor()); // Adds IP adres and url info to log records
Logger::registerGenericHandler($fileHandler);
if (Config::get('debugMode')) {
    $fileHandler = new \Monolog\Handler\RotatingFileHandler(__DIR__ . '/log/debug.log', 0, \Monolog\Logger::DEBUG);
    Logger::registerGenericHandler($fileHandler);
    // Browsers debuggers
    //$browserHandler = new \Monolog\Handler\ChromePHPHandler(\Monolog\Logger::DEBUG); // Log handler for Google Chrome
    //$browserHandler = new \Monolog\Handler\FirePHPHandler(\Monolog\Logger::DEBUG); // Log handler for Firebug in Mozilla Firefox
    //Logger::registerGenericHandler($browserHandler);
}
$execEngineHandler = new \Monolog\Handler\RotatingFileHandler(__DIR__ . '/log/execengine.log', 0, \Monolog\Logger::INFO);
Logger::registerHandlerForChannel('EXECENGINE', $execEngineHandler);
// User log handler
Logger::registerHandlerForChannel('USERLOG', new NotificationHandler(\Monolog\Logger::INFO));
/**************************************************************************************************
 * SERVER settings
 *************************************************************************************************/
// Config::set('serverURL', 'global', 'http://www.yourdomain.nl'); // defaults to http://localhost/<ampersand context name>