Dropbox API in Codiegniter Accessing files inside folders? - codeigniter

I want getting into the location of files which is in dropbox api.
I want to assign the value in detailsArray if the folder have any file assign it. If it is folder then go inside folder and get that file. I want to assign the values of all files which is inside the apps folder and also that files which are inside in the apps folder.
PHP CODE
public function access_account($p)
{
if($p == '/')
{
$curl = curl_init( 'https://api.dropbox.com/1/metadata/auto');
}
else
{
$curl = curl_init( 'https://api.dropbox.com/1/metadata/auto'.$p);
}
$headers = array('Authorization: Bearer xxxx');
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = json_decode(curl_exec( $curl ) );
//echo '<pre>'; print_r($auth); echo '</pre>'; exit();
return $auth;
//print_r($auth);echo '</pre>';
}
public function get_folders()
{
$p = "/";
$result = $this->access_account($p);
//echo '<pre>'; print_r($result);'</pre>'; exit();
foreach($result->contents as $folders)
{
if($folders->is_dir == 1)
{
$p = $folders->path;
$result = $this->access_account($p);
//echo '<pre>'; print_r($result);'</pre>'; exit();
}
else
{
$this->detailsArray[$this->counter]['path'] = $folders->path;
$this->detailsArray[$this->counter]['modified'] = $folders->modified;
$this->detailsArray[$this->counter]['size'] = $folders->size;
$this->counter++;
//echo "<pre>"; print_r($this->detailsArray); exit;
}
}
echo "<pre>"; print_r($this->detailsArray); exit;
}

Actually we have to put variable $p and $counter as global and update $this->p,$this->counter after the loop ends
public function access_account($auth_key,$p)
{
if($this->p == '/')
{
$curl = curl_init( 'https://api.dropbox.com/1/metadata/auto');
}
else
{
$curl = curl_init( 'https://api.dropbox.com/1/metadata/dropbox'.$this->p);
}
$headers = array('Authorization: Bearer '.$auth_key );
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = json_decode(curl_exec( $curl ) );
return $auth;
}
public function get_folders()
{
$result = $this->dropbox($auth_key,$this->p);
//echo '<pre>'; print_r($result); echo '</pre>';exit();
foreach($result->contents as $folders)
{
if($folders->is_dir == 1)
{
$this->p= $folders->path;
$this->access_account($auth_key,$this->p);
}
else
{
$this->detailsArray[$this->counter]['path'] = $folders->path;
$this->detailsArray[$this->counter]['modified'] = $folders->modified;
$this->detailsArray[$this->counter]['size'] = $folders->size;
$this->counter++;
}
}
$this->counter = 0;
$this->p = '/';
//echo '<pre>';print_r($this->detailsArray); exit();
return $this->detailsArray;
}

Related

I get this error when trying to verify the email of candidates, Array to String conversion

