Exemplo n.º 1
0
 /**
  * If we work with multiple collections,
  * it is necessary cleanup old data everywhere before saving
  *
  * @param string $locale
  */
 protected function _cleanup($name, $locale = null)
 {
     $collections = SlConfigure::read(null, 'populated', true);
     foreach ($collections as $collection) {
         SlConfigure::delete($name, true, $locale ? "{$collection}.{$locale}" : $collection);
     }
 }
Exemplo n.º 2
0
 function __construct()
 {
     $db = SlConfigure::read('Db');
     foreach ($db as $name => $value) {
         $this->{$name} = $value;
     }
 }
Exemplo n.º 3
0
 public static function started()
 {
     if (self::$_started === null) {
         $options = SlConfigure::read('Sl.session');
         session_write_close();
         foreach ($options as $option => $value) {
             if (isset($value)) {
                 ini_set("session.{$option}", $value);
             }
         }
         self::$_started = session_start();
         if (!self::$_started) {
             return false;
         }
         self::$data =& $_SESSION;
         // prevent proxy-jumping and session hijacks
         $ip = self::read('Security.remoteAddr');
         if ($ip && env('REMOTE_ADDR') != $ip) {
             session_write_close();
             session_regenerate_id(true);
             self::$_started = session_start();
         }
         if (empty($ip)) {
             self::write('Security.remoteAddr', env('REMOTE_ADDR'));
         }
     }
     return self::$_started;
 }
Exemplo n.º 4
0
 public function oauth()
 {
     if (isset($this->params['url']['code'])) {
         $code = $this->params['url']['code'];
     }
     SlSession::write('Api.facebook.accessToken', r('access_token=', '', $this->Facebook->graph("oauth/access_token", array('client_id' => SlConfigure::read('Api.facebook.appId'), 'redirect_uri' => Sl::url(true), 'client_secret' => SlConfigure::read('Api.facebook.secret'), 'code' => $code, 'decode' => false))));
     $this->redirect(SlConfigure::read('Api.facebook.oauthSuccess'));
 }
Exemplo n.º 5
0
 public function admin_index($activeSection = null)
 {
     $this->set('sections', $sections = SlConfigure::read2("Config.sections"));
     foreach ($sections as $section => $settings) {
         if (!SlAuth::isAuthorized('config' . Inflector::camelize($section))) {
             unset($sections[$i]);
         }
     }
     if (isset($this->data['_section'])) {
         $activeSection = $this->data['_section'];
     }
     if (empty($activeSection) || !isset($sections[$activeSection])) {
         $activeSection = reset(array_keys($sections));
     }
     $settings = $this->_getSettings($activeSection);
     $this->set('title', __t(SlConfigure::read2("Config.sections.{$activeSection}")));
     if ($this->data) {
         $locales = SlConfigure::read('I18n.locales');
         foreach ($settings as $name => &$setting) {
             if (is_int($name)) {
                 $name = "setting_{$name}";
             }
             if ($setting['collection'] == 'user') {
                 $setting['collection'] = 'User' . SlAuth::user('id');
             }
             if (empty($setting['translate'])) {
                 if (isset($this->data[$name])) {
                     $value = $this->data[$name];
                     if (isset($setting['type']) && $setting['type'] == 'json') {
                         $value = json_decode($value, true);
                     } elseif (isset($setting['type']) && $setting['type'] == 'array') {
                         $value = Set::normalize($value, false);
                     }
                     SlConfigure::write($setting['name'], $value, true, $setting['collection']);
                 }
             } else {
                 foreach ($locales as $locale) {
                     if (isset($this->data["{$name}_{$locale}"])) {
                         $value = $this->data["{$name}_{$locale}"];
                         if (isset($setting['type']) && $setting['type'] == 'json') {
                             $value = json_decode($value, true);
                         } elseif (isset($setting['type']) && $setting['type'] == 'array') {
                             $value = Set::normalize($value, false);
                         }
                         SlConfigure::write($setting['name'], $value, true, "{$setting['collection']}.{$locale}");
                     }
                 }
             }
         }
         $settings = $this->_getSettings($activeSection);
         $this->Session->setFlash(__t('Configuration saved'), array('class' => 'success'));
     }
     $this->data['_section'] = $activeSection;
     $this->set('settings', $settings);
 }
