slug() public static method

public static slug ( $string, $replace = '-' )
示例#1
1
 /**
  * Initialize the Cache Engine
  *
  * Called automatically by the cache frontend
  * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
  *
  * @param array $settings array of setting for the engine
  * @return boolean True if the engine has been successfully initialized, false if not
  */
 public function init($settings = array())
 {
     if (!class_exists('Memcache')) {
         return false;
     }
     if (!isset($settings['prefix'])) {
         $settings['prefix'] = Inflector::slug(APP_DIR) . '_';
     }
     $settings += array('engine' => 'Memcache', 'servers' => array('127.0.0.1'), 'compress' => false, 'persistent' => true);
     parent::init($settings);
     if ($this->settings['compress']) {
         $this->settings['compress'] = MEMCACHE_COMPRESSED;
     }
     if (is_string($this->settings['servers'])) {
         $this->settings['servers'] = array($this->settings['servers']);
     }
     if (!isset($this->_Memcache)) {
         $return = false;
         $this->_Memcache = new Memcache();
         foreach ($this->settings['servers'] as $server) {
             list($host, $port) = $this->_parseServerString($server);
             if ($this->_Memcache->addServer($host, $port, $this->settings['persistent'])) {
                 $return = true;
             }
         }
         return $return;
     }
     return true;
 }
示例#2
0
 public function beforeSave($options = array())
 {
     if (isset($this->data[$this->alias]['title'])) {
         $this->data[$this->alias]['slug'] = Inflector::slug($this->data[$this->alias]['title'], '-');
     }
     return true;
 }
示例#3
0
function season($indoor)
{
    // The configuration settings values have "0" for the year, to facilitate form input
    $today = date('0-m-d');
    $today_wrap = date('1-m-d');
    // Build the list of applicable seasons
    $seasons = Configure::read('options.season');
    unset($seasons['None']);
    if (empty($seasons)) {
        return 'None';
    }
    foreach (array_keys($seasons) as $season) {
        $season_indoor = Configure::read("season_is_indoor.{$season}");
        if ($indoor != $season_indoor) {
            unset($seasons[$season]);
        }
    }
    // Create array of which season follows which
    $seasons = array_values($seasons);
    $seasons_shift = $seasons;
    array_push($seasons_shift, array_shift($seasons_shift));
    $next = array_combine($seasons, $seasons_shift);
    // Look for the season that has started without the next one starting
    foreach ($next as $a => $b) {
        $start = Configure::read('organization.' . Inflector::slug(low($a)) . '_start');
        $end = Configure::read('organization.' . Inflector::slug(low($b)) . '_start');
        // Check for a season that wraps past the end of the year
        if ($start > $end) {
            $end[0] = '1';
        }
        if ($today >= $start && $today < $end || $today_wrap >= $start && $today_wrap < $end) {
            return $a;
        }
    }
}
示例#4
0
 /**
  * Checks whether the response was cached and set the body accordingly.
  *
  * @param CakeEvent $event containing the request and response object
  * @return CakeResponse with cached content if found, null otherwise
  */
 public function beforeDispatch(CakeEvent $event)
 {
     if (Configure::read('Cache.check') !== true) {
         return;
     }
     $path = $event->data['request']->here();
     if ($path === '/') {
         $path = 'home';
     }
     $prefix = Configure::read('Cache.viewPrefix');
     if ($prefix) {
         $path = $prefix . '_' . $path;
     }
     $path = strtolower(Inflector::slug($path));
     $filename = CACHE . 'views' . DS . $path . '.php';
     if (!file_exists($filename)) {
         $filename = CACHE . 'views' . DS . $path . '_index.php';
     }
     if (file_exists($filename)) {
         $controller = null;
         $view = new View($controller);
         $result = $view->renderCache($filename, microtime(true));
         if ($result !== false) {
             $event->stopPropagation();
             $event->data['response']->body($result);
             return $event->data['response'];
         }
     }
 }
