external classes and PHP files in Laravel - Class not found - laravel

I have two php files and I already created a folder called "ExternalClasses" and added the file to that folder. In my php file, I add this line:
namespace App\ExternalClasses;
and in my controller I add this line:
use App\ExternalClasses\CCheckMail;
and this is how I use it:
$pricesClass = new CCheckMail();
$email2 = ['myemail#gmail.com'];
$prices = $pricesClass->execute ($email2);
return view('pages.home', compact('prices'));
but it gave me an error:
Symfony \ Component \ Debug \ Exception \ FatalThrowableError
(E_ERROR) Class 'App\ExternalClasses\CCheckMail' not found
Here is my php file (CCheckMail.php):-
<?php
namespace App\ExternalClasses;
/*
* This script was writed by Setec Astronomy - setec#freemail.it
*
* This script is distributed under the GPL License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* http://www.gnu.org/licenses/gpl.txt
*
*/
define ('DEBUG_OK', false);
class CCheckMail
{
var $timeout = 10;
var $domain_rules = array ("aol.com", "bigfoot.com", "brain.net.pk", "breathemail.net",
"compuserve.com", "dialnet.co.uk", "glocksoft.com", "home.com",
"msn.com", "rocketmail.com", "uu.net", "yahoo.com", "yahoo.de");
function _is_valid_email ($email = "")
{ return preg_match('/^[.\w-]+#([\w-]+\.)+[a-zA-Z]{2,6}$/', $email); }
function _check_domain_rules ($domain = "")
{ return in_array (strtolower ($domain), $this->domain_rules); }
function execute ($email = "")
{
if (!$this->_is_valid_email ($email))
{ return false; }
$host = substr (strstr ($email, '#'), 1);
if ($this->_check_domain_rules ($host))
{ return false; }
$host .= ".";
if (getmxrr ($host, $mxhosts[0], $mxhosts[1]) == true)
{ array_multisort ($mxhosts[1], $mxhosts[0]); }
else
{
$mxhosts[0] = $host;
$mxhosts[1] = 10;
}
if (DEBUG_OK) { print_r ($mxhosts); }
$port = 25;
$localhost = $_SERVER['HTTP_HOST'];
$sender = 'info#' . $localhost;
$result = false;
$id = 0;
while (!$result && $id < count ($mxhosts[0]))
{
if (function_exists ("fsockopen"))
{
if (DEBUG_OK) { print_r ($id . " " . $mxhosts[0][$id]); }
if ($connection = fsockopen ($mxhosts[0][$id], $port, $errno, $error, $this->timeout))
{
fputs ($connection,"HELO $localhost\r\n"); // 250
$data = fgets ($connection,1024);
$response = substr ($data,0,1);
if (DEBUG_OK) { print_r ($data); }
if ($response == '2') // 200, 250 etc.
{
fputs ($connection,"MAIL FROM:<$sender>\r\n");
$data = fgets($connection,1024);
$response = substr ($data,0,1);
if (DEBUG_OK) { print_r ($data); }
if ($response == '2') // 200, 250 etc.
{
fputs ($connection,"RCPT TO:<$email>\r\n");
$data = fgets($connection,1024);
$response = substr ($data,0,1);
if (DEBUG_OK) { print_r ($data); }
if ($response == '2') // 200, 250 etc.
{
fputs ($connection,"data\r\n");
$data = fgets($connection,1024);
$response = substr ($data,0,1);
if (DEBUG_OK) { print_r ($data); }
if ($response == '2') // 200, 250 etc.
{ $result = true; }
}
}
}
fputs ($connection,"QUIT\r\n");
fclose ($connection);
if ($result) { return true; }
}
}
else
{ break; }
$id++;
}
return false;
}
}
?>
The second php file:
<?php
/*
* This script was writed by Setec Astronomy - setec#freemail.it
*
* On row 41 of CCheckMail.php substitute the following line
*
* if (getmxrr ($host, $mxhosts[0], $mxhosts[1]) == true)
*
* with
*
* if (getmxrr_portable ($host, $mxhosts[0], $mxhosts[1]) == true)
*
* to have a fully working portable (*nix and Windows) CCheckMail class
*
* This script is distributed under the GPL License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* http://www.gnu.org/licenses/gpl.txt
*
*/
function getmxrr_win ($hostname = "", &$mxhosts, &$weight)
{
$weight = array();
$mxhosts = array();
$result = false;
$command = "nslookup -type=mx " . escapeshellarg ($hostname);
exec ($command, $result);
$i = 0;
while (list ($key, $value) = each ($result))
{
if (strstr ($value, "mail exchanger"))
{ $nslookup[$i] = $value; $i++; }
}
while (list ($key, $value) = each ($nslookup))
{
$temp = explode ( " ", $value );
$mx[$key][0] = substr($temp[3],0,-1);
$mx[$key][1] = $temp[7];
$mx[$key][2] = gethostbyname ( $temp[7] );
}
array_multisort ($mx);
foreach ($mx as $value)
{
$mxhosts[] = $value[1];
$weight[] = $value[0];
}
$result = count ($mxhosts) > 0;
return $result;
}
function getmxrr_portable ($hostname = "", &$mxhosts, &$weight)
{
if (function_exists ("getmxrr"))
{ $result = getmxrr ($hostname, $mxhosts, $weight); }
else
{ $result = getmxrr_win ($hostname, $mxhosts, $weight); }
return $result;
}
?>

