예제 #1
0
파일: sl.php 프로젝트: sandulungu/StarLight
 /**
  * Class constructor
  *
  * @param AppController $controller
  */
 public function __construct($controller)
 {
     Sl::getInstance()->view = $this;
     parent::__construct($controller);
     $this->theme =& $controller->theme;
     $this->id =& $controller->id;
 }
예제 #2
0
 /**
  *
  * @param AppModel $model
  */
 public function refreshMirror($model, $checkPendingOperations = false)
 {
     if ($checkPendingOperations) {
         if ($this->_pending[$model->alias] > 0) {
             return;
         }
         $this->_pending[$model->alias] = 0;
     }
     $config = $this->settings[$model->alias];
     if ($model->Behaviors->enabled('Translate')) {
         if ($config['findOptions']['recursive'] >= 0 || $model->Behaviors->Translate->settings[$model->alias]) {
             $oldLang = SlConfigure::read('I18n.lang');
             $locales = SlConfigure::read('I18n.locales');
             $localesPreg = '/_' . implode('$|_', $locales) . '$/';
             foreach ($locales as $lang => $locale) {
                 Sl::setLocale($lang);
                 $data = $model->find($config['findType'], $config['findOptions']);
                 if ($config['collectionField']) {
                     $this->_cleanup($config['name'], $locale);
                 }
                 $this->_write($config['name'], $this->_prepareData($model, $config, $data, $localesPreg), $locale);
             }
             Sl::setLocale($oldLang);
             return;
         }
     }
     $data = $model->find($config['findType'], $config['findOptions']);
     if ($config['collectionField']) {
         $this->_cleanup($config['name']);
     }
     $this->_write($config['name'], $this->_prepareData($model, $config, $data));
 }
예제 #3
0
 public static function url($id, $options = array())
 {
     $options += array('full' => false, 'route' => true, 'slug' => true);
     $full = $options['full'];
     unset($options['full']);
     $slug = $options['slug'];
     unset($options['slug']);
     $route = $options['route'];
     unset($options['route']);
     if (!is_array($id)) {
         $node = self::read($id);
     } else {
         $node = isset($id['CmsNode']) ? $id : array('CmsNode' => $id);
         $id = $node['CmsNode']['id'];
     }
     if ($node['CmsNode']['model']) {
         $options += array('plugin' => $node['CmsNode']['plugin'], 'controller' => Inflector::tableize($node['CmsNode']['model']));
     } else {
         $options += array('plugin' => 'cms', 'controller' => 'cms_nodes');
     }
     $options += array('admin' => false, 'action' => 'view', $id);
     if ($slug && $node['CmsNode']['slug']) {
         $options[] = $node['CmsNode']['slug'];
     }
     return $route ? Sl::url($options, $full) : $options;
 }
예제 #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'));
 }
예제 #5
0
 function end($options = null)
 {
     $view = Sl::getInstance()->view;
     $options2 = is_array($options) ? $options : array();
     $options2 += array('validation' => true);
     if ($options2['validation'] && $view->model && isset($view->Validation)) {
         SlConfigure::write('Asset.js.jquery', 'head');
         SlConfigure::write('Asset.js.head.jqueryValidation', 'jquery.validation.min');
         $html = $view->Validation->bind($view->model);
     } else {
         $html = '';
     }
     return parent::end($options) . $html;
 }
