Category Archives: PHP

solr 6.4 managed schema to unmanaged schema change in schema.xml | solr migration from 5 to 6 in schema.xml

1. First change the managed schema to schema.xml in /var/solr/data/core??/conf/managed-schema. And copy or edit your desired file to it. You can follow the below link. What it said to remove ManagedIndexSchemaFactory from solrconfig.xml . You might not find the ManagedIndexSchemaFactory to remove. but don’t worry. if it is not there then its ok. And add . you can add this just after dataDir or lib dir.

https://cwiki.apache.org/confluence/display/solr/Schema+Factory+Definition+in+SolrConfig

2. Change the field type if necessary in schema.xml. Check in the log of solr admin. You should also check in the /var/log/apaceh2/error.log

http://stackoverflow.com/questions/11309494/solr-undefined-field-text

In my case I had to add lots of field like .

3. Restart the solr and try to connect the core from your application. For php I got a 404 because the connection denied. I see the log and found this Indexschema is not mutable. Search the google for “org.apache.solr.common.SolrException: This IndexSchema is not mutable” and found the solutions there.

http://stackoverflow.com/questions/31719955/solr-error-this-indexschema-is-not-mutable

You need to remove the AddSchemaFieldsUpdateProcessorFactory section from the updateRequestProcessorChain config in your solrconfig.xml and thats it for me. while restarting the solr service my app again connected to the solr 6.4 and start indexing my docs.

Always try to find out what is the problem in you solr admin log, apache log, and in my case my local app log also helped. I was using zend for solarium in php.

Pagination for Laravel 4.1 | Working with Laravel Custom Pagination | Laravel 4.1 Pagination

Working with Laravel 4.1 pagination was not so difficult though the resource in internet is low rather than the Laravel 4.0. Up to day Laravel 4.1 has some inbuilt problem (which they are making correction) had given me some hard time, like with the static function. Anyway I recovered them and lets talk about how we can manage the custom pagination with Laravel 4.1.

We will be using “paginate” method with Eloquent model or the Query Builder. We will be using Laravels “Paginator” class which has a “make” method which allow us to create the custom pagination. Oh, one thing, if you guys are using simple raw mysql queries its the high time that you should change it to a ORM. I will discuss the usefulness of ORM on another post, but, briefly it allows you to change the db frequently, gives you more handle to relational database, gives you more power to accumulate things shortly as they have lots of method to help you out to save your raw coding of sql’s. For example you want to find all the data of the table, and its very simple like $table->;find(), almost every ORM has method like this. Eloquent is one of the easiest ORM I have seen so far. Lets come to the point how we can do it icon smile Pagination for Laravel 4.1 | Working with Laravel Custom Pagination | Laravel 4.1 Pagination

In my case I am giving example of a contact table where all table information should in paginated form. To achieve this we will create a new method in my Contact repository. The code sample is like bellow.

/**
* Getting the contacts as paginated
*
* Get results by page
*
* @param int $page
* @param int $limit
* @return StdClass
*/
public function getByPage($page = 1, $limit = 10){
    $results = new StdClass;
    $results->page = $page;
    $results->limit = $limit;
    $results->totalItems = 0;
    $results->items = array();
    $contacts = Contact::skip($limit * ($page - 1))
                           ->take($limit)
                           ->get();  
    $totalCont = Contact::all()->count();
    $results->totalItems = $totalCont;
    $results->items = $contacts->all();  
    return $results;
}

Now in your controller call the getByPage method and make the pagination. The code should be as follows

/**
* Function to list contacts
* @author Zea
* @version 0.1
* @copyright iVive Labs
* @access pulic
* @param optional pagination-> page, limit
* @return contacts
*/
public function listContact(){
    $page = Input::get('page', 1);
    $limit = Input::get('limit', 10);
    $contact = new Contact;  // correct
    $data = $contact->getByPage($page, $limit);
    $contacts = Paginator::make($data->items, $data->totalItems, $limit);      

    foreach ($contacts->getCollection() as $key => $contact){
        $explode_contact[$key]= array (
            'id' => $contact->id,
            'name' => $contact->name,
            'street' => $contact->street,
            'zipcode' => $contact->zipcode,
            'city' => $contact->city
        );         
    }      
    $explode_contact['paging'] = (array("page"=>$contacts->getCurrentPage(),"pageSize" =>$contacts->count(), "pageCount"=>ceil($contacts->getTotal()/$contacts->getPerPage()),"total"=>$contacts->getTotal()));
       
    $explode_contact['success'] = true;
    return json_encode($explode_contact);
}

I guess it will solve the pagination things with Laravel 4.1

The Paginator class has lots of methods for creating the pagination. Some useful ones are as follows:

find
count
getTo
getFrom
getTotal
getPerPage
getLastPage
getCurrentPage

There are more methods over there, you can check it by this link.

MPTT — Managing Hierarchical Data in Mysql