Just type composer dumpautoload -o in your terminal.

It was typing error, I created a new project and redo my coding and it's working fine.

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();
}
}
}
}
}

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

how to use this simple acl library into codeigniter

i used cakephp before and now use codeigniter but Unfortunately hasn't any authentication or ACL built-in library ..after more search i have found a good library, but I do not know how to use it..it is no example to use it..any one have create controller and model as sample...thanks for helping
<?php
(defined('BASEPATH')) OR exit('No direct script access allowed');
class acl {
/* Actions::::
* Create 1
* Read 2
* Update 4
* Delete 8
* The allowance is made by a sum of the actions allowed.
* Ex.: user can read and update (2+4)=6 … so ill put 6 instead of 1 or 0.
*
* if(!$this->acl->hasPermission(‘entries_complete_access')) {
echo “No no”;
} else
* echo “yeah”;
}
*
*
*/
var $perms = array(); //Array : Stores the permissions for the user
var $userID; //Integer : Stores the ID of the current user
var $userRoles = array(); //Array : Stores the roles of the current user
var $ci;
function __construct($config = array()) {
$this->ci = &get_instance();
$this->userID = floatval($this->ci->session->userdata('account_id'));
$this->userRoles = $this->getUserRoles();
$this->buildACL();
}
function buildACL() {
//first, get the rules for the user's role
if (count($this->userRoles) > 0) {
$this->perms = array_merge($this->perms, $this->getRolePerms($this->userRoles));
}
//then, get the individual user permissions
$this->perms = array_merge($this->perms, $this->getUserPerms($this->userID));
}
function getPermKeyFromID($permID) {
//$strSQL = “SELECT `permKey` FROM `”.DB_PREFIX.”permissions` WHERE `ID` = ” . floatval($permID) . ” LIMIT 1″;
$this->ci->db->select('permKey');
$this->ci->db->where('id', floatval($permID));
$sql = $this->ci->db->get('perm_data', 1);
$data = $sql->result();
return $data[0]->permKey;
}
function getPermNameFromID($permID) {
//$strSQL = “SELECT `permName` FROM `”.DB_PREFIX.”permissions` WHERE `ID` = ” . floatval($permID) . ” LIMIT 1″;
$this->ci->db->select('permName');
$this->ci->db->where('id', floatval($permID));
$sql = $this->ci->db->get('perm_data', 1);
$data = $sql->result();
return $data[0]->permName;
}
function getRoleNameFromID($roleID) {
//$strSQL = “SELECT `roleName` FROM `”.DB_PREFIX.”roles` WHERE `ID` = ” . floatval($roleID) . ” LIMIT 1″;
$this->ci->db->select('roleName');
$this->ci->db->where('id', floatval($roleID), 1);
$sql = $this->ci->db->get('role_data');
$data = $sql->result();
return $data[0]->roleName;
}
function getUserRoles() {
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”user_roles` WHERE `userID` = ” . floatval($this->userID) . ” ORDER BY `addDate` ASC”;
$this->ci->db->where(array('userID' => floatval($this->userID)));
$this->ci->db->order_by('addDate', 'asc');
$sql = $this->ci->db->get('user_roles');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
$resp[] = $row->roleID;
}
return $resp;
}
function getAllRoles($format = 'ids') {
$format = strtolower($format);
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”roles` ORDER BY `roleName` ASC”;
$this->ci->db->order_by('roleName', 'asc');
$sql = $this->ci->db->get('role_data');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
if ($format == 'full') {
$resp[] = array('id' => $row->ID, 'name' => $row->roleName);
} else {
$resp[] = $row->ID;
}
}
return $resp;
}
function getAllPerms($format = 'ids') {
$format = strtolower($format);
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”permissions` ORDER BY `permKey` ASC”;
$this->ci->db->order_by('permKey', 'asc');
$sql = $this->ci->db->get('perm_data');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
if ($format == 'full') {
$resp[$row->permKey] = array('id' => $row->ID, 'name' => $row->permName, 'key' => $row->permKey);
} else {
$resp[] = $row->ID;
}
}
return $resp;
}
function getRolePerms($role) {
if (is_array($role)) {
//$roleSQL = “SELECT * FROM `”.DB_PREFIX.”role_perms` WHERE `roleID` IN (” . implode(“,”,$role) . “) ORDER BY `ID` ASC”;
$this->ci->db->where_in('roleID', $role);
} else {
//$roleSQL = “SELECT * FROM `”.DB_PREFIX.”role_perms` WHERE `roleID` = ” . floatval($role) . ” ORDER BY `ID` ASC”;
$this->ci->db->where(array('roleID' => floatval($role)));
}
$this->ci->db->order_by('id', 'asc');
$sql = $this->ci->db->get('role_perms'); //$this->db->select($roleSQL);
$data = $sql->result();
$perms = array();
foreach ($data as $row) {
$pK = strtolower($this->getPermKeyFromID($row->permID));
if ($pK == '') {
continue;
}
/* if ($row->value == '1′) {
$hP = true;
} else {
$hP = false;
} */
if ($row->value == '0') {
$hP = false;
} else {
$hP = $row->value;
}
$perms[$pK] = array('perm' => $pK, '1inheritted' => true, 'value' => $hP, 'name' => $this->getPermNameFromID($row->permID), 'id' => $row->permID);
}
return $perms;
}
function getUserPerms($userID) {
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”user_perms` WHERE `userID` = ” . floatval($userID) . ” ORDER BY `addDate` ASC”;
$this->ci->db->where('userID', floatval($userID));
$this->ci->db->order_by('addDate', 'asc');
$sql = $this->ci->db->get('user_perms');
$data = $sql->result();
$perms = array();
foreach ($data as $row) {
$pK = strtolower($this->getPermKeyFromID($row->permID));
if ($pK == '') {
continue;
}
/* if ($row->value == '1′) {
$hP = true;
} else {
$hP = false;
} */
if ($row->value == '0') {
$hP = false;
} else {
$hP = $row->value;
}
$perms[$pK] = array('perm' => $pK, '2inheritted' => false, 'value' => $hP, 'name' => $this->getPermNameFromID($row->permID), 'id' => $row->permID);
}
return $perms;
}
function hasRole($roleID) {
foreach ($this->userRoles as $k => $v) {
if (floatval($v) === floatval($roleID)) {
return true;
}
}
return false;
}
function actionPerm($value, $wanted) {
/* Actions::::
* Create 1
* Read, 2
* Update, 4
* Delete 8
*/
$action['create'] = array('1', '3', '5', '9', '11', '13', '15'); //1
$action['read'] = array('2', '3', '6', '10', '14', '15'); //2
$action['update'] = array('4', '5', '6', '7', '12', '13', '14', '15'); //4
$action['delete'] = array('8', '9', '10', '11', '12', '13', '14', '15'); //8
$action['all'] = array('15');
if (in_array($value, $action[$wanted], true)) {
return true;
} else {
return false;
}
}
function hasPermission($permKey, $action = 'all') {
$permKey = strtolower($permKey);
if (array_key_exists($permKey, $this->perms)) {
if ($this->actionPerm($this->perms[$permKey]['value'], $action)) {
return true;
} else {
return false;
}
} else {
return false;
}
/* OLD METHOD
if ($this->perms[$permKey]['value'] === '1′ || $this->perms[$permKey]['value'] === true)
{
return true;
} else {
return false;
}
} else {
return false;
}
*/
}
}
and this is the url
sample ACL Class for codeigniter
This is simple
Load it first in your controller
$this->load->library('acl');
Now call its method
$this->acl->buildACL();
EDIT
Use these for menuall assigning
$this->acl->perms = array('your values');
$this->acl->userID= 'user id';
$this->acl->userRoles = array('your values');
Note that you should have db table userRoles which will be invoked when the library is initialized getUserRoles method will be called and $userRoles parameter will have values.
I'm Brian from Tastybytes. My best solution would be to step through the tutorial that the code igniter ACL library is based on. It is a 100% straight port from the base php files to CI Library.
http://net.tutsplus.com/tutorials/php/a-better-login-system/
And possibly look at the very bottom of the page where I go through "Installation" and what not.