I have a laravel system that when someone registers, they get a link on their emails where they have to click on it to verify their email. Once they click the link, their information is stored in the users table and the candidates table.
However, values are only inserted in the users table and not the candidates table, and I get the error "Array to string conversion".
Also, the link works well in local host but not after hosting the system.
RegisiterController.php
Str.php`
public function registerCandidate(Request $request){
if(setting('general_enable_candidate_registration')!=1){
return abort(401);
}
$rules = [
'first_name'=>'required',
'last_name'=>'required',
'national_id'=>'required',
'gender'=>'required',
'email'=>'required|email|string|max:255|unique:users',
'date_of_birth_year'=>'required',
'date_of_birth_month'=>'required',
'date_of_birth_day'=>'required',
'categories'=>'required',
'picture' => 'nullable|max:'.config('app.upload_size').'|mimes:jpeg,png,gif',
'cv_path' => 'nullable|max:'.config('app.upload_size').'|mimes:'.config('app.upload_files'),
];
if(setting('general_candidate_captcha')==1){
$rules['captcha'] = 'required|captcha';
}
foreach(CandidateFieldGroup::where('registration',1)->orderBy('sort_order')->get() as $group){
foreach($group->candidateFields as $field){
if($field->type=='file'){
$required = '';
if($field->required==1){
$required = 'required|';
}
$rules['field_'.$field->id] = 'nullable|'.$required.'max:'.config('app.upload_size').'|mimes:'.config('app.upload_files');
}
elseif($field->required==1){
$rules['field_'.$field->id] = 'required';
}
}
}
$this->validate($request,$rules);
$requestData = $request->all();
$password= $request->password;
$requestData['name']= $request->first_name.' '.$request->last_name;
$requestData['display_name'] = $request->first_name;
$requestData['password'] = Hash::make($password);
$requestData['role_id'] = 3;
$fields = CandidateField::get();
//check if email verification is required
if(setting('general_candidate_verification')==1){
do{
$hash = Str::random(30);
}while(PendingUser::where('hash',$hash)->first());
$formData = $_POST;
$formData['name'] = $request->first_name.' '.$request->last_name;
$formData['display_name'] = $request->first_name;
$formData['role_id'] = 3;
if($request->hasFile('picture')) {
$path = $request->file('picture')->store(PENDING_USER_FILES,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$img = Image::make($file);
$img->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file);
$formData['picture'] = $file;
}
else{
$formData['picture'] =null;
}
if($request->hasFile('cv_path')) {
//$path = $request->file('cv_path')->store(CANDIDATES,'public_uploads');
$name = $_FILES['cv_path']['name'];
$extension = $request->cv_path->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = uniqid().'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('cv_path')->storeAs(PENDING_USER_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$formData['cv_path'] = $file;
}
else{
$formData['cv_path'] =null;
}
$pendingUser = PendingUser::create([
'role_id'=>3,
'data'=> serialize($formData),
'hash'=> $hash
]);
//scan for files
foreach($fields as $field){
if(isset($requestData['field_'.$field->id]) && $field->type=='file' && $request->hasFile('field_'.$field->id))
{
//generate name for file
$name = $_FILES['field_'.$field->id]['name'];
//dd($name);
$extension = $request->{'field_'.$field->id}->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = $pendingUser->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('field_'.$field->id)->storeAs(PENDING_USER_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$pendingUser->pendingUserFiles()->create([
'file_name'=>$_FILES['field_'.$field->id]['name'],
'file_path'=>$file,
'field_id'=>$field->id
]);
}
}
//send email to user
$link = route('confirm.candidate',['hash'=>$hash]);
$this->sendEmail($request->email,__('site.confirm-your-email'),__('site.confirm-email-mail',['link'=>$link]));
return redirect()->route('register.confirm');
}
//First create user
$user= User::create($requestData);
//Calculate date of birth
$dateOfBirth = $request->date_of_birth_year.'-'.$request->date_of_birth_month.'-'.$request->date_of_birth_day;
$requestData['date_of_birth'] = $dateOfBirth;
//checkfor picture
if($request->hasFile('picture')) {
$path = $request->file('picture')->store(CANDIDATES,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$img = Image::make($file);
$img->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file);
$requestData['picture'] = $file;
}
else{
$requestData['picture'] =null;
}
if($request->hasFile('cv_path')) {
//$path = $request->file('cv_path')->store(CANDIDATES,'public_uploads');
$name = $_FILES['cv_path']['name'];
$extension = $request->cv_path->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('cv_path')->storeAs(CANDIDATE_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$requestData['cv_path'] = $file;
}
else{
$requestData['cv_path'] =null;
}
$user->candidate()->create($requestData);
//save categories
$user->candidate->categories()->attach($request->categories);
//now save custom fields
$customValues = [];
//attach custom values
foreach($fields as $field){
if(isset($requestData['field_'.$field->id]))
{
if($field->type=='file'){
if($request->hasFile('field_'.$field->id)){
//generate name for file
$name = $_FILES['field_'.$field->id]['name'];
$extension = $request->{'field_'.$field->id}->extension();
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('field_'.$field->id)->storeAs(CANDIDATE_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$customValues[$field->id] = ['value'=>$file];
}
}
else{
$customValues[$field->id] = ['value'=>$requestData['field_'.$field->id]];
}
}
}
$user->candidateFields()->sync($customValues);
$message = __('mails.new-account',[
'siteName'=>setting('general_site_name'),
'email'=>$requestData['email'],
'password'=>$password,
'link'=> url('/login')
]);
$subject = __('mails.new-account-subj',[
'siteName'=>setting('general_site_name')
]);
$this->sendEmail($requestData['email'],$subject,$message);
//now login user
Auth::login($user, true);
//redirect to relevant page
if(session()->exists('candidate_destination')){
$url = session()->get('candidate_destination');
session()->remove('candidate_destination');
return redirect($url);
}
else{
return redirect()->route('home');
}
}
public function confirmCandidate($hash){
//get pending user
$pendingUser = PendingUser::where('hash',$hash)->first();
if(!$pendingUser){
abort(404);
}
$requestData = unserialize($pendingUser->data);
$password = $requestData['password'];
$requestData['password'] = Hash::make($password);
//check for profile picture and move to new directory
if(!empty($requestData['picture']) && file_exists($requestData['picture'])){
$file = basename($requestData['picture']);
$newPath = UPLOAD_PATH.'/'.CANDIDATES.'/'.$file;
rename($requestData['picture'],$newPath);
$requestData['picture'] = $newPath;
}
if(!empty($requestData['cv_path']) && file_exists($requestData['cv_path'])){
$file = basename($requestData['cv_path']);
$newPath = UPLOAD_PATH.'/'.CANDIDATE_FILES.'/'.$file;
rename($requestData['cv_path'],$newPath);
$requestData['cv_path'] = $newPath;
}
//First create user
$user= User::create($requestData);
//Calculate date of birth
$dateOfBirth = $requestData['date_of_birth_year'].'-'.$requestData['date_of_birth_month'].'-'.$requestData['date_of_birth_day'];
$requestData['date_of_birth'] = $dateOfBirth;
$user->candidate()->create($requestData);
//save categories
if(isset($requestData['categories'])){
$user->candidate->categories()->attach($requestData['categories']);
}
$fields = CandidateField::get();
$customValues = [];
//attach custom values
foreach($fields as $field){
if($field->type=='file'){
$pendingFile = $pendingUser->pendingUserFiles()->where('field_id',$field->id)->first();
if($pendingFile){
//generate name for file
$name = $pendingFile->file_name;
$info = new \SplFileInfo($name);
$extension = $info->getExtension();
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$file = UPLOAD_PATH.'/'.CANDIDATE_FILES.'/'.$name;
rename($pendingFile->file_path,$file);
$customValues[$field->id] = ['value'=>$file];
}
}
elseif(isset($requestData['field_'.$field->id])){
$customValues[$field->id] = ['value'=>$requestData['field_'.$field->id]];
}
}
$user->candidateFields()->sync($customValues);
$pendingUser->delete();
$message = __('mails.new-account',[
'siteName'=>setting('general_site_name'),
'email'=>$requestData['email'],
'password'=>$password,
'link'=> url('/login')
]);
$subject = __('mails.new-account-subj',[
'siteName'=>setting('general_site_name')
]);
$this->sendEmail($requestData['email'],$subject,$message);
//now login user
Auth::login($user, true);
//redirect to relevant page
if(session()->exists('candidate_destination')){
$url = session()->get('candidate_destination');
session()->remove('candidate_destination');
return redirect($url);
}
else{
return redirect()->route('home');
}
}
`

