how to set the full base url to a cdn while using HtmlHelper in cakephp? - cakephp

My cakephp app is running on 2.4.0
It is already running live on yourapp.com
I am attempting to use Amazon CloudFront to serve static assets like css, js, and images.
The CDN domain I chose was cdn.yourapp.com
Sadly, when I tried to use it this way:
echo $this->Html->css('alpha_landing/styles', array('fullBase' => $cdnBaseUrl));
where $cdnBaseUrl is http://cdn.yourapp.com/
I did not get back the correct url I was expecting.
I was expecting
http://cdn.yourapp.com/css/some.css
But I got back
http://yourapp.com/css/some.css
How can I overcome this problem?

Two solutions:
Simply write a HtmlHelper that can override the default image, css, etc functions
See https://stackoverflow.com/a/9601207/80353 for details
or
you can rewrite the assetUrl function in your AppHelper so that you need not rewrite all the related functions.
public function assetUrl($path, $options = array()) {
$cdnBaseUrl = Configure::read('App.assetsUrl');
$legitCDN = (strpos($cdnBaseUrl, '://') !== false);
if (is_array($path)) {
$path = $this->url($path, !empty($options['fullBase']));
if ($legitCDN) {
return rtrim($cdnBaseUrl, '/') . '/' . ltrim($path, '/');
}
return $path;
}
if (strpos($path, '://') !== false) {
return $path;
}
if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
list($plugin, $path) = $this->_View->pluginSplit($path, false);
}
if (!empty($options['pathPrefix']) && $path[0] !== '/') {
$path = $options['pathPrefix'] . $path;
}
if (
!empty($options['ext']) &&
strpos($path, '?') === false &&
substr($path, -strlen($options['ext'])) !== $options['ext']
) {
$path .= $options['ext'];
}
if (isset($plugin)) {
$path = Inflector::underscore($plugin) . '/' . $path;
}
$path = $this->_encodeUrl($this->assetTimestamp($this->webroot($path)));
if ($legitCDN) {
$path = rtrim($cdnBaseUrl, '/') . '/' . ltrim($path, '/');
}
return $path;
}
This is the sample code for the assetUrl
props to #lorenzo at https://github.com/cakephp/cakephp/issues/2149 for this solution
P.S.: I have rewritten the above as a Plugin.
So you can simply have the AppHelper extend this CDNAppHelper instead.
https://github.com/simkimsia/UtilityHelpers

If you are looking for simplest stuff just update few parameters in end of your core.php file
Configure::write('App.imageBaseUrl', 'http://cdn.yourdomain.com/img/');
Configure::write('App.cssBaseUrl', 'http://cdn.yourdomain.com/css/');
Configure::write('App.jsBaseUrl', 'http://cdn.yourdomain.com/js/');

echo $this->Html->css('alpha_landing/styles', array(
'fullBase' => true,
'pathPrefix'=>$cdnBaseUrl.'css/'));
Try this one

Related

Get file information form directory Laravel

I use the following method to get all files from a folder and my method returns some basic information about the files inside directory
public function getUploaded()
{
$files = [];
$filesInFolder = File::files(base_path() .'/'. self::UPLOAD_DIR);
foreach($filesInFolder as $path)
{
$files[] = pathinfo($path);
}
return response()->json($files, 200);
}
How would I get the size and the base name like ?
$files['name'] = ....
$files['size'] = ....
You could solve this quite neatly with a Laravel collection and SplFileInfo. Something along the following lines;
public function getUploaded()
{
$files = collect(File::files(base_path() . "/" . self::UPLOAD_DIR))->map(function ($filePath) {
$file = new \SplFileInfo($filePath);
return [
'name' => $file->getName(),
'size' => $file->getSize(),
];
});
return response()->json($files);
}
You can modify your code as follows:
foreach ($filesInFolder as $path) {
$file = pathinfo($path);
$file['size'] = File::size($path);
$file['name'] = File::name($path);
$files[] = $file;
}

List all controllers/actions in Cakephp 3

