Exemple #1
1
/**
 * Logs in with Behad credentials to enable Behat fixture use
 *
 * @return void
 */
function logInWithBehatCredentials()
{
    $creds = getBehatCredentials();
    $options = ['logger' => getLogger()];
    $auth = new AuthHelper($options);
    $auth->logInViaUsernameAndPassword($creds['username'], $creds['password']);
}
Exemple #2
0
 public static function raise($exception)
 {
     getLogger()->warn($exception->getMessage());
     $class = get_class($exception);
     $baseController = new BaseController();
     switch ($class) {
         case 'OPAuthorizationException':
         case 'OPAuthorizationSessionException':
             if (isset($_GET['__route__']) && substr($_GET['__route__'], -5) == '.json') {
                 echo json_encode($baseController->forbidden('You do not have sufficient permissions to access this page.'));
             } else {
                 getRoute()->run('/error/403', EpiRoute::httpGet);
             }
             die;
             break;
         case 'OPAuthorizationOAuthException':
             echo json_encode($baseController->forbidden($exception->getMessage()));
             die;
             break;
         default:
             getLogger()->warn(sprintf('Uncaught exception (%s:%s): %s', $exception->getFile(), $exception->getLine(), $exception->getMessage()));
             throw $exception;
             break;
     }
 }
Exemple #3
0
function mysql_1_3_0($sql, $params = array())
{
    try {
        getDatabase()->execute($sql, $params);
        getLogger()->info($sql);
    } catch (Exception $e) {
        getLogger()->crit($e->getMessage());
    }
}
 /**
  * Subscribe to a topic (creates a webhook).
  *
  * @return void
  */
 public function subscribe()
 {
     getAuthentication()->requireAuthentication();
     $params = $_POST;
     $params['verify'] = 'sync';
     if (isset($params['callback']) && isset($params['mode']) && isset($params['topic'])) {
         $urlParts = parse_url($params['callback']);
         if (isset($urlParts['scheme']) && isset($urlParts['host'])) {
             if (!isset($urlParts['port'])) {
                 $port = '';
             }
             if (!isset($urlParts['path'])) {
                 $path = '';
             }
             extract($urlParts);
             $challenge = uniqid();
             $queryParams = array();
             if (isset($urlParts['query']) && !empty($urlParts['query'])) {
                 parse_str($urlParts['query'], $queryParams);
             }
             $queryParams['mode'] = $params['mode'];
             $queryParams['topic'] = $params['topic'];
             $queryParams['challenge'] = $challenge;
             if (isset($params['verifyToken'])) {
                 $queryParams['verifyToken'] = $params['verifyToken'];
             }
             $queryString = '';
             if (!empty($queryParams)) {
                 $queryString = sprintf('?%s', http_build_query($queryParams));
             }
             $url = sprintf('%s://%s%s%s%s', $scheme, $host, $port, $path, $queryString);
             $ch = curl_init($url);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
             $handle = getCurl()->addCurl($ch);
             // verify a 2xx response and that the body is equal to the challenge
             if ($handle->code >= 200 && $handle->code < 300 && $handle->data == $challenge) {
                 $apiWebhook = $this->api->invoke('/webhook/create.json', EpiRoute::httpPost, array('_POST' => $params));
                 if ($apiWebhook['code'] === 200) {
                     header('HTTP/1.1 204 No Content');
                     getLogger()->info(sprintf('Webhook successfully created: %s', json_encode($params)));
                     return;
                 }
             }
             $message = sprintf('The verification call failed to meet requirements. Code: %d, Response: %s, Expected: %s, URL: %s', $handle->code, $handle->data, $challenge, $url);
             getLogger()->warn($message);
         } else {
             $message = sprintf('Callback url was invalid: %s', $params['callback']);
             getLogger()->warn($message);
         }
     } else {
         $message = sprintf('Not all required parameters were passed in to webhook subscribe: %s', json_encode($params));
         getLogger()->warn($message);
     }
     header('HTTP/1.1 400 Bad Request');
     echo $message;
 }
 public function remove()
 {
     $logger = getLogger();
     $input = JFactory::getApplication()->input;
     $ids = $input->post->get('cid', array(), 'array');
     JArrayHelper::toInteger($ids);
     $model = $this->getModel('whitelist');
     $message = $model->remove($ids, $logger);
     $this->setRedirect(JRoute::_('index.php?option=com_bfstop&view=whitelist', false), $message, 'notice');
 }