예제 #6
0
 function saveAll($data = null, $options = array())
 {
     $controller = Sl::getInstance()->controller;
     $isNew = !$controller->id;
     // set associated model info
     if ($controller->modelClass != 'CmsNode') {
         $data['CmsNode'] += array('model' => $controller->modelClass, 'plugin' => $controller->plugin);
     }
     // remove empty Images, Attachments from data to be saved
     if (!empty($data['CmsImage'])) {
         if (empty($data['CmsImage']['id']) && empty($data['CmsImage']['filename']['name'])) {
             unset($data['CmsImage']);
         }
     }
     if (!empty($data['CmsAttachment'])) {
         foreach ($data['CmsAttachment'] as $i => $image) {
             if (empty($image['id']) && empty($image['filename']['name'])) {
                 unset($data['CmsAttachment'][$i]);
             }
         }
     }
     if (!empty($data['ImageGallery'])) {
         foreach ($data['ImageGallery'] as $i => $image) {
             if (empty($image['id']) && empty($image['filename']['name'])) {
                 unset($data['ImageGallery'][$i]);
             }
         }
     }
     if ($isNew) {
         $data['CmsNode']['auth_user_id'] = SlAuth::user('id');
     }
     if (!empty($data['CmsNode']['model'])) {
         if (empty($options['validation']) || $options['validation'] != 'only') {
             if (!parent::saveAll($data, array('validate' => 'only', 'atomic' => true) + $options)) {
                 return false;
             }
         }
         $modelObject = ClassRegistry::init("{$data['CmsNode']['plugin']}.{$data['CmsNode']['model']}");
         if (!$modelObject->saveAll($data, $options)) {
             return false;
         }
         $data['CmsNode'] += array('foreign_key' => $modelObject->id);
     }
     $result = parent::saveAll($data, $options);
     if ($result && $isNew && $this->CmsImage->id) {
         $this->CmsImage->saveField('cms_node_id', $this->id);
     }
     return $result;
 }
예제 #7
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}");
 }
 function parse($html = null, $blockName = 'document', $blockParams = null)
 {
     $blockParams = (array) $blockParams;
     $blockParams += array('fields' => $this->_getVar('fields'), 'domId' => Sl::uniqid());
     if (!is_array($blockParams['fields'])) {
         return;
     }
     $form = $this->_getHelper('SlForm');
     $fields = array();
     $form->create('CmsContactForm');
     foreach ($blockParams['fields'] as $f => $o) {
         $fields[] = array('inputName' => $f, 'inputOptions' => $o, 'inputHtml' => $form->input($f, $o));
     }
     if ($fields) {
         $this->blocks['loop']->params[0] = $fields;
         $this->vars['domId'] = $blockParams['domId'];
         $this->vars['actionUrl'] = Sl::url();
         return parent::parse($html, $blockName);
     }
 }
예제 #9
0
 function parse($html = null, $blockName = 'document', $blockParams = null)
 {
     // set defaults
     $blockParams = (array) $blockParams;
     $blockParams += array('options' => array('fx' => 'backout'), 'menuClass' => 'lavaLampNoImage', 'domId' => Sl::uniqid(), 'recursive' => 0);
     $this->vars['domId'] = $id = $blockParams['domId'];
     // load & configure lavalamp
     $options = $blockParams['options'] ? json_encode($blockParams['options']) : '';
     SlConfigure::write('Asset.css.lavalamp', 'lavalamp/lavalamp_test');
     SlConfigure::write('Asset.js.footer.lavalamp', 'lavalamp/jquery.lavalamp.min');
     SlConfigure::write("Asset.js.ready.{$id}", "\$('#{$id}').lavaLamp({$options});");
     // custom fx easing effects
     if (!in_array($blockParams['options']['fx'], array('swing', 'linear'))) {
         SlConfigure::write('Asset.js.footer.easing', 'lavalamp/jquery.easing.min');
     }
     unset($blockParams['options']);
     // construct DOM
     self::$parseCallStack[] = $this;
     $html = Pheme::init('Menu')->parse($html, $blockName, $blockParams);
     array_pop(self::$parseCallStack);
     return $html;
 }
예제 #10
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);
     }
 }