Exemplo n.º 6
0
 /**
  * @return SlExtensions
  */
 public static function getInstance()
 {
     if (self::$_instance === null) {
         SlConfigure::read();
         // make sure core configuration is loaded BEFORE plugins'
     }
     if (self::$_instance === null) {
         self::$_instance = new SlExtensions();
     }
     return self::$_instance;
 }
Exemplo n.º 7
0
 function parse($html = null, $blockName = 'document', $blockParams = null, $noCycle = false)
 {
     $messages = SlConfigure::read2('Message');
     if ($messages) {
         SlSession::delete('Message');
     } else {
         $messages = array();
     }
     $this->vars['bufferedOutput'] = SlConfigure::read('View.bufferedOutput');
     SlConfigure::delete('View.bufferedOutput');
     if ($messages || $this->vars['bufferedOutput']) {
         $this->blocks["loop"]->params[0] = $messages;
         return parent::parse($html, $blockName);
     }
 }
Exemplo n.º 8
0
 /**
  * Mark a node change, triggering cascade cache clearing
  *
  * @param AppModel $model
  * @param int $id
  */
 public function changed($model, $id = null)
 {
     if (empty($id)) {
         $id = $model->getID();
     }
     if ($model->Behaviors->enabled('Translate')) {
         $locales = SlConfigure::read('I18n.locales');
         foreach ($locales as $locale) {
             $key = Inflector::underscore($model->alias) . "_{$id}_{$locale}";
             Cache::delete($key, 'models');
         }
     } else {
         $key = Inflector::underscore($model->alias) . "_{$id}";
         Cache::delete($key, 'models');
     }
 }
Exemplo n.º 9
0
 /**
  * @param AppController $controller
  * @return bool
  */
 public function constructClasses($controller)
 {
     // load FireCake (see FirePhp)
     if (!function_exists('firecake') && Configure::read() && strpos(env('HTTP_USER_AGENT'), 'FirePHP') !== false) {
         App::import('Vendor', 'DebugKit.FireCake');
     }
     // load toolbar
     if (empty($controller->params['bare']) && SlConfigure::read('Sl.debug.debugKit') && Configure::read()) {
         // IE6 not supported
         if (strpos(env('HTTP_USER_AGENT'), 'MSIE 6') === false) {
             // sometimes needed in Ajax requests by DebugKit
             //                $controller->helpers[] = 'Form';
             $controller->components['DebugKit.Toolbar'] = in_array('Interactive', App::objects('plugin')) ? array('panels' => array('Interactive.interactive')) : array();
         }
     }
     return true;
 }
Exemplo n.º 10
0
 public function getSession($scope = null)
 {
     $this->accessToken = SlSession::read('Api.facebook.accessToken');
     if ($this->accessToken) {
         return;
     }
     if (is_array($scope)) {
         $scope = implode(',', $scope);
     }
     $appId = SlConfigure::read('Api.facebook.appId');
     $redirectUrl = array('plugin' => 'api', 'controller' => 'facebook', 'action' => 'oauth');
     if (!empty($this->params['prefix'])) {
         $redirectUrl += array($this->params['prefix'] => false);
     }
     $redirectUrl = urlencode(Sl::url($redirectUrl, true));
     $this->controller->redirect("https://graph.facebook.com/oauth/authorize?client_id={$appId}&redirect_uri={$redirectUrl}&scope={$scope}");
 }
Exemplo n.º 11
0
 public function admin_add()
 {
     $newItem = empty($this->data);
     $this->admin_edit();
     if ($newItem && !empty($this->params['named']['cms_node_id'])) {
         $nodeId = $this->params['named']['cms_node_id'];
         $node = $this->CmsBlock->CmsNode->read(null, $nodeId);
         if ($node) {
             // set link title to node title
             $locales = SlConfigure::read('I18n.locales');
             foreach ($locales as $locale) {
                 $this->data['CmsBlock']['title_' . $locale] = $node["CmsNode"]['short_title_' . $locale] ? $node["CmsNode"]['short_title_' . $locale] : $node["CmsNode"]['title_' . $locale];
             }
             $this->data['CmsBlock']['cms_node_id'] = $nodeId;
             $this->data['CmsBlock']['url'] = SlNode::url($node, array('base' => false, 'slug' => false, 'lang' => false));
         }
     }
     $this->render('admin_edit');
 }