示例#5
0
 /**
  * Initialize the Cache Engine
  *
  * Called automatically by the cache frontend
  * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
  *
  * @param array $setting array of setting for the engine
  * @return boolean True if the engine has been successfully initialized, false if not
  * @access public
  */
 function init($settings = array())
 {
     if (!class_exists('Memcache')) {
         return false;
     }
     parent::init(array_merge(array('engine' => 'Memcache', 'prefix' => Inflector::slug(APP_DIR) . '_', 'servers' => array('127.0.0.1'), 'compress' => false), $settings));
     if ($this->settings['compress']) {
         $this->settings['compress'] = MEMCACHE_COMPRESSED;
     }
     if (!is_array($this->settings['servers'])) {
         $this->settings['servers'] = array($this->settings['servers']);
     }
     if (!isset($this->__Memcache)) {
         $return = false;
         $this->__Memcache =& new Memcache();
         foreach ($this->settings['servers'] as $server) {
             $parts = explode(':', $server);
             $host = $parts[0];
             $port = 11211;
             if (isset($parts[1])) {
                 $port = $parts[1];
             }
             if ($this->__Memcache->addServer($host, $port)) {
                 $return = true;
             }
         }
         return $return;
     }
     return true;
 }
 public function beforeSave($options = array())
 {
     if (empty($this->data['ProductCategory']['slug']) && isset($this->data['ProductCategory']['slug']) && !empty($this->data['ProductCategory']['name'])) {
         $this->data['ProductCategory']['slug'] = strtolower(Inflector::slug($this->data['ProductCategory']['name'], '-'));
     }
     return true;
 }
 /**
  * Initialize the Cache Engine
  *
  * Called automatically by the cache frontend
  * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
  *
  * @param array $settings array of setting for the engine
  * @return bool True if the engine has been successfully initialized, false if not
  */
 public function init($settings = [])
 {
     if (!class_exists('Memcached')) {
         return false;
     }
     if (!isset($settings['prefix'])) {
         $settings['prefix'] = Inflector::slug(APP_DIR) . '_';
     }
     $settings += ['engine' => 'Memcached', 'servers' => ['127.0.0.1'], 'compress' => false, 'persistent' => true];
     parent::init($settings);
     $this->_keys .= $this->settings['prefix'];
     if (!is_array($this->settings['servers'])) {
         $this->settings['servers'] = [$this->settings['servers']];
     }
     if (!isset($this->_Memcached)) {
         $return = false;
         $this->_Memcached = new Memcached($this->settings['persistent'] ? 'mc' : null);
         $this->_setOptions();
         if (!count($this->_Memcached->getServerList())) {
             $servers = [];
             foreach ($this->settings['servers'] as $server) {
                 $servers[] = $this->_parseServerString($server);
             }
             if ($this->_Memcached->addServers($servers)) {
                 $return = true;
             }
         }
         if (!$this->_Memcached->get($this->_keys)) {
             $this->_Memcached->set($this->_keys, '');
         }
         return $return;
     }
     return true;
 }
 public function factoryActions($action, $data)
 {
     switch ($action) {
         case 'create':
             // Get the current FactSite we are working on
             $FactSite = ClassRegistry::init('SiteFactory.FactSite');
             $FactSite->recursive = -1;
             $site = $FactSite->findById($data['FactSection']['fact_site_id']);
             // Get an available ID
             $CorkCorktile = ClassRegistry::init('Corktile.CorkCorktile');
             $data['FactSection']['metadata']['corktile_key'] = $CorkCorktile->getAvailableUuid();
             // Create the corktile
             $config = array('key' => $data['FactSection']['metadata']['corktile_key'], 'type' => 'cs_cork', 'location' => array('public_page', 'fact_sites', $site['FactSite']['mexc_space_id'], $data['FactSection']['metadata']['address']), 'title' => sprintf(__d('mexc_contacts', 'Texto da página \'%s\' do programa \'%s\'', true), $data['FactSection']['name'], $site['FactSite']['name']), 'editorsRecommendations' => __d('fact_site', 'O conteúdo da página pode ser editado aqui.', true), 'options' => array('type' => 'fact_site_static', 'cs_type' => 'fact_site_static'));
             if ($CorkCorktile->getData($config) == false) {
                 return false;
             }
             return $data;
             break;
         case 'save':
             if (empty($data['FactSection']['metadata']['address'])) {
                 $data['FactSection']['metadata']['address'] = $data['FactSection']['name'];
             }
             $data['FactSection']['metadata']['address'] = strtolower(Inflector::slug($data['FactSection']['metadata']['address']));
             return $data;
             break;
         case 'delete':
             if (!empty($data['FactSection']['metadata']['corktile_key'])) {
                 $CorkCorktile = ClassRegistry::init('Corktile.CorkCorktile');
                 return $CorkCorktile->delete($data['FactSection']['metadata']['corktile_key']);
             }
             break;
     }
     return true;
 }
