Example #1
0
 /**
  * @return ACache
  */
 public static function cache()
 {
     if (self::$cache === null) {
         self::$cache = new ACache();
     }
     return self::$cache;
 }
 public function tearDown()
 {
     // Empty cache
     foreach ($this->_transactionIds as $transactionId) {
         \App::cache()->remove($transactionId);
     }
 }
 public function clean($tags = array())
 {
     if ($this->_lifetime < 1) {
         return $this;
     }
     $tags = $this->_createCacheTags($tags);
     \App::log()->info("Cleaning " . $this->_itemClass . " cache. Tags: " . implode(', ', $tags));
     \App::cache()->clean(\Zend_Cache::CLEANING_MODE_MATCHING_TAG, $tags);
     return $this;
 }
Example #4
0
function loadAcl($files, $namespace, $format = 'yaml', $drop = false)
{
    if ($drop) {
        dropNamespace($namespace);
    }
    $class = "App_Acl_Loader_" . ucfirst($format);
    $loader = new $class();
    \App::cache()->clean(Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array('Namespace'));
    $loader->loadFromMultiFiles($files, $namespace);
    \App::cache()->clean(Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array('Namespace'));
}
 /**
  * 缓存并返回一个表的所有字段
  * 
  * @param mixed $table_name
  * @param mixed $db_name
  * @param bool $use_cache
  * @return Array
  */
 public function getTableColumns($table_name, $db_name, $use_cache = true)
 {
     $key = __METHOD__ . $db_name . $table_name;
     if (!isset(self::$colums[$key])) {
         $cache_data = App::cache($key);
         if (!$cache_data || !$use_cache) {
             $cache_data = $this->db->usedb($db_name)->getColumns($table_name);
             App::cache($key, $cache_data);
         }
         self::$colums[$key] = $cache_data;
     }
     return self::$colums[$key];
 }
function json2Acl($db, $ns, $file, $drop = false)
{
    $collection = "acl_" . $ns;
    $f = file_get_contents($file, 'r');
    if (!$f) {
        \App::log()->notice("Error to load file. Skiping {$ns}...");
        return;
    }
    //decoding json file
    $json_a = Zend_Json_Decoder::decode($f);
    if ($drop) {
        echo "\nDrop {$collection} from " . APPLICATION_ENV . " env \n";
        $db->{$collection}->drop();
    }
    foreach ($json_a as $element) {
        $db->{$collection}->save($element);
    }
    \App::cache()->clean(Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array('Namespace'));
}
Example #7
0
 /**
  * Build the Less file
  *
  * @param string $dest      The destination CSS file
  * @param bool   $force     If set to true, will build whereas the cache status
  * @param array  $variables Less variables to set before compiling the Less file
  */
 public function build($dest, $force = false, $variables = array())
 {
     if (!is_dir(dirname($dest))) {
         mkdir(dirname($dest), 0755, true);
     }
     $compiler = new \lessc();
     $lastCompilationFile = App::cache()->getCacheFilePath($this->getLastCompilationInfoFilename());
     if (!$force && is_file($lastCompilationFile)) {
         $cache = (include $lastCompilationFile);
     } else {
         $cache = $this->source;
     }
     $compiler->setFormatter('compressed');
     $compiler->setPreserveComments(false);
     $compilation = $compiler->cachedCompile($cache, $force);
     if (!is_array($cache) || $compilation['updated'] > $cache['updated']) {
         file_put_contents($dest, '/*** ' . date('Y-m-d H:i:s') . ' ***/' . PHP_EOL . $compilation['compiled']);
         $event = new Event('built-less', array('source' => $this->source, 'dest' => $dest));
         $event->trigger();
         // Save the compilation information
         unset($compilation['compiled']);
         $this->saveLastCompilationInfo($compilation);
     }
 }
 public function setUp()
 {
     \App::cache()->clean();
     $this->simMapper = SimMapper::getInstance();
     $this->_user = $this->_createAuthUser(array('userName' => 'SimUserTest', 'organizationId' => Application\Model\Organization\OrgServiceProviderModel::ORG_TYPE . '-' . 'sp1 (non-commercial)111111111111'));
 }
