CodeIgniter How to bring the id of image clicked in the url? - codeigniter

I'm developing an web app using codeigniter. When I try to click
an image (using detail method), it doesn't include the ID of the image in the link.
I have tried many times, but it still doesn't work. I've even run the same project on another team member's PC, but it still doesn't work on my PC.
Here's the code:
public function detail($url_title, $id = '') {
// Get user logged in id
$user_id = $this->auth->userid();
// Decode url id
$id = decode_safe_url(#$id);
// Get survey master info
// division 0 mean survey, status 0 is not publish
$survey = $this->egsurveymaster->get(array('id' => #$id, 'division' => '1', 'status != ' => "0"));
// Redirect if product review is not exist
if (!#$survey) {
redirect('andrasurvey');
}
// Update read count
if (isset($_COOKIE['eblo_pcid'])) {
$this->egsurveymaster->count_read(#$id, $_COOKIE['andra_pcid']);
}
// Title
$this->template->title = asset_title('Andra Survey - ' . #$survey->title);
// Vars
$vars = array(
'contents' => array(
'master_id' => #$survey->id,
'review' => $this->_overviewContent(#$survey->id, #$survey),
),
'snsContents' => array(
'title' => #$survey->title,
'image' => asset_url(#$survey->image),
'url' => base_url('andrasurvey/detail/' . url_title(#$survey->title) . '/' . encode_safe_url(#$survey->id)),
'content' => character_limiter(strip_tags(#$survey->content, 150)),
'keywords' => trim(#$survey->title) . ', ',
'username' => 'andraadmin',
),
);
// Content
$this->template->content->view(asset_content('detail'), #$vars);
// publish the template
$this->template->publish();
}
When I click the image, this is what I get:
http://localhost:1234/andrasurvey/survey/detail/umur-anda-yang-seharusnya/
I really need your help,
Thank you.

Related

How can i change the image upload directory and view image url in laravel

In my script all images uploaded goes into directory "ib" but i want to change that directory to a different name eg. "imgib"
here is what i did so far. i changed the code vlues from "ib" to "imgib"
} else {
// upload path
$path = 'imgib/';
// if path not exists create it
if (!File::exists($path)) {
File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
}
// move image to path
$upload = $request->file('uploads')->move($path, $imageName);
// file name
$filename = url($path) . '/' . $imageName;
// method server host
$method = 1;
}
// if image uploded
if ($upload) {
// if user auth get user id
if (Auth::user()) {$userID = Auth::user()->id;} else { $userID = null;}
// create new image data
$data = Image::create([
'user_id' => $userID,
'image_id' => $string,
'image_path' => $filename,
'image_size' => $fileSize,
'method' => $method,
]);
// if image data created
if ($data) {
// success array
$response = array(
'type' => 'success',
'msg' => 'success',
'data' => array('id' => $string),
);
// success response
return response()->json($response);
} else {
if (file_exists('imgib/' . $filename)) {$delete = File::delete('imgib/' . $filename);}
// error response
return response()->json(array(
'type' => 'error',
'errors' => 'Opps !! Error please refresh page and try again.',
));
}
so far everything looks ok and it creates "imgib" directory automatically and all uploads go into "imgib" directory.
But the issue is, image url still uses the same old directory name.
eg. site.org/ib/78huOP09vv
How to make it get the correct url eg. site.org/imgib/78huOP09vv
Thanks for the help everyone. I managed to fix the issue by editing viewimage.blade.php
Yes of course need to clear the browser cache after editing the files.

Drupal 8, add an image field from a BuildForm with preview

I created a custom form from a buildForm function. In this form, I would like add an image field.
I can do that via this code :
$form['main']['image'] = array(
'#type' => 'text_format',
'#title' => t('image'),
'#default_value' => array(10),
);
I can upload and remove the image from my form. However, when I upload an image, I haven't this preview.
I mean, when I create a content via the Drupal UI. I can add a preconfigured "image" field. When I upload an image via this "image" field, I have a preview of the image.
And here, when I create the field element programmatically, I haven't a preview of the image when I upload her.
How use api Drupal for have the preview of the image when I upload her via my "image" field ?
So here is how I got my form to display the thumbnail image. What I basically did was take the code in ImageWidget::process, put it in a theme preprocessor and set the #theme property of the element to image_widget.
Your image element in your form class should look like this:
$form['profile_image'] = [
'#type' => 'managed_file',
'#title' => t('Profile Picture'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
'file_validate_size' => array(25600000),
),
**'#theme' => 'image_widget',**
**'#preview_image_style' => 'medium',**
'#upload_location' => 'public://profile-pictures',
'#required' => TRUE,
];
In your name_of_default_theme.theme file, you need the following:
function name_of_default_theme_preprocess_image_widget(&$variables) {
$element = $variables['element'];
$variables['attributes'] = array('class' => array('image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix'));
if (!empty($element['fids']['#value'])) {
$file = reset($element['#files']);
$element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
$file_variables = array(
'style_name' => $element['#preview_image_style'],
'uri' => $file->getFileUri(),
);
// Determine image dimensions.
if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
$file_variables['width'] = $element['#value']['width'];
$file_variables['height'] = $element['#value']['height'];
} else {
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$file_variables['width'] = $image->getWidth();
$file_variables['height'] = $image->getHeight();
}
else {
$file_variables['width'] = $file_variables['height'] = NULL;
}
}
$element['preview'] = array(
'#weight' => -10,
'#theme' => 'image_style',
'#width' => $file_variables['width'],
'#height' => $file_variables['height'],
'#style_name' => $file_variables['style_name'],
'#uri' => $file_variables['uri'],
);
// Store the dimensions in the form so the file doesn't have to be
// accessed again. This is important for remote files.
$element['width'] = array(
'#type' => 'hidden',
'#value' => $file_variables['width'],
);
$element['height'] = array(
'#type' => 'hidden',
'#value' => $file_variables['height'],
);
}
$variables['data'] = array();
foreach (Element::children($element) as $child) {
$variables['data'][$child] = $element[$child];
}
}
The solution works well, but the image module is missing a class with the #FormElement annotation. That is why the element isn't rendered properly.
Can you try with managed_file type?
'#type' => 'managed_file'
First some clarifications, then some observations and then the code that worked for me.
Clarifications:
I am using Drupal 9, but the solution proposed below may work also
for Drupal 8.
By "default temporary directory" I mean the directory defined in the following settings
file
[DrupalrootDirectory]/sites/default/settings.php
using
$settings['file_temp_path'] = '/The/Absolute/Path/To/Your/Temporary/Directory';
or defined by your operating system and that you can check in the Drupal administration
menu:
[YourSiteWebAddress]/admin/config/media/file-system
When something is written inside square brackets [], like this, [DrupalrootDirectory], it means that you should replace it with the actual name in your system, Drupal installation or custom module/file, without the square brackets.
Observations:
No need to create apriory any directories inside the default
temporary directory. They will be created automatically.
When you click the Remove button (which appears automatically as soon you upload a file in your custom form), the image file and the thumbnail files are deleted from the default temporary directory.
It does not matter if you define your default temporary directory inside the default site location,
e.g.,
[DrupalrootDirectory]/sites/default/files
or outside it, for example,
[DrupalrootDirectory]/sites/other/files
In my case, I defined it to:
[DrupalrootDirectory]/sites/default/files/temp
No need to make changes to .htaccess (in Apache server) file inside the default temporary directory or
inside
[DrupalrootDirectory]/sites/default/files
Keep them as Drupal created them.
No need to change file rights to "777" inside the default temporary directory, "775" is enough.
Check that your Drupal installation is actually creating thumbnails for images uploaded using the
administration menu:
[YourSiteWebAddress]/admin/content/media
when using the "Add media" link
[YourSiteWebAddress]/media/add/image
No need to make any other changes inside Drupal settings
file
[DrupalrootDirectory]/sites/default/settings.php
The code that worked for me:
It is based in the code published above by "Je Suis Alrick". But his code was not working for me, neither I could not find in which part of his code the thumbnail image was actually created. In my search for it, this post helped
Generate programmatically image styles with Drupal 8
So, here is the final code:
In your custom module, in the custom form file, most probably located
in:
[DrupalrootDirectory]/modules/custom/[NameOfYourCustomModule]/src/Form/[NameOfYourCustomForm].php
you add the element to be used to upload the image file:
$form['profile_image'] = [
'#type' => 'managed_file',
'#title' => t('Profile Picture'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
'file_validate_size' => array(25600000),
),
'#theme' => 'image_widget',
'#preview_image_style' => 'medium',
'#required' => TRUE,
];
So far, the same as in the code of "Je Suis Alrick", except that I deleted the definition for '#upload_location', so the default temporary directory will be used avoiding security complaints.
The important part here is:
the definition of the '#theme', which may be any name, but in this case is 'image_widget';
and the definition of '#preview_image_style', which must be the machine name of one of the image styles defined in your Drupal installation, that you can check in your administration
menu
[YourSiteWebAddress]/admin/config/media/image-styles
For this case the style 'medium' will be used, which is one of the image styles created by default by Drupal.
Then, in the module file of your custom module, named [NameOfYourCustomModule].module and most probably located
in:
[DrupalrootDirectory]/modules/custom/[NameOfYourCustomModule]/
You will need to paste the following code:
<?php
use Drupal\image\Entity\ImageStyle;
function [NameOfYourCustomModule]_preprocess_image_widget(&$variables) {
$element = $variables['element'];
$variables['attributes'] = array('class' => array('image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix'));
if (!empty($element['fids']['#value'])) {
$file = reset($element['#files']);
$element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
$file_variables = array(
'style_name' => $element['#preview_image_style'],
'uri' => $file->getFileUri(),
);
// Determine image dimensions.
if (isset($element['width']['#value']) && isset($element['height']['#value'])) {
$file_variables['width'] = $element['width']['#value'];
$file_variables['height'] = $element['height']['#value'];
} else {
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$file_variables['width'] = $image->getWidth();
$file_variables['height'] = $image->getHeight();
$style = ImageStyle::load($file_variables['style_name']);
$image_uri = $file->getFileUri();
$destination = $style->buildUri($image_uri);
$style->createDerivative($image_uri, $destination);
}
else {
$file_variables['width'] = $file_variables['height'] = NULL;
}
}
$element['preview'] = array(
'#weight' => -10,
'#theme' => 'image_style',
'#width' => $file_variables['width'],
'#height' => $file_variables['height'],
'#style_name' => $file_variables['style_name'],
'#uri' => $file_variables['uri'],
);
// Store the dimensions in the form so the file doesn't have to be
// accessed again. This is important for remote files.
$element['width'] = array(
'#type' => 'hidden',
'#value' => $file_variables['width'],
);
$element['height'] = array(
'#type' => 'hidden',
'#value' => $file_variables['height'],
);
}
$variables['data'] = array();
foreach (\Drupal\Core\Render\Element::children($element) as $child) {
$variables['data'][$child] = $element[$child];
}
}
You should note that at the end of the name of the function, the name of the theme 'image_widget' is included, which tells Drupal to process your form element using the defined above function: [NameOfYourCustomModule]_preprocess_image_widget
What have I added?
The line at the
top:
use Drupal\image\Entity\ImageStyle;
And the following four lines that actually create the image thumbnail inside the default temporary directory:
$style = ImageStyle::load($file_variables['style_name']);
$image_uri = $file->getFileUri();
$destination = $style->buildUri($image_uri);
$style->createDerivative($image_uri, $destination);
With the addition of these five lines I got it working!
Nice answer thx, only change I'd make is using Token for upload location, and Bytes for file upload size, although I guess it depends on the use case. Something like the below (stripped out most of the code for the sake of simplicity.
namespace Drupal\my_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Component\Utility\Bytes;
use Drupal\Core\Utility\Token;
class SampleForm extends FormBase
{
protected $currentUser;
protected $token;
public function __construct(AccountProxyInterface $current_user, Token $token) {
$this->currentUser = $current_user;
$this->token = $token;
}
public static function create(ContainerInterface $container)
{
return new static(
$container->get('current_user'),
$container->get('token')
);
}
/**
* {#inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['sample_image'] = [
'#type' => 'managed_file',
'#title' => t('Profile Picture'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
'file_validate_size' => file_upload_max_size() / pow(Bytes::KILOBYTE, 2) . 'M',
),
'#theme' => 'image_widget',
'#preview_image_style' => 'medium',
'#upload_location' => $this->token->replace('private://[date:custom:Y]-[date:custom:m]'),
'#required' => TRUE,
];
return $form;
}
}
Theme it to work on multiple file upload. From #Je Suis Alrick answer above.
function themename_preprocess_image_widget(&$variables) {
$element = $variables['element'];
$variables['attributes'] = array('class' => array('image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix'));
if (!empty($element['fids']['#value'])) {
foreach ($element['#files'] as $file) {
$element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
$file_variables = array(
'style_name' => $element['#preview_image_style'],
'uri' => $file->getFileUri(),
);
// Determine image dimensions.
if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
$file_variables['width'] = $element['#value']['width'];
$file_variables['height'] = $element['#value']['height'];
} else {
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$file_variables['width'] = $image->getWidth();
$file_variables['height'] = $image->getHeight();
}
else {
$file_variables['width'] = $file_variables['height'] = NULL;
}
}
$element['preview'][] = array(
'#weight' => -10,
'#theme' => 'image_style',
'#width' => $file_variables['width'],
'#height' => $file_variables['height'],
'#style_name' => $file_variables['style_name'],
'#uri' => $file_variables['uri'],
);
// Store the dimensions in the form so the file doesn't have to be
// accessed again. This is important for remote files.
$element['width'] = array(
'#type' => 'hidden',
'#value' => $file_variables['width'],
);
$element['height'] = array(
'#type' => 'hidden',
'#value' => $file_variables['height'],
);
}
}
$variables['data'] = array();
foreach (\Drupal\Core\Render\Element::children($element) as $child) {
$variables['data'][$child] = $element[$child];
}
}

authorisation based on values not on verb

I'm implementing an authorisation process based on values not on verb.
Example:
all users/groups are allowed to update a db field
admin can set status to all possible values (confirmed | pending | cancelled)
supplier can set to 'confirmed'
All examples I find go around a user/group being able or not to insert,update or delete something.
Is there something out there to deal with situations like this out of the box, or this has be hard coded?
Basically what you need is something hard to maintain in any application: granular permissions.
You can get this to work easily using Cartalyst's Sentry. Here's how I do it:
All my routes are hierarchically organized and named as such:
<?php
Route::get('login', array('as'=>'logon.login', 'uses'=>'LogonController#login'));
Route::get('logged/out', array('as'=>'logon.loggedOut', 'uses'=>'LogonController#loggedOut'));
Route::group(array('before' => 'auth'), function()
{
Route::get('logout', array('as'=>'logon.logout', 'uses'=>'LogonController#logout'));
Route::group(array('before' => 'permissions'), function()
{
Route::get('store/checkout/shipping/address', array('as'=>'store.checkout.shipping.address', 'uses'=>'StoreController#shippingAddress'));
Route::get('store/checkout/payment/confirmed', array('as'=>'store.checkout.payment.confirmed', 'uses'=>'StoreController#confirmed'));
Route::get('profile', array('as'=>'profile.show', 'uses'=>'ProfileController#show'));
});
});
Those under the filter 'permissions' are subject to check if user has rights to use them:
Route::filter('permissions', function()
{
$name = Route::current()->getName();
$name = 'system' . ( ! empty($name) ? '.' : '') . $name;
if (!Permission::has($name)) {
App::abort(401, 'You are not authorized to access route '.$name);
}
});
Basically here I get the current route name, add 'system.' to it and check if the user has this particular permission.
Here's how I create my groups and populate permissions:
<?php
public function seedPermissions()
{
DB::table('groups')->truncate();
$id = 1;
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Super Administrators',
'permissions' => array(
'system' => 1,
),
));
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Administrators',
'permissions' => array(
'system.users' => 1,
'system.products' => 1,
'system.store' => 1,
'system.profile' => 1,
),
));
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Managers',
'permissions' => array(
'system.products' => 1,
'system.store' => 1,
'system.profile' => 1,
),
));
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Users',
'permissions' => array(
'system.store.checkout' => 1,
'system.profile' => 1,
),
));
}
So if a user is trying to add some shipping address, the route 'store.checkout.payment.confirmed', as every user has access to 'system.store.checkout', everything inside that route will available to him.
And this is how I check for permissions:
public static function has($permission)
{
$all = [];
$parts = explode('.',$permission);
$permission = '';
foreach($parts as $part) {
$permission .= (!empty($permission) ? '.' : '') . $part;
$all[] = $permission;
}
return Sentry::check() and Sentry::getUser()->hasAnyAccess($all);
}
It basically builds a list of routes:
system
system.store
system.store.checkout
system.store.checkout.payment
system.store.checkout.payment.confirmed
And if Sentry finds one of those in the users granular permissions it will return true.
Now I just have to add users to groups:
Sentry::findUserById(1)->addGroup( Sentry::getGroupProvider()->findByName('Users') );
And if I need to go granular on a particular user/permission I just need to:
$user = Sentry::findUserById(1);
$user->permissions['store.checkout.payment'] = false;
$user->save();
And the user will never be able to pay for anything in the store again. :)

custom phpbb3 registration

i am making a custom phpbb3 registration and i am trying to register a user form a external file but it not working . also i checked for errors . there is no error .can anyone help me out with where i am wrong . also if anyone has any easy idea how to add a new user record for phpbb3 please help me out with this .
<?php
$username = $_POST[username];
$password = $_POST[password];
$email_address = $_POST[email];
include('forums/common.php');
require('forums/includes/functions_user.php');
// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup('viewtopic');
global $config, $db, $user, $auth, $template, $phpbb_root_path, $phpEx;
$user_row = array(
'username' => $username, //REQUIRED IN FORM
'user_password' => md5($password), //REQUIRED IN FORM
'user_email' => $email_address, //REQUIRED IN FORM
'group_id' => 0,//(int) $group_id,
'user_timezone' => $timezone = date(Z) / 3600,//(float) $data[tz],
'user_dst' => date(I),//$is_dst,
'user_lang' => $user->lang_name,//$data[lang],
'user_type' => USER_NORMAL,//$user_type,
'user_actkey' => '',//$user_actkey,
'user_ip' => $user->ip,
'user_regdate' => time(),
'user_inactive_reason' => 0,//$user_inactive_reason,
'user_inactive_time' => 0,//$user_inactive_time,
);
// Register user...
$user_id = user_add($user_row);
?>
You must define
define('IN_PHPBB', true);
In other case your script will exit immediately in common.php and other required files. You can see
if (!defined('IN_PHPBB'))
{
exit;
}
in every required file

Sending a campaign to a segment

Anyone know how to get a campaign to send to a segment? This code isn't working. It will send an email to all people in the campaign. It will not use the segment. (This is some more text so I can get it to pass the validation of SO.)
My code:
//get member list
$memberArray = $api->listMembers($inStockListId);
foreach ($memberArray['data'] as $member) {
$memberInfo = $api->listMemberInfo($inStockListId, $member['email']);
$_productId = $memberInfo['data'][0]['merges']['PRODUCTID'];
$productId='34';
if ($productId == $_productId) {
array_push($emailArray, $member['email']);
}
}
//create new segment for campaign
$listStaticSegmentId = $api->listStaticSegmentAdd($inStockListId, 'inStockStaticSegment');
//add members to segment
$val = $api->listStaticSegmentMembersAdd($inStockListId, $listStaticSegmentId, $emailArray);
$conditions = array();
$conditions[] = array(
'field' => 'email',
'op' => 'like',
'value' => '%'
);
$segment_options = array(
'match' => 'all',
'conditions' => $conditions
);
$type = 'regular';
$options = array(
'template_id' => $campaignTemplateId,
'list_id' => $inStockListId,
'subject' => 'In-Stock Notification',
'from_email' => 'from#email.com',
'from_name' => 'My From Name'
);
$content = array(
'html_main' => 'some pretty html content',
'html_sidecolumn' => 'this goes in a side column',
'html_header' => 'this gets placed in the header',
'html_footer' => 'the footer with an *|UNSUB|* message',
'text' => 'text content text content *|UNSUB|*'
);
$newCampaignId = $api->campaignCreate($type, $options, $content, $segment_options);
I figured it out. Essentially, here is the flow. If you want detailed code, send me a message and I'll be glad to help.
$api = new MCAPI($this->_apiKey);
$api->listMemberInfo($this->_listId, $member['email']);
$api->listUpdateMember($this->_listId, $member['email'], $mergeVars);
$api->listStaticSegmentDel($this->_listId, $segment['id']);
$api->listStaticSegmentAdd($this->_listId, $segmentName);
$api->listStaticSegmentMembersAdd($this->_listId, $segmentId, $emailArray);
$api->campaignCreate($type, $options, $content, $segment_options);
//$api->campaignSendTest($newCampaignId, array($member['email']));
$api->campaignSendNow($newCampaignId);
Note, this is done via the MailChimp PHP API.

Resources