Integrating Doctrine in CodeIgniter

This is recipe for using Doctrine 2 in your
CodeIgniter framework.

Note

This might not work for all CodeIgniter versions and may require
slight adjustments.

Here is how to set it up:

Make a CodeIgniter library that is both a wrapper and a bootstrap
for Doctrine 2.

Setting up the file structure

Here are the steps:

  • Add a php file to your system/application/libraries folder
    called Doctrine.php. This is going to be your wrapper/bootstrap for
    the D2 entity manager.

  • Put the Doctrine folder (the one that contains Common, DBAL, and
    ORM) inside that same libraries folder.

  • Your system/application/libraries folder now looks like this:

    system/applications/libraries -Doctrine -Doctrine.php -index.html

  • If you want, open your config/autoload.php file and autoload
    your Doctrine library.

    <?php $autoload[‘libraries’] = array(‘doctrine’);

Creating your Doctrine CodeIgniter library

Now, here is what your Doctrine.php file should look like.
Customize it to your needs.

<?php
use Doctrine\Common\ClassLoader,
    Doctrine\ORM\Configuration,
    Doctrine\ORM\EntityManager,
    Doctrine\Common\Cache\ArrayCache,
    Doctrine\DBAL\Logging\EchoSQLLogger;

class Doctrine {

  public $em = null;

  public function __construct()
  {
    // load database configuration from CodeIgniter
    require_once APPPATH.'config/database.php';

    // Set up class loading. You could use different autoloaders, provided by your favorite framework,
    // if you want to.
    require_once APPPATH.'libraries/Doctrine/Common/ClassLoader.php';

    $doctrineClassLoader = new ClassLoader('Doctrine',  APPPATH.'libraries');
    $doctrineClassLoader->register();
    $entitiesClassLoader = new ClassLoader('models', rtrim(APPPATH, "/" ));
    $entitiesClassLoader->register();
    $proxiesClassLoader = new ClassLoader('Proxies', APPPATH.'models/proxies');
    $proxiesClassLoader->register();

    // Set up caches
    $config = new Configuration;
    $cache = new ArrayCache;
    $config->setMetadataCacheImpl($cache);
    $driverImpl = $config->newDefaultAnnotationDriver(array(APPPATH.'models/Entities'));
    $config->setMetadataDriverImpl($driverImpl);
    $config->setQueryCacheImpl($cache);

    $config->setQueryCacheImpl($cache);

    // Proxy configuration
    $config->setProxyDir(APPPATH.'/models/proxies');
    $config->setProxyNamespace('Proxies');

    // Set up logger
    $logger = new EchoSQLLogger;
    $config->setSQLLogger($logger);

    $config->setAutoGenerateProxyClasses( TRUE );

    // Database connection information
    $connectionOptions = array(
        'driver' => 'pdo_mysql',
        'user' =>     $db['default']['username'],
        'password' => $db['default']['password'],
        'host' =>     $db['default']['hostname'],
        'dbname' =>   $db['default']['database']
    );

    // Create EntityManager
    $this->em = EntityManager::create($connectionOptions, $config);
  }
}

Please note that this is a development configuration; for a
production system you’ll want to use a real caching system like
APC, get rid of EchoSqlLogger, and turn off
autoGenerateProxyClasses.

For more details, consult the
Doctrine 2 Configuration documentation.

Now to use it

Whenever you need a reference to the entity manager inside one of
your controllers, views, or models you can do this:

<?php
$em = $this->doctrine->em;

That’s all there is to it. Once you get the reference to your
EntityManager do your Doctrine 2.0 voodoo as normal.

Note: If you do not choose to autoload the Doctrine library, you
will need to put this line before you get a reference to it:

<?php
$this->load->library('doctrine');

Good luck!

What is SQL Injection. How to Prevent SQL Injection in Drupal

Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.

Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build an SQL query.

SQL Injection in Drupal

Drupal depends on a database to function correctly. Inside Drupal, a lightweight database abstraction layer exists between your code and the database. You may already know how to run db_query() in Drupal to query data from the database. What if your process an insertion which is a user-submitted data?. You should process user submitted data to avoid SQL injections. But in the other hand you can let Drupal to do that for you.