示例#9
0
 public function beforeSave($options = array())
 {
     if (empty($this->data['Rol']['machin_name'])) {
         $this->data['Rol']['machin_name'] = strtolower(Inflector::slug($this->data['Rol']['name']));
     }
     return true;
 }
示例#10
0
	function cached($url) {
		if (Configure::read('Cache.check') === true) {
			$path = $this->here;
			if ($this->here == '/') {
				$path = 'home';
			}
			if($this->Session->check('Auth.User._id')){
				//$path = $_SESSION['Auth']['User']['_id'].'_'.strtolower(Inflector::slug($path));
				$path = '4d33940fda220a9606000003_'.strtolower(Inflector::slug($path));
			}else{
				$path = strtolower(Inflector::slug($path));
			}

			$filename = CACHE . 'views' . DS . $path . '.php';

			if (!file_exists($filename)) {
				$filename = CACHE . 'views' . DS . $path . '_index.php';
			}

			if (file_exists($filename)) {
				if (!class_exists('View')) {
					App::import('View', 'View', false);
				}
				$controller = null;
				$view =& new View($controller);
				$return = $view->renderCache($filename, getMicrotime());
				if (!$return) {
					ClassRegistry::removeObject('view');
				}
				return $return;
			}
		}
		return false;
	}
示例#11
0
 public function beforeSave($options = array())
 {
     $result = parent::beforeSave($options);
     $slug = Inflector::slug($this->data['Page']['title']);
     $this->data['Page']['slug'] = $slug;
     return $result;
 }
示例#12
0
 function _prepareToWriteFiles(&$model, $field)
 {
     $this->toWrite[$field] = $model->data[$model->name][$field];
     // make filename URL friendly by using Cake's Inflector
     $this->toWrite[$field]['name'] = Inflector::slug(substr($this->toWrite[$field]['name'], 0, strrpos($this->toWrite[$field]['name'], '.'))) . substr($this->toWrite[$field]['name'], strrpos($this->toWrite[$field]['name'], '.'));
     // extension
 }
示例#13
0
文件: Qurl.php 项目: Jony01/LLD
 /**
  * Form the access url by key
  *
  * @param string $key
  * @return string Url (absolute)
  */
 public static function urlByKey($key, $title = null, $slugTitle = true)
 {
     if ($title && $slugTitle) {
         $title = Inflector::slug($title, '-');
     }
     return Router::url(array('admin' => false, 'plugin' => 'tools', 'controller' => 'qurls', 'action' => 'go', $key, $title), true);
 }
示例#14
0
 function newName($folder, $fileName)
 {
     //elimino gli spazi bianchi
     //$fileName = str_replace(' ', '_', $fileName);
     $fileParts = explode('.', $fileName);
     foreach ($fileParts as $n => $filePart) {
         $fileParts[$n] = Inflector::slug($filePart);
     }
     $fileName = implode('.', $fileParts);
     if (preg_match('/([0-9]+)([.][a-zA-Z0-9]{3,})$/', $fileName, $matches)) {
         //il file è numerato (nome123.ext)
         $fileName = preg_replace('/' . $matches[count($matches) - 2] . '/', (int) $matches[count($matches) - 2] + 1, $fileName);
     } else {
         //il file non è numerato (nome.ext): lo numero io
         $matches = explode('.', $fileName);
         $matches[count($matches) - 2] .= '1';
         $fileName = implode('.', $matches);
     }
     //controllo ricorsivo -> serve per assicurarsi di non sovrascrivere altri files
     if (is_file($folder . $fileName)) {
         return $this->newName($folder, $fileName);
     } else {
         return $fileName;
     }
 }
