Call to a member function select() on a non-object - joomla

I'm trying to retrieve some info using ajax. however when I call the select() method the system returns a fatal error. what is the reason for that?
here's my code:
define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define( 'JPATH_BASE', realpath(dirname(__FILE__).DS.'..' ));
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('id', 'product_id')));
$query->from($db->quoteName('sample_table'));
// ->where('application_id = 11');
$db->setQuery($query);
$results = $db->loadObjectList();
I have used this code several times on other versions and it worked. I think it might be related to the version..
thanks in advance.

As per your code , I think you are trying to use Joomla function in external function. The error indicates that you are using the factory object without including the factory class. Try include all these files :
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
define('JPATH_BASE', $_SERVER['DOCUMENT_ROOT'] . DS . '');
require_once (JPATH_BASE . DS . 'includes' . DS . 'defines.php');
require_once (JPATH_BASE . DS . 'includes' . DS . 'framework.php');
require_once (JPATH_BASE . DS . 'libraries' . DS . 'joomla' . DS . 'factory.php');
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('id', 'product_id')));
$query->from($db->quoteName('sample_table'));
// ->where('application_id = 11');
$db->setQuery($query);
$results = $db->loadObjectList();

Is that all of your code? It looks to me like you have not created a database connection. You need something like
jimport('joomla.database.database');
// System configuration.
$config = JFactory::getConfig();
// Note, this will throw an exception if there is an error
// Creating the database connection.
$this->dbo = JDatabase::getInstance(
array(
'driver' => $config->get('dbtype'),
'host' => $config->get('host'),
'user' => $config->get('user'),
'password' => $config->get('password'),
'database' => $config->get('db'),
'prefix' => $config->get('dbprefix'),
)
);
Overall with a stand alone application it takes a few more minutes the first time but I think you are better off using the API and putting it in a constructor. Here's an example https://github.com/elinw/AssetFix/blob/j3/assetfix.php#L65

Related

Function wp_generate_attachment_metadata returns always empty array in ajax function

I have searched far and wide, but have not found a solution.
I have a real estate ad insertion form, I need to be able to upload photos of the listings. I can upload the photos to the server via ajax, return the filenames in a textarea and always via ajax, after submitting the form, I can upload the photos to wordpress and attach them to the ad
The only problem is that it does not generate the photo metadata, wp_generate_attachment_metadata always returns an empty array.
I can't find a solution about it. I have another plugin with a similar form, but there I post the form not via ajax, but with the action = "post", and I can safely generate the metadata.
This is the code with which I insert the attachments and link them to the newly created post.
Hope someone can help me
//$filename = domoria-torino-strada-della-fornace-druento-15.jpg
if ($filename != '') {
$wp_upload_dir = wp_upload_dir();
$filename_path = $wp_upload_dir['path'] .'/'. $filename;
$filename_url = $wp_upload_dir['url'] .'/'. $filename;
$guid = $wp_upload_dir['url'] . '/' . basename( $filename_path );
$attachment = array(
'guid'=> $guid,
'post_mime_type' => 'image/jpeg',
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $post_id
);
$attach_id = wp_insert_attachment( $attachment, $filename_path);
if($iter === 0){
set_post_thumbnail( $post_id, $attach_id );
}
$ids [] = $attach_id; //this array needs for an ACF field
//filename_path = home/uxo80ef6/domains/homeprime.sviluppo.host/public_html/wp-content/uploads/2021/12/domoria-torino-strada-della-fornace-druento-15.jpg
//$attach_id = 629
$file_uploaded_path = get_attached_file($attach_id);
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_uploaded_path );
wp_update_attachment_metadata( $attach_id, $attach_data );
$iter++;
}
UPDATE: The problem is due to getimagesize called by wp_generate_attachment_metadata that can't find the file by file_path, however the file is on the server.
I rewrote some parts of the code you posted:
change hardcoded post_mime_type with wp_check_filetype() instead.
rename some of the variables to: $file_name, $file_path, $parent_post_id
removed unused $filename_url
added $parent_post_id as the third argument into wp_insert_attachment()
removed get_attached_file() function and used $file_path for wp_generate_attachment_metadata()
<?php
// $file_name = domoria-torino-strada-della-fornace-druento-15.jpg
if (!empty($file_name)) {
// The ID of the post this attachment is for.
// eg. $parent_post_id = 37;
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
$file_path = $wp_upload_dir['path'] . '/' . $file_name;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype(basename($file_path), null);
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($file_path),
'post_mime_type' => $filetype['type'],
'post_title' => sanitize_title($file_name),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment($attachment, $file_path, $parent_post_id);
// Set the first attachment as Featured image.
if ($iter === 0) {
set_post_thumbnail($parent_post_id, $attach_id);
}
// ACF field array data.
$ids[] = $attach_id;
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
wp_update_attachment_metadata($attach_id, $attach_data);
$iter++;
}