For a hierarchical table which has depth more than 3 is a tough one to fetch data and show it. And for a bigger table its near to impossible to fetch. It will give you time out. Even if you manage the time the application will be slower. Let me give an example. Suppose you have a region table which have got 4 level of depth and has data about only 100 rows. The levels are State, City, Town, Area. So to show it hierarchically you will have to loop all the data, for this case it will 4 loops which is 100*100*100*100 = 100000000, you might lesser it a bit by some breaks but still it is a n^3 times algorithm which will slow your system definitely and crash your system eventually.

So there is a technique which is called MPTT — modified preordered tree traversal algorithm for multiple depth search or to search hierarchical data. Its a very simple technique where the table in our case the region table is ordered accordingly and serve before the fetch. This technique reminds me the concept of set while I was in grade 8.

 MPTT    Managing Hierarchical Data in Mysql

From the above image you can see

New York State has the range from 1 – 8
New York City has the range from 2 – 7
Manhattan has the range from 3 – 6
Midtown has the range from 4 – 5

Similarly if you have more city or town you need to add them up and whole range would be larger then, for instance if you add two other city Long Island and Columbia then the range should be

New York State has the range from 1 – 12
New York City has the range from 2 – 7
Manhattan has the range from 3 – 6
Midtown has the range from 4 – 5
Long Island has the range from 8 – 9
Columbia has the range from 10 – 11

And you have to make the data base like this. Here we will use the left and right column for the range. Like for new york city the left column should be 2 and the right is 7. Every other rows should have the same thing. Now as I have used symfony2 with doctrine 2.2 with dql I will show how you can generate the full tree

 public function crossJoin(){

 $q = $this->_em->createQuery("
SELECT node.id, node.regionId, node.regionName
FROM ViveZeaBundle:RegionRedefines AS node,
ViveZeaBundle:RegionRedefines AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.regionId
ORDER BY node.lft  ");
return $q->getResult();

 }

Now in my controller I call it and I have used jquery tree to show it.

$tree = $em->getRepository("ViveZeaBundle:RegionRedefines")->crossJoin();
$result = '';
foreach ($tree as $node) {
foreach($tree as $traceTree){
if($traceTree['hierarchyId'] == $node['regionId']){
$trace_last_node=$traceTree;
break;
}
else{
$trace_last_node="";
}
}
$node_depth = $node['depth'];
$node_name = $node['regionName'];
if ($node_depth == $current_depth) {
if ($counter > 0)
$result .= '';
}

elseif ($node_depth > $current_depth) {
$result .= ”, $current_depth – $node_depth) . ”;
$current_depth = $current_depth – ($current_depth – $node_depth);
}

$result .= ‘<li ‘; if($trace_last_node!=””){ if($catName!=””) $tit = $catName.”-in-”.$node['regionName']; else $tit = $node['regionName'];              $tit = preg_replace(“/[^a-zA-Z0-9\/ _-]/”, ”, $tit); $tit = str_replace(‘ ‘,’-’, ucwords($tit)); $tit = str_replace(‘–’,’-’,$tit); $result .= ‘class = “expandable”‘;

$result .=$basePath.’/’.$tit.’/’.$categoryId.’/’.$node['regionId'].’/0/ $node_name . ”;
}

else{
if($catName!=””)
$tit = $catName.”-in-”.$node['regionName'];
else
$tit = $node['regionName'];
$result .=$basePath.’/’.$tit.’/’.$categoryId.’/’.$node['regionId'].’/0/ $node_name . ”;
}
++$counter;
$temp = ” . $node_name . ‘ ‘;
}
$result .= str_repeat(”, $node_depth) . ”;
$result .= ”;

Now just return the result.

Adjust Server timezone ( time zone ) by adding helper file in CodeIgniter (code igniter, codeigniter, ci )

It has been seen that often the server is located in differnt timezones than ours….. Its been too tough to change the timezones in CodeIgniter for me. To resolve this problem we can add a simple helper file. For this you need to do the following steps.

Step 1. Create a folder in your applications folder named ‘helpers’

Step2. Save a file with named ‘zea_helper.php’ containing

function bd_time() {
 return mktime((gmdate('H').'GMT')+6, date("i"), date("s"), date("m"), date("d"), date("y"));
}

in the above created ‘helpers’ folder.  I have used +6 bceause bangladesh time is GMT 6+, if your time is GMT -4 you should write “(gmdate(‘H’) . GMT’)-4,” instead (gmdate(‘H’) . ‘ GMT’)+6,

Step3. Go to your autoload.php in config folder and change the line $autoload['helper'] = array(”); to $autoload['helper'] = array(‘zea’); and save the file.

Step4. Now just load the helper just like other helpers in your controller like $this->load->helper(‘zea’);. and start using it as a helpers

ex: echo date(“F j, Y, g:i a”,bd_time());

dont forget to load the helper in the controller.

Turn on / off for $register_globals by .htaccess file, “change from php4 to php5″

  1. Create a  file called .htaccess with any editor (like WordPad or Notes or dreamweaver or anyting).
  2. Add the following line in .htaccess:
    php_flag register_globals on
  3. Upload the file to your web hosting account(generally inside of public_html folder). Make sure the name of the file dosen’t have any kind of extension. The file name should be only .htaccess

Fell free to ask about it….