示例#15
0
	/**
	 * Initialize the cache engine
	 *
	 * Called automatically by the cache frontend
	 *
	 * @param array $params Associative array of parameters for the engine
	 * @return boolean true if the engine has been succesfully initialized, false if not
	 * @access public
	 */
	function init($settings = array()) {
		if (!function_exists('eaccelerator_put')) {
			return false;
		}
          return parent::init(array_merge(array('engine' => 'Eaccelerator', 'prefix' => Inflector::slug(APP_DIR) . '_'), $settings));

	}
示例#16
0
 /**
  * Returns a link that toggles the display of another element on the page.
  * Options for $params:
  *  - $params['div'] set to false to prevent auto-generating a related div
  * 	- $params['update'] the selector used to locate the element to toggle.
  * 		If a div is being auto-generated, the # symbol will automatically
  * 		be prefixed to the selector
  *	- $params['url'] loads the target url using ajax into the target div
  * 	- $params['button'] set to true applies the button-skin class
  * 	- $params[etc] any other params are passed to the generated anchor element
  *
  * @param string $text 
  * @param string $url 
  * @param string $params 
  * @return void
  * @author Dean Sofer
  */
 public function toggle($text, $params = array())
 {
     $result = '';
     if (isset($params['update'])) {
         $id = $params['update'];
         unset($params['update']);
     } else {
         $id = Inflector::slug($text) . '-panel';
     }
     if (!isset($params['div'])) {
         $result .= "<div id='{$id}' class='loading'></div>\n";
         $params['rel'] = '#' . $id;
     } else {
         $params['rel'] = $id;
     }
     $class = 'toggle';
     if (isset($params['class'])) {
         $params['class'] .= ' ' . $class;
     } else {
         $params['class'] = $class;
     }
     if (isset($params['url'])) {
         $url = $params['url'];
         $params['class'] .= ' ajax';
         unset($params['url']);
     } else {
         $url = '#';
     }
     $result .= $this->Html->link($text, $url, $params);
     return $result;
 }
 function generateSlug($property_id)
 {
     $generated_slug = "";
     $prop = $this->Property->findBYId($property_id);
     //category slug
     $catSql = " SELECT group_concat(B.name,'-',A.name) as name FROM property_categories A INNER JOIN property_categories B ON A.parent_id = B.id WHERE A.id = " . $prop['Property']['property_category_id'] . "";
     $category = $this->PropertyCategory->query($catSql);
     $generated_slug .= $category['0']['0']['name'];
     //city slug
     if (!empty($prop['Property']['city_id'])) {
         $citySlug = $this->City->findById($prop['Property']['city_id']);
         $generated_slug .= "-" . $citySlug['City']['slug'];
     } else {
         $generated_slug .= "-" . $prop['Property']['city_other'];
     }
     //location slug
     if (!empty($prop['Property']['locality_id'])) {
         $locationSlug = $this->Locality->findById($prop['Property']['locality_id']);
         $generated_slug .= "-" . $locationSlug['Locality']['slug'];
     } else {
         $generated_slug .= "-" . $prop['Property']['locality_other'];
     }
     if ($prop['Property']['want_to'] == 1) {
         $generated_slug .= "-to-sale";
     }
     if ($prop['Property']['want_to'] == 2) {
         $generated_slug .= "-to-rent";
     }
     $generated_slug .= "-" . $prop['Property']['property_reference_id'];
     $generated_slug = Inflector::slug(strtolower($generated_slug), '_');
     //save
     $this->Property->id = $property_id;
     $this->Property->saveField('property_slug', $generated_slug);
     return $generated_slug;
 }