예제 #11
0
 function parse($html = null, $blockName = 'document', $blockParams = null)
 {
     // set defaults
     $blockParams = (array) $blockParams;
     $blockParams += array('type' => 'default', 'supersubs' => array('extraWidth' => 1.5), 'options' => array(), 'menuClass' => 'sf-menu', 'domId' => Sl::uniqid());
     $id = $blockParams['domId'];
     $blockParams['menuClass'] .= " {$id}";
     // load & configure supersubs
     if ($blockParams['supersubs']) {
         $ssOptions = json_encode($blockParams['supersubs']);
         $ssKey = "supersubs_{$id}";
         SlConfigure::write("Asset.js.footer.supersubs", 'superfish/js/supersubs');
         SlConfigure::write("Asset.js.ready.{$ssKey}", "\$('ul.{$id}').supersubs({$ssOptions});");
     }
     // load & configure superfish
     $sfOptions = $blockParams['options'] ? json_encode($blockParams['options']) : '';
     $sfKey = "superfish_{$id}";
     SlConfigure::write("Asset.css.superfish", 'superfish/css/superfish');
     SlConfigure::write("Asset.js.footer.superfish", 'superfish/js/superfish');
     SlConfigure::write("Asset.js.ready.{$sfKey}", "\$('ul.{$id}').superfish({$sfOptions});");
     // alternative styles
     switch ($blockParams['type']) {
         case 'vertical':
             $blockParams['menuClass'] .= " sf-vertical";
             SlConfigure::write("Asset.css.superfishVertical", 'superfish/js/superfish-vertical');
             break;
         case 'navbar':
             $blockParams['menuClass'] .= " sf-navbar";
             SlConfigure::write("Asset.css.superfishNavbar", 'superfish/js/superfish-navbar');
             break;
     }
     unset($blockParams['type']);
     unset($blockParams['supersubs']);
     unset($blockParams['options']);
     // construct DOM
     return Pheme::init('Menu')->parse($html, $blockName, $blockParams);
 }
예제 #12
0
 /**
  * Extended Router::url() with proper html entities and spaces replaced by '+'
  *
  * @param mixed $url Set to bool (true = 'with base' or false) to get current requestUri
  * @param bool $full
  * @return string
  * @static
  */
 function url($url = null, $full = false)
 {
     return h(r(' ', '+', Sl::url($url, $full)));
 }
예제 #13
0
 /**
  * Creates an HTML link.
  *
  * If $url starts with "http://" this is treated as an external link. Else,
  * it is treated as a path to controller/action and parsed with the
  * HtmlHelper::url() method.
  *
  * If the $url is empty, $title is used instead.
  *
  * @param  mixed  $title The content to be wrapped by <a> tags or a node $item.
  * @param  mixed   $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
  * @param  array   $options Array of HTML attributes.
  * @param  string  $confirmMessage JavaScript confirmation message.
  * @param  boolean $escapeTitle	Whether or not $title should be HTML escaped.
  * @return string	An <a /> element.
  */
 function link($title, $url = null, $options = array())
 {
     if (Sl::isHere($url)) {
         $options = $this->addClass($options, 'sl-active');
     }
     if ($url !== null) {
         $url = $url !== false ? empty($options['webroot']) ? $this->url($url) : $this->webroot($url) : '';
     } else {
         $url = $this->url($title);
         $title = $url;
     }
     unset($options['webroot']);
     if (!empty($options['escape'])) {
         $title = h($title);
     }
     unset($options['escape']);
     if (!empty($options['confirm'])) {
         $confirmMessage = r("'", "\\'", r('"', '\\"', $options['confirm']));
         $url2 = r("'", "\\'", r('"', '\\"', $url));
         $options['onclick'] = "if (window.Ext) { Ext.Msg.confirm('', '{$confirmMessage}', function(btn){ if (btn == 'yes') Sl.go('{$url2}'); }); return false; } return confirm('{$confirmMessage}');";
     }
     unset($options['confirm']);
     return $url ? sprintf('<a href="%s"%s>%s</a>', $url, $this->_parseAttributes($options), $title) : sprintf('<a%s>%s</a>', $this->_parseAttributes($options), $title);
 }
