function MAL_EVAL($ast, $env) { #echo "MAL_EVAL: " . _pr_str($ast) . "\n"; if (!_list_Q($ast)) { return eval_ast($ast, $env); } if ($ast->count() === 0) { return $ast; } // apply list $a0 = $ast[0]; $a0v = _symbol_Q($a0) ? $a0->value : $a0; switch ($a0v) { case "def!": $res = MAL_EVAL($ast[2], $env); return $env->set($ast[1], $res); case "let*": $a1 = $ast[1]; $let_env = new Env($env); for ($i = 0; $i < count($a1); $i += 2) { $let_env->set($a1[$i], MAL_EVAL($a1[$i + 1], $let_env)); } return MAL_EVAL($ast[2], $let_env); default: $el = eval_ast($ast, $env); $f = $el[0]; return call_user_func_array($f, array_slice($el->getArrayCopy(), 1)); } }
function MAL_EVAL($ast, $env) { #echo "MAL_EVAL: " . _pr_str($ast) . "\n"; if (!_list_Q($ast)) { return eval_ast($ast, $env); } if ($ast->count() === 0) { return $ast; } // apply list $a0 = $ast[0]; $a0v = _symbol_Q($a0) ? $a0->value : $a0; switch ($a0v) { case "def!": $res = MAL_EVAL($ast[2], $env); return $env->set($ast[1], $res); case "let*": $a1 = $ast[1]; $let_env = new Env($env); for ($i = 0; $i < count($a1); $i += 2) { $let_env->set($a1[$i], MAL_EVAL($a1[$i + 1], $let_env)); } return MAL_EVAL($ast[2], $let_env); case "do": #$el = eval_ast(array_slice($ast->getArrayCopy(), 1), $env); $el = eval_ast($ast->slice(1), $env); return $el[count($el) - 1]; case "if": $cond = MAL_EVAL($ast[1], $env); if ($cond === NULL || $cond === false) { if (count($ast) === 4) { return MAL_EVAL($ast[3], $env); } else { return NULL; } } else { return MAL_EVAL($ast[2], $env); } case "fn*": return function () use($env, $ast) { $fn_env = new Env($env, $ast[1], func_get_args()); return MAL_EVAL($ast[2], $fn_env); }; default: $el = eval_ast($ast, $env); $f = $el[0]; return call_user_func_array($f, array_slice($el->getArrayCopy(), 1)); } }
/** * @param MediaSourceManager $mediaBrowserConfiguration */ public function mediasourceLoad(MediaSourceManager $mediaBrowserConfiguration) { global $_ARRAYLANG; \Env::get('init')->loadLanguageData('MediaBrowser'); $mediaType = new MediaSource('files', $_ARRAYLANG['TXT_FILEBROWSER_FILES'], array($this->cx->getWebsiteImagesContentPath(), $this->cx->getWebsiteImagesContentWebPath()), array(), 1); $mediaBrowserConfiguration->addMediaType($mediaType); }
/** * Example of function that defines a setup process common to all the * application. May be take as a template, or used as-is. Suggestions on new * things to include or ways to improve it are welcome :) */ function bootstrap(int $env = Env::PROD) { // Set the encoding of the mb_* functions mb_internal_encoding('UTF-8'); // Set the same timezone as the one used by the database date_default_timezone_set('UTC'); // Get rid of PHP's default custom header header_remove('X-Powered-By'); // Determine the current environment Env::set($env); // Control which errors are fired depending on the environment if (Env::isProd()) { error_reporting(0); ini_set('display_errors', '0'); } else { error_reporting(E_ALL & ~E_NOTICE); ini_set('display_errors', '1'); } // Handling errors from exceptions set_exception_handler(function (\Throwable $e) { $data = ['title' => 'Unexpected exception', 'detail' => $e->getMessage() ?: '']; if (Env::isDev()) { $data['debug'] = ['exception' => get_class($e) . ' (' . $e->getCode() . ')', 'file' => $e->getFile() . ':' . $e->getLine(), 'trace' => $e->getTrace()]; } (new Response(HttpStatus::InternalServerError, [], $data))->send(); }); // Handling errors from trigger_error and the alike set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline, array $errcontext) { $data = ['title' => 'Unexpected error', 'detail' => $errstr ?: '']; if (Env::isDev()) { $data['debug'] = ['error' => $errno, 'file' => $errfile . ':' . $errline, 'context' => $errcontext]; } (new Response(HttpStatus::InternalServerError, [], $data))->send(); }); }
public static function registerYamlSettingEventListener() { $evm = \Env::get('cx')->getEvents(); $yamlSettingEventListener = new \Cx\Core\Config\Model\Event\YamlSettingEventListener(); $evm->addModelListener(\Doctrine\ORM\Events::preUpdate, 'Cx\\Core\\Setting\\Model\\Entity\\YamlSetting', $yamlSettingEventListener); $evm->addModelListener('postFlush', 'Cx\\Core\\Setting\\Model\\Entity\\YamlSetting', $yamlSettingEventListener); }
/** * @param Sigma $template */ public function preFinalize(Sigma $template) { if (count($this->mediaBrowserInstances) == 0) { return; } else { global $_ARRAYLANG; /** * @var $init \InitCMS */ $init = \Env::get('init'); $init->loadLanguageData('MediaBrowser'); foreach ($_ARRAYLANG as $key => $value) { if (preg_match("/TXT_FILEBROWSER_[A-Za-z0-9]+/", $key)) { \ContrexxJavascript::getInstance()->setVariable($key, $value, 'mediabrowser'); } } $thumbnailsTemplate = new Sigma(); $thumbnailsTemplate->loadTemplateFile($this->cx->getCoreModuleFolderName() . '/MediaBrowser/View/Template/Thumbnails.html'); $thumbnailsTemplate->setVariable('TXT_FILEBROWSER_THUMBNAIL_ORIGINAL_SIZE', sprintf($_ARRAYLANG['TXT_FILEBROWSER_THUMBNAIL_ORIGINAL_SIZE'])); foreach (UploaderConfiguration::getInstance()->getThumbnails() as $thumbnail) { $thumbnailsTemplate->setVariable(array('THUMBNAIL_NAME' => sprintf($_ARRAYLANG['TXT_FILEBROWSER_THUMBNAIL_' . strtoupper($thumbnail['name']) . '_SIZE'], $thumbnail['size']), 'THUMBNAIL_ID' => $thumbnail['id'], 'THUMBNAIL_SIZE' => $thumbnail['size'])); $thumbnailsTemplate->parse('thumbnails'); } \ContrexxJavascript::getInstance()->setVariable('thumbnails_template', $thumbnailsTemplate->get(), 'mediabrowser'); \JS::activate('mediabrowser'); \JS::registerJS('core_modules/MediaBrowser/View/Script/mediabrowser.js'); } }
/** * Do something after resolving is done * * @param \Cx\Core\ContentManager\Model\Entity\Page $page The resolved page */ public function postResolve(\Cx\Core\ContentManager\Model\Entity\Page $page) { global $plainCmd, $cmd, $_CORELANG; // CSRF code needs to be even in the login form. otherwise, we // could not do a super-generic check later.. NOTE: do NOT move // this above the "new cmsSession" line! Csrf::add_code(); // CSRF protection. // Note that we only do the check as long as there's no // cmd given; this is so we can reload the main screen if // the check has failed somehow. // fileBrowser is an exception, as it eats CSRF codes like // candy. We're doing \Cx\Core\Csrf\Controller\Csrf::check_code() in the relevant // parts in the module instead. // The CSRF code needn't to be checked in the login module // because the user isn't logged in at this point. // TODO: Why is upload excluded? The CSRF check doesn't take place in the upload module! if (!empty($plainCmd) && !empty($cmd) and !in_array($plainCmd, array('FileBrowser', 'Upload', 'Login', 'Home'))) { // Since language initialization in in the same hook as this // and we cannot define the order of module-processing, // we need to check if language is already initialized: if (!is_array($_CORELANG) || !count($_CORELANG)) { $objInit = \Env::get('init'); $objInit->_initBackendLanguage(); $_CORELANG = $objInit->loadLanguageData('core'); } Csrf::check_code(); } }
function langA($name, $args) { static $base = null; $value = Localization::instance()->lang($name); if (is_null($value)) { if (!Env::isDebugging()) { if (!$base instanceof Localization) { $base = new Localization(); $base->loadSettings("en_us", ROOT . "/language"); } $value = $base->lang($name); } if (is_null($value)) { $value = Localization::instance()->lang(str_replace(" ", "_", $name)); if (is_null($value)) { $value = Localization::instance()->lang(str_replace("_", " ", $name)); if (is_null($value)) { return "Missing lang: {$name}"; } } } } // We have args? Replace all {x} with arguments if (is_array($args) && count($args)) { $i = 0; foreach ($args as $arg) { $value = str_replace('{' . $i . '}', $arg, $value); $i++; } // foreach } // if // Done here... return $value; }
/** * Initialize this interface * * Loads all commands * @param \Cx\Core\Core\Controller\Cx $cx Cloudrexx main class */ public function __construct($cx) { $this->cx = $cx; \Env::get('ClassLoader')->loadFile(ASCMS_CORE_PATH . '/Typing/Model/Entity/AutoBoxedObject.class.php'); \Env::get('ClassLoader')->loadFile(ASCMS_CORE_PATH . '/Typing/Model/Entity/Primitives.class.php'); $this->commands = array('db' => new DbCommand($this), 'import' => new ImportCommand($this), 'create' => new CreateCommand($this), 'uninstall' => new UninstallCommand($this), 'activate' => new ActivateCommand($this), 'deactivate' => new DeactivateCommand($this), 'move' => new MoveCommand($this), 'copy' => new CopyCommand($this), 'remove' => new RemoveCommand($this), 'test' => new TestCommand($this), 'export' => new ExportCommand($this)); }
/** * Constructor * the class JsonLink handles, the link status whether the link is resolved or not. */ public function __construct() { $this->em = \Env::get('em'); if ($this->em) { $this->linkRepo = $this->em->getRepository('\\Cx\\Core_Modules\\LinkManager\\Model\\Entity\\Link'); } }
function find_cinemas_brazil() { $start = microtime(true); $cinemas_br = Env::path('temp/brasil.json'); $cinemas_br = file_get_contents($cinemas_br); $cinemas_br = json_decode($cinemas_br); //loop em todos os estados e cidades do estado $new_cinemas = array(); $invalid_cinemas = array(); foreach ($cinemas_br as $value) { $estado = $value->nome; $uf = $value->codigo; $cidades = $value->cidades; $cinema_finder = new CinemaFinder('br', $uf, $cidades); $cinemas = $cinema_finder->get_all_cinemas(); $template = new CinemaTemplate(); foreach ($cinemas as $cinema) { $base_dir = "cinema/br/"; //passa o codigo do estado temporariamente para depois alterar e verificar se o cinema é realmente desse local $cinema->state_code = $uf; $template->create($base_dir, $cinema); } $new_cinemas = array_merge($new_cinemas, $template->get_new_cinemas()); $invalid_cinemas = array_merge($invalid_cinemas, $template->get_invalid_cinemas()); } $total = Helper::elapsed_time($start); Log::write("Tempo total procurando cinemas: {$total}"); Sendmail::to_admin(count($new_cinemas) . " cinemas novos", $new_cinemas); Sendmail::to_admin(count($invalid_cinemas) . " cinemas sem cidade", $invalid_cinemas); }
public function preContentLoad(\Cx\Core\ContentManager\Model\Entity\Page $page) { global $_CONFIG, $objNewsML, $arrMatches, $page_template, $themesPages, $cl; // Set NewsML messages if ($_CONFIG['feedNewsMLStatus'] == '1') { if (preg_match_all('/{NEWSML_([0-9A-Z_-]+)}/', \Env::get('cx')->getPage()->getContent(), $arrMatches)) { /** @ignore */ if ($cl->loadFile(\Env::get('cx')->getCodeBaseModulePath() . '/Feed/Controller/NewsML.class.php')) { $objNewsML = new NewsML(); $objNewsML->setNews($arrMatches[1], \Env::get('cx')->getPage()->getContent()); } } if (preg_match_all('/{NEWSML_([0-9A-Z_-]+)}/', $page_template, $arrMatches)) { /** @ignore */ if ($cl->loadFile(\Env::get('cx')->getCodeBaseModulePath() . '/Feed/Controller/NewsML.class.php')) { $objNewsML = new NewsML(); $objNewsML->setNews($arrMatches[1], $page_template); } } if (preg_match_all('/{NEWSML_([0-9A-Z_-]+)}/', $themesPages['index'], $arrMatches)) { /** @ignore */ if ($cl->loadFile(\Env::get('cx')->getCodeBaseModulePath() . '/Feed/Controller/NewsML.class.php')) { $objNewsML = new NewsML(); $objNewsML->setNews($arrMatches[1], $themesPages['index']); } } } }
/** * Construct the MailController * * @access public * @param void * @return MailController */ function __construct() { parent::__construct(); prepare_company_website_controller($this, 'website'); Env::useHelper('MailUtilities.class', $this->plugin_name); require_javascript("AddMail.js", $this->plugin_name); }
public static function getInstance() { if (!self::$_instance) { self::$_instance = new self(); } return self::$_instance; }
function testGetAfterSet() { Env::set(Env::PROD); $this->assertEquals(Env::get(), Env::PROD); $this->assertTrue(Env::isProd()); $this->assertFalse(Env::isTest()); }
protected function preRender($lang) { if ($this->template->placeholderExists('LEVELS_FULL') || $this->template->placeholderExists('levels_full')) { $this->rootNode = \Env::get('em')->getRepository('Cx\\Core\\ContentManager\\Model\\Entity\\Node')->getRoot(); } $this->realPreRender($lang); }
/** * @param MediaSourceManager $mediaBrowserConfiguration */ public function mediasourceLoad(MediaSourceManager $mediaBrowserConfiguration) { global $_ARRAYLANG; \Env::get('init')->loadLanguageData('Contact'); $mediaType = new MediaSource('attach', $_ARRAYLANG['TXT_CONTACT_UPLOADS'], array($this->cx->getWebsiteImagesAttachPath(), $this->cx->getWebsiteImagesAttachWebPath())); $mediaBrowserConfiguration->addMediaType($mediaType); }
/** * Load your component. * * @param \Cx\Core\ContentManager\Model\Entity\Page $page The resolved page */ public function load(\Cx\Core\ContentManager\Model\Entity\Page $page) { global $objTemplate, $sessionObj; switch ($this->cx->getMode()) { case \Cx\Core\Core\Controller\Cx::MODE_FRONTEND: if (!isset($sessionObj) || !is_object($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } $objLogin = new \Cx\Core_Modules\Login\Controller\Login(\Env::get('cx')->getPage()->getContent()); $pageTitle = \Env::get('cx')->getPage()->getTitle(); $pageMetaTitle = \Env::get('cx')->getPage()->getMetatitle(); \Env::get('cx')->getPage()->setContent($objLogin->getContent($pageMetaTitle, $pageTitle)); break; case \Cx\Core\Core\Controller\Cx::MODE_BACKEND: if (\FWUser::getFWUserObject()->objUser->login(true)) { \Cx\Core\Csrf\Controller\Csrf::header('location: index.php'); } $this->cx->getTemplate()->addBlockfile('CONTENT_OUTPUT', 'content_master', 'LegacyContentMaster.html'); $objTemplate = $this->cx->getTemplate(); $objLoginManager = new \Cx\Core_Modules\Login\Controller\LoginManager(); $objLoginManager->getPage(); break; default: break; } }
/** * Load your component. * * @param \Cx\Core\ContentManager\Model\Entity\Page $page The resolved page */ public function load(\Cx\Core\ContentManager\Model\Entity\Page $page) { global $_CORELANG, $subMenuTitle, $objTemplate; switch ($this->cx->getMode()) { case \Cx\Core\Core\Controller\Cx::MODE_FRONTEND: $objJobs = new Jobs(\Env::get('cx')->getPage()->getContent()); \Env::get('cx')->getPage()->setContent($objJobs->getJobsPage()); if ($page->getCmd() === 'details') { $objJobs->getPageTitle(\Env::get('cx')->getPage()->getTitle()); \Env::get('cx')->getPage()->setTitle($objJobs->jobsTitle); \Env::get('cx')->getPage()->setContentTitle($objJobs->jobsTitle); \Env::get('cx')->getPage()->setMetaTitle($objJobs->jobsTitle); } break; case \Cx\Core\Core\Controller\Cx::MODE_BACKEND: $this->cx->getTemplate()->addBlockfile('CONTENT_OUTPUT', 'content_master', 'LegacyContentMaster.html'); $objTemplate = $this->cx->getTemplate(); \Permission::checkAccess(148, 'static'); $subMenuTitle = $_CORELANG['TXT_JOBS_MANAGER']; $objJobsManager = new JobsManager(); $objJobsManager->getJobsPage(); break; default: break; } }
/** * Just textile the text and return * * @param string $text Input text * @return string */ function do_textile($text) { Env::useLibrary('textile'); $textile = new Textile(); $text = $textile->TextileRestricted($text, false, false); return add_links($text); }
/** * Returns the group ids with access to front- or backend of a page * @param \Cx\Core\ContentManager\Model\Entity\Page $page Page to get the group ids of * @param boolean $frontend True for frontend access groups, false for backend * @return mixed Array of group ids or false on error * @throws PageGuardException */ public function getAssignedGroupIds($page, $frontend) { if ($frontend && !$page->isFrontendProtected()) { return array(); } if (!$frontend && !$page->isBackendProtected()) { return array(); } try { $accessId = $this->getAccessId($page, $frontend); } catch (PageGuardException $e) { // the selected page is listed as protected but does not have an access id. // this is probably due to a db inconsistency, which we should be able to handle gracefully: $accessId = \Permission::createNewDynamicAccessId(); if ($frontend && $accessId) { $page->setFrontendAccessId($accessId); } elseif (!$frontend && $accessId) { $page->setBackendAccessId($accessId); } else { // cannot create a new dynamic access id. throw new PageGuardException('This protected page doesn\'t have an access id associated with it. Contrexx encountered an error while generating a new access id.'); } Env::get('em')->persist($page); Env::get('em')->flush(); } return \Permission::getGroupIdsForAccessId($accessId); }
public function runTaskAction() { // load details $taskId = @$_GET['id']; $classMethod = @$_GET['method']; $mac = @$_GET['auth']; // verify hash $date = new \DateTime(); $password = hash('sha256', $date->format('Y-m-d H:i:s') . $taskId . Env::get('auth_salt')); $expectedMac = hash_hmac('sha256', $classMethod, $password); // if hash is invalid, try again with a 1 second ago date if ($mac != $expectedMac) { $date = (new \DateTime())->sub(new \DateInterval("PT1S")); $password = hash('sha256', $date->format('Y-m-d H:i:s') . $taskId . Env::get('auth_salt')); $expectedMac = hash_hmac('sha256', $classMethod, $password); } if ($mac != $expectedMac) { throw new \Exception('Invalid auth token'); } $classMethod = json_decode($classMethod); $class = $classMethod[0]; $method = $classMethod[1]; $obj = new $class(); $obj->{$method}(); }
public function showPrices() { global $_ARRAYLANG; $prices = $this->priceRepository->findAll(); if (empty($prices)) { $prices = new \Cx\Modules\Pim\Model\Entity\Price(); } $view = new \Cx\Core\Html\Controller\ViewGenerator($prices, array('header' => $_ARRAYLANG['TXT_MODULE_PIM_ACT_PRICE'], 'validate' => function ($formGenerator) { // this validation checks whether already a price for the currency and product exists $data = $formGenerator->getData()->toArray(); $currency = $data['currency']; $product = $data['product']; $priceRepository = \Env::get('cx')->getDb()->getEntityManager()->getRepository('Cx\\Modules\\Pim\\Model\\Entity\\Price'); $prices = $priceRepository->createQueryBuilder('p')->where('p.currency = ?1')->setParameter(1, $currency)->andWhere('p.product = ?2')->setParameter(2, $product); $prices = $prices->getQuery()->getResult(); if (!empty($data['editid']) && count($prices) > 1) { return false; } if (empty($data['editid']) && count($prices) > 0) { return false; } return true; }, 'functions' => array('add' => true, 'edit' => true, 'delete' => true, 'sorting' => true, 'paging' => true, 'filtering' => false))); $this->template->setVariable('PRICES_CONTENT', $view->render()); }
public function testEnv() { $this->assertTrue(Env::init()); putenv('FOO=123'); $this->assertSame(123, env('FOO')); $this->assertFalse(Env::init()); }
public function mediasourceLoad(MediaSourceManager $mediaBrowserConfiguration) { global $_ARRAYLANG; \Env::get('init')->loadLanguageData('Gallery'); $mediaType = new MediaSource('gallery', $_ARRAYLANG['TXT_THUMBNAIL_GALLERY'], array($this->cx->getWebsiteImagesGalleryPath(), $this->cx->getWebsiteImagesGalleryWebPath(), array(12, 67))); $mediaBrowserConfiguration->addMediaType($mediaType); }
private static function getClient() { if (!self::$_client) { self::$_client = new GuzzleHttp\Client(array('base_uri' => Env::get('github_api_url', 'https://api.github.com'))); } return self::$_client; }
public function preInit(\Cx\Core\Core\Controller\Cx $cx) { global $_CONFIG; $domainRepo = new \Cx\Core\Net\Model\Repository\DomainRepository(); $_CONFIG['domainUrl'] = $domainRepo->getMainDomain()->getName(); \Env::set('config', $_CONFIG); }
protected function handle_editor() { $this->art->body = Env::v('nl_body'); $this->art->title = Env::v('nl_title'); $this->art->append = Env::v('nl_append'); return true; }
public function mediasourceLoad(MediaSourceManager $mediaBrowserConfiguration) { global $_ARRAYLANG; \Env::get('init')->loadLanguageData('MediaDir'); $mediaType = new MediaSource('mediadir', $_ARRAYLANG['TXT_FILEBROWSER_MEDIADIR'], array($this->cx->getWebsiteImagesMediaDirPath(), $this->cx->getWebsiteImagesMediaDirWebPath()), array(153)); $mediaBrowserConfiguration->addMediaType($mediaType); }
private function initialize($name) { $log_file = Env::get('log_path') . date('Y-m-d') . '.log'; $log = new \Monolog\Logger($name); $log->pushHandler(new \Monolog\Handler\StreamHandler($log_file)); self::$logger[$name] = $log; }