示例#18
0
 /**
  * Blocks
  *
  * Blocks will be available in this variable in views: $blocks_for_layout
  *
  * @return void
  */
 public function blocks()
 {
     $regions = $this->Block->Region->find('active');
     $alias = $this->Block->alias;
     $roleId = $this->controller->Croogo->roleId();
     $status = $this->Block->status();
     $request = $this->controller->request;
     $slug = Inflector::slug(strtolower(urldecode($request->url)));
     $Filter = new VisibilityFilter($request);
     foreach ($regions as $regionId => $regionAlias) {
         $cacheKey = $regionAlias . '_' . $roleId;
         $this->blocksForLayout[$regionAlias] = array();
         $visibilityCachePrefix = 'visibility_' . $slug . '_' . $cacheKey;
         $blocks = Cache::read($visibilityCachePrefix, 'croogo_blocks');
         if ($blocks === false) {
             $blocks = $this->Block->find('published', array('regionId' => $regionId, 'roleId' => $roleId, 'cacheKey' => $cacheKey));
             foreach ($blocks as &$block) {
                 $block[$alias]['visibility_paths'] = $this->Block->decodeData($block[$alias]['visibility_paths']);
             }
             $blocks = $Filter->remove($blocks, array('model' => $alias, 'field' => 'visibility_paths', 'cache' => array('prefix' => $visibilityCachePrefix, 'config' => 'croogo_blocks')));
             Cache::write($visibilityCachePrefix, $blocks, 'croogo_blocks');
         }
         $this->processBlocksData($blocks);
         $this->blocksForLayout[$regionAlias] = $blocks;
     }
 }
示例#19
0
 /**
  * should be called in beforeRender()
  * 
  */
 public static function init(View $View)
 {
     $params = $View->request->params;
     if (Configure::read('UrlCache.pageFiles')) {
         $cachePageKey = '_misc';
         if (is_object($View)) {
             $path = $View->request->here;
             if ($path == '/') {
                 $path = 'uc_homepage';
             } else {
                 $path = strtolower(Inflector::slug($path));
             }
             if (empty($path)) {
                 $path = 'uc_error';
             }
             $cachePageKey = '_' . $path;
         }
         self::$cachePageKey = self::$cacheKey . $cachePageKey;
         self::$cachePage = Cache::read(self::$cachePageKey, '_cake_core_');
     }
     self::$cache = Cache::read(self::$cacheKey, '_cake_core_');
     # still old "prefix true/false" syntax?
     if (Configure::read('UrlCache.verbosePrefixes')) {
         unset(self::$paramFields[3]);
         self::$paramFields = array_merge(self::$paramFields, (array) Configure::read('Routing.prefixes'));
     }
     self::$extras = array_intersect_key($params, array_combine(self::$paramFields, self::$paramFields));
     $defaults = array();
     foreach (self::$paramFields as $field) {
         $defaults[$field] = '';
     }
     self::$extras = array_merge($defaults, self::$extras);
 }
示例#20
0
 function admin_product($product_id)
 {
     if ($this->request->is('post')) {
         //test si données ont été postées
         $data = $this->request->data['Media'];
         if (isset($date['url'])) {
             $this->redirect(array('action' => 'show', '?class=&alt=&src=' . urlencode($data['url'])));
         }
         $dir = IMAGES . date('Y');
         if (!file_exists($dir)) {
             //si le fichier de l'année n'éxiste pas on le crée
             mkdir($dir, 0777);
         }
         $dir .= DS . date('m');
         if (!file_exists($dir)) {
             //si le fichier du mois n'éxiste pas on le crée
             mkdir($dir, 0777);
         }
         $f = explode('.', $data['file']['name']);
         // on met le nom du fichier dans la variable f
         $ext = '.' . end($f);
         //on récupère l'extention
         $filename = Inflector::slug(implode('.', array_slice($f, 0, -1)), '-');
         //Sauvegarde BDD
         $success = $this->Media->save(array('name' => $data['name'], 'url' => date('Y') . '/' . date('m') . '/' . $filename . $ext, 'product_id' => $product_id));
         if ($success) {
             move_uploaded_file($data['file']['tmp_name'], $dir . DS . $filename . $ext);
         } else {
             $this->Session->setFlash("L'image n'est pas au bon format", "notif", array('type' => 'error'));
         }
     }
     $d['medias'] = $this->Media->find('all', array('conditions' => array('product_id' => $product_id)));
     $this->set($d);
 }