예제 #14
0
 /**
  * Redirects to given $url, after turning off $this->autoRender.
  * Script execution is halted after the redirect.
  *
  * @param mixed $url A string or array-based URL pointing to another location within the app, or an absolute URL
  * @param integer $status Optional HTTP status code (eg: 404)
  * @access public
  * @link http://book.cakephp.org/view/425/redirect
  */
 public function redirect($url, $status = null, $useReferer = true)
 {
     if ($useReferer) {
         $ref = SlSession::read('Routing.ref');
         if ($ref) {
             SlSession::delete('Routing.ref');
             if (Sl::url($ref) !== Sl::url()) {
                 $url = $ref;
             }
         }
     }
     // cyclic check
     if (Sl::url($url) === Sl::url()) {
         die('Infinite redirection loop detected.');
     }
     // code inspired from RequestHandlerComponent
     if ($this->RequestHandler->isAjax()) {
         foreach ($_POST as $key => $val) {
             unset($_POST[$key]);
         }
         echo Sl::requestAction($url, array('requested' => false));
         $this->_stop();
     }
     // show a human readable redirect message allowing debug output to be read
     if (headers_sent() || $this->output && Configure::read()) {
         $url = h(SL::url($url));
         if (empty($status)) {
             $status = 'null';
         }
         echo "<p style='background: #ff7; color: #000; padding: 1em;'>Redirect to <a href='{$url}'>{$url}</a> (code: {$status}) cancelled.</p>";
         while (ob_get_level()) {
             ob_end_flush();
         }
         $this->_stop();
     }
     parent::redirect(Sl::url($url, true), $status);
 }
예제 #15
0
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       cake
 * @subpackage    cake.app.config
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
/**
 * 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');
예제 #16
0
 /**
  * Automatically determine active collections based on the passed $item
  *
  * @param mixed $item
  */
 public static function setCollectionsMagic($item = null)
 {
     $controller = Sl::getInstance()->controller;
     $collections = array();
     if (is_string($item)) {
         $collections[] = $item;
     } else {
         if ($controller) {
             if (isset($item[$controller->modelClass]['id'])) {
                 $collections["{$controller->modelClass}{$item[$controller->modelClass]['id']}"] = 899;
             }
             if (empty($item['nodes']) && !empty($item['path'][0][$controller->modelClass]['id'])) {
                 $ids = Set::extract("{n}.{$controller->modelClass}.id", $data['path']);
                 foreach ($ids as $i => $id) {
                     $collections["{$controller->modelClass}{$id}"] = 800 + $i;
                 }
             }
         }
         if (!empty($item['nodes'])) {
             foreach ($item['nodes'] as $i => $nodeId) {
                 $collections["Node{$nodeId}"] = 600 + $i;
             }
         }
         if (!empty($item['tags'])) {
             foreach ($item['tags'] as $i => $tagId) {
                 $collections["Tag{$tagId}"] = 400 + $i;
             }
         }
         if (empty($collections) && is_array($item) && Set::numeric($item) && Set::countDim($item, true) == 1) {
             $collections = $item;
         }
     }
     return self::setCollections($collections);
 }
예제 #17
0
파일: sl.php 프로젝트: sandulungu/StarLight
 /**
  * A more ajax and user friendly way to var_dump.
  * Use instead of pr()
  *
  * @param mixed $var
  * @param bool $useFireCakeOutsideViews
  */
 static function krumo($var, $options = array())
 {
     $options = array('fireCake' => true, 'debug' => true);
     if ($options['debug'] && !Configure::read()) {
         return;
     }
     if ($options['fireCake'] && empty(Sl::getInstance()->view) && class_exists('FireCake')) {
         return FireCake::fb($var);
     }
     // force Pheme to keep the whitespace and line breaks
     echo "<!--{!preserveWhitespace}-->";
     App::import('vendor', 'krumo', array('file' => 'krumo/class.krumo.php'));
     return krumo::dump($var);
 }
예제 #18
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);
 }