How do I list all the controllers/actions on my site? Configure::listObjects('model') doesnt seem to exist anymore. I am trying to write a function to generate/add to the ACO's in my ACL setup. Thanks.
So here is what I did. In my Resource Controller:
Include the reflection class/method libraries
use ReflectionClass;
use ReflectionMethod;
To get the controllers:
public function getControllers() {
$files = scandir('../src/Controller/');
$results = [];
$ignoreList = [
'.',
'..',
'Component',
'AppController.php',
];
foreach($files as $file){
if(!in_array($file, $ignoreList)) {
$controller = explode('.', $file)[0];
array_push($results, str_replace('Controller', '', $controller));
}
}
return $results;
}
And now for the actions:
public function getActions($controllerName) {
$className = 'App\\Controller\\'.$controllerName.'Controller';
$class = new ReflectionClass($className);
$actions = $class->getMethods(ReflectionMethod::IS_PUBLIC);
$results = [$controllerName => []];
$ignoreList = ['beforeFilter', 'afterFilter', 'initialize'];
foreach($actions as $action){
if($action->class == $className && !in_array($action->name, $ignoreList)){
array_push($results[$controllerName], $action->name);
}
}
return $results;
}
Finally, to tie them boths together:
public function getResources(){
$controllers = $this->getControllers();
$resources = [];
foreach($controllers as $controller){
$actions = $this->getActions($controller);
array_push($resources, $actions);
}
return $resources;
}
I hope that helps some people.
It doesn't look like anything similar to this is still available in Cake3, nor is it still needed because of the namespaces I think.
So in short you can try to do this:
Read all controllers from the app level controller folder
Read all plugin controller folders (Get the plugin folder via Plugin::path())
Iterate over the controllers you've collected in the previous steps (You'll need to use App::uses())
Use reflections to get the public methods from each controller
I am using CakePHP 3.x and had problems with the function "getActions"
The correct syntax for "ReflectionClass" and "ReflectionMethod" is:
public function getActions($controllerName) {
$className = 'App\\Controller\\'.$controllerName.'Controller';
$class = new \ReflectionClass($className);
$actions = $class->getMethods(\ReflectionMethod::IS_PUBLIC);
$results = [$controllerName => []];
$ignoreList = ['beforeFilter', 'afterFilter', 'initialize'];
foreach($actions as $action){
if($action->class == $className && !in_array($action->name, $ignoreList)){
array_push($results[$controllerName], $action->name);
}
}
return $results;
}
Warning for "\" before ReflectionClass and ReflectionMethod.

page getting rendered after restrict drupal

I am using a custom module to restrict a role to a url in drupal 7 the code is as follows:
<?php
// Implements hook_init()
function restrict_access_init() {
$restrictions = restrict_access_restrictions();
global $user;
foreach ($restrictions as $path => $roles) {
// See if the current path matches any of the patterns provided.
if (drupal_match_path($_GET['q'], $path)) {
// It matches, check the current user has any of the required roles
$valid = FALSE;
foreach ($roles as $role) {
print implode("','",$user ->roles);
if (in_array($role, $user->roles)) {
$valid = TRUE;
break;
}
}
if (!$valid) {
drupal_access_denied();
}
}
}
}
function restrict_access_restrictions() {
// This array will be keyed by path and contain an array of allowed roles for that path
return array(
'path/path' => array('admin'),
);
}
?>
This does restrict access just fine but it then renders the page un-styled after the footer.
Any ideas why this may be happening?
I'm at a lost end with this now.
i needed to add module_invoke_all('exit'); exit(); under drupal_acess_denied();
e.g.
drupal_acess_denied();
module_invoke_all('exit');
exit();

upload a file in cakePHP

