Laravel HTTP Client Pool catch ConnectException - laravel

How do I deal with failures in Laravel's Concurrent Requests? For example I have 10 requests in a pool and half of them return GuzzleHttp\Exception\ConnectException. I want to catch them and retry with a different proxy server.
<?php
$responses = Illuminate\Support\Facades\Http::pool(
function (Illuminate\Http\Client\Pool $pool) use ($params) {
$url = "https://example.com/api/endpoint?foo=%s";
$return = [];
$proxy = $this->proxyManager->get();
foreach($params as $param) {
// Number of retries
for($i = 0; $i < 10; $i++) {
try {
// This returns GuzzleHttp\Promise\Promise
$return[] = $pool->as($param)
->withOptions(['proxy' => $proxy])
->get(\sprintf($url, $param))
->otherwise(function ($e) {
// This never happens
dd( $e );
});
break;
} catch(\Exception $e) {
$proxy = $this->proxyManager->get();
continue;
}
}
}
return $return;
}
);
// Some fail, some ok
dd( $responses );

Had to use Guzzle with custom Middleware to archive what I wanted:
app/Http/Client/Middleware.php
<?php
namespace App\Http\Client;
final class Middleware
{
public static function retry( callable $decider, callable $delay = null ): callable
{
return static function( callable $handler ) use ( $decider, $delay ): RetryMiddleware
{
return new RetryMiddleware( $decider, $handler, $delay );
};
}
}
app/Http/Client/RetryMiddleware.php
<?php
namespace App\Http\Client;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class RetryMiddleware
{
private $nextHandler;
private $decider;
private $delay;
public function __construct(callable $decider, callable $nextHandler, callable $delay = null)
{
$this->decider = $decider;
$this->nextHandler = $nextHandler;
$this->delay = $delay ?: __CLASS__ . '::defaultDelay';
}
public static function defaultDelay(int $retries): int
{
return 0;
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
if (!isset($options['retries'])) {
$options['retries'] = 0;
}
$fn = $this->nextHandler;
return $fn($request, $options)
->then(
$this->onFulfilled($request, $options),
$this->onRejected($request, $options)
);
}
private function onFulfilled(RequestInterface $request, array $options): callable
{
return function ($value) use ($request, $options) {
if (!($this->decider)(
$options['retries'],
$request,
$value,
null
)) {
return $value;
}
return $this->doRetry($request, $options, $value);
};
}
private function onRejected(RequestInterface $req, array $options): callable
{
return function ($reason) use ($req, $options) {
if (!($this->decider)(
$options['retries'],
$req,
null,
$reason
)) {
return P\Create::rejectionFor($reason);
}
return $this->doRetry($req, $options);
};
}
private function doRetry(RequestInterface $request, array $options, ResponseInterface $response = null): PromiseInterface
{
$options['delay'] = ($this->delay)(++$options['retries'], $response);
// Callback?
if( $options['on_retry'] )
{
\call_user_func_array( $options['on_retry'], [
&$request,
&$options,
$response
] );
}
return $this($request, $options);
}
}
Then make asynchronous requests like this:
<?php
$url = "https://example.com/api/endpoint?foo=%s";
$data = [];
$handlerStack = \GuzzleHttp\HandlerStack::create( new \GuzzleHttp\Handler\CurlMultiHandler() );
$handlerStack->push( \App\Http\Client\Middleware::retry( function( $retries, $request, $response = null, $exception = null )
{
// Limit the number of retries to 10
if( $retries >= 10 )
{
return false;
}
// Retry connection exceptions
if( $exception )
{
return true;
}
return false;
} ) );
$client = new \GuzzleHttp\Client( [
'handler' => $handlerStack,
'on_retry' => function( &$request, &$options )
{
$options['proxy'] = $this->proxyManager->get();
}
] );
$requests = function() use ( $client, $url, $params )
{
foreach( $params as $param )
{
$get = \sprintf( $url, $param );
yield function() use ( $client, $get )
{
return $client->getAsync( $get, [
'proxy' => $this->proxyManager->get()
] );
};
}
};
$pool = new \GuzzleHttp\Pool( $client, $requests(), [
'concurrency' => 5, // maximum number of requests to send concurrently
'fulfilled' => function( \GuzzleHttp\Psr7\Response $response, $index ) use ( &$data )
{
$data[] = json_decode( $response->getBody(), true );
}, // this is delivered each successful response
'rejected' => function( \Exception $e, $index )
{
}, // this is delivered each failed request
] );
$pool->promise()->wait();
If you want to make synchronous requests with retry then Laravel's HttpClient works:
<?php
$url = "https://example.com/api/endpoint";
$response = \Illuminate\Support\Facades\Http::withOptions( [
'proxy' => $this->proxyManager->get(),
'on_retry' => function( &$request, &$options )
{
$options['proxy'] = $this->proxyManager->get();
}
] )
->withMiddleware( \App\Http\Client\Middleware::retry( function( $retries, $request, $response = null, $exception = null )
{
// Limit the number of retries to 10
if( $retries >= 10 )
{
return false;
}
// Retry connection exceptions
if( $exception )
{
return true;
}
return false;
} ) )
->get( $url );

Related

PhpStorm cannot track some file changes