示例#21
0
	/**
	 * Initialize the Cache Engine
	 *
	 * Called automatically by the cache frontend
	 * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
	 *
	 * @param array $setting array of setting for the engine
	 * @return boolean True if the engine has been successfully initialized, false if not
	 * @access public
	 */
	function init($settings) {
		parent::init(array_merge(array(
			'engine' => 'Xcache', 'prefix' => Inflector::slug(APP_DIR) . '_', 'PHP_AUTH_USER' => 'user', 'PHP_AUTH_PW' => 'password'
			), $settings)
			);
			return function_exists('xcache_info');
	}
示例#22
0
 public function beforeSave()
 {
     if (!empty($this->data[$this->alias]['name'])) {
         $this->data[$this->alias]['name'] = strtolower(Inflector::slug($this->data[$this->alias]['name']));
     }
     return true;
 }
示例#23
0
    /**
     * Write a cached version of the file
     *
     * @param string $content view content to write to a cache file.
     * @param string $timestamp Duration to set for cache file.
     * @param bool $useCallbacks Whether to include statements in cached file which
     *   run callbacks.
     * @return bool success of caching view.
     */
    protected function _writeFile($content, $timestamp, $useCallbacks = false)
    {
        $now = time();
        if (is_numeric($timestamp)) {
            $cacheTime = $now + $timestamp;
        } else {
            $cacheTime = strtotime($timestamp, $now);
        }
        // CUSTOMIZE 2014/08/11 ryuring
        // $this->request->here で、URLを取得する際、URL末尾の 「index」の有無に関わらず
        // 同一ファイルを参照すべきだが、別々のURLを出力してしまう為、
        // 正規化された URLを取得するメソッドに変更
        // >>>
        //$path = $this->request->here();
        // ---
        $path = $this->request->normalizedHere();
        // <<<
        if ($path === '/') {
            $path = 'home';
        }
        $prefix = Configure::read('Cache.viewPrefix');
        if ($prefix) {
            $path = $prefix . '_' . $path;
        }
        $cache = strtolower(Inflector::slug($path));
        if (empty($cache)) {
            return;
        }
        $cache = $cache . '.php';
        $file = '<!--cachetime:' . $cacheTime . '--><?php';
        if (empty($this->_View->plugin)) {
            $file .= "\n\t\t\tApp::uses('{$this->_View->name}Controller', 'Controller');\n\t\t\t";
        } else {
            $file .= "\n\t\t\tApp::uses('{$this->_View->plugin}AppController', '{$this->_View->plugin}.Controller');\n\t\t\tApp::uses('{$this->_View->name}Controller', '{$this->_View->plugin}.Controller');\n\t\t\t";
        }
        $file .= '
				$request = unserialize(base64_decode(\'' . base64_encode(serialize($this->request)) . '\'));
				$response->type(\'' . $this->_View->response->type() . '\');
				$controller = new ' . $this->_View->name . 'Controller($request, $response);
				$controller->plugin = $this->plugin = \'' . $this->_View->plugin . '\';
				$controller->helpers = $this->helpers = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->helpers)) . '\'));
				$controller->layout = $this->layout = \'' . $this->_View->layout . '\';
				$controller->theme = $this->theme = \'' . $this->_View->theme . '\';
				$controller->viewVars = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->viewVars)) . '\'));
				Router::setRequestInfo($controller->request);
				$this->request = $request;';
        if ($useCallbacks) {
            $file .= '
				$controller->constructClasses();
				$controller->startupProcess();';
        }
        $file .= '
				$this->viewVars = $controller->viewVars;
				$this->loadHelpers();
				extract($this->viewVars, EXTR_SKIP);
		?>';
        $content = preg_replace("/(<\\?xml)/", "<?php echo '\$1'; ?>", $content);
        $file .= $content;
        return cache('views' . DS . $cache, $file, $timestamp);
    }