Exemplo n.º 12
0
 /**
  * Get all data of a node (cached)
  *
  * @param int $id
  * @parsm bool $hit True to increment the hit counter
  * @return array
  */
 public static function read($id, $options = array())
 {
     if (empty($id)) {
         $id = self::getModel()->getID();
     }
     $options += array('hit' => false, 'auth' => false);
     $key = "cms_node_{$id}_" . SlConfigure::read('I18n.locale');
     $data = Cache::read($key, 'models');
     if (empty($data)) {
         $data = self::getModel()->readCached($id);
     }
     if ($options['hit']) {
         //...
     }
     if ($options['auth']) {
         //...
     }
     return $data;
 }
Exemplo n.º 13
0
    function parse($html = null, $blockName = 'document', $blockParams = null)
    {
        if (empty($html)) {
            $id = SlConfigure::read('Api.google.analytics.id');
        }
        if (empty($html)) {
            return;
        }
        SlConfigure::write("Asset.js.footer.{$html}", array('weight' => 1000, 'after' => <<<end
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$html}']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
end
));
    }
Exemplo n.º 14
0
 public function send($to, $message, $params = array())
 {
     $params += SlConfigure::read('Api.hqSms') + array('encoding' => 'utf-8', 'test' => false, 'details' => false);
     if (is_array($to)) {
         $multiple = true;
         foreach ($to as $i => &$phone) {
             $phone = $this->standartizePhoneNoMd($phone);
             if (empty($phone)) {
                 unset($to[$i]);
             }
         }
         $params['to'] = implode(',', $to);
     } else {
         $multiple = false;
         $params['to'] = $this->standartizePhoneNoMd($to);
     }
     if (empty($params['to'])) {
         return;
     }
     $protocol = $params['secure'] && SlConfigure::read('Sl.options.sslTransport') ? 'https' : 'http';
     unset($params['secure']);
     if (strlen($params['password']) != 32) {
         $params['password'] = md5($params['password']);
     }
     $params['message'] = $message;
     App::import('Core', 'HttpSocket');
     $socket = new HttpSocket();
     Sl::krumo($params);
     $result = $socket->post("{$protocol}://www.hqsms.com/api/send.do", $params);
     if ($multiple) {
         $result = explode(';', $result);
         foreach ($result as &$item) {
             $item = explode(':', $item);
         }
         return $result;
     } else {
         return explode(':', $result);
     }
 }
Exemplo n.º 15
0
 /**
  *
  * @param AppModel $model
  */
 public function beforeSave($model)
 {
     $localizedFields = $model->Behaviors->enabled('Translate') ? $model->Behaviors->Translate->settings[$model->alias] : array();
     $fields = $this->settings[$model->alias];
     $locales = SlConfigure::read('I18n.locales');
     foreach ($fields as $field => $field2) {
         if (is_int($field)) {
             $field = $field2;
             $field2 = "markdown_{$field}";
         }
         if (in_array($field, $localizedFields)) {
             foreach ($locales as $locale) {
                 if (isset($model->data[$model->alias]["{$field}_{$locale}"])) {
                     $model->data[$model->alias]["{$field2}_{$locale}"] = $this->_markdown($model->data[$model->alias]["{$field}_{$locale}"]);
                 }
             }
         }
         if (isset($model->data[$model->alias][$field])) {
             $model->data[$model->alias][$field2] = $this->_markdown($model->data[$model->alias][$field]);
         }
     }
     return true;
 }
Exemplo n.º 16
0
 public function migrate()
 {
     $this->set('title', __t('StarLight installation: Database upgrade'));
     $form = Sl::version('core');
     $to = SlConfigure::read('Sl.version');
     Sl::version('core', $to);
 }