N-tier navigation in codeigniter

How to create top navigation in code-igniter?
In controller I have declare a function and call model
private function getNavigation(){
$this->load->model('xx');
$data['nav'] = $this->xx->prepareTree();
$this->load->view('index',$data);
}
And In model I have declare three functions
public function prepareTree(){
$this->db->select("`catalog_parent` as parent_id, `catalog_name` as menu_item, `catalog_id` as id, `catalog_template` as pager_id");
$this->db->from("catalog_category");
$this->db->where("`catalog_navigation` = '1'");
$this->q = $this->db->get();
$create = '';
if ($this->q->num_rows() > 0) {
$create = $this->prepareList($this->q->result_array());
}
if(!empty($create)){
return $this->category_tree($create);
} else {
return '';
}
}
private function prepareList(array $items, $pid = 0) {
$output = array();
foreach ($items as $item) {
if ((int) $item['parent_id'] == $pid) {
if ($children = $this->prepareList($items, $item['id'])) {
$item['children'] = $children;
}
$output[] = $item;
}
}
return $output;
}
private function category_tree($menu_items, $child = false){
$output = '';
if (count($menu_items)>0) {
$output .= ($child === false) ? '<ul id="main-menu" class="sm sm-blue">' : '<ul>' ;
foreach ($menu_items as $item) {
$output .= '<li>';
$output .= ''.$item['menu_item'].'';
if (isset($item['children']) && count($item['children'])) {
$output .= $this->category_tree($item['children'], true);
}
$output .= '</li>';
}
$output .= '</ul>';
}
return $output;
}
If some suggest an more easy way please suggest us.
Thanks

