What could be the possible issue with this library? - codeigniter

I have created a library in codeigniter. It is not working.
My Library file is;
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Image_pixelete{
function __construct()
{
$this->ci=&get_instance();
}
public function do_pixel()
{
$image = imagecreatefromjpeg(base_url().'photo/Penguins.jpg');
$imagex = imagesx($image);
$imagey = imagesy($image);
$pixelate_y=10;
$pixelate_x=10;
$height=$imagey;
$width=$imagex;
for($y = 0;$y < $height;$y += $pixelate_y+1)
{
for($x = 0;$x < $width;$x += $pixelate_x+1)
{
// get the color for current pixel
$rgb = imagecolorsforindex($image, imagecolorat($image, $x, $y));
// get the closest color from palette
$color = imagecolorclosest($image, $rgb['red'], $rgb['green'], $rgb['blue']);
imagefilledrectangle($image, $x, $y, $x+$pixelate_x, $y+$pixelate_y, $color);
}
}
}
Here is my controller call
public function pixel()
{
$this->load->library('Image_pixelete');
$this->Image_pixelete->do_pixel();
}
and here is my error;
I am confused about exact nature of the problem to cope it out. can you please review it?

Try by loading and using your library with lower case.
$this->load->library('image_pixelete');
$this->image_pixelete->do_pixel();
Check this similar question codeigniter cannot load library

Related

Composer: Troubleshooting autoloading

I'm submitting this question because I have been searching on the topic of troubleshooting autoloading in Composer and can't seem to find anything straightforward. I added several classes to a library and then referenced them in a project. The project can't find the classes. Here are the pertinent facts:
• I've already been using the library in the project for some time.
• I double-checked the namespace declaration in the code file for the class in the library:
namespace \Library\Package\Subpackage;
class Widget { ...
• I double-checked the use statement that aliases the library and the instantiation:
use \Library\Package\Subpackage as Subpackage;
$e = new Subpackage\Widget();
• For grins, I altered the alias:
use \Library\Package\Subpackage\Widget as Widget;
$e = new Widget();
• For even more grins, I tried a direct reference:
$e = new \Library\Package\Subpackage\Widget();
• I also made sure to composer update and make sure the file is actually there, at the right path:
composer update
find . -name Widget.php
./vendor/organization/library/Package/Subpackage/Widget.php
• As a sanity check, I added a reference to another item in the same library but in a different subpackage.
$f = new \Library\Package2\Widget2(); // this works fine
• As an absolute last resort, I put the reference in a PHP file all by itself and ran that.
require_once __DIR__.'/vendor/autoload.php';
$e = new \Library\Package\Subpackage\Widget();
• And for the coup de grace, I wrote a unit test that checks every file in the library's vendor folder:
class AutoloadTest extends \PHPUnit\Framework\TestCase
{
public function classDataProvider()
{
$data = array();
$path = realpath('organization/library/Package/');
$directory_iterator = new \RecursiveDirectoryIterator($path);
$iterator_iterator = new \RecursiveIteratorIterator($directory_iterator);
foreach ($iterator_iterator as $iterator_result) {
$real_path = $iterator_result->getRealPath();
if (substr($real_path, -4, 4) != '.php') {
continue;
}
$split = explode('organization/library/Package/', $real_path);
$processed_path = substr($split[1], 0, -4);
$class_fqname = sprintf('\Library\%s', str_replace("/", '\\', $processed_path));
$data[] = array($class_fqname);
}
return $data;
}
public function test($class_name)
{
$assertion = class_exists($class_name) || trait_exists($class_name) || interface_exists($class_name);
$this->assertTrue($assertion, "$class_name is not recognized as a class, trait or interface.");
}
}
My questions are:
What is the most likely culprit?
What can I do with Composer to get tracing information about the paths that it is trying? Is there some way to feed Composer a path and have it tell me whether or not it can resolve it?
Extraneous backslash.
namespace \Library\Package\Subpackage;
^ oops!
Removing this backslash resolved the problem.
Ultimately, the unit test that I wrote helped me find and resolve the problem. So for the second part of my question, I'm offering the test class that I wrote. The provider receives pairs of the path to scan and the namespace in which the files belong. It scans the paths given and finds the classes in that namespace. The test checks asserts that each qualified-class name corresponds to a class, trait or interface. (Requires an autoloader to load the classes, of course.)
abstract class AutoloadTestBase extends \PHPUnit\Framework\TestCase
{
public function pathProvider()
{
$data = array();
foreach ($this->directories() as $directory_specification) {
list($path, $namespace) = $directory_specification;
if (empty($path)) {
continue;
}
$directory_iterator = new \RecursiveDirectoryIterator($path);
$iterator_iterator = new \RecursiveIteratorIterator($directory_iterator);
foreach ($iterator_iterator as $iterator_result) {
$real_path = $iterator_result->getRealPath();
$split1 = explode($path.'/', $real_path);
if (count($split1) < 2) {
continue;
}
$success = preg_match('/^(.+)\.php$/', $split1[1], $split2);
if (!$success || substr($split2[1], 0, 5) == 'Tests') {
continue;
}
$class_fqname = sprintf('%s\%s', $namespace, str_replace("/", '\\', $split2[1]));
$data[] = array($class_fqname);
}
}
return $data;
}
/**
* #dataProvider pathProvider
*/
public function test($class_name)
{
$assertion = class_exists($class_name) || trait_exists($class_name) || interface_exists($class_name);
$this->assertTrue($assertion, "$class_name is not recognized as a class, trait or interface.");
}
}
class AutoloadTest extends AutoloadTestBase
{
protected function directories()
{
return array(
array('Package1/Subpackage1','\Library1\Package1\Subpackage1'),
array('vendor/organization2/package2/Subpackage2','\Library2\Package2\Subpackage2')
);
}
}

Why does this pattern not work in preg_match

I use preg_match in a function to prevent image extensions from being submitted!
Now I want to block " ~ " character also!
Can anyone tell me how I can do that?
function is_valid($url) {
$res = 1;
if (isset($url['path'])) {
if (preg_match('/\b.jpg\b/i', $url['path'])) { $res = 0; }
if (preg_match('/\b.gif\b/i', $url['path'])) { $res = 0; }
if (preg_match('/\b.png\b/i', $url['path'])) { $res = 0; }
if (preg_match('/\b.bmp\b/i', $url['path'])) { $res = 0; }
}
return $res;
}
I tried this, but it does not work:
if (strpos('~', $url['path'])) {
$res = 0;
}
First of all, you should really read something about regular expressions! If you have done that, read the manual for phps strpos.
You may try preg_match('/[^~]+\.(png|jpg|gif|bmp)/i', $url['path']) or if you want to stick to your version,
if (strpos($url['path'], '~') !== FALSE) {
$res = 0;
}
But anyway, your check will just not be very safe. Example: Someone renames a php file into png and uploads it, if you have mime_magic activated on your apache, the code will get executed. So it is much safer to check the mimetype of the file. See How do I find the mime-type of a file with php? as an example. The accepted answer there mentions a (now) deprecated function, but you can use http://de3.php.net/manual/en/function.finfo-file.php if you have PHP 5.3+

TYPO3 Extbase: How to render the pagetree from my model?

I want to create some kind of sitemap in extbase/fluid (based on the pagetree). I have loaded the pages table into a model:
config.tx_extbase.persistence.classes.Tx_MyExt_Domain_Model_Page.mapping.tableName = pages
I have created a controller and repository, but get stuck on the part wich can load the subpages as relation into my model.
For example:
$page = $this->pageRepository->findByPid($rootPid);
Returns my rootpage. But how can I extend my model that I can use $page->getSubpages() or $page->getNestedPages()?
Do I have to create some kind of query inside my model? Or do I have to resolve this with existing functions (like the object storage) and how?
I tried a lot of things but can simply figure out how this should work.
you have to overwrite your findByPid repository-method and add
public function findByPid($pid) {
$querySettings = $this->objectManager->create('Tx_Extbase_Persistence_Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);
$this->setDefaultQuerySettings($querySettings);
$query = $this->createQuery();
$query->matching($query->equals('pid', $pid));
$pages = $query->execute();
return $pages;
}
to get all pages. Than you can write your own getSubpages-method like
function getSubpages($currentPid) {
$subpages = $this->pagesRepository->findByPid($currentPid);
if (count($subpages) > 0) {
$i = 0;
foreach($subpages as $subpage) {
$subpageUid = $subpage->getUid();
$subpageArray[$i]['page'] = $subpage;
$subpageArray[$i]['subpages'] = $this->getSubpages($subpageUid);
$i++;
}
} else {
$subpageArray = Array();
}
return $subpageArray;
}
i didn't test this method, but it looks like this to get alle subpages.
i wonder that i could´t find a typo3 method that return the complete Page-Tree :( So i write a little function (you can use in an extbase extension), for sure not the best or fastes way, but easy to extend or customize ;)
first you need an instance of the PageRepository
$this->t3pageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
this->t3pageRepository->init();
make the init, to set some basic confs, like "WHERE deletet = 0 AND hidden = 0..."
then with this function you get an array with the page data and subpages in. I implement yust up to three levels:
function getPageTree($pid,$deep=2){
$fields = '*';
$sortField = 'sorting';
$pages = $this->t3pageRepository->getMenu($pid,$fields,$sortField);
if($deep>=1){
foreach($pages as &$page) {
$subPages1 = $this->t3pageRepository->getMenu($page['uid'],$fields,$sortField);
if(count($subPages1)>0){
if($deep>=2){
foreach($subPages1 as &$subPage1){
$subPages2 = $this->t3pageRepository->getMenu($subPage1['uid'],$fields,$sortField);
if(count($subPages2>0)){
$subPage1['subpages'] = $subPages2;
}
}
}
$page['subpages'] = $subPages1;
}
}
}
return $pages;
}

Codeigniter change database config at runtime

Can I change the database config per method in a controller?
$db['default']['db_debug'] = TRUE;
The default is TRUE, while I need to make it false in a certain method to catch the error and do something else (for example show 404 page).
When I tried $this->config->load('database') it fails.
Another question :
Can I check an incorrect query and catch it to some variables rather than displaying it to users other than setting the db_debug config to FALSE?
I checked the code of system/database/DB_Driver and found that:
$this->db->db_debug = FALSE;
will work in my controller to enable/disable the debug thing on the fly.
Expanding on the answer by comenk, you can extend the database class and implement various methods by which to achieve your goal.
First, you'll need to extend the core Loader class by creating a MY_Loader.php file
class MY_Loader extends CI_Loader
{
function __construct()
{
parent::__construct();
}
/**
* Load the Standard and/or Extended Database function & Driver class
*
* #access public
* #return string
*/
function database( $params = '', $return = FALSE, $active_record = NULL )
{
$ci =& get_instance();
if (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($ci->db) AND is_object($ci->db))
{
return FALSE;
}
$my_db = config_item('subclass_prefix').'DB';
$my_db_file = APPPATH.'core/'.$my_db.EXT;
if(file_exists($my_db_file))
{
require_once($my_db_file);
}
else
{
require_once(BASEPATH.'database/DB'.EXT);
}
// Load the DB class
$db =& DB($params, $active_record);
$my_driver = config_item('subclass_prefix').'DB_'.$db->dbdriver.'_driver';
$my_driver_file = APPPATH.'core/'.$my_driver.EXT;
if(file_exists($my_driver_file))
{
require_once($my_driver_file);
$db = new $my_driver(get_object_vars($db));
}
if ($return === TRUE)
{
return $db;
}
// Initialize the db variable. Needed to prevent
// reference errors with some configurations
$ci->db = '';
$ci->db = $db;
}
}
By implementing the above this will allow you to create a MY_DB_mysqli_driver.php whereby mysqli is replaced by whatever driver you're using in your CI database.php config.
At this point you'd add comenk's answer to MY_DB_mysqli_driver.php
function debug_on() {
return $this->db_debug = TRUE;
}
function debug_off() {
return $this->db_debug = FALSE;
}
function in_error() {
return (bool) $this->_error_number();
}
Then in your model/controller,
$this->db->debug_off();
$this->db->query('SELECT * FROM `table`');
if( $this->db->in_error() ) {
show_404();
}
$this->db->debug_on();
you must add function on system/database/DB_driver.php
function debug_on()
{
$this->db_debug = TRUE;
return TRUE;
}
function debug_off()
{
$this->db_debug = FALSE;
return FALSE;
}
after that you can simply do this command to changes at run-time
$this->db->debug_off();
$this->db->reconnect();
$this->db->db_debug = 0; // 0: off, 1: on
That worx for me...
You can look at the $GLOBALS variable to locate this generic setting.
To hide bad SQL (and other errors) from users, you need to set the php error reporting level. CodeIgniter ships in basically development mode.
Go to index.php and replace this
error_reporting(E_ALL);
with this
error_reporting(0);
This is the quick way to do it. You can also implement this using a hook, so you don't have to touch CI files. You can also add logic to that hook so that it only sets it on the production server.
For debugging SQL, you can create a class that inherits from CI_Model, then create all your model classes to extend that class. In that class, you can add code for running queries that writes the queries to the log so that you can debug them easier. This won't help if the query itself is bad, but you should be able to figure that out before you get to that point.

Bringing in value of Coupon Code into "tax" calculation.php in magento

Im trying to pull in the name of the discount code currently applied to the cart into the calculation.php file. The name of the discount code is optionalTax but Im having trouble passing it through or retrieving it directly. Its appears to be referenced as $quote->getCouponCode() in mage/sales/model/quote.php and I want to use it in
mage/tax/model/calculation.php
Anyone have any idea on how to call it in as I've tried using the model as per (which I think is correct)
public function calcTaxAmount($price, $taxRate, $priceIncludeTax=false, $round=true)
{
$taxRate = $taxRate/100;
if ($priceIncludeTax) {
$amount = $price*(1-1/(1+$taxRate));
} else {
$cModel = Mage::getModel('catalog/sales');
$thisDiscountCode = $cModel->$quote->getCouponCode();
die($thisDiscountCode);
$amount = $price*$taxRate;
}
if ($round) {
return $this->round($amount);
} else {
return $amount;
}
}
Chris
you need to get the quote from right model i guess:
Mage::getSingleton('checkout/session')->getQuote();

Resources