Example #9
0
 /**
  * Load a language file
  *
  * @param string $plugin   The plugin to load
  * @param string $language The language to get the translations in
  * @param string $force    If set to true, force to reload the translations
  */
 private static function load($plugin, $language = LANGUAGE, $force = false)
 {
     if (!isset(self::$keys[$plugin][$language]) || $force || $language !== self::$usedLanguage) {
         App::logger()->debug('Reload keys for plugin ' . $plugin . ' and for language ' . $language);
         self::$keys[$plugin][$language] = array();
         $instance = new self($plugin, self::DEFAULT_LANGUAGE);
         $instance->build();
         self::$keys[$plugin][$language] = App::cache()->includeCache($instance->cacheFile);
         if ($language !== self::DEFAULT_LANGUAGE) {
             $instance = new self($plugin, $language);
             $instance->build();
             $translations = App::cache()->includeCache($instance->cacheFile);
             if (!is_array($translations)) {
                 $translations = array();
             }
             self::$keys[$plugin][$language] = array_merge(self::$keys[$plugin][$language], $translations);
         }
         self::$usedLanguage = $language;
     }
 }
Example #10
0
 /**
  * Update Hawk
  */
 public function updateHawk()
 {
     try {
         $api = new HawkApi();
         $nextVersions = $api->getCoreAvailableUpdates();
         if (empty($nextVersions)) {
             throw new \Exception("No newer version is available for Hawk");
         }
         // Update incrementally all newer versions
         foreach ($nextVersions as $version) {
             // Download the update archive
             $archive = $api->getCoreUpdateArchive($version['version']);
             // Extract the downloaded file
             $zip = new \ZipArchive();
             if ($zip->open($archive) !== true) {
                 throw new \Exception('Impossible to open the zip archive');
             }
             $zip->extractTo(TMP_DIR);
             // Put all modified or added files in the right folder
             $folder = TMP_DIR . 'update-v' . $version['version'] . '/';
             App::fs()->copy($folder . 'to-update/*', ROOT_DIR);
             // Delete the files to delete
             $toDeleteFiles = explode(PHP_EOL, file_get_contents($folder . 'to-delete.txt'));
             foreach ($toDeleteFiles as $file) {
                 if (is_file(ROOT_DIR . $file)) {
                     unlink(ROOT_DIR . $file);
                 }
             }
             // Remove temporary files and folders
             App::fs()->remove($folder);
             App::fs()->remove($archive);
         }
         // Execute the update method if exist
         $updater = new HawkUpdater();
         $methods = get_class_methods($updater);
         foreach ($nextVersions as $version) {
             $method = 'v' . str_replace('.', '_', $version['version']);
             if (method_exists($updater, $method)) {
                 $updater->{$method}();
             }
         }
         App::cache()->clear('views');
         App::cache()->clear('lang');
         App::cache()->clear(Autoload::CACHE_FILE);
         App::cache()->clear(Lang::ORIGIN_CACHE_FILE);
         $response = array('status' => true);
     } catch (\Exception $e) {
         $response = array('status' => false, 'message' => DEBUG_MODE ? $e->getMessage() : Lang::get('admin.update-hawk-error'));
     }
     App::response()->setContentType('json');
     return $response;
 }
Example #11
0
#!/usr/bin/env php
<?php 
/**
 * Script to flush cache
 */