Exemplo n.º 17
0
 public function logout()
 {
     SlAuth::logout();
     $this->redirect(SlConfigure::read('Auth.url.afterLogout'));
 }
Exemplo n.º 18
0
 protected function _eval($blockParams)
 {
     $var = null;
     if (!empty($blockParams['blockCount'])) {
         $data = SlConfigure::read2("Block." . $blockParams['blockCount']);
         $var = count($data);
     } elseif (!empty($blockParams['config'])) {
         $var = SlConfigure::read2($blockParams['config']);
     } elseif (!empty($blockParams['collection'])) {
         $collections = SlConfigure::read();
         $var = in_array($blockParams['collection'], $collections);
     } elseif (!empty($blockParams['param'])) {
         $var = $this->_getParam($blockParams['param']);
     }
     if ($var !== null) {
         $blockParams['var'] = '_sl';
         $this->vars['_sl'] = $var;
     }
     return parent::_eval($blockParams);
 }
Exemplo n.º 19
0
 public static function delete($name, $path = null, $domain = null, $secure = null)
 {
     self::ready();
     SlConfigure::delete($name, false, 'cookie');
     if (empty($path)) {
         $path = SlConfigure::read('Sl.cookie.path');
     }
     if ($domain === null) {
         $domain = SlConfigure::read('Sl.cookie.domain');
     }
     if ($secure === null) {
         $secure = SlConfigure::read('Sl.cookie.secure');
     }
     setcookie(self::$_cookieName . "[{$name}]", '', time() - 42000, $path, $domain, $secure);
 }
Exemplo n.º 20
0
 /**
  * Callback...
  *
  * Set language flags
  *
  * @param AppModel $model
  */
 public function beforeSave($model)
 {
     //    	$this->_checkSchema($model);
     $fields = $this->settings[$model->alias];
     if (empty($fields)) {
         return true;
     }
     $locales = SlConfigure::read('I18n.locales');
     $currLocale = SlConfigure::read('I18n.locale');
     if (empty($currLocale)) {
         return true;
     }
     foreach ($fields as $field) {
         // reversed binding - its use is still under question
         if (!isset($model->data[$model->alias][$field . '_' . $currLocale]) && isset($model->data[$model->alias][$field])) {
             $model->data[$model->alias][$field . '_' . $currLocale] = $model->data[$model->alias][$field];
             unset($model->data[$model->alias][$field]);
         }
         foreach ($locales as $locale) {
             if (isset($model->data[$model->alias][$field . '_' . $locale]) || isset($model->data[$model->alias][$field])) {
                 $model->data[$model->alias]['_' . $locale] = !empty($model->data[$model->alias]['_' . $locale]) || !empty($model->data[$model->alias][$field . '_' . $locale]);
             }
         }
     }
     // foreach
     return true;
 }
Exemplo n.º 21
0
 function assetTimestamp($path)
 {
     if (strpos($path, '?') === false && SlConfigure::read('Asset.options.timestamp')) {
         return $this->assetUrl(preg_replace('/^' . preg_quote($this->webroot, '/') . '/', '', $path));
     }
     return $path;
 }
Exemplo n.º 22
0
 /**
  *
  * @param array $params Parameters for controller
  * @access public
  */
 function dbConnectionError()
 {
     extract(SlConfigure::read('Db.default'));
     $this->controller->set('title', __t('No database connection to {$params} ({$password})', array('params' => "{$login}@{$host}/{$database}", 'password' => __t($password ? "uses password" : "no password"))));
     $this->_outputMessage('dbConnectionError');
 }
Exemplo n.º 23
0
 * Here, we are connecting '/' (base path) to controller called 'Pages',
 * its action called 'display', and we pass a param to select the view file
 * to use (in this case, /app/views/pages/home.ctp)...
 */