Exemple #6
0
function mysql_3_0_6($sql, $params = array())
{
    try {
        getDatabase()->execute($sql, $params);
        getLogger()->info($sql);
    } catch (Exception $e) {
        getLogger()->crit($e->getMessage());
        return false;
    }
    return true;
}
 private function createPost($photo)
 {
     $conf = $this->getConf();
     $this->adn->setAccessToken($conf->accessToken);
     $data = array('annotations' => array(array('type' => 'net.app.core.oembed', 'value' => array('type' => 'photo', 'version' => '1.0', 'url' => $photo['pathBase'], 'width' => $photo['width'], 'height' => $photo['height'], 'provider_url' => 'https://trovebox.com', 'thumbnail_url' => $photo['path100x100xCR'], 'thumbnail_width' => 100, 'thumbnail_height' => 100))));
     try {
         $this->adn->createPost(sprintf('I just posted a new photo. %s', $photo['url']), $data);
     } catch (AppDotNetException $e) {
         getLogger()->warn('Could not create ADN post update.', $e);
     }
 }
Exemple #8
0
 /**
  * @vcr utils#checkCurrentVersion
  */
 public function testCheckForUpdate()
 {
     $log_file = getLogFileName();
     setOutputDestination($log_file);
     $cache = new FileCache();
     $cache->putData('latest_release', ['check_date' => strtotime('8 days ago')]);
     Utils\checkForUpdate(getLogger());
     $file_contents = explode("\n", file_get_contents($log_file));
     $this->assertFalse(strpos(array_pop($file_contents), 'An update to Terminus is available.'));
     resetOutputDestination($log_file);
 }
Exemple #9
0
 public function __construct()
 {
     $this->api = getApi();
     $this->config = getConfig()->get();
     $this->logger = getLogger();
     $this->route = getRoute();
     $this->session = getSession();
     $this->cache = getCache();
     // really just for setup when the systems don't yet exist
     if (isset($this->config->systems)) {
         $this->db = getDb();
         $this->fs = getFs();
     }
 }
Exemple #10
0
 public function verifyEmail($args)
 {
     if (!$this->isActive) {
         getLogger()->crit('The FacebookConnect plugin is not active and needs to be for the Facebook Login adapter.');
         return false;
     }
     $user = $this->fb->getUser();
     if (!$user) {
         return false;
     }
     $response = $this->fb->api('/me');
     if (!isset($response['email'])) {
         return false;
     }
     return $response['email'];
 }
 function display($tpl = null)
 {
     // clear the messages still enqueued from the invalid login attempt:
     $session = JFactory::getSession();
     $session->set('application.queue', null);
     // try to unblock:
     $input = JFactory::getApplication()->input;
     $token = $input->getString('token', '');
     $logger = getLogger();
     if (strcmp($token, '') != 0) {
         $this->model = $this->getModel();
         $unblockSuccess = $this->model->unblock($token, $logger);
         $this->message = $unblockSuccess ? JText::sprintf('UNBLOCKTOKEN_SUCCESS', $this->getLoginLink(), $this->getPasswordResetLink()) : JText::_('UNBLOCKTOKEN_FAILED');
     } else {
         $this->message = JText::_('UNBLOCKTOKEN_INVALID');
     }
     parent::display($tpl);
 }
 public function testNotify()
 {
     $emailAddress = $this->getParam('emailaddress', 'params', '');
     $userID = (int) $this->getParam('userID', 'params', -1);
     $userGroup = (int) $this->getParam('userGroup', 'params', -1);
     $groupNotifEnabled = (bool) $this->getParam('groupNotificationEnabled', 'params', false);
     $logger = getLogger();
     $db = new BFStopDBHelper($logger);
     $notifier = new BFStopNotifier($logger, $db, $emailAddress, $userID, $userGroup, $groupNotifEnabled);
     if (count($notifier->getNotifyAddresses()) == 0) {
         $result = false;
     } else {
         $subject = JText::sprintf('TEST_MAIL_SUBJECT', $notifier->getSiteName());
         $body = JText::sprintf('TEST_MAIL_BODY', $notifier->getSiteName());
         $application = JFactory::getApplication();
         $application->enqueueMessage(JText::sprintf("TEST_MAIL_SENT", $subject, $body, implode(", ", $notifier->getNotifyAddresses())), 'notice');
         $result = $notifier->sendMail($subject, $body, $notifier->getNotifyAddresses());
     }
     // redirect back to settings view:
     $this->setRedirect(JRoute::_('index.php?option=com_bfstop&view=settings', false), $result ? JText::_('TEST_NOTIFICATION_SUCCESS') : JText::_('TEST_NOTIFICATION_FAILED'), $result ? 'notice' : 'error');
 }