require_once realpath(dirname(__FILE__) . '/lib/Cli.php');
$cli = new Cli();
try {
    \App::cache()->clean();
    echo "Cache flushed \n";
} catch (Exception $e) {
    echo 'AN ERROR HAS OCCURRED:' . PHP_EOL;
    echo $e->getMessage() . PHP_EOL;
    exit(1);
}
// generally speaking, this script will be run from the command line
exit(0);
 public static function init()
 {
     if (self::$is_inited) {
         return true;
     }
     /** 载入基本配置 **/
     $app_config = self::loadConfig();
     $default_config = (require FRAME_PATH . '/config/default.php');
     self::$config = array_merge($default_config, $app_config);
     /** 初始化缓存信息 **/
     self::$cache = self::getInstance(ucfirst(self::$config['cache_type']) . 'Cache');
     /** 初始化DB配置及连接 **/
     foreach (self::$config['db_source'] as $key => $val) {
         /** 通过URL方式配置获得[scheme],[user],[pass],[host],[port]索引变量 **/
         $val = parse_url($val);
         self::$db[$key] = self::getInstance(ucfirst($val['scheme']) . 'Db');
         self::$db[$key]->init($val, self::$config['db_charset']);
         self::$config['db.' . $key] = $val;
         if (self::$db_default === false) {
             self::$db_default = $key;
         }
     }
     self::$input = self::getInstance('AppInput');
     self::$output = self::getInstance('AppOutput');
     /** 处理当前请求类型 **/
     if (isset($_SERVER["CONTENT_TYPE"]) && $_SERVER['CONTENT_TYPE'] == 'application/x-amf') {
         self::$model = 'amf';
     }
     /** 进行输入处理 **/
     if (self::$model == 'text') {
         $argv = $_SERVER['argv'];
         $script = array_shift($argv);
         parse_str(implode('&', $argv), $args);
         $args['script'] = $script;
         self::in($args);
     } else {
         $uri = self::getInstance('URI');
         $data_array = array_merge($_GET, $_POST, $uri->getVars());
         self::in($data_array);
         /*
         foreach( $data_array as $key=>$val ) {
             self::$input->$key = self::addslash($val);
         }
         */
         unset($_GET, $_POST);
     }
     if (!empty(self::$config['session_start'])) {
         session_start();
     }
     self::$is_inited = true;
 }
 protected function _getListGroupsSimType(PB\Inventory\ListQuery $req)
 {
     $status = array(PB\SimType::GLOBALTYPE => 'GLOBAL', PB\SimType::LOCALTYPE => 'LOCAL');
     $maxFirstPage = $req->getGroupsWithFirstPage() !== null ? $req->getGroupsWithFirstPage() : 5;
     $response = new PB\Inventory\ListQuery\Response();
     $result = new PB\Result();
     $response->setResult($result);
     if ($req->getFilter() === null) {
         $filterMess = new PB\Inventory\ListQuery\Filter();
     } else {
         $filterMess = $req->getFilter();
     }
     try {
         foreach ($status as $state => $label) {
             $auxReq = clone $req;
             $criteria = new Criteria();
             $criteria->setType(Criteria\Type::SIM_TYPE);
             $criteria->setSimType($state);
             $criteria->setReverse(false);
             $auxReq->setFilter(clone $filterMess);
             $auxReq->getFilter()->addCriterias($criteria);
             $sims = $this->_listSims($auxReq);
             $data = new PB\Inventory\ListQuery\Response\Data();
             $cacheData = $auxReq->serialize();
             $cacheId = uniqid();
             \App::cache()->save($cacheData, 'mock' . $cacheId, array(), $req->getQueryPaging()->getMaxTimeout());
             $data->setHandler($cacheId);
             $data->setDescription($label);
             $result->setCode(0);
             $result->setReason('Ok');
             $data->setRowCounter($sims->count());
             if ($maxFirstPage > 0) {
                 while ($sims->hasNext()) {
                     $sims->getNext();
                     $sim = $sims->current();
                     $sim['id'] = $sim['_id'];
                     unset($sim['_id']);
                     $row = new PB\Inventory\Row();
                     $row->parse($sim, new \DrSlump\Protobuf\Codec\PhpArray());
                     $data->addPage($row);
                 }
             }
             $maxFirstPage--;
             $response->addData($data);
         }
     } catch (Exception $e) {
         \App::log()->WARN($e);
         $result->setCode(1);
         $result->setReason($e->getMessage());
     }
     return $response;
 }
Example #14
0
/**
 * @var MongoCollection
 */