// check installation
if (Sl::version() != SlConfigure::read('Sl.version')) {
    if (!preg_match('!/install|/users/login!', Sl::url(false))) {
        SlConfigure::write('Message.migrate', array('message' => __t('System files have been recently updated. Proceeding to database migration...'), 'params' => array('class' => 'message')));
        Router::connect(Sl::url(false), array('controller' => 'install', 'action' => 'migrate'));
    }
}
// localized routes
$langRules = array('lang' => implode('|', SlConfigure::read('I18n.langs')));
// home
$home = SlConfigure::read1('Routing.home');
Router::connect('/', $home);
Router::connect('/:lang', $home, $langRules);
// prefixed homes
$prefixedRoutes = SlConfigure::read('Routing.prefixes');
foreach ($prefixedRoutes as $prefix => $route) {
    Router::connect("/{$prefix}", $route);
}
// custom routes
$routes = SlConfigure::read('Routing.routes');
foreach ($routes as $expr => $route) {
    Router::connect($expr, $route);
    Router::connect("/:lang{$expr}", $route, $langRules);
}
Router::connect('/:lang/:plugin/:controller/:action/*', array(), $langRules);
Router::connect('/:lang/:controller/:action/*', array(), $langRules);
Router::parseExtensions();
Exemplo n.º 24
0
 /**
  * Loads Components and prepares them for initialization.
  * Models will be lazy loaded by default
  *
  * @return mixed true if models found and instance created, or cakeError if models not found.
  * @access public
  * @see Controller::loadModel()
  * @link http://book.cakephp.org/view/977/Controller-Methods#constructClasses-986
  */
 function constructClasses()
 {
     if (SlExtensions::getInstance()->dependencyError) {
         $params = SlExtensions::getInstance()->dependencyError;
         SlExtensions::getInstance()->dependencyError = false;
         $this->cakeError('missingDependence', $params);
     }
     SlExtensions::trigger('constructClasses', $this);
     $this->__mergeVars();
     // Component class sets components by reference, hence triggering an uneeded read operation
     // Avoid magic __get() method calls by setting null values
     $this->components = Set::normalize($this->components);
     foreach ($this->components as $component => $settings) {
         if (strpos($component, '.') !== false) {
             list($plugin, $component) = explode('.', $component);
         }
         $this->{$component} = null;
     }
     if (!SlConfigure::read('Sl.options.lazyLoadModels')) {
         return parent::constructClasses();
     }
     $this->Component->init($this);
     if ($this->uses !== null || $this->uses !== array()) {
         if ($this->uses) {
             $uses = is_array($this->uses) ? $this->uses : array($this->uses);
             $modelClassName = $uses[0];
             if (strpos($uses[0], '.') !== false) {
                 list($plugin, $modelClassName) = explode('.', $uses[0]);
             }
             $this->modelClass = $modelClassName;
         }
     }
     return true;
 }
Exemplo n.º 25
0
 *     'models' =>  array('/full/path/to/models/', '/next/full/path/to/models/'),
 *     'views' => array('/full/path/to/views/', '/next/full/path/to/views/'),
 *     'controllers' => array('/full/path/to/controllers/', '/next/full/path/to/controllers/'),
 *     'datasources' => array('/full/path/to/datasources/', '/next/full/path/to/datasources/'),
 *     'behaviors' => array('/full/path/to/behaviors/', '/next/full/path/to/behaviors/'),
 *     'components' => array('/full/path/to/components/', '/next/full/path/to/components/'),
 *     'helpers' => array('/full/path/to/helpers/', '/next/full/path/to/helpers/'),
 *     'vendors' => array('/full/path/to/vendors/', '/next/full/path/to/vendors/'),
 *     'shells' => array('/full/path/to/shells/', '/next/full/path/to/shells/'),
 *     'locales' => array('/full/path/to/locale/', '/next/full/path/to/locale/')
 * ));
 *
 */
App::build(array('plugins' => array(APP . 'extensions/')));
/**
 * As of 1.3, additional rules for the inflector are added below
 *
 * Inflector::rules('singular', array('rules' => array(), 'irregular' => array(), 'uninflected' => array()));
 * Inflector::rules('plural', array('rules' => array(), 'irregular' => array(), 'uninflected' => array()));
 *
 */