예제 #19
0
 function parse($html = null, $blockName = 'document', $blockParams = null, $noCycle = false)
 {
     $this->vars['href'] = null;
     $blockParams = (array) $blockParams;
     $blockParams += array('align' => false, 'var' => 'CmsImage', 'thumb' => 'icon', 'zoomCrop' => false, 'quality' => 75, 'link' => empty($blockParams['filter']) || $blockParams['filter'] !== 'full' ? 'auto' : false, 'rel' => empty($blockParams['href']) ? 'colorbox' : null, 'href' => null);
     $autoLink = $blockParams['link'] == 'auto';
     if (!empty($blockParams['id'])) {
         $image = ClassRegistry::init('Image');
         list($data) = $image->find('first', array('conditions' => array('id' => $blockParams['id']), 'recursive' => -1));
     } elseif (isset($blockParams['index'])) {
         $data = $this->_getVar("ImageGallery.{$blockParams['index']}");
     } else {
         $data = $this->_getVar($blockParams["var"]);
     }
     if (!empty($data['filename'])) {
         // support for skin-specific filter versions
         if (!empty($blockParams['width']) && !empty($blockParams['height'])) {
             $blockParams['thumb'] = $filter = "{$blockParams['width']}x{$blockParams['height']}{$blockParams['crop']}";
             $targetFilename = r('/', DS, WWW_ROOT . "files/cms_images/thumb/{$blockParams['thumb']}/{$data['filename']}");
             // check for file
             if (!file_exists($targetFilename)) {
                 $sourceFilename = WWW_ROOT . "files/cms_images/{$data['filename']}";
                 $this->_thumb($sourceFilename, $targetFilename, $blockParams);
             }
         }
         $src = "files/cms_images/thumb/{$blockParams['thumb']}/{$data['filename']}";
         if ($blockParams['href']) {
             $href = h(r(' ', '+', Sl::url($blockParams['href'])));
         } elseif ($blockParams['link']) {
             if (!$autoLink || !$this->_getVar('href')) {
                 $href = $this->_getHelper('SlHtml')->webroot("files/cms_images/{$data['filename']}");
             }
         }
     }
     if (!empty($src)) {
         $this->vars['align'] = $blockParams['align'];
         $this->vars['rel'] = empty($href) ? $autoLink ? null : false : $blockParams['rel'];
         $this->vars['title'] = empty($data['title']) ? false : $data['title'];
         $this->vars['src'] = $src;
         $this->vars['href'] = empty($href) ? $autoLink ? null : false : $href;
         return parent::parse($html, $blockName);
     }
 }
예제 #20
0
 function parse($html, $blockName = 'document', $blockParams = null)
 {
     return Sl::requestAction(trim(parent::parse($html)), (array) $blockParams);
 }
예제 #21
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);
     }
 }