$db = $cli->getResource('mongo');
define("DEFAULT_ACL_BASEPATH", realpath(APPLICATION_PATH . '/../data/acl'));
try {
    $env = $cli->getOption('e');
    $drop = $cli->getOption('d') ? true : false;
    $f = file_get_contents(DEFAULT_ACL_BASEPATH . "/build/acl_out.json", 'r');
    if (!$f) {
        throw new Exception("Error to load file \n");
    }
    //decoding json file
    $json_a = Zend_Json_Decoder::decode($f);
    if ($drop) {
        echo "\nDrop acl_portal from " . $env . " env \n";
        $db->acl_portal->drop();
    }
    foreach ($json_a as $element) {
        $db->acl_portal->insert($element);
    }
    \App::cache()->clean(Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array('Namespace'));
    echo "JSON data to mongo collection acl_portal ..OK \n\n";
} catch (Exception $e) {
    echo 'AN ERROR HAS OCCURRED:' . PHP_EOL;
    echo $e->getMessage() . PHP_EOL;
    echo $cli->getUsageMessage();
    exit(1);
}
// generally speaking, this script will be run from the command line
exit(0);
 /**
  * Get an specific sim by its Id
  */
 public function getAction()
 {
     $id = $this->getRequest()->getParam('id');
     $idType = $this->getRequest()->getParam('idType');
     if ($this->getRequest()->getParam('_avoidCache', false)) {
         \App::cache()->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('Sim', $id));
     }
     if ($idType) {
         $sim = $this->_simSrv->load($id, \App::getOrgUserLogged(), $idType);
     } else {
         $sim = $this->_simSrv->load($id, \App::getOrgUserLogged());
     }
     if (empty($sim)) {
         throw new NotFoundException("Sim {$id} not found");
     }
     // Check if it's allowed to perform this action
     $this->_helper->checkSimReadPermissions($sim);
     try {
         $this->_helper->allowed('read_alarm_sim_detail', $sim);
         // Add alarms list to sim response (depends on alarm permissions)
         $this->_addAlarms($sim);
     } catch (\Application\Exceptions\ForbiddenException $e) {
         $sim->setAlarms(null);
     }
     $this->view->data = $sim;
 }
 /**
  *
  * @param string|AsyncTransaction $transaction
  */
 protected function _delete($transaction)
 {
     if (!$transaction instanceof AsyncTransaction) {
         $transaction = $this->load($transaction);
     }
     // Clean the related ids
     $ids = $transaction->getIds();
     if (is_array($ids)) {
         foreach ($ids as $id) {
             \App::log()->debug("Removing item '{$id}' from cache.");
             \App::cache()->remove(\App_Util_String::toCacheId($id));
         }
     }
     // Clean the related tags
     $tags = $transaction->getTags();
     if (is_array($tags)) {
         $tagList = implode("', '", $tags);
         \App::log()->debug("Removing tags '{$tagList}' from cache.");
         foreach ($tags as &$tag) {
             $tag = \App_Util_String::toCacheId($tag);
         }
         \App::cache()->clean(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, $tags);
     }
     // Clean the transaction itself
     // GLOBALPORTAL-28156: Juanjo Martín Rodríguez added a comment - 05/Dec/12 5:35 PM
     // 2012-12-04T18:42:06+01:00 [3so0gz-11xvrt] CRIT Application error: Invalid id or tag '136cp3c-11xp7y-50be35e6c6df8' : must use only [a-zA-Z0-9_]
     \App::cache()->remove($this->_getCacheId($transaction->getId()));
 }
Example #17
0
 //or use mysql sessions
 new \sb\Session\Mysql(App::$db);

 //or use memcache sessions
 new \sb\Session\Memcache('localhost', 11211);

 </code>
*/
//session handler
if (!headers_sent()) {
    session_start();
}
/**
* ASSIGN APP's OTHER STATIC PROPERTIES HERE
* All static properties of App class, found in this directory are avaiable throughout your code in any scope.
* Remember before assigning properties they must be documented on the App class itself in App.php.  If you put the proper phpDoc
* comments on the properties of App, the code completion will be available in eclipse/zend studio
* Example include, the application cache and your database connections.
* 
 <code>
 //define the App user
 App::$user = new \sb\User();
 App::$user->uname = 'tester';
 </code>
*/
//define the application's main caching engine
App::$cache = new \sb\Cache\FileSystem();
//define the application's main logging engine
App::$logger = new \sb\Logger\FileSystem();
\sb\Application\Debugger::init();
Example #18
0
 /**
  * Generate a view from a string
  *
  * @param string $content The string of the origin template
  * @param array  $data    The data to apply to the view
  *
  * @return string The HTML result of the string
  */
 public static function makeFromString($content, $data = array())
 {
     $file = tempnam(TMP_DIR, '');
     file_put_contents($file, $content);
     // calculate the view
     $view = new self($file);
     $view->setData($data);
     $result = $view->display();
     // Remove temporary files
     unlink($file);
     App::cache()->clear($view->cacheFile);
     return $result;
 }