Cache::config('sl', array('engine' => 'File', 'prefix' => 'sl_', 'duration' => Configure::read() ? '+10 seconds' : '+999 days'));
Cache::config('models', array('engine' => 'File', 'prefix' => 'sl_', 'path' => CACHE . 'models' . DS, 'duration' => '+7 days'));
App::import('lib', 'sl');
App::import('lib', 'sl_configure');
App::import('lib', 'sl_extensions');
App::import('lib', 'sl_session');
App::import('lib', 'sl_cookie');
SlExtensions::trigger('bootstrap');
Configure::write('Routing.prefixes', array_keys(SlConfigure::read('Routing.prefixes')));
Exemplo n.º 26
0
 function parse($html = null, $blockName = 'document', $blockParams = null)
 {
     if (empty($blockParams['id'])) {
         if (preg_match('/^[a-zA-Z0-9_.-]+$/', $html)) {
             $blockParams['id'] = parent::parse($html);
             $html = null;
         } else {
             return;
         }
     }
     $id = $blockParams['id'];
     $cacheKey = empty($blockParams['cacheKey']) ? 'default' : $blockParams['cacheKey'];
     $data = SlConfigure::read2("Block.{$id}");
     if ($data) {
         $id = r('.', '-', $id);
         $this->vars = array('id' => $id, 'title' => false);
         $defaults = SlConfigure::read2('Block.defaults');
         $blocks = array();
         foreach ($data as $key => $block) {
             if ($block) {
                 if (!is_array($block)) {
                     $block = array('body' => $block);
                 }
                 $block = Set::merge($defaults, $block);
                 if (empty($block['id'])) {
                     $block['id'] = "{$id}-{$key}";
                 }
                 if (!empty($block['cache']) && !is_array($block['cache'])) {
                     $block['cache'] = array('time' => $block['cache']);
                 }
                 if (!empty($block['cache_time'])) {
                     $block['cache']['time'] = $block['cache_time'];
                 }
                 if (isset($block['cache']['time']) && is_numeric($block['cache']['time'])) {
                     $block['cache']['time'] += time();
                 }
                 if (!empty($block['cache']['spread'])) {
                     if (!is_numeric($block['cache']['time'])) {
                         $block['cache']['time'] = strtotime($block['cache']['time'], time());
                     }
                     $block['cache']['time'] += mt_rand(-$block['cache']['spread'], $block['cache']['spread']);
                 }
                 if (!empty($block['cache']) && empty($block['cache']['key'])) {
                     $block['cache']['key'] = $block['id'] . '-' . md5(serialize($block) . SlConfigure::read('I18n.lang'));
                 }
                 if (!empty($block['cache']['time'])) {
                     $cacheFile = 'views/block_' . $cacheKey . '_' . $block['cache']['key'];
                     $cache = cache($cacheFile, null, $block['cache']['time']);
                     if (is_string($cache)) {
                         $blocks[] = unserialize($cache);
                         continue;
                     }
                 }
                 // dynamic block (from custom controller)
                 if (!empty($block['url'])) {
                     $block['body'] = Sl::requestAction($block['url']);
                     if (!isset($block['title'])) {
                         $block['title'] = SlConfigure::read('View.lastRenderTitle');
                     }
                 } elseif (!empty($block['body'])) {
                     $block['body'] = parent::parse($block['body']);
                 } else {
                     continue;
                 }
                 $blocks[] = $block;
                 // update cache
                 if (!empty($block['cache']['time'])) {
                     // we don't wanna cache administrative stuff
                     if (!strpos($block['body'], 'sl-node-actions')) {
                         cache($cacheFile, serialize($block), $block['cache']['time']);
                     }
                 }
             }
         }
         if (empty($blocks)) {
             return;
         }
         $this->blocks["loop"]->params[0] = $blocks;
         return parent::parse($html, $blockName);
     }
 }