I have noticed that some of my files in PhpStorm does not detect any changes while in other files I can see the changes immediately if I did some code changes.
Is there a way to find where in the PhpStorm settings to auto-detect all files edited?
I've already checked my .gitignore file but I can't see the untrackable file isn't there.
For instance, in my UserScopeTrait.php file, I did code changes and I've seen changes automatically when I git status. but in my UserTrait.php file if I made changes in it there are no changes found.
Here are the exact files I've made some changes:
This is the UserScopeTrait.php file and this can be auto detected file changes:
<?PHP
namespace App\Traits;
use App\Jobs\SendEmployeeInvitationEmail;
use App\Jobs\SendEmployeeInvitationMondayTuesdayJob;
use App\Jobs\UpdateAdminEmployeeSurvey;
use App\Language;
use App\Location;
use App\LocationManager;
use App\Mail\SendWeeklySurvey;
use App\Mail\SurveyResultsAvailableNotification;
use App\Mail\SurveySentNotification;
use App\Repositories\UserCompanyRepository;
use App\Survey;
use App\Team;
use App\TeamManager;
use App\User;
use App\UserCompany;
use App\UsersAnswer;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Mail;
trait UserScopeTrait
{
public function scopeDispatchEmployeeInvites($query)
{
$users = $query->whereHas('userCompany', function ($company) {
$company->where('company_id', auth()->user()->company->id)->where('role_name', 'employee');
})->where('invite_sent', 0)->get();
$auth = auth()->user();
$dispatcher = new User();
$toSend = 0;
$notifyState = [];
// this is the changes I've made
adsfdsfasdfas
if ($users->count() == 5) {
/**
* first survey batch send
* date of action: all days except Monday, Tuesday
* send invitation & update survey details for admin and then mimic admin survey details to employee
*/
if (!Carbon::now()->isMonday() && !Carbon::now()->isTuesday()) {
$this->updateSurveyDetailsAdminEmployee(null, $auth, 'admin');
}
}
foreach ($users as $employee) {
$notifyState['total'] = $users->count();
$employee->invite_sent = true;
$employee->save();
$toSend++;
if ($notifyState['total'] == $toSend) {
$notifyState['last'] = true;
// Admin receive an email notification about surveys sent
$dispatcher->dispatchAdminSurveySentNotification($auth);
} else {
$notifyState['last'] = false;
}
/**
* counter reaches to 5 this means that this is the first survey
* and should update survey details for both admin & employee
*/
if ($users->count() == 5) {
if (Carbon::now()->isMonday()||Carbon::now()->isTuesday()) {
/**
* first survey batch send
* date of action: Monday, Tuesday
* send invitation only
*/
SendEmployeeInvitationMondayTuesdayJob::dispatch($employee, auth()->user())->onQueue('notification');
} else {
/**
* first survey batch send
* date of action: all days except Monday, Tuesday
* send invitation & mimic admin survey details to employee
*/
$this->updateSurveyDetailsAdminEmployee($employee, $auth, 'employee');
SendEmployeeInvitationEmail::dispatch($auth, $employee, $notifyState)->onQueue('notification');
}
}
/**
* not first survey batch & single execution
*/
else {
if ($users->count() >=2 && $users->count() <= 3) {
/**
* not first survey batch execution
* date of action: Monday, Tuesday
* send invitation only
*/
if (Carbon::now()->isMonday()||Carbon::now()->isTuesday()) {
SendEmployeeInvitationMondayTuesdayJob::dispatch($employee, auth()->user())->onQueue('notification');
}
/**
* not first survey batch execution
* date of action: all days except Monday, Tuesday
* send invitation & update survey details for employee only mimic admin survey details
*/
else {
$this->updateSurveyDetailsAdminEmployee($employee, $auth, 'employee');
SendEmployeeInvitationEmail::dispatch($auth, $employee, $notifyState)->onQueue('notification');
}
}
if ($users->count() == 1) {
/**
* not first survey single execution
* date of action: Monday, Tuesday
* send invitation only
*/
if (Carbon::now()->isMonday()||Carbon::now()->isTuesday()) {
SendEmployeeInvitationMondayTuesdayJob::dispatch($employee, auth()->user())->onQueue('notification');
}
/**
* not first survey single execution
* date of action: all days except Monday, Tuesday
* send invitation & update survey details for employee mimic admin survey details
*/
else {
$this->updateSurveyDetailsAdminEmployee($employee, $auth, 'employee');
SendEmployeeInvitationEmail::dispatch($auth, $employee, $notifyState)->onQueue('notification');
}
}
}
}
}
private function updateSurveyDetailsAdminEmployee($employee, $auth, $type)
{
$currentDate = Carbon::now();
$nextSurveyDate = clone $currentDate;
if ($type == 'admin') {
date_default_timezone_set($auth->timezone);
// Set next_survey_date base on account owner survey frequency setting
if ($auth->account->survey_frequency == 'every_week_wednesday') {
$nextSurveyDate = $nextSurveyDate->next(Carbon::WEDNESDAY);
} else {
$nextSurveyDate = $nextSurveyDate->next(Carbon::WEDNESDAY)->next(Carbon::WEDNESDAY);
}
// Update survey_date and next_survey_number for admin
$auth->current_survey_date = $currentDate;
$auth->next_survey_date = $nextSurveyDate;
$auth->first_survey = true;
$auth->next_survey_number = (new User())->getNextSurveyNumber($auth);
$auth->save();
}
else if ($type == 'employee') {
date_default_timezone_set($employee->timezone);
// Update next_survey_date and next_survey_number for employee
$employee->next_survey_date = $auth->next_survey_date;
$employee->current_survey_id = $auth->current_survey_id;
$employee->current_survey_date = $currentDate;
$employee->next_survey_number = $auth->next_survey_number;
$employee->invite_sent_time = now()->toDateTimeString();
$employee->save();
}
}
public function scopeUpdateMessageNotificationCounter($query, $data)
{
$managers = $query->whereHas('userCompany', function ($userCompany) use ($data) {
$userCompany->where('company_id', (new User())->authUserCompanyId())->where('role_name', 'manager');
})->get();
foreach ($managers as $user) {
$user->wait_for_my_reply = $data['waitingForMyReply'];
$user->wait_for_employee_organization_reply = $data['waitingForEmployeeOrganizationReply'];
$user->save();
}
$admin = User::whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
$admin->wait_for_my_reply = $data['waitingForMyReply'];
$admin->wait_for_employee_organization_reply = $data['waitingForEmployeeOrganizationReply'];
$admin->save();
}
public function scopeUserHasSurvey($query, $id)
{
$currentSurveyDate = $query->find($id)->current_survey_date;
$nextSurveyDate = $query->find($id)->next_survey_date;
if ($currentSurveyDate != null && $nextSurveyDate != null) {
return true;
} else {
return false;
}
}
public function scopeUserCompanyId($query, $id)
{
return $query->find($id)->company->id;
}
public function scopeUserCurrentSurveyId($query, $id)
{
return $query->find($id)->current_survey_id;
}
public function scopeFilterAdminAccess()
{
if (auth()->user()->freeze_account > 0 && auth()->user()->role_name == 'admin') {
return redirect()->route('billing')->with(['info' => 'Your account is freeze']);
}
}
public function scopeActiveAdmin($query)
{
$query = $query->role('admin')->where('freeze_account', 0);
$query = $query->whereNotNull('email_verified_at')->where('active', 1)->get();
return $query;
}
public function scopeTrialGracePeriodActiveAdmin($query)
{
return $query->role('admin')
->where('freeze_account', 0)
->whereNotNull('email_verified_at')
->where('active', 1)
->where('trial_grace_period', true);
}
public function scopeActiveEmployee($query, $companyId)
{
$query = $query->whereHas('roles', function ($roles) {
$roles->where('name', 'employee');
});
$query = $query->whereNotNull('email_verified_at')->where('active', 1);
$query = $query->whereHas('userCompany', function ($userCompany) use ($companyId) {
$userCompany->where('company_id', $companyId);
})->get();
return $query->count();
}
public function scopeAdminReplies($query)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
return $query->total_replies;
}
public function scopeIncrementReplies($query, $message)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
if (!is_null($message)) {
$query->increment('total_replies');
}
}
public function scopeSendSurveyResultNotification($query)
{
$user = new User();
$admin = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
// process survey result for admin
$user->processSurveyResult($admin);
$managers = User::whereHas('userCompany', function ($userCompany) use ($admin) {
$userCompany->where('company_id', $admin->company->id)->where('role_name', 'manager');
})->get();
if ($managers->count() > 0) {
foreach ($managers as $manager) {
// process survey result for manager
$user->processSurveyResultManager($manager);
}
}
}
public function scopeIncrementUserColumn($query, $column)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
switch ($column) {
case 'surveys_completed':
$query->increment('surveys_completed');
break;
case 'email_notification_sent':
$query->increment('email_notification_sent');
break;
case 'cheers_sent':
$query->increment('cheers_sent');
break;
case 'resolved_issues':
$query->increment('resolved_issues');
break;
case 'total_answers':
$query->increment('total_answers');
break;
case 'uncompleted_replies':
$query->increment('uncompleted_replies');
break;
case 'add_more':
$query->increment('add_more');
break;
}
}
public function scopeDecrementUserColumn($query, $column)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
switch ($column) {
case 'uncompleted_replies':
$query->decrement('uncompleted_replies');
break;
}
if ($query->uncompleted_replies < 1) {
$query->add_more = 0;
$query->save();
}
}
public function scopeDecrementResolvedIssues($query)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
$query->decrement('resolved_issues');
}
public function scopeGetUserEmployeeId($query)
{
$query = $query->whereHas('roles', function ($q) {
$q->where('name', 'employee');
})->get();
$query = $query->pluck('id');
return $query;
}
public function sendSurvey($query)
{
$users = User::get();
foreach ($users as $user) {
if ($user->employees >= 5) {
// Get all employees where company is equal to $this->user
$userId = UserCompany::where('company_id', $user->company->id)->pluck('user_id');
}
}
}
public function scopeGetCompanyId($query, $userId)
{
$query = $query->find($userId)->userCompany->company_id;
return $query;
}
public function scopeGetSurveyCompleted($query)
{
$users = User::whereHas('roles', function ($role) {
$role->where('name', 'admin');
});
}
public function scopeGetCurrentSurveyDetails($query, $request = null)
{
$companyId = null;
$userAnswerFilter = new UsersAnswer();
if (!is_null($request)) {
// this is checking request parameters from super admin's vibe monitor
if (isset($request['id'])) {
$user = $query->find($request['id']);
} else {
$user = $query->find(auth()->id());
}
} else {
$user = $query->find(auth()->id());
}
if ($user->role_name == 'admin') {
$companyId = $user->company->id;
} elseif ($user->role_name == 'manager') {
$companyId = $user->userCompany->company_id;
}
$employeeCount = UserCompany::where('company_id', $companyId)
->where('role_name', 'employee')
->where('last_login_at', '!=', null);
$surveyCompleted = UserCompany::where('company_id', $companyId)
->where('role_name', 'employee')
->where('survey_completed', true);
$userAnswerFilter->filter($request, $surveyCompleted);
$userAnswerFilter->filter($request, $employeeCount);
$surveyCompleted = $surveyCompleted->count();
$employeeCount = $employeeCount->count();
if ($surveyCompleted > 0) {
$completionPercentage = round(($surveyCompleted / $employeeCount) * 100);
} else {
$completionPercentage = 0;
}
// date_default_timezone_set($user->timezone);
$now = Carbon::now();
$start = Carbon::parse($user->current_survey_date);
$end = Carbon::parse($user->current_survey_date)->next(Carbon::TUESDAY)->endOfDay();
// $end = $user->next_survey_date;
// $surveyStarts = Carbon::parse($start);
$surveyStarts = Carbon::parse($start)->format('Y-m-d');
// $surveyEnds = Carbon::parse($end);
$surveyEnds = Carbon::parse($end)->format('Y-m-d');
$now = Carbon::parse($now);
// $start = Carbon::parse($start);
// $end = Carbon::parse($end);
$diff = $end->diffInDays($now);
$status = $diff > 1 ? ('(' . $diff . ' days left)') : ('(' . $diff . ' day left)');
// $start = Carbon::parse($start)->isoFormat('LL');
// $end = Carbon::parse($end)->isoFormat('LL');
return [
'surveyId' => $user->current_survey_id,
'employeeCount' => $employeeCount,
'surveyCompleted' => $surveyCompleted,
'completionPercentage' => $completionPercentage,
'status' => $status,
'difference' => $diff,
'start' => $start->isoFormat('LL'),
'end' => $end->isoFormat('LL'),
'surveyStarts' => $surveyStarts,
'surveyEnds' => $surveyEnds
];
}
public function scopeGetUpcomingSurveyDetails($query, $userId = null)
{
$uId = $userId ?? auth()->id();
$auth = $query->find($uId);
// $surveyStarts = Carbon::createFromFormat('m-d-Y', $auth->next_survey_date);
$surveyStarts = Carbon::parse($auth->next_survey_date);
// Set survey ends base on account owner survey frequency setting
if ($auth->account->survey_frequency == 'every_week_wednesday') {
// $surveyEnds = $surveyStarts->addDays(7)->format('m-d-Y');
$surveyEnds = $surveyStarts->next(Carbon::TUESDAY)->endOfDay();
} else {
// $surveyEnds = $surveyStarts->addDays(14)->format('m-d-Y');
$surveyEnds = $surveyStarts->next(Carbon::TUESDAY)->next(Carbon::TUESDAY)->endOfDay();
}
// $now = Carbon::now()->format('m-d-Y');
$start = $auth->next_survey_date;
$end = $surveyEnds;
$now = Carbon::now();
$start = Carbon::parse($auth->next_survey_date);
$end = Carbon::parse($end);
$dateStartDbFormat = $auth->next_survey_date;
$dateEndDbFormat = $end;
$diff = $end->diffInDays($now);
$status = $diff > 1 ? ('(' . $diff . ' days left)') : ('(' . $diff . ' day left)');
$start = Carbon::parse($start)->isoFormat('LL');
$end = Carbon::parse($end)->isoFormat('LL');
return [
'surveyId' => $userId != null ? 'this is for email notification' : (new User())->authUserNextSurveyId(),
'status' => $status,
'start' => $start,
'dateStartDbFormat' => $dateStartDbFormat,
'dateEndDbFormat' => $dateEndDbFormat,
'end' => $end
];
}
public function scopeGetUpcomingSurveyDetails2($query)
{
$auth = $query->find(auth()->id());
$surveyStarts = Carbon::createFromFormat('m-d-Y', $auth->next_survey_date);
// Set survey ends base on account owner survey frequency setting
if ($auth->account->survey_frequency == 'every_week_wednesday') {
$surveyEnds = $surveyStarts->addDays(7)->format('m-d-Y');
} else {
$surveyEnds = $surveyStarts->addDays(14)->format('m-d-Y');
}
$now = Carbon::now()->format('m-d-Y');
$start = $auth->next_survey_date;
$end = $surveyEnds;
$now = Carbon::createFromFormat('m-d-Y', $now);
$start = Carbon::createFromFormat('m-d-Y', $start);
$end = Carbon::createFromFormat('m-d-Y', $end);
$dateStartDbFormat = $auth->next_survey_date;
$dateEndDbFormat = $end->format('m-d-Y');
$diff = $end->diffInDays($now);
$status = $diff > 1 ? ('(' . $diff . ' days left)') : ('(' . $diff . ' day left)');
$start = Carbon::parse($start, 'Asia/Manila')->isoFormat('LL');
$end = Carbon::parse($end, 'Asia/Manila')->isoFormat('LL');
return [
'surveyId' => (new User())->authUserNextSurveyId(),
'status' => $status,
'start' => $start,
'dateStartDbFormat' => $dateStartDbFormat,
'dateEndDbFormat' => $dateEndDbFormat,
'end' => $end
];
}
public function scopeGetPastSurveys($query)
{
$auth = $query->find(auth()->id());
$currentSurveyDate = Carbon::createFromFormat('m-d-Y', $auth->current_survey_date);
}
public function scopeAccountNotificationsSchedule($query, $schedule)
{
$users = $query->where('email_verified_at', '!=', null)->where('active', 1)->get();
foreach ($users as $user) {
$notification = $user->account->notifications['new_message'] ?? null;
if ($notification) {
$frequency = null;
switch ($notification) {
case 'every_10_minutes':
$frequency = 'everyTenMinutes';
break;
case '1x_per_hour':
$frequency = 'hourly';
break;
case '1x_per_day':
$frequency = 'daily';
break;
default:
break;
}
if ($user->total_replies != $user->new_messages_notification) {
$schedule->call(function () use ($user, $frequency) {
$language = $user->language;
$newMessages = $user->new_messages_notification;
$totalReply = $user->total_replies;
if ($newMessages > 1) {
$newMessages = $totalReply - $newMessages;
} else {
$newMessages = $user->total_replies;
}
if ($user->account->language_setting) {
$language = Language::find($user->account->language_setting)->language;
}
/** this should have job to avoid rapid sending of email that spikes email service provider */
Mail::to($user)->locale($language)->send(new \App\Mail\SendNewMessagesNotification($user, $newMessages));
$user->new_messages_notification = $user->total_replies;
$user->save();
})->$frequency();
}
}
}
}
}