How to fix this issue with advanced search codeigniter

I want to build advanced search script but I have this error with search_all function in the model
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to string
Filename: models/search_model.php
Line Number: 129
i have four fildes
1- input text to write the book name
2- select box for the author
3- select box for the publisher
3-select box for the section
the model is
class search_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
/* This function get all search in database sort by order asc.*/
function get_new_one($id)
{
$this->db->where('ne_id',$id);
$result=$this->db->get('d_search');
return $result->row();
}
//////////////frontend//////////////////////////////////////////////////////////
function show_new($id)
{
$result=$this->db->query("SELECT * , COUNT( d_comments_search.cn_new_id ) as count
FROM d_search
left JOIN d_comments_search ON d_search.ne_id = d_comments_search.cn_new_id and d_search.ne_hide='1'
inner join d_search_category on d_search_category.nc_id = d_search.ne_category_id and d_search_category.nc_hide= '1'
and d_search.ne_id= $id group by d_search.ne_id");
return $result->row() ;
}
function generate_results($keyword,$row=0){
$result1 = $this->db->query("SELECT bo_id,bo_name,bo_state,bo_about FROM d_book where (bo_name like '%$keyword%' or bo_about like '%$keyword%') and bo_state = '1' limit $row,20");
$result2 = $this->db->query("SELECT au_id,au_name,au_state,au_info FROM d_author where (au_name like '%$keyword%' or au_info like '%$keyword%') and au_state = '1' limit $row,20");
$result3 = $this->db->query("SELECT pub_id,pub_name,pub_state,pub_info FROM d_publishing where (pub_name like '%$keyword%' or pub_info like '%$keyword%') and pub_state = '1' limit $row,20");
$results = array_merge($result1->result_array(),$result2->result_array(),$result3->result_array());
return $results;
}
// get total number of users
function getNumUsers($keyword)
{
$result1 = $this->db->query("SELECT bo_id,bo_name,bo_state,bo_about FROM d_book where (bo_name like '%$keyword%' or bo_about like '%$keyword%') and bo_state = '1'");
$result1 = $result1->num_rows();
$result2 = $this->db->query("SELECT au_id,au_name,au_state,au_info FROM d_author where (au_name like '%$keyword%' or au_info like '%$keyword%') and au_state = '1'");
$result2 = $result2->num_rows();
$result3 = $this->db->query("SELECT pub_id,pub_name,pub_state,pub_info FROM d_publishing where (pub_name like '%$keyword%' or pub_info like '%$keyword%') and pub_state = '1'");
$result3 = $result3->num_rows();
return $result1 + $result2 + $result3;
}
//////////////////////////////////end paging///////////////////
function get_publishing()
{
$this->db->where('pub_state','1');
$result=$this->db->get('d_publishing')->result_array();
return $result;
}
function get_author()
{
$this->db->where('au_state','1');
$result=$this->db->get('d_author')->result_array();
return $result;
}
function get_section()
{
$this->db->where('sec_state','1');
$result=$this->db->get('d_section')->result_array();
return $result;
}
function search_name()
{
$bo_name=$_POST['bo_name'];
$this->db->order_by("bo_ord","asc");
$this->db->like('bo_name',$bo_name);
return $this->db->get('d_book')->result_array();
}
function search_all() {
$publish = $this->input->post('publish');
$author = $this->input->post('author');
$sec_name = $this->input->post('section');
$sql = $this->db->query("SELECT * FROM `d_book`");
$searches = array();
if ($publish != 'choose')
$searches[] = "`bo_pub_id` = '$publish'";
if ($author != 'choose')
$searches[] = "`bo_au_id` = '$author'";
if ($sec_name != 'choose')
$searches[] = "`bo_sec_id` = '$sec_name'";
if (count($searches) > 0) {
$sql .= "WHERE " . implode(" AND ", $searches);
}
$sql .= ';';
}
}
this is controller
class Search extends front_end {
var $temp;
function __construct(){
parent::__construct();
$this->load->library('form_validation');
//echo $this->input->post("keyboard");
}
public function index()
{
$this->overview();
}
/**
* This function display all search
* #param integer $row
*/
public function overview($row=0)
{
$this->form_validation->set_rules('keyword', 'كلمة البحث', 'trim|required|xss_clean|htmlspecialchars');
$this->form_validation->run();
$this->store_keyword();
//echo $this->session->flashdata('keyword');
if ($this->session->flashdata('keyword') != ''){
$keyword=$this->session->flashdata('keyword');
$this->generate_results($this->session->flashdata('keyword'),$row);
}else{
$this->generate_results($this->input->post("keyword"),$row);
}
//$this->session->set_flashdata('keyword', $this->input->post("keyword"));
$data = $this->temp;
//$this->session->keep_flashdata('keyword');
$this->view('search/site/results', $data);
}
/**
* This function generate result of search
* #param string $keyword
* #param integer $row
*/
public function generate_results($keyword,$row=0){
$this->load->model('search/search_model','search');
$this->load->library('pagination');
$config['base_url'] = base_url().'search/search/overview/';
$config['total_rows'] = $this->search->getNumUsers($keyword);
$config['per_page'] = '20';
$config['uri_segment'] = '4';
$this->pagination->initialize($config);
$data['page'] = $row;
$data['results'] = $this->search->generate_results($keyword,$row);
$data['total_rows'] = $this->search->getNumUsers($keyword);
$data['links']=$this->pagination->create_links();
$this->temp = $data;
}
/**
* This function display detail of new
* #param integer $id
*/
public function show($id)
{
$data['new']=$this->search->show_new($id);
$count=$data['new']->ne_count_visit;
$this->search->add_count($count,$id);
$data['comments']=$this->search->show_comments($id);
$this->view('site/new', $data);
}
/**
* This function store keyword to use in search
*/
private function store_keyword(){
if($this->input->post("keyword")){
$this->session->set_userdata('keyword', $this->input->post("keyword"));
}
}
public function search_form()
{
$this->load->model('search/search_model','search');
$data['publish']=$this->search->get_publishing();
$data['author']=$this->search->get_author();
$data['section']=$this->search->get_section();
$this->view('search/site/adv_search_form',$data);
}
public function search_adv()
{
$this->load->model('search/search_model','search');
$data['bo_name']=$this->input->post('bo_name');
$data['section']=$this->input->post('section');
$data['publish']=$this->input->post('publish');
$data['author']=$this->input->post('author');
$data['result1'] = '';
$data['result2'] = '';
$data['result3'] = '';
$data['result4'] = '';
if($data['bo_name'] == NULL and $data['section']== NULL and $data['publish']==NULL and $data['author']== NULL){
$this->search_form();
}else{
if(isset($data['bo_name']) and $data['bo_name']!= NULL)
{
$data['result1'] = $this->search->search_name();
}
if(isset($data['section']) and $data['section'] != NULL)
{
$data['result2']=$this->search->search_all();
}
if(isset($data['publish']) and $data['publish'] != NULL)
{
$data['result3']=$this->search->search_all();
}
if(isset($data['author']) and $data['author']!= NULL)
{
$data['result4']=$this->search->search_all();
}
$data['no_results'] = '';
if(! $data['result1'] && !$data['result2'] && !$data['result3'] && !$data['result4']){
$data['no_results'] = TRUE;
}else{
$data['no_results'] = FALSE;
}
$this->view('search/site/search_result',$data);
}
}
}
/* End of file dashboard.php */
$this->db->query() doesn't store a query string for later use. It actually executes the query right away and return an object of CI_DB_mysql_result. You should build the query string before you call $this->db->query() and store it into a variable, then pass it into the method.
$sql = "SELECT * FROM `d_book` ";
$searches = array();
if ($publish != 'choose')
{
$searches[] = "`bo_pub_id` = '__some_id__'";
}
if ($author != 'choose')
{
$searches[] = "`bo_au_id` = '__some_id__'";
}
if ($sec_name != 'choose')
{
$searches[] = "`bo_sec_id` = '__some_id__'";
}
if (count($searches) > 0)
{
$sql .= "WHERE " . implode(" AND ", $searches);
}
$sql .= ';';
$this->db->query($sql);