Exemplo n.º 27
0
 /**
  * Returns a JavaScript script tag.
  *
  * Options:
  *
  *  - allowCache: boolean, designates whether this block is cacheable using the
  * current cache settings.
  *  - safe: boolean, whether this block should be wrapped in CDATA tags.  Defaults
  * to helper's object configuration.
  *  - inline: whether the block should be printed inline, or written
  * to cached for later output (i.e. $scripts_for_layout).
  *
  * @param string $script The JavaScript to be wrapped in SCRIPT tags.
  * @param array $options Set of options:
  * @return string The full SCRIPT element, with the JavaScript inside it, or null,
  *   if 'inline' is set to false.
  */
 function codeBlock($script = null, $options = array())
 {
     if (!is_array($options)) {
         $options = array('inline' => $options);
     } elseif (empty($options)) {
         $options = array();
     }
     $defaultOptions = array('safe' => true, 'inline' => true);
     $options = array_merge($defaultOptions, $options);
     // convert an array to a script string
     if (is_array($script)) {
         foreach ($script as &$line) {
             if (substr($line, -1) !== ';') {
                 $line .= ';';
             }
         }
         $script = implode("\n", $script);
     }
     $safe = $options['safe'] || SlConfigure::read('View.options.safeJsCodeBlocks');
     if ($safe) {
         $script = "\n" . '//<![CDATA[' . "\n" . $script;
         $script .= "\n" . '//]]>' . "\n";
     }
     if ($options['inline']) {
         return sprintf($this->tags['javascriptblock'], $script);
     } else {
         $view =& ClassRegistry::getObject('view');
         $view->addScript(sprintf($this->tags['javascriptblock'], $script));
     }
 }
Exemplo n.º 28
0
 /**
  * Private helper method to create associated models of a given class.
  *
  * @param string $assoc Association name
  * @param string $className Class name
  * @deprecated $this->$className use $this->$assoc instead. $assoc is the 'key' in the associations array;
  * 	examples: var $hasMany = array('Assoc' => array('className' => 'ModelName'));
  * 					usage: $this->Assoc->modelMethods();
  *
  * 				var $hasMany = array('ModelName');
  * 					usage: $this->ModelName->modelMethods();
  * @return void
  * @access private
  */
 function __constructLinkedModel($assoc, $className = null)
 {
     if (!SlConfigure::read('Sl.options.lazyLoadModels')) {
         return parent::__constructLinkedModel($assoc, $className);
     }
     if (empty($className)) {
         $className = $assoc;
     }
     $this->_lazyLoaderBusy = true;
     if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
         $model = array('class' => $className, 'alias' => $assoc);
         $this->_lazyLoadedModels[$assoc] = $model;
         // <-- the magic starts here
     }
     $this->_lazyLoaderBusy = false;
 }