示例#24
0
 public function add($event = null)
 {
     if ($event === null) {
         return FALSE;
     }
     if (!isset($event['Event']['alias'])) {
         $event['Event']['alias'] = Inflector::slug(mb_strtolower($event['Event']['title']), '-');
     }
     if (empty($event['EventDate'])) {
         unset($event['EventDate']);
     }
     if (empty($event['EventPrice'])) {
         unset($event['EventPrice']);
     }
     // init transaction
     $this->begin();
     if ($this->saveAll($event, array('validate' => 'first'))) {
         // save database changes
         $this->commit();
         return TRUE;
     }
     // has an error
     $this->rollback();
     return FALSE;
 }
示例#25
0
 public function beforeSave($options = array())
 {
     if (isset($this->data[$this->alias]['slug']) && empty($this->data[$this->alias]['slug'])) {
         $this->data[$this->alias]['slug'] = strtolower(Inflector::slug($this->data[$this->alias]['title'], '-'));
     }
     return parent::beforeSave($options);
 }
示例#26
0
 public function upload(Model $Model, $arquivo = array(), $altura = 800, $largura = 600, $pasta = null, $nome_arquivo)
 {
     // App::uses('Vendor', 'wideimage');
     App::import('Vendor', 'WideImage', array('file' => 'WideImage' . DS . 'WideImage.php'));
     App::uses('Folder', 'Utility');
     $ext = array('image/jpg', 'image/jpeg', 'image/pjpeg', 'image/x-jps', 'image/png', 'image/gif');
     if ($arquivo['error'] != 0 || $arquivo['size'] == 0) {
         return false;
     }
     $img = WideImage::load($arquivo['tmp_name']);
     $folder = new Folder();
     $pathinfo = pathinfo($arquivo['name']);
     if ($folder->create(WWW_ROOT . 'img' . DS . $pasta . DS)) {
         //se conseguiu criar o diretório eu dou permissão
         $folder->chmod(WWW_ROOT . 'img' . DS . $pasta . DS, 0755, true);
     } else {
         return false;
     }
     $pathinfo['filename'] = strtolower(Inflector::slug($pathinfo['filename'], '-'));
     $arquivo['name'] = $nome_arquivo . '.' . $pathinfo['extension'];
     $img->saveToFile(WWW_ROOT . 'img' . DS . $pasta . DS . 'original_' . $arquivo['name']);
     $img = $img->resize($largura, $altura, 'fill');
     $img->saveToFile(WWW_ROOT . 'img' . DS . $pasta . DS . $arquivo['name']);
     // debug(WWW_ROOT.'img'.DS.$pasta.DS.$arquivo['name']); die;
     return $arquivo['name'];
 }
 function admin_add($formId = null)
 {
     $response = false;
     if (!empty($this->request->data)) {
         if (empty($this->request->data['FormField']['name'])) {
             $original_name = 'New Field question';
             $this->request->data['FormField']['name'] = 'new_field';
         } else {
             $original_name = $this->request->data['FormField']['name'];
             $this->request->data['FormField']['name'] = Inflector::slug(strtolower($original_name));
         }
         if (empty($this->request->data['FormField']['label'])) {
             $this->request->data['FormField']['label'] = $original_name;
         }
         $this->FormField->create();
         if ($this->FormField->save($this->request->data)) {
             $response = $this->FormField->id;
         }
         $this->set('response', $response);
         $this->render('../../Plugin/Cforms/View/Elements/ajax_response');
     } elseif ($formId) {
         $this->request->data['FormField']['cform_id'] = $formId;
         $types = $this->FormField->types;
         $this->set('types', $types);
         $this->render('admin_add');
     }
 }