error reading db in joomla

While i run a component i am getting 500 - An error has occurred error reading db in joomla.
My configuration file is perfect.
I don't know what else to change..
Any guidance will be helpful
Thanks in advance...
//No direct acesss
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class DealsModelDeals extends JModel {
function getDeals(){
$db = $this->getDBO();
$db->setQuery('SELECT * from #__todaysdeal');
$deals = $db->loadObjectList();
if ($deals === null)
JError::raiseError(500, 'Error reading db');
return $deals;
}
function getDeal($id){
$query = ' SELECT * FROM #__todaysdeal '. ' WHERE id = '.$id;
$db = $this->getDBO();
$db->setQuery($query);
$deal = $db->loadObject();
if ($deal === null)
JError::raiseError(500, 'Deal with ID: '.$id.' not found.');
else
return $deal;
}
/**
* Method that returns an empty greeting with id 0
*
* #access public
*/
function getNewDeal(){
$dealTableRow =& $this->getTable('deals');
$dealTableRow->id=0;
$dealTableRow->clientName='';
return $dealTableRow;
}
/**
* Method to store a greeting in the DB
*
* #access public
*/
function saveDeal($deal)
{
//Parameter not necessary because our model is named DealsModelDeals (used to ilustrate that you can specify an alternative name to the JTable extending class)
$dealTableRow =& $this->getTable('deals');
//print_r($dealTableRow);
//print_r($_FILES); exit;
// Bind the form fields to the todaysdeal table
if (!$dealTableRow->bind($deal)) {
JError::raiseError(500, 'Error binding data');
}
// Make sure the deal record is valid
if (!$dealTableRow->check()) {
JError::raiseError(500, 'Invalid data');
}
// Insert/update this record in the db
if (!$dealTableRow->store()) {
$errorMessage = $dealTableRow->getError();
JError::raiseError(500, 'Error binding data: '.$errorMessage);
}
$id = $dealTableRow->id;
if(!empty($_FILES['dealImage']))
{
$file = $_FILES['dealImage'];
$id = $dealTableRow->id;
if ((($_FILES["dealImage"]["type"] == "image/gif") || ($_FILES["dealImage"]["type"] == "image/jpeg") || ($_FILES["dealImage"]["type"] == "image/pjpeg")) && ($_FILES["dealImage"]["size"] < 150000))
{
if ($_FILES["dealImage"]["error"] > 0)
{
echo "Return Code: " . $_FILES["dealImage"]["error"] . "<br />";
}
else
{
if (file_exists("components/com_deals/dealImages/" . $_FILES["dealImage"]["name"])) {
$_FILES["dealImage"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["dealImage"]["tmp_name"], "components/com_deals/dealImages/" .$id."_".$_FILES["dealImage"]["name"]);
echo "Stored in: " . "dealImages/" . $_FILES["dealImage"]["name"];
}
}
}
else
{
}
}
$dealImage = $_FILES['dealImage']['name'];
$dealImage .= (!empty($_FILES['dealImage']['name'])) ? ' ' . $_FILES['dealImage']['name'] : '';
$query = "UPDATE #__todaysdeal SET dealImage='".$id."_".$_FILES['dealImage']['name']."' WHERE id='".$id."'";
$db = $this->getDBO();
$db->setQuery($query);
$db->query();
//If we get here and with no raiseErrors, then everythign went well
}
function deleteDeals($arrayIDs)
{
$query = "DELETE FROM #__todaysdeal WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error deleting Deals: '.$errorMessage);
}
}
function dealsUploadPhoto($file, $id)
{
//UPLOAD FILE
$config = & JComponentHelper::getParams('com_deals');
$allowed = array('image/pjpeg', 'image/jpeg', 'image/jpg', 'image/png', 'image/x-png', 'image/gif', 'image/ico', 'image/x-icon');
$pwidth = $config->get('pwidth');
$pheight = $config->get('pheight');
$maxsize = $config->get('maxsize');
if($file['size'] > 0 && ($file['size'] / 1024 < $maxsize)){
if(!file_exists(JPATH_SITE . DS. 'images' . DS . 'deals'))
{
if(mkdir(JPATH_SITE . DS . 'images' . DS . 'deals')) {
JPath::setPermissions(JPATH_SITE . DS . 'images' . DS . 'deals', '0777');
if(file_exists(JPATH_SITE . DS . 'images' . DS . 'index.html')) {
copy(JPATH_SITE . DS . 'images' . DS . 'index.html', JPATH_SITE . DS . 'images' . DS . 'deals/index.html');
}
}
}
if($file['error'] != 0){
tpJobsMsgAlert('Upload file photo error.');
exit ();
}
if($file['size'] == 0){
$file = null;
}
if(!in_array($file['type'], $allowed)) {
$file = null;
}
if ($file != null){
$dest = JPATH_SITE.DS.'images'.DS.'deals'.DS.$id.'.jpg';
if(file_exists($dest))
{
$del = unlink($dest);
}
$soure = $file['tmp_name'];
jimport('joomla.filesystem.file');
$uploaded = JFile::upload($soure,$dest);
$fileAtr = getimagesize($dest);
$widthOri = $fileAtr[0];
$heightOri = $fileAtr[1];
$type = $fileAtr['mime'];
$img = false;
switch ($type)
{
case 'image/jpeg':
case 'image/jpg':
case 'image/pjpeg':
$img = imagecreatefromjpeg($dest);
break;
case 'image/ico':
$img = imagecreatefromico($dest);
break;
case 'image/x-png':
case 'image/png':
$img = imagecreatefrompng($dest);
break;
case 'image/gif':
$img = imagecreatefromgif($dest);
break;
}
if(!$img)
{
return false;
}
$curr = #getimagesize($dest);
$perc_w = $pwidth / $widthOri;
$perc_h = $pheight / $heightOri;
if(($widthOri<$pwidth) && ($heightOri<$height))
{
return;
}
if($perc_h > $perc_w)
{
$pwidth = $pwidth;
$pheight = round($heightOri * $perc_w);
}
else
{
$pheight = $pheight;
$pwidth = round($widthOri * $perc_h);
}
$nwimg = imagecreatetruecolor($pwidth, $pheight);
imagecopyresampled($nwimg, $img, 0, 0, 0, 0, $pwidth, $pheight, $widthOri, $heightOri);
imagejpeg($nwimg, $dest, 100);
imagedestroy($nwimg);
imagedestroy($img);
}
}else{
if($file['size'] / 1024 > $maxsize){
dealsMsgAlert('Size of file photo is too big. Maximum size".$maxsize." KB');
exit ();
}
}
}
function dealsMsgAlert($msg)
{
if (!headers_sent())
{
while(#ob_end_clean());
ob_start();
echo "<script> alert('".$msg."'); window.history.go(-1); </script>\n";
$out = ob_get_contents();
ob_end_clean();
echo $out;
exit();
}
echo "<script> alert('".$msg."'); window.history.go(-1); </script>\n";
exit();
}
}
?>
The problem that causes the red screen with 500 Error is happening because you are raising an exception if the requested quote is does not exist. You should not use JError::raiseError().
Use one of the following instead:
// This will set error to the model. You can get the errors from
// the model by your controller $model->getErrors() and output them to the screen.
$this->setError('ERROR MESSAGE GOES HERE');
OR
// This will output errors to the screen right the way
JFactory::getApplication()->enqueueMessage('ERROR MESSAGE GOES HERE', 'message');
Model already has _db property, you do not need to get db into variable. You can access it like this $this->_db. You can read about Joomla Model class here.
Also within your model you are using
$db = $this->getDBO();
$db->setQuery('SELECT * from #__todaysdeal');
$deals = $db->loadObjectList();
Model has simplified method to load list of object, like so
$deals =& $this->_getList('SELECT * from #__todaysdeal');

Resources