Exemple #13
0
function initLogger()
{
    $loggerName = "log";
    // Iterate over all declared classes
    $classes = get_declared_classes();
    foreach ($classes as $class) {
        $reflection = new ReflectionClass($class);
        // If the class is internally defined by PHP or has no property called "logger", skip it.
        if ($reflection->isInternal() || !$reflection->hasProperty($loggerName)) {
            continue;
        }
        // Get information regarding the "logger" property of this class.
        $property = new ReflectionProperty($class, $loggerName);
        // If the "logger" property is not static or not public, then it is not the one we are interested in. Skip this class.
        if (!$property->isStatic() || !$property->isPublic()) {
            continue;
        }
        // Initialize the logger for this class.
        $reflection->setStaticPropertyValue($loggerName, getLogger());
    }
}
Exemple #14
0
 public function __construct()
 {
     $this->api = getApi();
     $this->config = getConfig()->get();
     $this->plugin = getPlugin();
     $this->route = getRoute();
     $this->session = getSession();
     $this->logger = getLogger();
     $this->template = getTemplate();
     $this->theme = getTheme();
     $this->utility = new Utility();
     $this->url = new Url();
     $this->template->template = $this->template;
     $this->template->config = $this->config;
     $this->template->plugin = $this->plugin;
     $this->template->session = $this->session;
     $this->template->theme = $this->theme;
     $this->template->utility = $this->utility;
     $this->template->url = $this->url;
     $this->template->user = new User();
     $this->apiVersion = Request::getApiVersion();
 }
Exemple #15
0
/**
 * The public interface for instantiating an image obect.
 * This returns the appropriate type of object by reading the config.
 * Accepts a set of params that must include a type and targetType
 *
 * @return object An image object that implements ImageInterface
 */