Note : User-submitted data should be passed in as separate parameters so the values can be sani-tized to avoid SQL injection attacks. Drupal uses the printf syntax (see http://php.net/printf) as placeholders for these values within queries. There are different % modifiers depending on the data type of the user-submitted information.Wrong way of insertion:

  db_query("INSERT INTO {video_files} (fid, status, dimensions) VALUES ($video['fid'], VIDEO_RENDERING_PENDING, '$video['dimensions']')");

Correct way of insertion:

    db_query("INSERT INTO {video_files} (fid, status, dimensions) VALUES (%d, %d, '%s')", $video['fid'], VIDEO_RENDERING_PENDING, $video['dimensions']);

Difference between hook_boot and hook_init Drupal

hook_boot hook_init
  • Even cached page executes this hook
  • Cached page doesn’t run this hook.
  • This hook is called before modules or most include files are loaded into memory.
  • When this hook is called, all modules are already loaded in memory.
  • It happens while Drupal is still in bootstrap mode.
  • It happens after bootstrap mode.

Render view’s exposed form anywhere in a theme/module with custom module


/**
* Returns rendered exposed form for a given view.
* $view_name
* - A string with a view name,
* $display_id
* - A string with a name of view display,
* @return
* Rendered exposed form.
*/
function MY_MODULE_render_exposed_form($view_name, $display_id = 'page') {
$view = views_get_view($view_name);
$view->set_display($display_id);
$view->init_handlers();
$form_state = array(
'view' => $view,
'display' => $view->display_handler->display,
'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
'method' => 'get',
'rerender' => TRUE,
'no_redirect' => TRUE,
);
$form = drupal_build_form('views_exposed_form', $form_state);
return drupal_render($form);
}

Create a product order in magento with Php Code

Create Order
Below is the php code to create an order in magento. It requires a valid customer account with shipping and billing address setup.

$id=1; // get Customer Id
$customer = Mage::getModel('customer/customer')->load($id);

$transaction = Mage::getModel('core/resource_transaction');
$storeId = $customer->getStoreId();
$reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);

$order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($storeId)
->setQuoteId(0)
->setGlobal_currency_code('USD')
->setBase_currency_code('USD')
->setStore_currency_code('USD')
->setOrder_currency_code('USD');
//Set your store currency USD or any other

// set Customer data
$order->setCustomer_email($customer->getEmail())
->setCustomerFirstname($customer->getFirstname())
->setCustomerLastname($customer->getLastname())
->setCustomerGroupId($customer->getGroupId())
->setCustomer_is_guest(0)
->setCustomer($customer);

// set Billing Address
$billing = $customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultBilling())
->setCustomer_address_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$order->setBillingAddress($billingAddress);

$shipping = $customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());

$order->setShippingAddress($shippingAddress)
->setShipping_method('flatrate_flatrate');
/*->setShippingDescription($this->getCarrierName('flatrate'));*/
/*some error i am getting here need to solve further*/

//you can set your payment method name here as per your need
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($storeId)
->setCustomerPaymentId(0)
->setMethod('purchaseorder')
->setPo_number(' – ');
$order->setPayment($orderPayment);

// let say, we have 1 product
//check that your products exists
//need to add code for configurable products if any
$subTotal = 0;
$products = array(
'1' => array(
'qty' => 2
)
);

foreach ($products as $productId=>$product) {
$_product = Mage::getModel('catalog/product')->load($productId);
$rowTotal = $_product->getPrice() * $product['qty'];
$orderItem = Mage::getModel('sales/order_item')
->setStoreId($storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($productId)
->setProductType($_product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($_product->getName())
->setSku($_product->getSku())
->setPrice($_product->getPrice())
->setBasePrice($_product->getPrice())
->setOriginalPrice($_product->getPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal);

$subTotal += $rowTotal;
$order->addItem($orderItem);
}

$order->setSubtotal($subTotal)
->setBaseSubtotal($subTotal)
->setGrandTotal($subTotal)
->setBaseGrandTotal($subTotal);

$transaction->addObject($order);
$transaction->addCommitCallback(array($order, 'place'));
$transaction->addCommitCallback(array($order, 'save'));
$transaction->save();

Increasing Drupal’s File Size Upload Limit

  1. Go to your Admin menu. Under Site Configuration, select File Uploads
  2. Find the Default maximum file size per upload and set it to 128mb

    Second, Modify Apache

    1. Find your php.ini file. On my machine, this is located at /etc/php5/apache2/php.ini
    2. Find upload_max_filesize and change it so it reads:
      upload_max_filesize = 128M
    3. Find post_max_size and change it also:
      post_max_size = 128M
    4. Restart apache

    Yay, you should be able to upload huge files now! Make sure you set your up your per-user upload settings if you want non-admin users to be able to upload huge files.

    Alternate Apache Option: Edit your .htaccess file

    If you don’t have access to your php.ini file, you should be able to set the php options in your .htaccess file using the following syntax:

    php_value upload_max_filesize 128M
    php_value post_max_size 128M