Exemplo n.º 29
0
 /**
  * Set current language
  *
  * @param string $lang
  * @return bool Success
  */
 public static function setLocale($lang = null, $setCookie = false)
 {
     $locales = SlConfigure::read('I18n.locales');
     if (empty($locales)) {
         $languages = SlConfigure::read1('I18n.languages');
         $langs = array_keys($languages);
         $locales = array();
         $catalogs = array();
         if (!$langs) {
             $langs = array('en');
         }
         App::import('Core', 'l10n');
         $l10n = new L10n();
         foreach ($langs as $lang_) {
             $catalog = $l10n->catalog($lang_);
             if ($catalog) {
                 $catalogs[$lang_] = $catalog;
                 $locales[$lang_] = $catalog['locale'];
             }
         }
         $langs = array_keys($locales);
         SlConfigure::write('I18n.langs', $langs);
         SlConfigure::write('I18n.catalogs', $catalogs);
         SlConfigure::write('I18n.locales', $locales);
         if (empty($lang)) {
             $lang = SlCookie::read('I18n.lang');
             // guess language based on Accept-Language header
             if (empty($lang)) {
                 $envLangs = explode(',', env('HTTP_ACCEPT_LANGUAGE'));
                 foreach ($envLangs as $envLang) {
                     list($envLang) = explode(';', $envLang);
                     if (isset($locales[$envLang])) {
                         $lang = $envLang;
                         break;
                     }
                 }
                 if (empty($lang)) {
                     $lang = SlConfigure::read('I18n.lang');
                 }
             }
             // convert locale_id to lang_id
             $lang_ = array_search($lang, $locales);
             if ($lang_) {
                 $lang = $lang_;
             }
             if (empty($lang) || !isset($locales[$lang])) {
                 $lang = $langs[0];
             }
         }
     } else {
         $catalogs = SlConfigure::read('I18n.catalogs');
     }
     if ($lang) {
         // convert locale_id to lang_id
         $lang_ = array_search($lang, $locales);
         if ($lang_) {
             $lang = $lang_;
         }
         if (isset($locales[$lang])) {
             SlConfigure::write('I18n.lang', $lang);
             SlConfigure::write('I18n.catalog', $catalogs[$lang]);
             SlConfigure::write('I18n.locale', $locales[$lang]);
             Configure::write('Config.language', $locales[$lang]);
             if ($setCookie) {
                 SlCookie::write('I18n.lang', $lang, false, "+1 year");
             }
             SlConfigure::localeChanged();
             return true;
         }
     }
     return false;
 }
 public function view($node_id)
 {
     // node common stuff
     $this->set('cmsNode', $node = SlNode::read($node_id));
     if (!$node) {
         $this->cakeError();
     }
     $this->set('title', $node['CmsNode']['title']);
     // contact form specific stuff
     $fields = array();
     $fields2 = empty($node['CmsContactForm']['fields']) ? array('From|email', 'Text|textarea') : explode("\n", $node['CmsContactForm']['fields']);
     // prepare the array of user fields
     foreach ($fields2 as $i => $field) {
         $parts = explode('|', r("\r", " ", $field));
         $parts = array_map('trim', $parts);
         $label = __t(empty($parts[0]) ? 'Unknown' : $parts[0]);
         $type = empty($parts[1]) ? 'text' : $parts[1];
         if ($type === 'email') {
             $type = 'text';
         }
         // we use only the 'after' setting, assuming that section title and other stuff
         // can be place here and show up correctly with proper css rules
         $after = empty($parts[2]) ? null : "<div class='after'>{$parts['2']}</div>";
         // 'options' and 'multiple' settings
         $options = empty($parts[3]) ? null : explode(',', $parts[3]);
         $multiple = false;
         if ($options) {
             $options = array_map('trim', $options);
             $options = array_combine($options, $options);
             if ($type === 'checkbox') {
                 $multiple = 'checkbox';
                 $type = null;
             } elseif ($type === 'multiple') {
                 $multiple = true;
                 $type = null;
             }
             if (!$type) {
                 $type = 'select';
             }
         }
         $fields["f{$i}"] = compact('label', 'type', 'multiple', 'after');
         if ($options) {
             $fields["f{$i}"]['options'] = $options;
         }
         if ($type === 'radio') {
             $fields["f{$i}"]['legend'] = $label;
         }
     }
     if (!empty($this->data['CmsContactForm'])) {
         // TODO: Validate feedback fields
         $this->SwiftMailer->_set(SlConfigure::read('Api.swiftMailer'));
         $this->SwiftMailer->to = $node['CmsContactForm']['email'];
         //set variables to template as usual
         $this->set(compact('fields'));
         // send email
         try {
             if ($this->SwiftMailer->send('contact_form', __t(SlConfigure::read2('Api.swiftMailer.subject'), array('siteTitle' => SlConfigure::read2('Site.title'))), SlConfigure::read2('Api.swiftMailer.method'))) {
                 $this->Session->setFlash(__t('Email sent. Thank you!'), array('class' => 'success'));
                 // after the message has been sent, we no longer need for the form to show
                 $this->viewVars['fields'] = null;
             } else {
                 $this->Session->setFlash(__t('An unknown error occured.<br /> Please use you email client to send your message to <a href="mailto:{$email}">{$email}</a>', array('email' => $this->SwiftMailer->to)), array('class' => 'error'));
             }
         } catch (Exception $e) {
             $this->Session->setFlash(__t('An internal error occured.<br /> Please use you email client to send your message to <a href="mailto:{$email}">{$email}</a>', array('email' => $this->SwiftMailer->to)), array('class' => 'error'));
             trigger_error($e->getMessage(), E_USER_WARNING);
         }
     } else {
         $this->set(compact('fields'));
     }
 }