laravel livewire intervention images

I am trying to use Intervention image with Livewire to reduce the sizes and I am not succeeding. They can guide me or tell me if Livewire may not allow it.
I am trying to pass this methodology:
foreach ($this->imagenes as $pathGaleria) {
$imgUrl = $pathGaleria->store('imagenesPropiedades');
$img = imgPropiedades::create([
'url' => $imgUrl,
'property_id' => $this->propiedadId
]);
to this other way:
foreach ($this->imagenes as $pathGaleria) {
$imgUrl = $pathGaleria->store('imagenesPropiedades');
Image::make($pathGaleria)->resize(1200, null, function ($constraint) {
$constraint->aspectRatio();
})
->save($imgUrl);
$img = imgPropiedades::create([
'url' => $imgUrl,
'property_id' => $this->propiedadId
]);
}
but the page remains blank. Thank you.
I found this today, may work for you
https://gist.github.com/daugaard47/659984245d31b895d00ee5dcbdee44ec
+
$images = Collection::wrap($request->file('file'));
$images->each(function ($image) use ($id) {
$basename = Str::random();
$original = $basename . '.' . $image->getClientOriginalExtension();
$thumbnail = $basename . '_thumb.' . $image->getClientOriginalExtension();
ImageManager::make($image)
->fit(250, 250)
->save(public_path('/images/' . $thumbnail));
$image->move(public_path('/images/'), $original);
Model::create([
]);
});

Google drive api folder permissions

I have problem with google drive api v3.
I took google example and I tried. I could read folder content but I did nothing with folder permission.
I received error 403, "Insufficient Permission".
I can't create or read all permissions for the folder.
<?php
require_once __DIR__.'/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->addScope(Google_Service_Drive::DRIVE);
$client->setAccessType('offline');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$drive = new Google_Service_Drive($client);
$folderId = '1_ip3-WUs4F6atNdElJ3KHccAV4lI0nLL';
$optParams = array(
'pageSize' => 100,
'fields' => "nextPageToken, files(id,name)",
'q' => "'".$folderId."' in parents"
);
$results = $drive->files->listFiles($optParams);
if (count($results->getFiles()) != 0) {
foreach ($results->getFiles() as $file) {
echo "Id: " . $file->getId() . " Name: " . $file->getName() . "<br>";
}
}
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
//+!+!+!+!+!+!+!+!+!+! Next code doesn't WORK !+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!//
$fileId = '1UXSg5W-XIX82izGK8uEXXWPUCLcDGRa1';
$userPermission = new Google_Service_Drive_Permission(array(
'type' => 'user',
'role' => 'reader',
'emailAddress' => 'email#gmail.com'
));
$request = $drive->permissions->create($fileId, $userPermission, array('fields' => 'id'));
echo $request;
?>
It may be that wrong permissions have been set when creating the folder, even though you said you did nothing. I do not see the code for creating the folder here, just an ID, which indicates that the folder has already been created.
I suggest trying to list the permissions using Drive.Permissions.List first. Particularly, look at the type and role or teamDrivePermissionDetails[].role properties. See the permissions guide on what operations each role or type can do. You can also visit this documentation on managing sharing in case you need to.

logging all queries after execution in codeigniter

i want to log all queries after execution using hooks.
-i enabled hooks in config.php
-this is my hook-->
$hook['post_controller'] = array(
'class' => 'Db_log',
'function' => 'logQueries',
'filename' => 'db_log.php',
'filepath' => 'hooks'
);
-and this is hook defination-->
class Db_log
{
function __construct()
{
}
function logQueries()
{
$CI = & get_instance();
$filepath = APPPATH . 'logs/Query-log-' . date('Y-m-d') . '.php';
$handle = fopen($filepath, "a+");
$times = $CI->db->query_times;
foreach ($CI->db->queries as $key => $query)
{
$sql = $query . " \n Execution Time:" . $times[$key];
fwrite($handle, $sql . "\n\n");
}
fclose($handle);
}
}
--its creating query_log file
--but no records of queries being stored
Your Code looks fine - the only reason why this doesn't work is in your DB Configuration - take a look #your DB Connection in the database.php under application/config/
There is an option "save_queries" which should be set to true
$db['default'] = array(
...
'save_queries' => TRUE
);
For me it only worked when I define de $hook array in config/hooks.php .

Resize to 3 different size at a time to different path using intervention in laravel 5.0

I am trying to resize images in Laravel 4.2 using intervention, but i want to move images to 2 different folders at a time.
If i run the below code
if(Input::hasFile('product_images')) {
$images = Input::file('product_images');
foreach($images as $image) {
if($image->isValid()) {
$file_name = microtime();
$file_name = str_replace(' ', '_', $file_name);
$file_name = str_replace('.', '_', $file_name);
$file_name = $file_name . '.' . $image->getClientOriginalExtension();
$file_name = $image->getClientOriginalExtension();
$image->move(public_path() . '/uploads/', $file_name);
$file = Image::make(sprintf('uploads/%s', $file_name))->resize(800, 600)->save();
It(above code) runs proper for uploads folder but, if i create another folder called thumbnail inside uploads & add below line i'll get error as....,
("Intervention\Image\Exception\NotReadableException","message":"Image source not readable")........
$file = Image::make(sprintf('uploads/thumbnail/%s', $file_name))->resize(75,75)->save();
Thanks in advance
The issue with the above code is original file being resized to a blurry images. It can be avoided by using aspectRatio as used in the below code.
Also set memory limit to -1. So that it'll be easier to upload a larger images for a Web page, 30 to 60 KB and larger.
Implementation will be much like:
$imageType = array(
'thumbnail' => array(
'width' => 50,
'height' => 50
),
'detail_page' => array(
'width' => 200,
'height' => 200
),
'product' => array(
'width' => 400,
'height' => 400
),
);
if(Request::hasFile('image')) {
$image = Request::file('image');
if($image->isValid()) {
ini_set('memory_limit', '-1');
$file_name = microtime();
$file_name = str_replace(' ', '_', $file_name);
$file_name = str_replace('.', '_', $file_name);
$file_name = $file_name . '.' . $image->getClientOriginalExtension();
$image->move(public_path() . '/uploads/', $file_name);
$response['file_name'] = $file_name;
foreach ($imageType as $key => $value) {
$file = Image::make(sprintf('uploads/%s', $file_name))->resize($value['width'], $value['height'],
function($constraint) {
$constraint->aspectRatio();
});
$file->save(public_path() . '/uploads/'.$value['width'].'X'.$value['height'].'/'. $file_name);
}
$product_image_url = URL::to('uploads/' . $file_name);
I finally managed to resize images in Laravel 4.2 using intervention, also to move images to different folders at a time in one line of code.
See the code snippet below,
$file = Image::make(sprintf('uploads/%s', $file_name))
->resize(800, 600)->save()
->resize('1280', '1024')->save(public_path() . '/uploads/1280x1024/' . $file_name)
->resize('316', '255')->save(public_path() . '/uploads/316x255/' . $file_name)
->resize('118', '95')->save(public_path() . '/uploads/118x95/' . $file_name);
As you can see, I have created 3 folders named 1280x1024, 316x255, 118x95 in uploads folder in public_path.
So if you use above code, after resize() give the path to save() function and keep on repeating to save all resized images at a time.
If anyone knows even better answers, please try to post it and improve it.
Use the intervention/image package
public function upload() {
$image = \Image::make(\Input::file('image'));
$path = storage_path('app')."/";
// encode image to png
$image->encode('png');
// save original
$image->save($path."original.png");
//resize
$image->resize(300,200);
// save resized
$image->save($path."resized.png");
}
if(Input::file()){
$image = Input::file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('profilepics/' . $filename);
Image::make($image->getRealPath())->resize(200, 200)->save($path);
$user->image = $filename;
$user->save();
}

Resources