function getImage()
{
    static $type;
    $modules = getConfig()->get('modules');
    if (!$type && isset($modules->image)) {
        $type = $modules->image;
    }
    try {
        switch ($type) {
            case 'GraphicsMagick':
                return new ImageGraphicsMagick();
                break;
            case 'ImageMagick':
                return new ImageImageMagick();
                break;
            case 'GD':
                return new ImageGD();
                break;
        }
    } catch (OPInvalidImageException $e) {
        getLogger()->warn("Invalid image exception thrown for {$type}");
        return false;
    }
}
Exemple #16
0
 /**
  * Object constructor
  *
  * @access public
  *
  * @param string $description Error description
  * @param int    $stop        Stop (0 - stop script execution, 1 - show warning and continue script execution)
  * @param int    $short       Short (default 0)
  * @return void
  */
 public function __construct($description, $stop = 0, $short = 0)
 {
     $script = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
     $description = $script . "\nError:\n" . $description;
     $log = getLogger();
     $log->error($description);
     if (defined("DEBUG_MODE")) {
         if (!$short) {
             $this->alert(nl2br($description));
         } else {
             echo nl2br($description);
         }
     } else {
         if (!$short) {
             $this->alert("");
         } else {
             echo "Warning...<br>";
         }
     }
     sendmail("errors@" . PROJECT_DOMAIN, PROJECT_BUGTRACK, "Error reporting: {$script}", $description);
     if ($stop) {
         exit;
     }
 }
 public function flow()
 {
     if (isset($_GET['oauth_token'])) {
         $consumerKey = $_GET['oauth_consumer_key'];
         $consumerSecret = $_GET['oauth_consumer_secret'];
         $token = $_GET['oauth_token'];
         $tokenSecret = $_GET['oauth_token_secret'];
         $verifier = $_GET['oauth_verifier'];
         try {
             $consumer = getDb()->getCredential($token);
             $oauth = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
             $oauth->setVersion('1.0a');
             $oauth->setToken($token, $tokenSecret);
             $accessToken = $oauth->getAccessToken(sprintf('%s://%s/v1/oauth/token/access', $this->utility->getProtocol(false), $_SERVER['HTTP_HOST']), null, $verifier);
             $accessToken['oauth_consumer_key'] = $consumerKey;
             $accessToken['oauth_consumer_secret'] = $consumerSecret;
             setcookie('oauth', http_build_query($accessToken));
             if (!isset($accessToken['oauth_token']) || !isset($accessToken['oauth_token_secret'])) {
                 echo sprintf('Invalid response when getting an access token: %s', http_build_query($accessToken));
             } else {
                 echo sprintf('You exchanged a request token for an access token<br><a href="?reloaded=1">Reload to make an OAuth request</a>', $accessToken['oauth_token'], $accessToken['oauth_token_secret']);
             }
         } catch (OAuthException $e) {
             $message = OAuthProvider::reportProblem($e);
             getLogger()->info($message);
             OPException::raise(new OPAuthorizationOAuthException($message));
         }
     } else {
         if (!isset($_GET['reloaded'])) {
             $callback = sprintf('%s://%s/v1/oauth/flow', $this->utility->getProtocol(false), $_SERVER['HTTP_HOST']);
             $name = isset($_GET['name']) ? $_GET['name'] : 'OAuth Test Flow';
             echo sprintf('<a href="%s://%s/v1/oauth/authorize?oauth_callback=%s&name=%s">Create a new client id</a>', $this->utility->getProtocol(false), $_SERVER['HTTP_HOST'], urlencode($callback), urlencode($name));
         } else {
             try {
                 parse_str($_COOKIE['oauth']);
                 $consumer = getDb()->getCredential($oauth_token);
                 $oauth = new OAuth($oauth_consumer_key, $oauth_consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
                 $oauth->setToken($oauth_token, $oauth_token_secret);
                 $oauth->fetch(sprintf('http://%s/v1/oauth/test?oauth_consumer_key=%s', $_SERVER['HTTP_HOST'], $oauth_consumer_key));
                 $response_info = $oauth->getLastResponseInfo();
                 header("Content-Type: {$response_info["content_type"]}");
                 echo $oauth->getLastResponse();
             } catch (OAuthException $e) {
                 $message = OAuthProvider::reportProblem($e);
                 getLogger()->info($message);
                 OPException::raise(new OPAuthorizationOAuthException($message));
             }
         }
     }
 }
Exemple #18
0
 /**
  * Initialize the database by creating the database and tables needed.
  * This is called from the Setup controller.
  *
  * @return boolean
  */
 public function initialize($isEditMode)
 {
     $version = $this->version();
     // we're not running setup for the first time and we're not in edit mode
     if ($version !== '0.0.0' && $isEditMode === false) {
         // email address has to be unique
         // getting a null back from getUser() means we can proceed
         $user = true;
         if ($this->owner != '') {
             $user = $this->getUser($this->owner);
         }
         // getUser returns null if the user does not exist
         if ($user === null) {
             return true;
         }
         getLogger()->crit(sprintf('Could not initialize user for MySql due to email conflict (%s).', $this->owner));
         return false;
     } elseif ($version === '0.0.0') {
         try {
             return $this->executeScript(sprintf('%s/upgrade/db/mysql/mysql-base.php', getConfig()->get('paths')->configs), 'mysql');
         } catch (EpiDatabaseException $e) {
             getLogger()->crit($e->getMessage());
             return false;
         }
     }
     return true;
 }
Exemple #19
0
 /**
  * Write out the settings config file
  *
  * @return boolean  TRUE on success, FALSE on error
  */
 private function writeConfigFile()
 {
     // continue if no errors
     $secret = $this->getSecret();
     $baseDir = $this->utility->getBaseDir();
     $htmlDir = "{$baseDir}/html";
     $libDir = "{$baseDir}/libraries";
     $configDir = "{$baseDir}/configs";
     $replacements = array('{adapters}' => "{$libDir}/adapters", '{configs}' => $configDir, '{controllers}' => "{$libDir}/controllers", '{docroot}' => "{$htmlDir}", '{external}' => "{$libDir}/external", '{libraries}' => "{$libDir}", '{models}' => "{$libDir}/models", '{photos}' => "{$htmlDir}/photos", '{plugins}' => "{$libDir}/plugins", '{templates}' => "{$baseDir}/templates", '{themes}' => "{$htmlDir}/assets/themes", '{temp}' => sys_get_temp_dir(), '{userdata}' => "{$baseDir}/userdata", '{exiftran}' => exec('which exiftran'), '{autoTagWithDate}' => '1', '{localSecret}' => $secret, '{awsKey}' => "", '{awsSecret}' => "", '{s3Bucket}' => getSession()->get('s3BucketName'), '{s3Host}' => getSession()->get('s3BucketName') . '.s3.amazonaws.com', '{mySqlHost}' => "", '{mySqlUser}' => "", '{mySqlPassword}' => "", '{mySqlDb}' => "", '{mySqlTablePrefix}' => "", '{dropboxKey}' => "", '{dropboxSecret}' => "", '{dropboxToken}' => "", '{dropboxTokenSecret}' => "", '{dropboxFolder}' => "", '{fsRoot}' => "", '{fsHost}' => "", '{lastCodeVersion}' => getConfig()->get('defaults')->currentCodeVersion, '{theme}' => getSession()->get('theme'), '{email}' => getSession()->get('ownerEmail'));
     // Session keys whose value it is ok to log.
     // Other session keys available at this point are:
     //   awsKey, awsSecret, dropboxKey, dropboxSecret, dropboxToken, dropboxTokenSecret,
     //   flowDropboxKey, flowDropboxSecret, mySqlPassword, mySqlUser, password, secret, step
     // It is safer to explicitly list keys that are ok to log, rather than exclude those that are
     // sensitive, as one might forget to exclude new keys.
     $settingsToLog = array('step', 'appId', 'ownerEmail', 'isEditMode', 'theme', 'imageLibrary', 'database', 'mySqlDb', 'mySqlHost', 'mySqlTablePrefix', 'fileSystem', 'fsHost', 'fsRoot', 'dropboxFolder', 'flowDropboxFolder', 's3BucketName');
     $pReplace = array();
     $session = getSession()->getAll();
     foreach ($session as $key => $val) {
         if ($key != 'email' && $key != 'password') {
             $pReplace["{{$key}}"] = $val;
         }
         // Write keys to the log file. If key is in whitelist then log the value as well.
         if (in_array($key, $settingsToLog)) {
             $logMessage = sprintf("Storing `%s` as '%s'", $key, $val);
         } else {
             $logMessage = sprintf("Storing `%s`", $key);
         }
         getLogger()->info($logMessage);
     }
     $replacements = array_merge($replacements, $pReplace);
     $generatedIni = str_replace(array_keys($replacements), array_values($replacements), file_get_contents("{$configDir}/template.ini"));
     $iniWritten = getConfig()->write(sprintf("%s/userdata/configs/%s.ini", $baseDir, getenv('HTTP_HOST')), $generatedIni);
     if (!$iniWritten) {
         return false;
     }
     // clean up the session
     foreach ($session as $key => $val) {
         if ($key != 'email') {
             getSession()->set($key, '');
         }
     }
     return true;
 }
 private function putFileInDirectory($directory, $localFile, $destinationName)
 {
     $createDirectory = false;
     $destinationDirectory = sprintf('%s/%s', $this->dropboxFolder, $directory);
     try {
         $this->dropbox->getMetaData($destinationDirectory);
         if (isset($queryDropboxFolder['is_deleted']) && $queryDropboxFolder['is_deleted'] == 1) {
             $createDirectory = true;
         }
     } catch (Dropbox_Exception_NotFound $e) {
         $createDirectory = true;
     } catch (Exception $e) {
         getLogger()->warn('Dropbox exception from getMetaData call', $e);
         return false;
     }
     if ($createDirectory) {
         try {
             getLogger()->info(sprintf('Creating dropbox directory %s', $destinationDirectory));
             $this->dropbox->createFolder($destinationDirectory);
         } catch (Dropbox_Exception $e) {
             getLogger()->info('Failed creating dropbox directory.', $e);
             return false;
         }
     }
     try {
         $this->dropbox->putFile(sprintf('%s/%s', $destinationDirectory, $destinationName), $localFile);
         getLogger()->info(sprintf('Successfully stored file (%s) on dropbox.', $destinationName));
         return true;
     } catch (Dropbox_Exception $e) {
         getLogger()->crit('Could not put file on dropbox.', $e);
     }
     return false;
 }
 public function initialize($isEditMode)
 {
     if (!file_exists($this->root)) {
         @mkdir($this->root, 0775, true);
     }
     if (file_exists($this->root)) {
         return true;
     } else {
         getLogger()->crit("Could not create {$this->root}");
         return false;
     }
 }
Exemple #22
0
 /**
  * Initialize the remote file system by creating buckets and setting permissions and settings.
  * This is called from the Setup controller.
  * @return boolean
  */
 public function initialize($isEditMode)
 {
     getLogger()->info('Initializing file system');
     if (!$this->fs->validate_bucketname_create($this->bucket) || !$this->fs->validate_bucketname_support($this->bucket)) {
         getLogger()->warn("The bucket name you provided ({$this->bucket}) is invalid.");
         return false;
     }
     $buckets = $this->fs->get_bucket_list("/^{$this->bucket}\$/");
     if (count($buckets) == 0) {
         getLogger()->info("Bucket {$this->bucket} does not exist, creating it now");
         $res = $this->fs->create_bucket($this->bucket, AmazonS3::REGION_US_E1, AmazonS3::ACL_PUBLIC);
         if (!$res->isOK()) {
             getLogger()->crit('Could not create S3 bucket: ' . var_export($res, 1));
             return false;
         }
     }
     // TODO add versioning?
     // Set a policy for this bucket only
     $policy = new CFPolicy($this->fs, array('Version' => '2008-10-17', 'Statement' => array(array('Sid' => 'AddPerm', 'Effect' => 'Allow', 'Principal' => array('AWS' => '*'), 'Action' => array('s3:*'), 'Resource' => array("arn:aws:s3:::{$this->bucket}/*")))));
     $res = $this->fs->set_bucket_policy($this->bucket, $policy);
     if (!$res->isOK()) {
         getLogger()->crit('Failed to set bucket policy');
     }
     return $res->isOK();
 }
Exemple #23
0
 /**
  * Title
  *
  * Description
  *
  * @access public
  */
 function runScript($id, $params = '')
 {
     $rec = SQLSelectOne("SELECT * FROM scripts WHERE ID='" . (int) $id . "' OR TITLE LIKE '" . DBSafe($id) . "'");
     if ($rec['ID']) {
         $rec['EXECUTED'] = date('Y-m-d H:i:s');
         if ($params) {
             $rec['EXECUTED_PARAMS'] = serialize($params);
         }
         SQLUpdate('scripts', $rec);
         try {
             $code = $rec['CODE'];
             $success = eval($code);
             if ($success === false) {
                 getLogger($this)->error(sprintf('Error in script "%s". Code: %s', $rec['TITLE'], $code));
             }
         } catch (Exception $e) {
             getLogger($this)->error(sprintf('Error in script "%s"', $rec['TITLE']), $e);
         }
     }
 }
Exemple #24
0
function fatal($msg)
{
    $args = func_get_args();
    $log = getLogger();
    $log->fatal(implode(', ', $args));
}
Exemple #25
0
 /**
 * Title
 *
 * Description
 *
 * @access public
 */
 function callMethod($name, $params = 0, $parent = 0)
 {
     startMeasure('callMethod');
     $original_method_name = $this->object_title . '.' . $name;
     startMeasure('callMethod (' . $original_method_name . ')');
     if (!$parent) {
         $id = $this->getMethodByName($name, $this->class_id, $this->id);
     } else {
         $id = $this->getMethodByName($name, $this->class_id, 0);
     }
     if ($id) {
         $method = SQLSelectOne("SELECT * FROM methods WHERE ID='" . $id . "'");
         $method['EXECUTED'] = date('Y-m-d H:i:s');
         if (!$method['OBJECT_ID']) {
             if (!$params) {
                 $params = array();
             }
             $params['ORIGINAL_OBJECT_TITLE'] = $this->object_title;
         }
         if ($params) {
             $method['EXECUTED_PARAMS'] = serialize($params);
         }
         SQLUpdate('methods', $method);
         if ($method['OBJECT_ID'] && $method['CALL_PARENT'] == 1) {
             $this->callMethod($name, $params, 1);
         }
         if ($method['SCRIPT_ID']) {
             /*
              $script=SQLSelectOne("SELECT * FROM scripts WHERE ID='".$method['SCRIPT_ID']."'");
              $code=$script['CODE'];
             */
             runScript($method['SCRIPT_ID']);
         } else {
             $code = $method['CODE'];
         }
         if ($code != '') {
             /*
             if (defined('SETTINGS_DEBUG_HISTORY') && SETTINGS_DEBUG_HISTORY==1) {
              $class_object=SQLSelectOne("SELECT NOLOG FROM classes WHERE ID='".$this->class_id."'");
              if (!$class_object['NOLOG']) {
             
               $prevLog=SQLSelectOne("SELECT ID, UNIX_TIMESTAMP(ADDED) as UNX FROM history WHERE OBJECT_ID='".$this->id."' AND METHOD_ID='".$method['ID']."' ORDER BY ID DESC LIMIT 1");
               if ($prevLog['ID']) {
                $prevRun=$prevLog['UNX'];
                $prevRunPassed=time()-$prevLog['UNX'];
               }
             
               $h=array();
               $h['ADDED']=date('Y-m-d H:i:s');
               $h['OBJECT_ID']=$this->id;
               $h['METHOD_ID']=$method['ID'];
               $h['DETAILS']=serialize($params);
               if ($parent) {
                $h['DETAILS']='(parent method) '.$h['DETAILS'];
               }
               $h['DETAILS'].="\n".'code: '."\n".$code;
               SQLInsert('history', $h);
              }
             }
             */
             try {
                 $success = eval($code);
                 if ($success === false) {
                     getLogger($this)->error(sprintf('Error in "%s.%s" method. Code: %s', $this->object_title, $name, $code));
                 }
             } catch (Exception $e) {
                 getLogger($this)->error(sprintf('Exception in "%s.%s" method', $this->object_title, $name), $e);
             }
         }
         endMeasure('callMethod', 1);
         endMeasure('callMethod (' . $original_method_name . ')', 1);
         if ($method['OBJECT_ID'] && $method['CALL_PARENT'] == 2) {
             $this->callMethod($name, $params, 1);
         }
     } else {
         endMeasure('callMethod (' . $original_method_name . ')', 1);
         endMeasure('callMethod', 1);
         return false;
     }
 }
Exemple #26
0
/**
 * The public interface for instantiating an maps object.
 * This returns the appropriate type of object by reading the config.
 * Accepts a set of params that must include a type and targetType
 *
 * @return object A maps object that implements MapsInterface
 */
function getMap()
{
    static $type;
    $map = getConfig()->get('map');
    if (!$type && isset($map->service)) {
        $type = $map->service;
    }
    try {
        switch ($type) {
            case 'osm':
                return new MapOsm();
                break;
            case 'google':
                return new MapGoogle();
                break;
        }
    } catch (OPInvalidMapException $e) {
        getLogger()->warn("Invalid mapping exception thrown for {$type}");
        return false;
    }
}
 /**
  * Write out the settings config file
  *
  * @return boolean  TRUE on success, FALSE on error
  */
 private function writeConfigFile()
 {
     // continue if no errors
     $secret = $this->getSecret();
     $baseDir = $this->utility->getBaseDir();
     $htmlDir = "{$baseDir}/html";
     $libDir = "{$baseDir}/libraries";
     $configDir = "{$baseDir}/configs";
     $replacements = array('{adapters}' => "{$libDir}/adapters", '{configs}' => $configDir, '{controllers}' => "{$libDir}/controllers", '{docroot}' => "{$htmlDir}", '{external}' => "{$libDir}/external", '{libraries}' => "{$libDir}", '{models}' => "{$libDir}/models", '{photos}' => "{$htmlDir}/photos", '{plugins}' => "{$libDir}/plugins", '{templates}' => "{$baseDir}/templates", '{themes}' => "{$htmlDir}/assets/themes", '{temp}' => sys_get_temp_dir(), '{userdata}' => "{$baseDir}/userdata", '{exiftran}' => exec('which exiftran'), '{autoTagWithDate}' => '1', '{localSecret}' => $secret, '{awsKey}' => "", '{awsSecret}' => "", '{s3Bucket}' => getSession()->get('s3BucketName'), '{s3Host}' => getSession()->get('s3BucketName') . '.s3.amazonaws.com', '{simpleDbDomain}' => "", '{mySqlHost}' => "", '{mySqlUser}' => "", '{mySqlPassword}' => "", '{mySqlDb}' => "", '{mySqlTablePrefix}' => "", '{dropboxKey}' => "", '{dropboxSecret}' => "", '{dropboxToken}' => "", '{dropboxTokenSecret}' => "", '{dropboxFolder}' => "", '{fsRoot}' => "", '{fsHost}' => "", '{lastCodeVersion}' => getConfig()->get('defaults')->currentCodeVersion, '{theme}' => getSession()->get('theme'), '{email}' => getSession()->get('ownerEmail'));
     $pReplace = array();
     $session = getSession()->getAll();
     foreach ($session as $key => $val) {
         if ($key != 'email') {
             $pReplace["{{$key}}"] = $val;
         }
         getLogger()->info(sprintf('Storing %s as %s', $key, $val));
     }
     $replacements = array_merge($replacements, $pReplace);
     $generatedIni = str_replace(array_keys($replacements), array_values($replacements), file_get_contents("{$configDir}/template.ini"));
     $iniWritten = getConfig()->write(sprintf("%s/userdata/configs/%s.ini", $baseDir, getenv('HTTP_HOST')), $generatedIni);
     if (!$iniWritten) {
         return false;
     }
     // clean up the session
     foreach ($session as $key => $val) {
         if ($key != 'email') {
             getSession()->set($key, '');
         }
     }
     return true;
 }
Exemple #28
0
<?php

$domains = $this->db->get_domain_list("/^{$this->domainPhoto}(Action|Credential|Group|Tag|User|Webhook)?\$/");
if (count($domains) == 7) {
    return true;
}
$domainsToCreate = array($this->domainAction, $this->domainActivity, $this->domainAlbum, $this->domainCredential, $this->domainGroup, $this->domainPhoto, $this->domainTag, $this->domainUser, $this->domainWebhook);
$queue = new CFBatchRequest();
foreach ($domainsToCreate as $domainToCreate) {
    if (!in_array($domainToCreate, $domains)) {
        $this->db->batch($queue)->create_domain($domainToCreate);
        getLogger()->info(sprintf('Queueing request to create domain: %s', $domainToCreate));
    }
}
$responses = $this->db->batch($queue)->send();
getLogger()->info(sprintf('Attempting to create %d domains.', count($responses)));
$this->logErrors($responses);
$status = $responses->areOK();
return $status;
 private function putFileInDirectory($localFile, $destinationName)
 {
     try {
         $file = $this->adn->createFile($localFile, array('metadata' => 'com.trovebox', 'name' => $destinationName));
         $this->metaDataMap[$localFile] = array('adnFileId' => $file['id']);
         getLogger()->info(sprintf('Successfully stored file (%s) on ADN.', $destinationName));
         return true;
     } catch (AppDotNetException $e) {
         getLogger()->crit('Could not put file on ADN.', $e);
     }
     return false;
 }
Exemple #30
0
 private function putFileInDirectory($directory, $localFile, $destinationName)
 {
     $createDirectory = false;
     // TODO confirm is this is the best way to do this
     //  it maybe a noop but calling get_file_info might be faster
     try {
         $newFolder = new Box_Client_Folder();
         $newFolder->attr('name', $directory);
         $newFolder->attr('parent_id', $this->boxFolderId);
         $newFolder->attr('share', 0);
         $status = $this->box->create($newFolder);
         if ($status !== self::statusCreatedOk && $status !== self::statusFolderExists) {
             getLogger()->warn(sprintf('Box API returned an unexpected response of (%s) from folder create call', $status));
             return false;
         }
     } catch (Box_Rest_Client_Exception $e) {
         getLogger()->warn('Box exception from folder create call', $e);
         return false;
     }
     try {
         // The way Box_Rest_Client works it uses the file's name as the display name
         $file = new Box_Client_File($localFile, $destinationName);
         $file->attr('folder_id', $newFolder->attr('folder_id'));
         $result = $this->box->upload($file, array('new_copy' => '1'), true);
         if ($result === self::statusUploadOk) {
             $this->metaDataMap[$localFile] = array('boxFileId' => $file->attr('id'));
             getLogger()->info(sprintf('Successfully stored file (%s) on Box.', $destinationName));
             return true;
         } else {
             getLogger()->crit('Could not put file on Box.', $e);
             return false;
         }
     } catch (Box_Rest_Client_Exception $e) {
         getLogger()->warn('Box exception from upload call', $e);
         return false;
     }
 }