Movies here: film izle

formats

PHP Snippet of the day – Sort Object by field name

Published on December 1, 2012 by in PHP

If you find you need to sort an returned object this snippet will save your life.

/** * Sort array of objects by field.
 *
 * @param array $objects Array of objects to sort.
 * @param string $on Name of field.
 * @param string $order (ASC|DESC)
 */
function sort_on_field(&$objects, $on, $order = 'ASC') {
    $comparer = ($order === 'DESC')
        ? "return -strcmp(\$a->{$on},\$b->{$on});"
        : "return strcmp(\$a->{$on},\$b->{$on});";
    usort($objects, create_function('$a,$b', $comparer));
}

//Example Usage:

sort_on_field($view->result,'node_title','ASC');
 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 
formats

Drupal custom form with autocomplete drop down

Published on April 2, 2011 by in Drupal, PHP

I had been putting off doing an custom autocomplete programmatically in drupal for a long time. I finally sat down and decided to work it out for a project i was doing. It was surprisingly very easy. My project consisted of pulling an autocomplete text field from a taxonomy list.

The first step is to build your menu callbacks via hook_menu api. For those not as familiar with drupal what a menu call back does is setup a path or route that when entered in a url executes a function.

The first menu item is to setup the form. The page callback calls drupal_get_form and we are passing the defined search form to that callback.

The second menu item is the autocomplete query callback. This is where the actual query is performed that returns the list of categories.

//Hook Menu items:
function mymodule_menu() { 
  $items['searchform'] = array(
          'page callback' => 'drupal_get_form',
          'page arguments' => array('mymodule_form'),
          'access arguments' => array('access content'),
          'type' => MENU_CALLBACK,
          ); 

$items['category/autocomplete'] = array(      
      'title' => 'Autocomplete for categories',
      'page callback' => '_category_autocomplete',
      'access callback' =>TRUE,
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK
    );
}

The Next step is to define your form using hook_form api. This is where we attach the autocomplete callback, for when you type in the text field it performs the query, and returns the data. The key parameter field is the #autocomplete_path entry in the form elements. This path is the menu callback path we defines above in the hook_menu section of the code.

 

//hook form 
 function mymodule_form(&$form_state = NULL){
     // drupal_add_js('sites/all/misc/autocomplete.js', 'theme', 'header');
     // Added custom overide for drupals built in autocomplete.js 
     // this allowed me to overide some of the internal autocomplete settings.
     // You can remove the drupal_add_js  line for default values in your autocomplete
    $form = array();      
    $form['category'] = array(
    '#type' => 'textfield',
    '#title' => 'Category',
    '#maxlength' => 128,
    '#autocomplete_path' => 'category/autocomplete',
  );

      // add a submit button
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  // return form array
  return $form;   
     }

The final step is to create your query and pass the data back to your form. Note this can be any type of query you like, I used views to build the queury I needed and I copied that for the code below. The drupal_to_js basically returns a JSON array back to the form. If you are using Drupal 7 you will need to change this to drupal_json_encode instead.

 
//Autocomplete queries:

function _category_autocomplete($string) {
  $matches = array();
  // searching in database, only city column
  $result = db_query_range("SELECT term_data.tid AS tid,
   term_data.name AS term_data_name,
   term_data.vid AS term_data_vid
 FROM term_data term_data 
 WHERE LOWER(term_data.name) LIKE LOWER('%s%%') and term_data.vid in ('2')
   ORDER BY term_data_name ASC", $string, 0, 10);
  // found wrote into $matches
  while ($data = db_fetch_object($result)) {
    $matches[$data->term_data_name] = check_plain($data->term_data_name);
  }
  // return for JS
  print drupal_to_js($matches);
  // for drupal 7 comment out drupal_to_js and uncomment below
  //drupal_json_encode($matches);

  // we don't need goto next PHP
  exit();
}

I have not tested this under drupal 7 yet, but with a few minor changes like I notated above, it should work.

Here is the complete code below:

 
//Hook Menu items:
function mymodule_menu() { 
  $items['searchform'] = array(
          'page callback' => 'drupal_get_form',
          'page arguments' => array('mymodule_form'),
          'access arguments' => array('access content'),
          'type' => MENU_CALLBACK,
          ); 

$items['category/autocomplete'] = array(      
      'title' => 'Autocomplete for categories',
      'page callback' => '_category_autocomplete',
      'access callback' =>TRUE,
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK
    );
}

//hook form 
 function mymodule_form(&$form_state = NULL){
     // drupal_add_js('sites/all/misc/autocomplete.js', 'theme', 'header');
     // Added custom overide for drupals built in autocomplete.js 
     // this allowed me to overide some of the internal autocomplete settings.
     // You can remove the drupal_add_js  line for default values in your autocomplete
    $form = array();      
    $form['category'] = array(
    '#type' => 'textfield',
    '#title' => 'Category',
    '#maxlength' => 128,
    '#autocomplete_path' => 'category/autocomplete',
  );

      // add a submit button
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  // return form array
  return $form;   
     } 

//Autocomplete queries:

function _category_autocomplete($string) {
  $matches = array();
  // searching in database, only city column
  $result = db_query_range("SELECT term_data.tid AS tid,
   term_data.name AS term_data_name,
   term_data.vid AS term_data_vid
 FROM term_data term_data 
 WHERE LOWER(term_data.name) LIKE LOWER('%s%%') and term_data.vid in ('2')
   ORDER BY term_data_name ASC", $string, 0, 10);
  // found wrote into $matches
  while ($data = db_fetch_object($result)) {
    $matches[$data->term_data_name] = check_plain($data->term_data_name);
  }
  // return for JS
  print drupal_to_js($matches);
  // for drupal 7 comment out drupal_to_js and uncomment below
  //drupal_json_encode($matches);

  // we don't need goto next PHP
  exit();
}
 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 
formats

Creating an Alpha Pager with Views 2 and Drupal 6

Published on July 22, 2010 by in Drupal, PHP

This is a reprint of an article I found here:

http://tedserbinski.com/tags/drupal/creating-alpha-pager-with-views-2-and-drupal-6

This is article that saved me tons of hours while I was chasing my tail trying to find an easy way to do this, reprinted so I can remember it later:

From reading all of the docs and quietly watching development commits, I knew Views 2 was going to eliminate a lot of the Views 1 helper modules and open up a whole new world of awesomeness. While I haven’t seen many blog posts detailing just which functionality/modules have been replaced with Views 2, I wanted to kickstart things with my own discovery as I played around with Views 2 quite thoroughly this afternoon.

With Views 1, to build an alpha pager you would use the views alpha pager module in conjunction with your view. But what about Views 2?

Well it’s not so straightforward. I read somewhere about some sort of “glossary” view, but how could that be used to create an alpha pager? Well turns out, quite easy. Here’s how:

  1. First, create a new page view and set your path to “directory”
  2. Assuming you want your pager to be based on the nodes title, add in an argument: “Node: Title”
  3. Set title equal to: “Directory: %1”
  4. Action to take if argument is not present: “Display all values”
  5. Check “Glossary Mode”
  6. Set character limit to “1”
  7. Case: “upper case”
  8. Case in path: “lower case”
  9. Save and update
  10. Add in a header under basic settings
  11. Set up your alpha pager:
<div> class="alpha-pager">

<a href="/directory/a">A</a>
<a href="/directory/b">B</a>
........
</div>
 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 
formats

Drupal node templates based on node id

Published on June 26, 2010 by in Drupal, PHP

Code Snippet to allow you to override and specify node templates based on node id.

Put the code in your template.php file

/**
* Override or insert variables into the node templates.
*
* @param $vars
*   An array of variables to pass to the theme template.
* @param $hook
*   The name of the template being rendered ("node" in this case.)
*/

function mytheme_main_preprocess_node(&$vars, $hook) {
  switch ($hook) {
    case 'node':
      // Here is the way to switch to a different node- template based on node properties.
      if ($vars['page']) {
        // This is LIFO (Last In First Out) so put them in reverse order, i.e
        // most important last.
        $vars['template_files'] = array('node-default-page', 'node-'. $vars['node']->type .'-page', 'node-'. $vars['node']->nid .'-page');
      }
      else {
        $vars['template_files'] = array('node-'. $vars['node']->nid);
      }
    break;
  }
}
 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 
formats

Display dhtml menu over the top of a flash movie

Published on October 14, 2009 by in Flash, html

One of my bigest complaints about flash is that I had thought you couldn't layer over the top of it.   By default a flash object is placed as the topmost layer of your web page. No matter what type of z-index you would place it would still be on top.

Recently I was researching via google and discovered that flash added a way to fix it. The other good news is most browsers now also support it.

Flash has a parameter called WMODE.   This parameter allows you to the Window Mode property of the Flash movie for transparency, layering, and positioning in the browser.

It has the following options:

  • window - movie plays in its own rectangular window on a web page.
  • opaque - the movie hides everything on the page behind it.
  • transparent - the background of the HTML page shows through all transparent portions of the movie, this may slow animation performance.

Place the following parameter in your object tag. Be sure you put it in both the embed as well as the object or you may find one browser it works and the other it does not.

<param name=wmode value="transparent">

View the code here:

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0"
id="acgmm3" type="application/x-shockwave-flash" data="movie.swf" height="192" width="238">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="movie.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="wmode" value="transparent" />
<!--[if !IE] > <-->
<object type="application/x-shockwave-flash" data="movie.swf" height="192" width="238">
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="wmode" value="transparent" />
</object>
<!--> <![endif]-->
</object>


Been a while since I posted anything, so thought this tidbit of info might help someone, or help me at a later date when I forgot how to do it.

 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 
formats

Drupal, a pleasant surprise

Published on March 26, 2009 by in Drupal

I've spent the last number of years developing my own CMS (content management systlogoem) as well as using many others. Several years ago I looked at Drupal for about 10 mins then moved on. I didn't give it a respectful look, or the time it would take to give it a fair review. The only other decent CMS I had worked with was Joomla. While its pretty good it really did many things back*sswards from what I prefer. Ive been thrown into many a project using it and continue to pound my head into a brick wall when ever I have to do something out of the ordinary with it. So I usually fall back to my own trusty CMS to do all the work I do for client projects. This was generally the two choices I have made.

Fast forward to today or I should say over the last month or so. I had been called into help a company update their website that was done using Drupal. The original programmer didn't have the time to devote to it and I gave the company a nice deal, since I would be learning Drupal on the fly. Most CMS's are very similar in nature, they provide a nice easy interface for a user to enter content to show up on their website.

This was my chance to give Drupal a real try. I was very skeptical at first thinking I was going to have to convert the whole project over to my CMS. I started reading and I realized that I had not given it a chance when I first had looked.

As a programmer, the first thing you run into is how easily you can customize a program to meet your clients needs. In my research of Drupal I found it has a VERY extensive API.   It's  not just a CMS, its more of a CMS programming framework.  Once you get your head wrapped around that issue is when you realize the true power.

Drupal lets you do code add on for almost anything. Need to add items to the main content, add it. Need to change how a article behaves, you can change it. Need to over-ride a theme for a specific page, you can over ride it. Almost anything can be added in to change how things work within drupal.

Drupal has a very cool  module system.  With Drupal contributed modules you can easily add to its functionality, a module search will reveal 100s of different varying modules and you can create your own custom modules to override items to add to it.

Drupal is community driven!   I should say Drupal IS COMMUNITY! I have had some great help along the way from the community. They have internal forums, IRC channels, Twitter groups, screen casts, books. A huge amount of information can be found to help you. I have been very impressed with the community as a whole. 100s of people devote their time and are willing to help where they can.

drupalcurveThere is a bit of a learning curve. That is unless you have someone to train you. I didn't have that option so was able to learn it fairly quickly since I had a project to work on. It was fairly slow start, but after I got the concepts down I have found I am doing even more complex things with it.

Again. a pleasant surprise. I am certain I will be blogging even more about it in the future.

 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 
formats

javascript change input box type to password

Published on December 12, 2008 by in Javascript

Well its been quite a while since I blogged last.  I have loads of new stuff to write but will get to that later.

How to change input text field to a password type

My most recent challenge was a client did not want to use labels for his login boxes on his website.   He wanted to have Username in the username field and password in the password field.  This in itself isn't to hard.  All you do is set the field values to Username and password.  No big deal.  We all know that the password field needs to be a password field type so if you set the value of this item it is set to ******** instead of saying password

loginbar

The other thing we need to do to each field is clear them.   You can do this with the following code in your input box:

You can make it an onclick or an onfocus, either should work.
Now the problem with the password field is we need to change the field type from text to password once its clicked. You can do this with the following code:

  

This works great with firefox, but throws an error with IE. To fix it you need to actually replace the entire input field. Its a bit tougher to do but here is the code sniplet that will work, I can not take credit for the solution as I found it on the Codeing forums

# put the script in the head of your html 

The above code will replace and re-type the input field from a text field to a password field and it will clear the value at the same time. This works for both Internet Explorer and Firefox. It was a lifesaver, hopefully someone will find it useful.

 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 
formats

sql file splitter to the rescue

Published on May 31, 2008 by in mysql, PHP

My Adventures in sql dumping and database migration

My latest problem project presented itself as a phpbb conversion. The client was having some issues with the old versions of phpbb so we elected to move them to the new version. While this is a great idea on the surface I did not realize how big the database was. I started out doing an export using phpMyAdmin not knowing the file sizes I was dealing with. When that failed I decided to do a mysqldump from the shell. Imagine the look of shock and dumbfoundedness on my face when I finished the dump to discover a 300 meg + sql file.

Why is this a problem? Well most ISPs have upload limits usually under 20meg for import uploads using phpMyAdmin. My default install of Xampp limit is 16 meg. I decided to try to gzip the file with a 100meg + result. At least now I could download the file to my local machine to try to figure out what to do.

First Trial PhpMyAdmin Local File upload

I edited my php.ini files and change the file_upload, and max_execution time to try and enable a way to upload the file.

  1. max_execution_time = 560
  2. max_input_time = 160
  3. memory_limit = 60M
  4. upload_max_filesize = 160M

After an hour of battling the settings to try and get one that would work, I had to read some phpMyadmin documentation and see if I could find a solution.

PhpMyAdmin Config Change
My first config setting change was a nice config setting called $cfg['UploadDir']. With this option set to a local server folder, you can select a direct data upload from a local drive. When you open phpMyAdmin it will give you a list of files to select from in the folder. You can then select the file and it will perform a direct import of the larger than limit sql file. However, this still didn't solve the timeout problems with a 100meg sql file. I had to look further.

SQL file splitter

After kicking around some work a rounds, I realized the only way to beat this, was to split the file into parts. I can either do this by hand, or find a solution.

Google is a wonderful tool for finding things and it didn't let me down this time either.

I found a blog the outlined exactly what I was looking for: Sql file splitter From reviewing his blog It appeared he had the exact same issues I had. The solution was a program called SQLDumpSplitter 2, by Philip Lehmann-Böhm (http://www.philiplb.de). The main links on the blog no longer worked, but a dutch website had left a blog comment with a direct link to the file. You can download from here: Sqldumpsplitter2 Hopefully that file link will stick around for a while.

I split the 300 meg file into 23 16-meg chunks. This worked very well, I was able to import the large 300 meg file, but it still took baby sitting and remembering what the last file I used was. In fact I spent several hours importing and then still experienced some time out issues.

I then decided to see if I could find another solution, so it was back to google.

php mysql large file importer

was the keyword search I did. What I found was this blog: How to import large mysql data files. This WAS the solution to all my problems!!! In this blog, there was a link to a site and a program called Bigdump.

Bigdump is a staggered mysql dump importer. What this means, is you start the file, and it will automatically import the large file till it is complete. That means, no file splitting. It is truly an amazing piece of 10K of code.

To import a large file you perform the following steps:

  1. 1 - Copy bigdump.php to the website where you want to import the file.
  2. 2 - If the file size is larger that the upload limit of the server, copy the
  3. file to the same foldere.
  4. 3 - Edit the bigdump.php file, set the database name, the username and password.
  5. 4 - If the file size is larger than the limit, enter the filename into the
  6. "filename" field.
  7. 5 - Execute the bigdump file by going to http://yourdomainlocation/bigdump.com
  8. 6 - Wait for the import to complete and be prepared for the shock and awe.

For my test I used the uncompressed 300 meg sql file. The documentation states, you can use the gzipped version also. It took approx 15 minutes or less, to import that file with the bigdump program. I still am amazed. Had I found this earlier today, this blog may not actually exist.

Hurrah for Bigdump!!!! I gladly sent a paypal donation for this code! It saved my life.

I hope that the users that are looking for a sql splitter will find this blog and save themselves the initial headaches I had.

 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 
formats

Palm Centro, my new phone

Published on May 19, 2008 by in Electronics

WOOT!! I got a new phone! Only reason I did, was I broke my Treo 650 a second time. Same issue, I managed to short out the headphone jack. I don't know why they bother to put them on, if they don't give them more industrial strength. I checked with AT&T online and found I was eligible for a new phone.

Smart Phone Choices have grown with leap and bounds. The top ones are Iphone, Blackberry, Treo just to name a few. I really thought I might wait for a cheaper version of the Iphone, but I've been a Palm person for years, that and right now the Iphone is about $200 more than I wanted to spend.

After a little research I decided to go with the Palm Centro, most of the reviews compared it to the Treo 680, and since I was just leaving a 650 it sounded like the most economical choice. The Phone with a new contract is $199, but you can get a $100 rebate if you get it with a data plan. At $99 its gotta be one of the cheapest choices of smart phones on the market.

The Palm Centro is by far the smallest smart phone that I have seen. Its an amazing difference in size to my Treo 650. As you can see in the picture. It reminds me of my first small nokia phone, I can more easily put it in a shirt or pants pocket where with the treo, it was just very bulky.

One of the selling points for me was it has an optional micro SD port. Now I can move all the data, and media from my old phones SD fairly easily to the new phone. The pricing of SD and micro-SD has dropped significatly from when I bought my last 1gig. I had paid near a hundred dollars about 2 years ago. I found a 4gig micro SD for $27 shipped this more than compensated for the fact I had to buy a micro instead of a regular SD ram. I love ever changing technology. Makes my toys MUCH cheaper.

The Keyboard
While the keys are closer together, they actually still very easy to get to, either that or I have just gotten better at typing on small keyboards. One cool difference is they added a menu button. On the treo there wasn't one, and it was rather annoying when the app wouldn't let you easily get to the menus. I can quickly type and get to menu functions even one-handed.

Minor Issues
One of the few issues I have had is I could not get the SMS messages to work with my Agendus Mail. Not a real big deal, just couldn't figure out where my SMS messages were going when I received them. Once I removed and reinstalled Agendus Mail without the SMS option it fixed the problem.

The Camera
The camera has been upgraded to a 1.3 MP camera, pictures are fantastic compared to the Treo 640.

Data Package
Due to the discount requirements I had to buy the data package. My issues with it right now is I have a hard time paying $30/month for unlimited internet when its as slow as it is. Hopefully the speed will be taken care of over time, but when your spoiled with 10 MB Cable speeds, its hard to deal with at times. The Web browser works fairly well, I can use most of the google mobile web applications with very little problems. The built in IM software is currently working off and on I am unsure if thats due to the network or the software.

Overall I absolutely love the phone. It is light weight, small and fits in my pocket easily. Works better than my treo 650. Half the time, no one even knows its a smart phone. In the world where some think bigger is better this small phone is incredible for the price.

 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 
formats

PHP day count and date comparison

Published on May 13, 2008 by in PHP

Dealing with date based data can be a mind numbing experience. Calculation date differences, doing date comparisons can really stretch you to the limits at times. There is a variety of ways to deal with date based data but the first step usually is to convert it into a standard format that you can easily deal with. That format is the unix timestamp.

The unix time stamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970. Therefore, the unix time stamp is merely the number of seconds between a particular date and the Unix Epoch.

Below is a code snippet for creating a timestamp from formatted date data. For this example the date_in variable contains a date in the format of YYYY-MM-DD and is passed from a previously executed form post.

  1. $datearray=explode("-",$_POST['date_in']);
  2. $year=$datearray[0];
  3. $month=$datearray[1];
  4. $day=$datearray[2];
  5. $mytimestamp=mktime(0,0,0,$month,$day$year);

Recently I discovered an easier way to get a date converted to a timestamp. This just goes to show you that a programmer is always learning. There will always be functions that are overlooked and underused.

strtotime() function this function will take an english based date format and convert it to timestamp. The code below illustrates how much easier this is.

  1. $mytimestamp=strtotime($_POST['date_in']);

One line of code! No exploding parts, just a quick and easy solution.

Calculate Number of days

Now that timestamps have been reviewed to show you some easy way to take two days and return a total number of days. The example below will take an arbitrary date of April 4, 2008 and May 12, 2008 (the current date I wrote the article)

  1. $time_A = strtotime("April 4, 2008");
  2. $time_B=strtotime(now);
  3. $numdays=intval(($time_B-$time_A)/86400)+1;

The number of seconds in a day is 86400 and the calculations usually shorts you a day so thats why we add a 1. This is do the fact the now() returns the current time which is not a complete day.

Another example of using date comparisons is expiring accounts in a database. If you can let the database do the work for you, DO IT, as anytime you can save code calculations the easier it is on you. This code will take the current date and compare it to the user_expdate and delete those records that are less than or equal to 0.

  1. $current_date=date("Y-m-d G:i:s");
  2.  
  3. $query="delete from {$db_prefix}users where user_expdate!='0000-00-00
  4. 00:00:00' and datediff(user_expdate,'".$current_date."')<= 0 ";
  5. if (!$result=$db->execute($query)){
  6. $db->ErrorMsg();
  7. }

Date comparisons

Date comparisons are now simple a matter of comparing the timestamps. Given 2 timestamps you can compare them and know very simply which is greater. Note: in the example below we forced the today variable to midnight so only days before the two timestamps are selected.

  1. $today=strtotime(date("Y-m-d")." 00:00:00");
  2. $datecheck = strtotime($year."-".$month."-".$day);
  3. if ($datecheck < $today){
  4. //find all dates before today and block them out
  5. }

Date comparisons in mysql can be done similarly. However mysql give a variety of date tools to work with as you are calculating dates.

The following code snipplet shows a way to delete code based on a timestamp comparison. Note: The code uses ADODB Lite calls. The $db->qstr function add's the appropriate quote code.

  1. $today=strtotime(date("Y-m-d")." 00:00:00");
  2.  
  3. $query="delete from {$db_prefix}users where user_expdate!='0000-00-00
  4. 00:00:00' and timestamp(user_expdate) < ".$db->qstr($today) ";
  5. if (!$result=$db->execute($query)){
  6. $db->ErrorMsg();
  7. }
  8.  

While these are some basic ways to do this, there are many other ways. I always welcome comments, feel free to add your own two cents.

Just make sure you register as No Spammers are allowed.

 
Tags:
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 
© Brainstorms of a Webdev
credit