Trying to get my data to display on the view- codeigniter

From my controller, I am able to get the session date to display on my view, I however an missing something in the syntax when it comes to displaying the data from my table. i.e $data['modelData']. How do I do that?
Controller:
function validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|trim');
$this->form_validation->set_rules('password', 'Password', 'required|md5');
if ($this->form_validation->run() == FALSE )
{
$this->load->view('login_form');
//return false;
}
else{
$this->load->model('login_model');
$email = $this->input->post('email');
$password = $this->input->post('password');
//echo $email;
// echo $password;
$result = $this->login_model->match_login($email, $password);
if ($result ==false) {
echo "Invalid Cardinals";
}
else
{
$session = array(
'id'=>$result[0]['id'],
'email'=>$this->input->post('email'),
'is_logged_in'=> 1
);
if (!$this->session->set_userdata($session)) {
$data['modelData'] = $result;
$data['sessionData'] = $session;
$this->load->view('dashboard_view', $data);
}
else {
echo "Error in session";
}
}
}
}
Model
class Login_model extends CI_Model{
//client..model
public function match_login($email, $password){
$this->db->where('email', $email);
$this->db->where('password', $password);
$query = $this->db->get('user');
$result = $query->result_array();
if (empty($result))
{
return false;
}
else
{
return $result;
}
}
}
Try this
In Controller
if (!$this->session->set_userdata($session)) { # Changed
echo "Error in session";
}
else {
$data['modelData'] = $result;
$data['sessionData'] = $session;
$this->load->view('dashboard_view', $data);
}
In View
// retrieving modelData
foreach ($modelData as $modelItem) {
echo "Model ID is ".$modelItem['id'];
}
// retrieving sessionData
foreach ($sessionData as $sessionitem) {
echo "Session ID is ".$sessionitem['id'];
echo "Session Email is ".$sessionitem['email'];
}
Replace:
if (!$this->session->set_userdata($session)) {
$data['modelData'] = $result;
$data['sessionData'] = $session;
$this->load->view('dashboard_view', $data);
}
with
if ($this->session->set_userdata($session)) {
$data['modelData'] = $result;
$data['sessionData'] = $session;
$this->load->view('dashboard_view', $data);
}
Explantion:
You could not get data from the table since the set_userdata function returned true therefore the control statement ignored the statements if block.

Email Contact retrieivng code running well on localhost but not server