Example #19
0
 protected function _fetchPage($rawData)
 {
     $listQueryClass = $this->_spec['listQueryClass'];
     $fetchResponseClass = $this->_spec['orgPageClass'];
     $response = new $fetchResponseClass();
     $result = new \Application\Proto\Result();
     $response->setResult($result);
     try {
         $cacheData = \App::cache()->load('mock' . $rawData->getQueryFetch()->getHandler());
         if (!$cacheData) {
             $result->setCode(-1);
             $result->setReason("Handler does not exist.");
             return $response;
         }
         $oldMessage = new $listQueryClass($cacheData);
         $oldMessage->setQueryPaging($rawData->getQueryFetch()->getQueryPaging());
         $orgs = $this->_listOrgs($oldMessage, $this->getRestMethod()->mock->orgType);
         $result->setCode(0);
         $result->setReason('Ok');
         while ($orgs->hasNext()) {
             $orgs->getNext();
             $response->addRows($this->_createListData($orgs->current()));
         }
     } catch (Exception $e) {
         \App::log()->WARN($e);
         $result->setCode(1);
         $result->setReason($e->getMessage());
     }
     return $response;
 }
Example #20
0
 /**
  * Write Session - commit data to resource
  *
  * @param string $id
  * @param mixed  $data
  */
 public function write($id, $data)
 {
     try {
         if (empty($_SESSION)) {
             $this->destroy($id);
             return;
         }
         $exists = isset($this->_sessionHashes[$id]);
         $modified = $exists && $this->_sessionHashes[$id] !== md5($data);
         if (!$exists || $modified) {
             $filter = array('_id' => $id);
             $options = array('upsert' => true, 'multiple' => false);
             $update = array('data' => $data, 'metadata.created' => new MongoDate(time()), 'rawData' => $_SESSION);
             if (!$exists) {
                 $update['metadata.expire'] = new MongoDate(time() + $this->_maxLifeTime);
             }
             \App::cache()->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('session'));
             $result = $this->_collection->update($filter, array('$set' => $update), $options);
             if ($result['ok'] == 1) {
                 return true;
             }
         } else {
             return true;
         }
     } catch (Exception $e) {
         \App::log()->crit($e);
     }
     return false;
 }
use Core\Service\WatcherService;
use Core\Model\EventModel;
use Application\Exceptions\InvalidArgumentException;
require_once realpath(dirname(__FILE__) . '/lib/Cli.php');
/**
 * Script
 */
$cli = new Cli(array('file|f-s' => "Json file for event.", 'cacheId|c-s' => "CacheId of event.", 'scopes|s=s' => "Coma separated scopes", 'low|l' => "Mark as priority low. If it isn't send it use high priority."));
try {
    if ($file = $cli->getOption('f')) {
        if (!file_exists($file)) {
            throw new InvalidArgumentException("File doesn't exist");
        }
        $json = file_get_contents($file);
        unlink($file);
        $data = Zend_Json::decode($json);
        $event = new EventModel($data);
    } else {
        if (!($cacheId = $cli->getOption('c')) || !($event = \App::cache()->load($cacheId))) {
            throw new InvalidArgumentException("File or cacheId valid is required");
        }
    }
    $scopes = explode(',', $cli->getOption('s'));
    $priority = $cli->getOption('l') ? WatcherModel::PRIORITY_HIGH : WatcherModel::PRIORITY_LOW;
    PopboxService::getInstance()->sendNotification($scopes, $event, $priority);
    //create JSON file from acl_portal collection
} catch (Exception $e) {
    echo "Error:\n";
    echo get_class($e) . ": " . $e->getMessage() . "\n";
    echo $e->getTraceAsString();
}
Example #22
0
 /**
  *
  * @param  string $resource
  * @param  string $key
  * @return array
  */
 protected function _getConfig($resource, $key)
 {
     if (!in_array($resource, array(self::RESOURCE_REPORT, self::RESOURCE_SIM))) {
         throw new InvalidArgumentException("Invalid config resource ({$resource})");
     }
     if (!in_array($key, array(self::KEY_HEADERS, self::KEY_FILTERS, self::KEY_FILE_HEADERS, self::KEY_FILE_FOOTERS))) {
         throw new InvalidArgumentException("Invalid config key ({$key})");
     }
     // Get CSV configuration
     $cacheId = \App_Util_String::toCacheId('csv_config_' . $resource);
     $config = \App::cache()->load($cacheId);
     if (empty($config)) {
         $config = new \Tid_Zend_Config_Yaml(APPLICATION_PATH . "/modules/default/views/csv/{$resource}.yml");
         \App::cache()->save($config, $cacheId);
     }
     return $config;
 }