예제 #22
0
 /**
  * Uploads the files
  *
  * @param $model Object
  * @param $data Array Optional Containing data to be saved
  * @return array
  * @author Vinicius Mendes
  */
 function _uploadFile(&$model, $data = null)
 {
     if (!isset($data) || !is_array($data)) {
         $data =& $model->data;
     }
     foreach ($this->__fields[$model->alias] as $fieldName => $options) {
         // Patched by sandu@lungu.info on 08/28/2010: Added support for random filenames
         $data[$model->alias]['_uniqid'] = Sl::uniqid();
         // end of patch
         // Take care of removal flagged field
         // However, this seems to be kind of code duplicating, see line ~711
         if (!empty($data[$model->alias][$fieldName]['remove'])) {
             $this->_markForDeletion($model, $fieldName, $data, $options['default']);
             $data = $this->_nullifyDataFields($model, $fieldName, $data, $options);
             $result = array('return' => true, 'data' => $data);
             continue;
         }
         // If no file was selected we do not need to proceed
         if (empty($data[$model->alias][$fieldName]['name'])) {
             unset($data[$model->alias][$fieldName]);
             $result = array('return' => true, 'data' => $data);
             continue;
         }
         $pos = strrpos($data[$model->alias][$fieldName]['type'], '/');
         $sub = substr($data[$model->alias][$fieldName]['type'], $pos + 1);
         list(, $ext) = $this->_splitFilenameAndExt($data[$model->alias][$fieldName]['name']);
         // Put in a subfolder if the user wishes it
         if (isset($options['folderAsField']) && !empty($options['folderAsField']) && is_string($options['folderAsField'])) {
             $options['dir'] = $options['dir'] . DS . $data[$model->alias][$options['folderAsField']];
             $this->__fields[$model->alias][$fieldName]['dir'] = $options['dir'];
         }
         // Check whether or not the behavior is in useTable mode
         if ($options['useTable'] == false) {
             $this->_includeDefaultReplacement($options['default']);
             $this->_fixName($model, $fieldName, false);
             $saveAs = $options['dir'] . DS . $data[$model->alias][$options['uploadName']] . '.' . $sub;
             // Attempt to move uploaded file
             $copyResults = $this->_copyFileFromTemp($data[$model->alias][$fieldName]['tmp_name'], $saveAs);
             if ($copyResults !== true) {
                 $result = array('return' => false, 'reason' => 'validation', 'extra' => array('field' => $fieldName, 'error' => $copyResults));
                 continue;
             }
             // If the file is an image, try to make the thumbnails
             if (count($options['thumbsizes']) > 0 && count($options['allowedExt']) > 0 && in_array($data[$model->alias][$fieldName]['type'], $this->_imageTypes)) {
                 $this->_createThumbnails($model, $data, $fieldName, $saveAs, $ext, $options);
             }
             $data = $this->_unsetDataFields($model->alias, $fieldName, $model->data, $options);
             $result = array('return' => true, 'data' => $data);
             continue;
         } else {
             // if the file is marked to be deleted, use the default or set the field to null
             if (!empty($data[$model->alias][$fieldName]['remove'])) {
                 if ($options['default']) {
                     $data[$model->alias][$fieldName] = $options['default'];
                 } else {
                     $data[$model->alias][$fieldName] = null;
                 }
                 //if the record is already saved in the database, set the existing file to be removed after the save is sucessfull
                 if (!empty($data[$model->alias][$model->primaryKey])) {
                     $this->_setFileToRemove($model, $fieldName);
                 }
             }
             // If no file has been upload, then unset the field to avoid overwriting existant file
             if (!isset($data[$model->alias][$fieldName]) || !is_array($data[$model->alias][$fieldName]) || empty($data[$model->alias][$fieldName]['name'])) {
                 if (!empty($data[$model->alias][$model->primaryKey]) || !$options['default']) {
                     unset($data[$model->alias][$fieldName]);
                 } else {
                     $data[$model->alias][$fieldName] = $options['default'];
                 }
             }
             //if the record is already saved in the database, set the existing file to be removed after the save is sucessfull
             if (!empty($data[$model->alias][$model->primaryKey])) {
                 $this->_setFileToRemove($model, $fieldName);
             }
             // save in encrypted folder if specified
             if ($options['encryptedFolder']) {
                 // setup UUID as a unique folder name
                 $options['dir'] .= DS . String::uuid();
             }
             // Fix the filename, removing bad characters and avoiding from overwriting existing ones
             if ($options['default'] == true) {
                 $this->_includeDefaultReplacement($options['default']);
             }
             $this->_fixName($model, $fieldName);
             // Also save the original image as uploadName if that option is not empty
             if (isset($options['uploadName']) && !empty($options['uploadName'])) {
                 $saveAs = $options['dir'] . DS . $data[$model->alias][$options['uploadName']] . '.' . $ext;
             } else {
                 $saveAs = $options['dir'] . DS . $data[$model->alias][$fieldName]['name'];
             }
             // Attempt to move uploaded file
             $copyResults = $this->_copyFileFromTemp($data[$model->alias][$fieldName]['tmp_name'], $saveAs);
             if ($copyResults !== true) {
                 $result = array('return' => false, 'reason' => 'validation', 'extra' => array('field' => $fieldName, 'error' => $copyResults));
                 continue;
             }
             // If the file is an image, try to make the thumbnails
             if (count($options['thumbsizes']) > 0 && count($options['allowedExt']) > 0 && in_array($data[$model->alias][$fieldName]['type'], $this->_imageTypes)) {
                 $this->_createThumbnails($model, $data, $fieldName, $saveAs, $ext, $options);
             }
             // Update model data
             $data[$model->alias][$options['fields']['dir']] = $options['dir'];
             $data[$model->alias][$options['fields']['mimetype']] = $data[$model->alias][$fieldName]['type'];
             $data[$model->alias][$options['fields']['filesize']] = $data[$model->alias][$fieldName]['size'];
             if (isset($options['uploadName']) && !empty($options['uploadName'])) {
                 $data[$model->alias][$fieldName] = $data[$model->alias][$options['uploadName']] . '.' . $ext;
             } else {
                 $data[$model->alias][$fieldName] = $data[$model->alias][$fieldName]['name'];
             }
             $result = array('return' => true, 'data' => $data);
             continue;
         }
     }
     if (isset($result)) {
         return $result;
     } else {
         return true;
     }
 }