Prestashop shipping costs cleared after order confirmation

I'm on Prestashop 1.7.6. I made a simple test module for adding a custom carrier and manage it programmatically.
Everything works well during checkout: I see new carrier with the correct cost, if I select it the total of cart is correct! (the shipping cost is added).
After choosing the payment method and confirming the order (and I'm redirected to order confirmation page), the shipping costs disappear: is always free shipping!
I do not understand why..
I report the code of this test:
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
class TxShipping extends CarrierModule
{
const PREFIX = 'tx_';
public $id_carrier;
private $loopCount = 0;
private $shipCost = 0;
protected $_hooks = array(
'actionCarrierUpdate',
'displayOrderConfirmation',
);
protected $_carriers = array(
//"Public carrier name" => "technical name",
'My new carrier' => 'txshipping',
);
public function __construct()
{
$this->name = 'txshipping';
$this->tab = 'shipping_logistics';
$this->version = '1.0.0';
$this->author = 'Gerry';
$this->need_instance = 0;
$this->ps_versions_compliancy = [
'min' => '1.7.1.0',
'max' => _PS_VERSION_
];
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Tx Shipping');
$this->description = $this->l('manage shipping costs');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
if (!Configuration::get('TXSHIPPING_NAME')) {
$this->warning = $this->l('No name provided');
}
}
public function getTemplate($area, $file)
{
return 'views/templates/' . $area . '/' . $file;
}
//-------------------------------------------------
// Hooks
//-------------------------------------------------
public function hookActionCarrierUpdate($params)
{
if ($params['carrier']->id_reference == Configuration::get(self::PREFIX . 'fcd_reference')) {
Configuration::updateValue(self::PREFIX . 'fcd', $params['carrier']->id);
}
}
public function getOrderShippingCost($params = null, $shipping_cost = 0) {
$curPage = $this->context->controller->php_self;
/* using test on which page is running cause the following code is always executed (even if is loading home page!?)
I don't understand why */
if ($curPage == "order") {
$this->loopCount++; // attempt for not to run the same code over and over.. but it doesn't work very well
if ($this->loopCount == 1) {
$this->shipCost = 77;
/*
$address = new Address($params->id_address_delivery);
$cap = $address->postcode;
$curID = $this->id_carrier; */
}
return floatval($this->shipCost);
} elseif ($curPage == "order-confirmation") {
$test = 76; // for simple test
return floatval($test);
} else {
if ($curPage != "pagenotfound") {
$this->loopCount = 0;
$this->shipCost = 0;
}
}
}
public function getOrderShippingCostExternal($params){
//return 999; costi spedizione
return $this->getOrderShippingCost($params, 0);
}
//-------------------------------------------------
// Setup
//-------------------------------------------------
public function install()
{
if (parent::install()) {
foreach ($this->_hooks as $hook) {
if (!$this->registerHook($hook)) {
return false;
}
}
if (!$this->createCarriers()) {
return false;
}
return true;
}
return false;
}
public function uninstall()
{
if (parent::uninstall()) {
foreach ($this->_hooks as $hook) {
if (!$this->unregisterHook($hook)) {
return false;
}
}
if (!$this->deleteCarriers()) {
return false;
}
return true;
}
return false;
}
//-------------------------------------------------
// Funzioni private
//-------------------------------------------------
protected function createCarriers()
{
foreach ($this->_carriers as $key => $value) {
//Create own carrier
$carrier = new Carrier();
$carrier->name = $key;
$carrier->id_tax_rules_group = 0;
$carrier->active = 1;
$carrier->deleted = 0;
foreach (Language::getLanguages(true) as $language)
$carrier->delay[(int)$language['id_lang']] = 'Delay [1-2 days]';
$carrier->shipping_handling = false;
$carrier->range_behavior = 0;
$carrier->is_module = true;
$carrier->shipping_external = true;
$carrier->external_module_name = $this->name;
$carrier->need_range = true;
if ($carrier->add()) {
$groups = Group::getGroups(true);
foreach ($groups as $group) {
Db::getInstance()->autoExecute(_DB_PREFIX_ . 'carrier_group', array(
'id_carrier' => (int) $carrier->id,
'id_group' => (int) $group['id_group']
), 'INSERT');
}
$rangePrice = new RangePrice();
$rangePrice->id_carrier = $carrier->id;
$rangePrice->delimiter1 = '0';
$rangePrice->delimiter2 = '1000000';
$rangePrice->add();
$rangeWeight = new RangeWeight();
$rangeWeight->id_carrier = $carrier->id;
$rangeWeight->delimiter1 = '0';
$rangeWeight->delimiter2 = '1000000';
$rangeWeight->add();
$zones = Zone::getZones(true);
foreach ($zones as $z) {
Db::getInstance()->autoExecute(_DB_PREFIX_ . 'carrier_zone',
array('id_carrier' => (int) $carrier->id, 'id_zone' => (int) $z['id_zone']), 'INSERT');
Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_ . 'delivery',
array('id_carrier' => $carrier->id, 'id_range_price' => (int) $rangePrice->id, 'id_range_weight' => NULL, 'id_zone' => (int) $z['id_zone'], 'price' => '0'), 'INSERT');
Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_ . 'delivery',
array('id_carrier' => $carrier->id, 'id_range_price' => NULL, 'id_range_weight' => (int) $rangeWeight->id, 'id_zone' => (int) $z['id_zone'], 'price' => '0'), 'INSERT');
}
copy(dirname(__FILE__) . '/views/img/carrier.jpg', _PS_SHIP_IMG_DIR_ . '/' . (int) $carrier->id . '.jpg');
Configuration::updateValue(self::PREFIX . $value, $carrier->id);
Configuration::updateValue(self::PREFIX . $value . '_reference', $carrier->id);
}
}
return true;
}
protected function deleteCarriers()
{
foreach ($this->_carriers as $value) {
$tmp_carrier_id = Configuration::get(self::PREFIX . $value);
$carrier = new Carrier($tmp_carrier_id);
$carrier->delete();
}
return true;
}
}
Im my opinion it has something to do with your $curPage
I'd go for this if instead:
if ($this->context->controller instanceof CartController || $this->context->controller instanceof OrderController) {
I don't understand this part of code:
} elseif ($curPage == "order-confirmation") {
why would you do something different on real order-confirmation page where order is already placed?

CodeIgniter Unable to connect to database

when i open CodeIgniter project than it can display not able to connect to database
Error message
A Database Error Occurred
Unable to connect to your database server using the provided settings.
Filename: C:\wamp\www\CodeIgniter-Standard-Project-master\system\database\DB_driver.php
Line Number: 76
DB_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CI_DB_driver {
var $username = 'root';
var $password = '';
var $hostname = 'localhost';
var $database = 'groups';
var $dbdriver = 'mysql';
var $dbprefix = '';
var $char_set = 'utf8';
var $dbcollat = 'utf8_general_ci';
var $autoinit = TRUE; // Whether to automatically initialize the DB
var $swap_pre = '';
var $port = '';
var $pconnect = true;
var $conn_id = FALSE;
var $result_id = FALSE;
var $db_debug = true;
var $benchmark = 0;
var $query_count = 0;
var $bind_marker = '?';
var $save_queries = TRUE;
var $queries = array();
var $query_times = array();
var $data_cache = array();
var $trans_enabled = TRUE;
var $trans_strict = TRUE;
var $_trans_depth = 0;
var $_trans_status = TRUE; // Used with transactions to determine if a rollback should occur
var $cache_on = FALSE;
var $cachedir = '';
var $cache_autodel = FALSE;
var $CACHE; // The cache class object
var $_protect_identifiers = TRUE;
var $_reserved_identifiers = array('*'); // Identifiers that should NOT be escaped
// These are use with Oracle
var $stmt_id;
var $curs_id;
var $limit_used;
function __construct($params)
{
if (is_array($params))
{
foreach ($params as $key => $val)
{
$this->$key = $val;
}
}
log_message('debug', 'Database Driver Class Initialized');
}
function initialize()
{
// If an existing connection resource is available
// there is no need to connect and select the database
if (is_resource($this->conn_id) OR is_object($this->conn_id))
{
return TRUE;
}
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
// No connection resource? Throw an error
if ( ! $this->conn_id)
{
log_message('error', 'Unable to connect to the database');
if ($this->db_debug)
{
$this->display_error('db_unable_to_connect');
}
return FALSE;
}
// ----------------------------------------------------------------
// Select the DB... assuming a database name is specified in the config file
if ($this->database != '')
{
if ( ! $this->db_select())
{
log_message('error', 'Unable to select database: '.$this->database);
if ($this->db_debug)
{
$this->display_error('db_unable_to_select', $this->database);
}
return FALSE;
}
else
{
// We've selected the DB. Now we set the character set
if ( ! $this->db_set_charset($this->char_set, $this->dbcollat))
{
return FALSE;
}
return TRUE;
}
}
return TRUE;
}
// --------------------------------------------------------------------
function db_set_charset($charset, $collation)
{
if ( ! $this->_db_set_charset($this->char_set, $this->dbcollat))
{
log_message('error', 'Unable to set database connection charset: '.$this->char_set);
if ($this->db_debug)
{
$this->display_error('db_unable_to_set_charset', $this->char_set);
}
return FALSE;
}
return TRUE;
}
function platform()
{
return $this->dbdriver;
}
function version()
{
if (FALSE === ($sql = $this->_version()))
{
if ($this->db_debug)
{
return $this->display_error('db_unsupported_function');
}
return FALSE;
}
$driver_version_exceptions = array('oci8', 'sqlite', 'cubrid');
if (in_array($this->dbdriver, $driver_version_exceptions))
{
return $sql;
}
else
{
$query = $this->query($sql);
return $query->row('ver');
}
}
// --------------------------------------------------------------------
function query($sql, $binds = FALSE, $return_object = TRUE)
{
if ($sql == '')
{
if ($this->db_debug)
{
log_message('error', 'Invalid query: '.$sql);
return $this->display_error('db_invalid_query');
}
return FALSE;
}
// Verify table prefix and replace if necessary
if ( ($this->dbprefix != '' AND $this->swap_pre != '') AND ($this->dbprefix != $this->swap_pre) )
{
$sql = preg_replace("/(\W)".$this->swap_pre."(\S+?)/", "\\1".$this->dbprefix."\\2", $sql);
}
if ($this->cache_on == TRUE AND stristr($sql, 'SELECT'))
{
if ($this->_cache_init())
{
$this->load_rdriver();
if (FALSE !== ($cache = $this->CACHE->read($sql)))
{
return $cache;
}
}
}
// Compile binds if needed
if ($binds !== FALSE)
{
$sql = $this->compile_binds($sql, $binds);
}
// Save the query for debugging
if ($this->save_queries == TRUE)
{
$this->queries[] = $sql;
}
// Start the Query Timer
$time_start = list($sm, $ss) = explode(' ', microtime());
// Run the Query
if (FALSE === ($this->result_id = $this->simple_query($sql)))
{
if ($this->save_queries == TRUE)
{
$this->query_times[] = 0;
}
// This will trigger a rollback if transactions are being used
$this->_trans_status = FALSE;
if ($this->db_debug)
{
// grab the error number and message now, as we might run some
// additional queries before displaying the error
$error_no = $this->_error_number();
$error_msg = $this->_error_message();
// We call this function in order to roll-back queries
// if transactions are enabled. If we don't call this here
// the error message will trigger an exit, causing the
// transactions to remain in limbo.
$this->trans_complete();
// Log and display errors
log_message('error', 'Query error: '.$error_msg);
return $this->display_error(
array(
'Error Number: '.$error_no,
$error_msg,
$sql
)
);
}
return FALSE;
}
// Stop and aggregate the query time results
$time_end = list($em, $es) = explode(' ', microtime());
$this->benchmark += ($em + $es) - ($sm + $ss);
if ($this->save_queries == TRUE)
{
$this->query_times[] = ($em + $es) - ($sm + $ss);
}
// Increment the query counter
$this->query_count++;
// Was the query a "write" type?
// If so we'll simply return true
if ($this->is_write_type($sql) === TRUE)
{
// If caching is enabled we'll auto-cleanup any
// existing files related to this particular URI
if ($this->cache_on == TRUE AND $this->cache_autodel == TRUE AND $this->_cache_init())
{
$this->CACHE->delete();
}
return TRUE;
}
// Return TRUE if we don't need to create a result object
// Currently only the Oracle driver uses this when stored
// procedures are used
if ($return_object !== TRUE)
{
return TRUE;
}
// Load and instantiate the result driver
$driver = $this->load_rdriver();
$RES = new $driver();
$RES->conn_id = $this->conn_id;
$RES->result_id = $this->result_id;
if ($this->dbdriver == 'oci8')
{
$RES->stmt_id = $this->stmt_id;
$RES->curs_id = NULL;
$RES->limit_used = $this->limit_used;
$this->stmt_id = FALSE;
}
// oci8 vars must be set before calling this
$RES->num_rows = $RES->num_rows();
// Is query caching enabled? If so, we'll serialize the
// result object and save it to a cache file.
if ($this->cache_on == TRUE AND $this->_cache_init())
{
$CR = new CI_DB_result();
$CR->num_rows = $RES->num_rows();
$CR->result_object = $RES->result_object();
$CR->result_array = $RES->result_array();
// Reset these since cached objects can not utilize resource IDs.
$CR->conn_id = NULL;
$CR->result_id = NULL;
$this->CACHE->write($sql, $CR);
}
return $RES;
}
function load_rdriver()
{
$driver = 'CI_DB_'.$this->dbdriver.'_result';
if ( ! class_exists($driver))
{
include_once(BASEPATH.'database/DB_result.php');
include_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result.php');
}
return $driver;
}
function simple_query($sql)
{
if ( ! $this->conn_id)
{
$this->initialize();
}
return $this->_execute($sql);
}
function trans_off()
{
$this->trans_enabled = FALSE;
}
function trans_strict($mode = TRUE)
{
$this->trans_strict = is_bool($mode) ? $mode : TRUE;
}
function trans_start($test_mode = FALSE)
{
if ( ! $this->trans_enabled)
{
return FALSE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
if ($this->_trans_depth > 0)
{
$this->_trans_depth += 1;
return;
}
$this->trans_begin($test_mode);
}
function trans_complete()
{
if ( ! $this->trans_enabled)
{
return FALSE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
if ($this->_trans_depth > 1)
{
$this->_trans_depth -= 1;
return TRUE;
}
// The query() function will set this flag to FALSE in the event that a query failed
if ($this->_trans_status === FALSE)
{
$this->trans_rollback();
// If we are NOT running in strict mode, we will reset
// the _trans_status flag so that subsequent groups of transactions
// will be permitted.
if ($this->trans_strict === FALSE)
{
$this->_trans_status = TRUE;
}
log_message('debug', 'DB Transaction Failure');
return FALSE;
}
$this->trans_commit();
return TRUE;
}
function trans_status()
{
return $this->_trans_status;
}
function compile_binds($sql, $binds)
{
if (strpos($sql, $this->bind_marker) === FALSE)
{
return $sql;
}
if ( ! is_array($binds))
{
$binds = array($binds);
}
// Get the sql segments around the bind markers
$segments = explode($this->bind_marker, $sql);
// The count of bind should be 1 less then the count of segments
// If there are more bind arguments trim it down
if (count($binds) >= count($segments)) {
$binds = array_slice($binds, 0, count($segments)-1);
}
// Construct the binded query
$result = $segments[0];
$i = 0;
foreach ($binds as $bind)
{
$result .= $this->escape($bind);
$result .= $segments[++$i];
}
return $result;
}
function is_write_type($sql)
{
if ( ! preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD DATA|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s+/i', $sql))
{
return FALSE;
}
return TRUE;
}
function elapsed_time($decimals = 6)
{
return number_format($this->benchmark, $decimals);
}
function total_queries()
{
return $this->query_count;
}
function last_query()
{
return end($this->queries);
}
function escape($str)
{
if (is_string($str))
{
$str = "'".$this->escape_str($str)."'";
}
elseif (is_bool($str))
{
$str = ($str === FALSE) ? 0 : 1;
}
elseif (is_null($str))
{
$str = 'NULL';
}
return $str;
}
function escape_like_str($str)
{
return $this->escape_str($str, TRUE);
}
function primary($table = '')
{
$fields = $this->list_fields($table);
if ( ! is_array($fields))
{
return FALSE;
}
return current($fields);
}
function list_tables($constrain_by_prefix = FALSE)
{
// Is there a cached result?
if (isset($this->data_cache['table_names']))
{
return $this->data_cache['table_names'];
}
if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
{
if ($this->db_debug)
{
return $this->display_error('db_unsupported_function');
}
return FALSE;
}
$retval = array();
$query = $this->query($sql);
if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
if (isset($row['TABLE_NAME']))
{
$retval[] = $row['TABLE_NAME'];
}
else
{
$retval[] = array_shift($row);
}
}
}
$this->data_cache['table_names'] = $retval;
return $this->data_cache['table_names'];
}
// --------------------------------------------------------------------
/**
* Determine if a particular table exists
* #access public
* #return boolean
*/
function table_exists($table_name)
{
return ( ! in_array($this->_protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables())) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Fetch MySQL Field Names
*
* #access public
* #param string the table name
* #return array
*/
function list_fields($table = '')
{
// Is there a cached result?
if (isset($this->data_cache['field_names'][$table]))
{
return $this->data_cache['field_names'][$table];
}
if ($table == '')
{
if ($this->db_debug)
{
return $this->display_error('db_field_param_missing');
}
return FALSE;
}
if (FALSE === ($sql = $this->_list_columns($table)))
{
if ($this->db_debug)
{
return $this->display_error('db_unsupported_function');
}
return FALSE;
}
$query = $this->query($sql);
$retval = array();
foreach ($query->result_array() as $row)
{
if (isset($row['COLUMN_NAME']))
{
$retval[] = $row['COLUMN_NAME'];
}
else
{
$retval[] = current($row);
}
}
$this->data_cache['field_names'][$table] = $retval;
return $this->data_cache['field_names'][$table];
}
// --------------------------------------------------------------------
/**
* Determine if a particular field exists
* #access public
* #param string
* #param string
* #return boolean
*/
function field_exists($field_name, $table_name)
{
return ( ! in_array($field_name, $this->list_fields($table_name))) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Returns an object with field data
*
* #access public
* #param string the table name
* #return object
*/
function field_data($table = '')
{
if ($table == '')
{
if ($this->db_debug)
{
return $this->display_error('db_field_param_missing');
}
return FALSE;
}
$query = $this->query($this->_field_data($this->_protect_identifiers($table, TRUE, NULL, FALSE)));
return $query->field_data();
}
// --------------------------------------------------------------------
/**
* Generate an insert string
*
* #access public
* #param string the table upon which the query will be performed
* #param array an associative array data of key/values
* #return string
*/
function insert_string($table, $data)
{
$fields = array();
$values = array();
foreach ($data as $key => $val)
{
$fields[] = $this->_escape_identifiers($key);
$values[] = $this->escape($val);
}
return $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
}
// --------------------------------------------------------------------
/**
* Generate an update string
*
* #access public
* #param string the table upon which the query will be performed
* #param array an associative array data of key/values
* #param mixed the "where" statement
* #return string
*/
function update_string($table, $data, $where)
{
if ($where == '')
{
return false;
}
$fields = array();
foreach ($data as $key => $val)
{
$fields[$this->_protect_identifiers($key)] = $this->escape($val);
}
if ( ! is_array($where))
{
$dest = array($where);
}
else
{
$dest = array();
foreach ($where as $key => $val)
{
$prefix = (count($dest) == 0) ? '' : ' AND ';
if ($val !== '')
{
if ( ! $this->_has_operator($key))
{
$key .= ' =';
}
$val = ' '.$this->escape($val);
}
$dest[] = $prefix.$key.$val;
}
}
return $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $dest);
}
// --------------------------------------------------------------------
/**
* Tests whether the string has an SQL operator
*
* #access private
* #param string
* #return bool
*/
function _has_operator($str)
{
$str = trim($str);
if ( ! preg_match("/(\s|<|>|!|=|is null|is not null)/i", $str))
{
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Enables a native PHP function to be run, using a platform agnostic wrapper.
*
* #access public
* #param string the function name
* #param mixed any parameters needed by the function
* #return mixed
*/
function call_function($function)
{
$driver = ($this->dbdriver == 'postgre') ? 'pg_' : $this->dbdriver.'_';
if (FALSE === strpos($driver, $function))
{
$function = $driver.$function;
}
if ( ! function_exists($function))
{
if ($this->db_debug)
{
return $this->display_error('db_unsupported_function');
}
return FALSE;
}
else
{
$args = (func_num_args() > 1) ? array_splice(func_get_args(), 1) : null;
return call_user_func_array($function, $args);
}
}
// --------------------------------------------------------------------
/**
* Set Cache Directory Path
*
* #access public
* #param string the path to the cache directory
* #return void
*/
function cache_set_path($path = '')
{
$this->cachedir = $path;
}
// --------------------------------------------------------------------
/**
* Enable Query Caching
*
* #access public
* #return void
*/
function cache_on()
{
$this->cache_on = TRUE;
return TRUE;
}
// --------------------------------------------------------------------
/**
* Disable Query Caching
*
* #access public
* #return void
*/
function cache_off()
{
$this->cache_on = FALSE;
return FALSE;
}
// --------------------------------------------------------------------
/**
* Delete the cache files associated with a particular URI
*
* #access public
* #return void
*/
function cache_delete($segment_one = '', $segment_two = '')
{
if ( ! $this->_cache_init())
{
return FALSE;
}
return $this->CACHE->delete($segment_one, $segment_two);
}
// --------------------------------------------------------------------
/**
* Delete All cache files
*
* #access public
* #return void
*/
function cache_delete_all()
{
if ( ! $this->_cache_init())
{
return FALSE;
}
return $this->CACHE->delete_all();
}
// --------------------------------------------------------------------
/**
* Initialize the Cache Class
*
* #access private
* #return void
*/
function _cache_init()
{
if (is_object($this->CACHE) AND class_exists('CI_DB_Cache'))
{
return TRUE;
}
if ( ! class_exists('CI_DB_Cache'))
{
if ( ! #include(BASEPATH.'database/DB_cache.php'))
{
return $this->cache_off();
}
}
$this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
return TRUE;
}
// --------------------------------------------------------------------
/**
* Close DB Connection
*
* #access public
* #return void
*/
function close()
{
if (is_resource($this->conn_id) OR is_object($this->conn_id))
{
$this->_close($this->conn_id);
}
$this->conn_id = FALSE;
}
// --------------------------------------------------------------------
/**
* Display an error message
*
* #access public
* #param string the error message
* #param string any "swap" values
* #param boolean whether to localize the message
* #return string sends the application/error_db.php template
*/
function display_error($error = '', $swap = '', $native = FALSE)
{
$LANG =& load_class('Lang', 'core');
$LANG->load('db');
$heading = $LANG->line('db_error_heading');
if ($native == TRUE)
{
$message = $error;
}
else
{
$message = ( ! is_array($error)) ? array(str_replace('%s', $swap, $LANG->line($error))) : $error;
}
// Find the most likely culprit of the error by going through
// the backtrace until the source file is no longer in the
// database folder.
$trace = debug_backtrace();
foreach ($trace as $call)
{
if (isset($call['file']) && strpos($call['file'], BASEPATH.'database') === FALSE)
{
// Found it - use a relative path for safety
$message[] = 'Filename: '.str_replace(array(BASEPATH, APPPATH), '', $call['file']);
$message[] = 'Line Number: '.$call['line'];
break;
}
}
$error =& load_class('Exceptions', 'core');
echo $error->show_error($heading, $message, 'error_db');
exit;
}
// --------------------------------------------------------------------
/**
* Protect Identifiers
*
* This function adds backticks if appropriate based on db type
*
* #access private
* #param mixed the item to escape
* #return mixed the item with backticks
*/
function protect_identifiers($item, $prefix_single = FALSE)
{
return $this->_protect_identifiers($item, $prefix_single);
}
function _protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
{
if ( ! is_bool($protect_identifiers))
{
$protect_identifiers = $this->_protect_identifiers;
}
if (is_array($item))
{
$escaped_array = array();
foreach ($item as $k => $v)
{
$escaped_array[$this->_protect_identifiers($k)] = $this->_protect_identifiers($v);
}
return $escaped_array;
}
// Convert tabs or multiple spaces into single spaces
$item = preg_replace('/[\t ]+/', ' ', $item);
// If the item has an alias declaration we remove it and set it aside.
// Basically we remove everything to the right of the first space
$alias = '';
if (strpos($item, ' ') !== FALSE)
{
$alias = strstr($item, " ");
$item = substr($item, 0, - strlen($alias));
}
// This is basically a bug fix for queries that use MAX, MIN, etc.
// If a parenthesis is found we know that we do not need to
// escape the data or add a prefix. There's probably a more graceful
// way to deal with this, but I'm not thinking of it -- Rick
if (strpos($item, '(') !== FALSE)
{
return $item.$alias;
}
// Break the string apart if it contains periods, then insert the table prefix
// in the correct location, assuming the period doesn't indicate that we're dealing
// with an alias. While we're at it, we will escape the components
if (strpos($item, '.') !== FALSE)
{
$parts = explode('.', $item);
// Does the first segment of the exploded item match
// one of the aliases previously identified? If so,
// we have nothing more to do other than escape the item
if (in_array($parts[0], $this->ar_aliased_tables))
{
if ($protect_identifiers === TRUE)
{
foreach ($parts as $key => $val)
{
if ( ! in_array($val, $this->_reserved_identifiers))
{
$parts[$key] = $this->_escape_identifiers($val);
}
}
$item = implode('.', $parts);
}
return $item.$alias;
}
// Is there a table prefix defined in the config file? If not, no need to do anything
if ($this->dbprefix != '')
{
// We now add the table prefix based on some logic.
// Do we have 4 segments (hostname.database.table.column)?
// If so, we add the table prefix to the column name in the 3rd segment.
if (isset($parts[3]))
{
$i = 2;
}
// Do we have 3 segments (database.table.column)?
// If so, we add the table prefix to the column name in 2nd position
elseif (isset($parts[2]))
{
$i = 1;
}
// Do we have 2 segments (table.column)?
// If so, we add the table prefix to the column name in 1st segment
else
{
$i = 0;
}
// This flag is set when the supplied $item does not contain a field name.
// This can happen when this function is being called from a JOIN.
if ($field_exists == FALSE)
{
$i++;
}
// Verify table prefix and replace if necessary
if ($this->swap_pre != '' && strncmp($parts[$i], $this->swap_pre, strlen($this->swap_pre)) === 0)
{
$parts[$i] = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $parts[$i]);
}
// We only add the table prefix if it does not already exist
if (substr($parts[$i], 0, strlen($this->dbprefix)) != $this->dbprefix)
{
$parts[$i] = $this->dbprefix.$parts[$i];
}
// Put the parts back together
$item = implode('.', $parts);
}
if ($protect_identifiers === TRUE)
{
$item = $this->_escape_identifiers($item);
}
return $item.$alias;
}
// Is there a table prefix? If not, no need to insert it
if ($this->dbprefix != '')
{
// Verify table prefix and replace if necessary
if ($this->swap_pre != '' && strncmp($item, $this->swap_pre, strlen($this->swap_pre)) === 0)
{
$item = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $item);
}
// Do we prefix an item with no segments?
if ($prefix_single == TRUE AND substr($item, 0, strlen($this->dbprefix)) != $this->dbprefix)
{
$item = $this->dbprefix.$item;
}
}
if ($protect_identifiers === TRUE AND ! in_array($item, $this->_reserved_identifiers))
{
$item = $this->_escape_identifiers($item);
}
return $item.$alias;
}
}
If you have wampp server use this configuration.
If you have xampp use htdocx instead of www
C/wampp/www/Your-project-folder/application/config/database.php
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => DB_HOST,
'username' => DB_USER,
'password' => DB_PASSWORD,
'database' => DB_NAME,
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Uncomment #mysql_connect($this->hostname, $this->username, $this->password, TRUE);
on system/database/mysql/mysql_driver in db_connect method delete the # from #mysql_connect($this->hostname, $this->username, $this->password, TRUE);
This will show you the connection error and post result here
PHP 5 or above and CI 3 supports only mysqli
EDIT
$db['default'] = array(
'dsn' => '',
'hostname' => DB_HOST,
'username' => DB_USER,
'password' => DB_PASSWORD,
'database' => DB_NAME,
'dbdriver' => 'mysqli',
Refer
Edit: application/database/config.php

Get the information you entered to ID

This file is the database ID information all the fields and went and came to a Blade, I want to an ID information entered in the same panel Blade I send my face.
class DataGrid extends DataSet
{
protected $fields = array();
/** #var Column[] */
public $columns = array();
public $headers = array();
public $rows = array();
public $output = "";
public $attributes = array("class" => "table");
public $checkbox_form = false;
protected $row_callable = array();
/**
* #param string $name
* #param string $label
* #param bool $orderby
*
* #return Column
*/
public function add($name, $label = null, $orderby = false)
{
$column = new Column($name, $label, $orderby);
$this->columns[$column->name] = $column;
if (!in_array($name,array("_edit"))) {
$this->headers[] = $label;
}
if ($orderby) {
$this->addOrderBy($column->orderby_field);
}
return $column;
}
//todo: like "field" for DataForm, should be nice to work with "cell" as instance and "row" as collection of cells
public function build($view = '')
{
($view == '') and $view = 'rapyd::datagrid';
parent::build();
Persistence::save();
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
$cell = new Cell($column->name);
$sanitize = (count($column->filters) || $column->cell_callable) ? false : true;
$value = $this->getCellValue($column, $tablerow, $sanitize);
$cell->value($value);
$cell->parseFilters($column->filters);
if ($column->cell_callable) {
$callable = $column->cell_callable;
$cell->value($callable($cell->value, $tablerow));
}
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
$this->rows[] = $row;
}
$routeParamters = \Route::current()->parameters();
return \View::make($view, array('dg' => $this, 'buttons'=>$this->button_container, 'label'=>$this->label,
'current_entity' => $routeParamters['entity']));
}
public function buildCSV($file = '', $timestamp = '', $sanitize = true,$del = array())
{
$this->limit = null;
parent::build();
$segments = \Request::segments();
$filename = ($file != '') ? basename($file, '.csv') : end($segments);
$filename = preg_replace('/[^0-9a-z\._-]/i', '',$filename);
$filename .= ($timestamp != "") ? date($timestamp).".csv" : ".csv";
$save = (bool) strpos($file,"/");
//Delimiter
$delimiter = array();
$delimiter['delimiter'] = isset($del['delimiter']) ? $del['delimiter'] : ';';
$delimiter['enclosure'] = isset($del['enclosure']) ? $del['enclosure'] : '"';
$delimiter['line_ending'] = isset($del['line_ending']) ? $del['line_ending'] : "\n";
if ($save) {
$handle = fopen(public_path().'/'.dirname($file)."/".$filename, 'w');
} else {
$headers = array(
'Content-Type' => 'text/csv',
'Pragma'=>'no-cache',
'"Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Disposition' => 'attachment; filename="' . $filename.'"');
$handle = fopen('php://output', 'w');
ob_start();
}
fputs($handle, $delimiter['enclosure'].implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $this->headers) .$delimiter['enclosure'].$delimiter['line_ending']);
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
if (in_array($column->name,array("_edit")))
continue;
$cell = new Cell($column->name);
$value = str_replace('"', '""',str_replace(PHP_EOL, '', strip_tags($this->getCellValue($column, $tablerow, $sanitize))));
$cell->value($value);
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
fputs($handle, $delimiter['enclosure'] . implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $row->toArray()) . $delimiter['enclosure'].$delimiter['line_ending']);
}
fclose($handle);
if ($save) {
//redirect, boolean or filename?
} else {
$output = ob_get_clean();
return \Response::make(rtrim($output, "\n"), 200, $headers);
}
}
protected function getCellValue($column, $tablerow, $sanitize = true)
{
//blade
if (strpos($column->name, '{{') !== false ||
strpos($column->name, '{!!') !== false) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = $this->parser->compileString($column->name, $array);
//eager loading smart syntax relation.field
} elseif (preg_match('#^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$#i',$column->name, $matches) && is_object($tablerow) ) {
//switch to blade and god bless eloquent
$_relation = '$'.trim(str_replace('.','->', $column->name));
$expression = '{{ isset('. $_relation .') ? ' . $_relation . ' : "" }}';
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$value = $this->parser->compileString($expression, $array);
//fieldname in a collection
} elseif (is_object($tablerow)) {
$value = #$tablerow->{$column->name};
if ($sanitize) {
$value = $this->sanitize($value);
}
//fieldname in an array
} elseif (is_array($tablerow) && isset($tablerow[$column->name])) {
$value = $tablerow[$column->name];
//none found, cell will have the column name
} else {
$value = $column->name;
}
//decorators, should be moved in another method
if ($column->link) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$array = $tablerow->getAttributes();
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = ''.$value.'';
}
if (count($column->actions)>0) {
$key = ($column->key != '') ? $column->key : $this->key;
$keyvalue = #$tablerow->{$key};
$routeParamters = \Route::current()->parameters();
$value = \View::make('rapyd::datagrid.actions', array('uri' => $column->uri, 'id' => $keyvalue, 'actions' => $column->actions,
'current_entity' => $routeParamters['entity']));
}
return $value;
}
public function getGrid($view = '')
{
$this->output = $this->build($view)->render();
return $this->output;
}
public function __toString()
{
if ($this->output == "") {
//to avoid the error "toString() must not throw an exception"
//http://stackoverflow.com/questions/2429642/why-its-impossible-to-throw-exception-from-tostring/27307132#27307132
try {
$this->getGrid();
}
catch (\Exception $e) {
$previousHandler = set_exception_handler(function (){ });
restore_error_handler();
call_user_func($previousHandler, $e);
die;
}
}
return $this->output;
}
public function edit($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->add('_edit', $label)->actions($uri, explode('|', $actions))->key($key);
}
public function getColumn($column_name)
{
if (isset($this->columns[$column_name])) {
return $this->columns[$column_name];
}
}
public function addActions($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->edit($uri, $label, $actions, $key);
}
public function row(\Closure $callable)
{
$this->row_callable[] = $callable;
return $this;
}
protected function sanitize($string)
{
$result = nl2br(htmlspecialchars($string));
return Config::get('rapyd.sanitize.num_characters') > 0 ? str_limit($result, Config::get('rapyd.sanitize.num_characters')) : $result;
}
public function rowCount()
{
return count($this->rows);
}
}
This is the source of a rapyd-laravel widget/package, not a custom code.
According to DataGrid/DataSet documentation, you can use many sources:
https://github.com/zofe/rapyd-laravel/wiki/DataSet
DataSet/DataGrid are presenters, you can retrieve all data of your data source using
{{ $item->field }} or {{ $row->field }} respectively
See the docs please
https://github.com/zofe/rapyd-laravel/wiki

Return false limits multiple error message to one?

On my multiple upload library, I have a set error function.
On my upload function I use a in_array to check file extensions. If the in_array detects error it displays multiple error messages correct.
The problem I am having is for some reason when I use return FALSE; under the $this->set_error('file_extension_not_allowed') then will on display one message. Not sure why return FALSE limits error messages.
Question: How is it possible to use my return false but be able to display multiple message correct.
<?php
class Multiple_upload {
public $set_errors = array();
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1)) {
$this->set_error('file_extension_not_allowed', 'extension_check');
return FALSE;
}
}
return $this;
}
}
public function set_error($message, $type) {
$this->CI->lang->load('upload', 'english');
$this->error_message[] = $this->CI->lang->line($message);
return $this;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
foreach($this->error_message as $msg) {
var_dump($msg);
}
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
Maybe this can help...
public function upload($field = 'userfile')
{
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path))
{
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path))
{
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0]))
{
$check_error = 0;//added this
foreach ($this->files[$field]['name'] as $key => $value)
{
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1))
{
$this->set_error('file_extension_not_allowed', 'extension_check');
$check_error++;
}
}
if($check_error > 0 )
{
return FALSE;
}
return $this;
}
}

Resources