示例#28
0
 public function admin_add()
 {
     if ($this->request->is('post')) {
         $this->Technology->create();
         //$data = $this->request->data['Technology'];
         $slug = Inflector::slug($this->request->data['Technology']['title']);
         $data[] = $this->request->data['Technology'];
         $data[] = array('alias' => $slug);
         $data = array_merge($data[0], $data[1]);
         if (isset($this->request->query['lang']) && $this->request->query['lang'] == 'kz') {
             $this->Technology->locale = 'kz';
         } elseif (isset($this->request->query['lang']) && $this->request->query['lang'] == 'en') {
             $this->Technology->locale = 'en';
         } else {
             $this->Technology->locale = 'ru';
         }
         // debug($data);
         //  if(!$data['img']['name']){
         //  	unset($data['img']);
         // }
         if ($this->Technology->save($data)) {
             $this->Session->setFlash('Сохранено', 'default', array(), 'good');
             // debug($data);
             return $this->redirect($this->referer());
         } else {
             $this->Session->setFlash('Ошибка', 'default', array(), 'bad');
         }
     }
 }
 function generateSlug($EvaluateProperty_id)
 {
     $generated_slug = "";
     $prop = $this->EvaluateProperty->findBYId($EvaluateProperty_id);
     //category slug
     //city slug
     if (!empty($prop['EvaluateProperty']['city_id'])) {
         $citySlug = $this->City->findById($prop['EvaluateProperty']['city_id']);
         $generated_slug .= "-" . $citySlug['EvaluateProperty']['slug'];
     } else {
         $generated_slug .= "-" . $prop['EvaluateProperty']['city_other'];
     }
     //location slug
     if (!empty($prop['EvaluateProperty']['locality_id'])) {
         $locationSlug = $this->Locality->findById($prop['EvaluateProperty']['locality_id']);
         $generated_slug .= "-" . $locationSlug['EvaluateProperty']['slug'];
     } else {
         $generated_slug .= "-" . $prop['EvaluateProperty']['locality_other'];
     }
     if ($prop['EvaluateProperty']['want_to'] == 1) {
         $generated_slug .= "-to-sale";
     }
     if ($prop['EvaluateProperty']['want_to'] == 2) {
         $generated_slug .= "-to-rent";
     }
     $generated_slug .= "-" . $prop['EvaluateProperty']['property_reference_id'];
     $generated_slug = Inflector::slug(strtolower($generated_slug), '_');
     //save
     $this->EvaluateProperty->id = $EvaluateProperty_id;
     $this->EvaluateProperty->saveField('property_slug', $generated_slug);
     return $generated_slug;
 }
示例#30
0
 public function processUpload($check = array())
 {
     // deal with uploaded file
     if (!empty($check['filename']['tmp_name'])) {
         // check file is uploaded
         if (!is_uploaded_file($check['filename']['tmp_name'])) {
             return FALSE;
         }
         // build full filename
         $filename = WWW_ROOT . $this->uploadDir . DS . Inflector::slug(pathinfo($check['filename']['name'], PATHINFO_FILENAME)) . '.' . pathinfo($check['filename']['name'], PATHINFO_EXTENSION);
         // @todo check for duplicate filename
         // try moving file
         if (!move_uploaded_file($check['filename']['tmp_name'], $filename)) {
             return FALSE;
             // file successfully uploaded
         } else {
             // save the file path relative from WWW_ROOT e.g. uploads/example_filename.jpg
             $this->data[$this->alias]['filepath'] = str_replace(DS, "/", str_replace(WWW_ROOT, "", $filename));
         }
         /*    $piece = 'uploads' . '\job.pdf ';
                       $filename = WWW_ROOT . $piece;
         
                       echo $filename;
                       echo exec('convert ' . $filename . ' C:\wamp\www\new\dmishare\app\webroot\uploads\job.jpg '); */
     }
     return TRUE;
 }