I have the following script which retrieves code from gmail. the code runs well in localhost, but gives error when i upload it on server and make it eun. The script is made in codeigniter.
<?php
class invite_friends extends CI_Controller{
var $FEED_URL = "http://www.google.com/m8/feeds/contacts/default/full";
var $LOGIN_URL = "https://www.google.com/accounts/ClientLogin";
var $username = "my_qmail#gmail.com";
var $passwd = "my_passowrd";
var $postData = array();
function __construct() {
parent::__construct();
session_start();
}
function index()
{
if(isset($_SESSION['logged_user']))
redirect(base_url().'home');
$this->load->view('header');
$this->load->view('invite_friends');
$this->load->view('footer');
}
/*function GmailContacts_lib($gUsername, $gPassword) {
//constructor function
$this->username = $gUsername;
$this->passwd = $gPassword;
}*/
function get_gmail_contacts() {
$emailLists = array();
//create an array for post data
$this->postData = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => $this->username,
"Passwd" => $this->passwd,
"service" => "cp",
"source" => "anything"
);
//initialize the curl object
$curl = curl_init($this->LOGIN_URL);
//set the curl options
$this->set_curl_options($curl, CURLOPT_POST, true);
$this->set_curl_options($curl, CURLOPT_POSTFIELDS, $this->postData);
$this->set_curl_options($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
$this->set_curl_options($curl, CURLOPT_SSL_VERIFYPEER, false);
$this->set_curl_options($curl, CURLOPT_RETURNTRANSFER, 1);
//following variable contains the responses
$response = curl_exec($curl);
//check if the user has logged in sucessfully
//and save auth key if logged in
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
if( !empty($auth)) {
$headers = array("Authorization: GoogleLogin auth=".$auth);
//make the request to google contacts feed with the auth key maximum contacts is 10000
$curl1 = curl_init($this->FEED_URL);
//passing the headers of auth key
$this->set_curl_options($curl1, CURLOPT_HTTPHEADER, $headers);
//return the result in a variable
$this->set_curl_options($curl1, CURLOPT_RETURNTRANSFER, 1);
//results response
$feed = curl_exec($curl1);
//parse the feed and return email list array
$emailLists = $this->parse_response($feed);
}
else {
$emailLists = array("Invalid Username/Password");
}
print_r($emailLists);
}
//function to set curl options
function set_curl_options($ch, $option, $value) {
//make the post TRUE
return curl_setopt($ch, $option, $value);
}
//function to parse response
public function parse_response($feed) {
$contacts = array();
$doc = new DOMDocument();
//load the XML response
$doc->loadXML($feed);
//check the entry tag
$nodeList = $doc->getElementsByTagName( 'entry' );
foreach($nodeList as $node) {
//children of each entry tag
$entry_nodes = $node->childNodes;
$tempArray = array();
foreach($entry_nodes as $child) {
//get the tagname of the child
$domNodesName = $child->nodeName;
switch($domNodesName) {
case "title":
{ $tempArray['fullName'] = $child->nodeValue; }
break;
case "gd:email":
{
if (strpos($child->getAttribute('rel'),'home')!==false)
$tempArray['email_1']=$child->getAttribute('address');
elseif(strpos($child->getAttribute('rel'),'work')!=false)
$tempArray['email_2']=$child->getAttribute('address');
elseif(strpos($child->getAttribute('rel'),'other')!==false)
$tempArray['email_3']=$child->getAttribute('address');
}
break;
} //end of switch for nodeNames
} //end of foreach for entry_nodes child nodes
if( !empty($tempArray['email_1'])) $contacts[$tempArray['email_1']] = $tempArray;
if( !empty($tempArray['email_2'])) $contacts[$tempArray['email_2']] = $tempArray;
if( !empty($tempArray['email_3'])) $contacts[$tempArray['email_3']] = $tempArray;
}
return $contacts;
}
}
?>
it gives error and here is the error
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: controllers/invite_friends.php
Line Number: 54
I would suggest changing your code to the following
if(preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches))
{
$auth = $matches[1];
}
else
{
$auth = null;
}
You could set $auth to null or 0. But if you set it to null I would then instead check:
if(!is_null($auth)) {

creating high secured encrypted id to website url in codeigniter?

Controller:
function verifyuser()
{
$uri = $this->uri->uri_to_assoc(4);
//print_r($uri);
if( isset( $uri['id'] ) && $uri['id'] != '' )
{
$where = array();
$where['roll_number'] = $uri['id'];
$this->data['verification'] = $this->admin_model->verify($where);
}
else
{
$this->data['verification'] = array();
}
$this->data['content'] = 'admin/verification';
$this->view($this->data);
}
MODEL:
function verify($where='')
{
$this->db->select('*');
$this->db->from( $this->db->dbprefix('members') );
if( !(empty( $where )) )
$this->db->where( $where );
$result = $this->db->get();
//echo $this->db->last_query();
return $result->result();
}
www.example.com/user/admin/verify/345
to
www.example.com/user/admin/verify/hgf_877%%%_oi
like this.
you can use any of encoding's defined in PHP.net Manual for your security purposes. But i prefer base64_encode and base64_decode. Which i am using my application for encoding comples strings.
<?php
$temp = 345;
$res = base64_encode($temp);
echo $res;echo "<br>";
$result = base64_decode($res);
echo $result;
?>
You can find small example in this link also.

Resources