Hi I want to upload a file using cake php, i got the file and i am using
move_uploaded_file() to move to a specific location but it is not moving my simple logic is
shown below
if (move_uploaded_file($this->data['Add']['upload']['tmp_name'], APP . 'views' . DS .
'static' . DS.'uploads'.DS.'Rajaram'.DS )) {
LogUtil::$logger->debug('KMP File upload Url :
'.var_export($this->data, true));
}
Thanks in Advance.
File uploading is something CakePHP doesn’t do out of the box, which is one of the only thing that annoys me about the framework.
I tackled this by adding file handling to a model using callback methods. I upload the actual file with beforeSave(), and delete the file from the file system with beforeDelete(). A sample model looks like this:
<?php
App::uses('File', 'Utility');
class Image extends AppModel {
public $name = 'Image';
public function beforeSave($options = array()) {
$fieldName = 'filename';
$field = $this->data[$this->alias][$fieldName];
if (!is_array($field)) {
$this->validationErrors[$fieldName][] = 'No file detected';
return false;
}
switch ($field['error']) {
case UPLOAD_ERR_OK:
$newFilename = time() . '.jpg';
$uploadDir = WWW_ROOT . 'files/';
$source = $field['tmp_name'];
$destination = $uploadDir . $newFilename;
if (move_uploaded_file($source, $destination)) {
$this->data[$this->alias][$fieldName] = $newFilename;
return true;
}
else {
$this->validationErrors[$fieldName][] = 'No file detected';
return false;
}
break;
default:
$this->validationErrors[$fieldName][] = 'No file detected';
return false;
break;
}
}
public function beforeDelete($cascade = true) {
$image = $this->findById($this->id);
$file = new File(WWW_ROOT . 'files/' . $image['Image']['filename']);
return $file->delete();
}
}
Obviously this isn’t a perfect implementation, so feel free to take from it, learn from it, adapt it.
This was written off-the-cuff for a project recently where there’s only one model that has images attached, but on a larger project I’d more than likely wrap it up into a nice model behavior.
In your model you can use the afterSave callback method to handle your file upload:-
public function afterSave($created) {
if (isset($_FILES['data']['name'][$this->alias]['filename'])) {
$filename = $_FILES['data']['name'][$this->alias]['filename'];
$fileInfo = pathinfo($filename);
$fileExt = isset($fileInfo['extension']) ? $fileInfo['extension'] : '';
$filename = $fileInfo['filename'];
$newFilename = "$filename.$fileExt";
$dir = WWW_ROOT . 'files' . DS . 'uploads';
$target = $dir . DS . $newFilename;
move_uploaded_file($source, $target);
}
}
You can use $newFilename to change the filename to something appropriate if need be (I tend to check if a file with the same name already exists and rename the new one to avoid overwriting it.

How do I use fixed fields in CakeDC's csvUpload behavior in Util plugin

I am using the csvUpload behavior of the Utils plugin by CakeDC, on a CakePHP 2.2.1 install.
I have it working great it's processing a rather large csv successfully. However there are two fields in my table / Model that would be considered fixed, as they are based on ID's from from associated models that are not consistent. So I need to get these fixed values via variables which is easy enough.
So my question is, how do I use the fixed fields aspect of csvUpload? I have tried that following and many little variation, which obviously didn't work.
public function upload_csv($Id = null) {
$unique_add = 69;
if ( $this->request->is('POST') ) {
$records_count = $this->Model->find( 'count' );
try {
$fixed = array('Model' => array('random_id' => $Id, 'unique_add' => $unique_add));
$this->Model->importCSV($this->request->data['Model']['CsvFile']['tmp_name'], $fixed);
} catch (Exception $e) {
$import_errors = $this->Model->getImportErrors();
$this->set( 'import_errors', $import_errors );
$this->Session->setFlash( __('Error Importing') . ' ' . $this->request->data['Model']['CsvFile']['name'] . ', ' . __('column name mismatch.') );
$this->redirect( array('action'=>'import') );
}
$new_records_count = $this->Model->find( 'count' ) - $records_count;
$this->Session->setFlash(__('Successfully imported') . ' ' . $new_records_count . ' records from ' . $this->request->data['Model']['CsvFile']['name'] );
$this->redirect(array('plugin'=>'usermgmt', 'controller'=>'users', 'action'=>'dashboard'));
}
}
Any help would be greatly appreciated as I have only found 1 post concerning this behavior when I searching...
I made my custom method to achieve the same task. Define the following method in app\Plugin\Utils\Model\Behavior
public function getCSVData(Model &$Model, $file, $fixed = array())
{
$settings = array(
'delimiter' => ',',
'enclosure' => '"',
'hasHeader' => true
);
$this->setup($Model, $settings);
$handle = new SplFileObject($file, 'rb');
$header = $this->_getHeader($Model, $handle);
$db = $Model->getDataSource();
$db->begin($Model);
$saved = array();
$data = array();
$i = 0;
while (($row = $this->_getCSVLine($Model, $handle)) !== false)
{
foreach ($header as $k => $col)
{
// get the data field from Model.field
$col = str_replace('.', '-', trim($col));
if (strpos($col, '.') !== false)
{
list($model,$field) = explode('.', $col);
$data[$i][$model][$field] = (isset($row[$k])) ? $row[$k] : '';
}
else
{
$col = str_replace(' ','_', $col);
$data[$i][$Model->alias][$col] = (isset($row[$k])) ? $row[$k] : '';
}
}
$is_valid_row = false;
foreach($data[$i][$Model->alias] as $col => $value )
{
if(!empty($data[$i][$Model->alias][$col]))
{
$is_valid_row = true;
}
}
if($is_valid_row == true)
{
$i++;
$data = Set::merge($data, $fixed);
}
else
{
unset($data[$i]);
}
}
return $data;
}
And you can use it using:
$csv_data = $this->Model->getCSVData($this->request->data['Model']['CsvFile']['tmp_name'], $fixed);
Here $csv_data will contain an array of all of those records from the csv file which are not empty and with the fixed field in each record index.
So as I was telling Arun, I answered my own question and figured it out. I was looking to broad instead of really examining what was in front of me. I started running some debugging and figured it out.
First of all, $unique_add = 69 is seen as an int, duh. In order for it to be added to the csv it need to viewed as a string. So it simply becomes, $unique_add = '69'.
I couldn't enter the value of $Id directly into the fixed array. So I just had to perform a simple find to get the value I needed.
$needed_id = $this->Model->find('first', array(
'condition'=>array('Model.id'=>$Id)
)
);
$random_id = $needed_id['Model']['id'];
Hopefully this won't be needed to help anyone because hopefully no one else will make this silly mistake. But one plus... Now there's actually more than one post on the internet documenting the use of fixed fields in the CakeDC Utils plugin.

Resources