Find number of weekdays (Mon, Tues etc) between two dates

Posted by deepak on in PHP

<?php
function workingDays( $fromDate, $interval )  {
$date_array = explode(‘-’, $fromDate );
$day         = $date_array[0];
$month         = $date_array[1];
$year         = $date_array[2];
$working_date = array();

for ( $i = 1;  $i <= $interval; $i++ )               {
$working_date[] = date(“l”, mktime(0, 0, 0,$month,$day +(int)$i,$year));

}

return $working_date;

}

$getDays = workingDays(’30-11-2011′, 30 );
str_replace(array(‘Friday’),array(‘Friday’) ,$getDays, $dupweekDays); // trick to check the occurrence of  week days
echo $dupweekDays;
?>

Explanation of the above code:

$getWorkingDays = workingDays(’30-11-2011′, 30 );

W call the workingDays  function  it accept two prams a) the start date 2) the number of days between to dates

This function will return the name of weekdays i.e Monday, Tuesday,Wednesday , Thursday , Friday  , Saturday , Sunday

——————————————————————————————————————————————————————————————————————-Below is str_replace(array(‘Friday’) , array(‘Friday’) ,$getDays, $dupweekDays); // trick to check the occurrence of  week days
echo $dupweekDays;

the login to find the repeating  days  so we we need to find number of Mondays  then we need to replace the first and second  parameter  of str_replace function  with array(‘Monday’)

The $dupweekDays  will the variable having the count of repeating Mondays

 

Facebook Connect (Graph API) in cake php

Posted by deepak on in Cakephp

To implement Facebook  connect using graph API  you need to follow the steps

1) Extract the  facebook_core_files.zip file and put all of them in vendors folder of cake php

2)  In your apps controller include this code at the top of the file App::import(‘Vendor’, ‘facebook’, array(‘file’ => ‘facebook.php’));

3)  in your apps controller  add this function ( before filter )

function beforeFilter()
{
//facebook application
$user            = null; //facebook user uid
$userInfo        = null;

// Create our Application instance.
$facebook = new Facebook(array(
‘appId’  => YOURAPPID,
‘secret’ => YOURSECRET
));

//Facebook Authentication part
$user       = $facebook->getUser();

if ($user) {
try {
// Proceed knowing you have a logged in user who’s authenticated.
$fql    =   “select name,current_location,email,sex,verified,pic_square from user where uid=” . $user;
$param  =   array(
‘method’    => ‘fql.query’,
‘query’     => $fql,
‘callback’  => ”
);

$userInfo   =   $facebook->api($param);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
}

$userInfo  variable will  contain list of data returned by facebook .

In your BODY of HTML page put the below code

<div id=”fb-root”></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: ‘APPID’,
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe(‘auth.login’, function(response) {
window.location.href = ‘/users/facebookLogged’;
});
FB.Event.subscribe(‘auth.logout’, function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement(‘script’); e.async = true;
e.src = document.location.protocol +
‘//connect.facebook.net/en_US/all.js’;
document.getElementById(‘fb-root’).appendChild(e);
}());
</script>
<fb:login-button autologoutlink=”true” scope=”email,user_birthday,status_update,publish_stream,user_location,offline_access”></fb:login-button>

 

Cakephp not working on Ubuntu – Error 404 not found

Posted by Sukhwant on in Cakephp, Ubuntu (Linux)

If you are facing problems with Cakephp not working on Ubuntu after all googling and doing all other things, please try this one:

Open Places->Computer->File System->etc->apache2->sites-available

In this folder open file name ‘default

In this file search for

<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride none
Order allow,deny
allow from all
</Directory>

and replace it with

<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all
</Directory>

You will find your cakephp working very fine now.

Hope this will help.

Thanks

 

Using Internet data card like Tata photon on Ubuntu

Posted by Sukhwant on in Ubuntu (Linux)

If you are having problems with using any kind of INTERNET data card like Tata photon or else, then please follow as described below:

Please install usb-modeswitch on your systems regarding usage of Tata photon when required.

Please follow the steps for installation:

1. Open System->Administration->Synaptic Package manager.
2. Search for usb-modeswitch and install it.
3. Now open Applications->Accessories->Terminal. Type sudo gedit /etc/usb_modeswitch.d/12d1:1446
- In the line TargetProductList, add 140b. Save and Close.

Hope this will help you resolving the problem.

Thanks

 

CakePHP not working – cake.generic.css not found in Ubuntu

Posted by paraselixir on in Bug Tracker

If you have done all the things right in installation of cakephp on Ubuntu system as per specified in various sites and have made changes in apaches settings  but still cakephp is not working on Ubuntu then try uncommenting the

Configure::write(‘App.baseUrl’, env(‘SCRIPT_NAME’));

line in core.php of cakephp installation.

 

Overcome XSS scripting or cross site scripting

Posted by behnish on in PHP

Just paste this code in a header file which is included in the site. You can exclude the fields like description while filtering the POST And GET.


foreach ($_GET as $key => $value) {
$_GET[$key] = strip_tags($value);
}

foreach ($_POST as $key => $value) {
$_POST[$key] = strip_tags($value);
}

foreach ($_SERVER as $key => $value) {
$_SERVER[$key] = strip_tags($value);
}
 
 

TFS 2010 Build Service

Posted by Ravneet Arora on in Version Control

We often get the following message after configuring the TFS 2010 Build Service.

The agent status has been automatically changed by the TFS Server.

Reason: There was no endpoint listening at…http:///Build/v3.0/services/Controller that could accept the message. This is often caused by an incorrect address or SOAP action.

Cause: This is caused because of Team Foundation Server’s hostname is not resolved sometimes, or your machine cannot connect to TFS.

Solution:
Follow the below simple steps

  1. Delete all agents defined from the machine by going to Team Foundation Server Console.
  2. Delete all Build Controllers from the machine.
  3. Unregister the Build Service.
  4. Restart the machine. This is required; TFS services Port 9191 will be reset.
  5. Register the service again, Add the TFS URL http://abc:port/tfs
  6. Select the Collection and connect to TFS
  7. Create the Build Controller; make sure to enter the IP address of the machine where you want to run the Build.
  8. Now click “Test Connection”. This will bring your Controller status to Ready.
  9. Create the Agent and associate with the same Controller created at point 8.

This resolves the problem.

 

Make your business funtional with “on page seo”

Posted by Navneet Kumar on in SEO

What is SEO?

Search engine optimization (Seo) a word optimization define the “functional as possible” seo a web marketing strategy help to promote your business products by using different planning policies and make your product functional by achieving high rank in search engine result.

On page Seo

“On page” seo means the functional information on your site which crawler and user can easily rip up.

Foremost for on page.

1. Title tag

As it display in the top bar of browser so it play a vital role for achieving high rank it is cardinal that title must contain HTML tag.

General rules for Title tag:

  • Up to 100 characters and max 3 keywords
  • Use primary keyword in the beginning of title than secondary
  • Don’t repeat keywords again n again to avoid spam/caps

<title>abc company, primary keyword, secondary keyword</title>

2. Meta description

Communicate your site content with numerous keywords in description which make your site spider responsive.

  • Up to 255 characters and
  • Maximum 3-4 keywords
  • Content must be in logical sentence
  • Avoid grammatical mistakes

3.  Meta keywords

Meta keyword provides you right to add some serviceable text for spider to do indexing from your site page.

<meta “keywords” content = “keywords, relevant to site, separated by, coma ‘,’ pipeline ‘|’ ”>

  • Up to 1000 characters and 45 words
  • Primary k1, secondary k2, ……….
  • Keyword must be relevant to your site
  • Use adwords.google to select keyword

4. Body content

It is a fact that “Content is king” in seo which help your site to get top position in search engines and users also. Content is data which users actually looking for when come to your site

  • Content must be fresh and confine
  • Provide the information which help users
  • Use keywords in content which help spider to indexing from your site.
  • Bold or Italic the content which is more useful
  • Avoid duplicate content it will make your site spam

5. Extra visuals

Search engine not read images, flash, scripting language so to make our image or flash crawler friendly we use html tags which define what the information all about to describe these functions we use “<alt tag>”

<img src=“abc.jpg” alt=“A picture of abc define what image rectify/>.

 

Color Picker – jQuery plugin

Posted by Rajinder on in JQuery

About

A simple component to select color in the same way you select color in Adobe Photoshop

Features

  • Flat mode – as element in page
  • Powerful controls for color selection
  • Easy to customize the look by changing some images
  • Fits into the viewport

Examples

Flat mode.

$('#colorpickerHolder').ColorPicker({flat: true});
                

Custom skin and using flat mode to display the color picker in a custom widget.

Attached to an text field and using callback functions to update the color with field’s value and set the value back in the field by submiting the color.

$('#colorpickerField1, #colorpickerField2, #colorpickerField3').ColorPicker({
	onSubmit: function(hsb, hex, rgb, el) {
		$(el).val(hex);
		$(el).ColorPickerHide();
	},
	onBeforeShow: function () {
		$(this).ColorPickerSetColor(this.value);
	}
})
.bind('keyup', function(){
	$(this).ColorPickerSetColor(this.value);
});

Attached to DOMElement and using callbacks to live preview the color and adding animation.

$('#colorSelector').ColorPicker({
	color: '#0000ff',
	onShow: function (colpkr) {
		$(colpkr).fadeIn(500);
		return false;
	},
	onHide: function (colpkr) {
		$(colpkr).fadeOut(500);
		return false;
	},
	onChange: function (hsb, hex, rgb) {
		$('#colorSelector div').css('backgroundColor', '#' + hex);
	}
});

Download

colorpicker.zip (89 kb): jQuery, Javscript files, CSS files, images, examples and instructions.

 

Cakephp – Logable behaviour

Posted by Sukhwant on in Cakephp

LogableBehavior

This behavior is created to easily let you (the developer) log users activities that relates to database modifications (ie, add, edit and delete). If you just want to see what your users are doing or need to be able to say “That is not a bug, I can see from my log that you deleted the post yesterday.” and don’t want to spend more time that it takes to do “var $actsAs = array(‘Logable’);” then this behavior is for you.

What

The intent of this behavior is to create a row in a log table every time a model’s data (or all the model that the behavior is applied to) is created, edited or deleted. The developer can set this log table up to include as much detail as is required, and that is all the configuration that is needed.

How
Requirements:

  1. The behavior found below in this Article.
  2. A Log model( empty but for a order variable [created DESC]
  3. actsAs = array(“Logable”); on models that should be logged:
  4. A “logs” table with these fields required :
  • id (int)
  • title (string) automagically filled with the display field of the model that was modified.
  • created (date/datetime) filled by cake in normal way

Supply configuration to the Model Class. Below is the Example:

<?php
class Apple extends AppModel {
var $name = 'Apple';
var $actsAs = array('Logable' => array(
'userModel' => 'User',
'userKey' => 'user_id',
'change' => 'list', // options are 'list' or 'full'
'description_ids' => TRUE // options are TRUE or FALSE
));
[..]
?>

The change fields modifies what will be automagic filled in the change field if the log table has it.

Usage

If you are using the user feature of the behavior, the models needs to know the id of the active user. This is most easily set in app controller in this way, but note that you may use the Logable::setUserData() method manually should you so desire.
Controller Class:


<?php
// In AppController (or single controller if only needed once) add these lines to beforeFilter :
if (sizeof($this->uses) && $this->{$this->modelClass}->Behaviors->attached('Logable')) {
$this->{$this->modelClass}->setUserData($this->activeUser);
}
?>

Where “$activeUser” should be an array in the standard format for the User model used.

Get the logs out

To extract the logs, no matter of you want all events, or just for one model or one user, or even one user’s activity on one model, you can ask any model that the behavior is enabled on. There are two methods:

  • findLog($params)
  • findUserActions($user_id, $params)

You can off course query the Log model in the normal way.

findLog

This is the main function for retrieving the logged activities. It will by default (when called with no parameters) return all activities for the model it is called from, but it can also be used for any or all models from any model. The available options are listed bellow.

  • model (string)
  • action (string) (add/edit/delte) defaults to NULL (ie. all)
  • fields (array)
  • order (string) defaults to ‘created DESC’
  • conditions (array) add custom conditions
  • model_id (int) ForeignKey for a single instance of logged model
  • user_id (int) defaults to NULL (all users).

Remember to user your own foreignKey if you did not use ‘user_id’


<?php // examples
// All acitivities on current model
$data = $this->Apple->findLog();
// All acitivities on current model instance
$data = $this->Apple->findLog('model_id'=>32);
// I am in apple controller, but i want acitivities for the user on a specific Logo isntance
$data = $this->Apple->findLog(array('user_id'=>66,'model'=>'Logo','model_id'=>123));
?>

findUserActions

The first parameter is compulsory and is the ID of the user (foreignKey). The second is an array of options. The available options are listed bellow. Model and fields does the expected things, while events will create a description on the fly. This function is intended to be improved in the next version to be translatable / customizable.

  • model (string)
  • [li]events (boolean)
  • [li]fields (array)


<?php // examples
// note we are asking for a different model
$data = $this->User->findUserActions(301,array('model' => 'BookTest'));
$data = $this->Apple->findUserActions(301,array('events' => true));
$data = $this->Model->findUserActions(301,array('fields' => array('id','model'),'model' => 'BookTest');
?>

You can download the newest version, including tests, here :

http://code.google.com/p/alkemann/downloads/list
Or you can grab version 1.3 here

Behavior Class:


<?php
class LogableBehavior extends ModelBehavior
{
var $user = NULL;
var $UserModel = FALSE;
function setup(&$Model, $config = null) {
$this->settings = array(
'userModel' => 'User',
'userKey' => 'user_id',
'change' => 'list',
'description_ids' => TRUE
);
if ($config) {
$this->settings = array_merge($this->settings, $config);
}

App::import('model','Log');
$this->Log = new Log();
if ($this->settings['userModel'] != $Model->alias) {
if (App::import('model',$this->settings['userModel'])) {
$this->UserModel = new $this->settings['userModel']();
}
} else {
$this->UserModel = $Model;
}

}

function settings(&$Model) {
return $this->settings;
}

function findLog(&$Model, $params = array()) {
$defaults = array(
'model' => NULL,
'action' => NULL,
'order' => 'created DESC',
$this->settings['userKey'] => NULL,
'conditions' => array(),
'model_id' => NULL,
'fields' => array(),
);
$params = array_merge($defaults, $params);
$options = array('order' => $params['order'], 'conditions' => $params['conditions'], 'fields' => $params['fields']);
if ($params['model'] === NULL) {
$params['model'] = $Model->alias;
}
if ($params['model']) {
if (isset($this->Log->_schema['model'])) {
$options['conditions']['model'] = $params['model'];
} elseif (isset($this->Log->_schema['description'])) {
$options['conditions']['description LIKE '] = $params['model'].'%';
} else {
return FALSE;
}
}
if ($params['action'] && isset($this->Log->_schema['action'])) {
$options['conditions']['action'] = $params['action'];
}
if ($params[ $this->settings['userKey'] ] && $this->UserModel && is_numeric($params[ $this->settings['userKey'] ])) {
$options['conditions'][$this->settings['userKey']] = $params[ $this->settings['userKey'] ];
}
if ($params['model_id'] && is_numeric($params['model_id'])) {
$options['conditions']['model_id'] = $params['model_id'];
}
return $this->Log->find('all',$options);
}

function findUserActions(&$Model, $user_id, $params = array()) {
if (!$this->UserModel) {
return NULL;
}
// if logged in user is asking for her own log, use the data we allready have
if ( isset($this->user)
&& isset($this->user[$this->UserModel->alias][$this->UserModel->primaryKey])
&& $user_id == $this->user[$this->UserModel->alias][$this->UserModel->primaryKey]
&& isset($this->user[$this->UserModel->alias][$this->UserModel->displayField]) ) {
$username = $this->user[$this->UserModel->alias][$this->UserModel->displayField];
} else {
$this->UserModel->recursive = -1;
$user = $this->UserModel->find(array($this->UserModel->primaryKey => $user_id));
$username = $user[$this->UserModel->alias][$this->UserModel->displayField];
}
$fields = array();
if (isset($params['fields'])) {
if (is_array($params['fields'])) {
$fields = $params['fields'];
} else {
$fields = array($params['fields']);
}
}
$conditions = array($this->settings['userKey'] => $user_id);
if (isset($params['model'])) {
$conditions['model'] = $params['model'];
}
$data = $this->Log->find('all', array(
'conditions' => $conditions,
'recursive' => -1,
'fields' => $fields
));
if (! isset($params['events']) || (isset($params['events']) && $params['events'] == false)) {
return $data;
}
$result = array();
foreach ($data as $key => $row) {$one = $row['Log'];
$result[$key]['Log']['id'] = $one['id'];
$result[$key]['Log']['event'] = $username;
// have all the detail models and change as list :
if (isset($one['model']) && isset($one['action']) && isset($one['change']) && isset($one['model_id'])) {
if ($one['action'] == 'edit') {
$result[$key]['Log']['event'] .= ' edited '.$one['change'].' of '.low($one['model']).'(id '.$one['model_id'].')';
//    ' at '.$one['created'];
} elseif ($one['action'] == 'add') {
$result[$key]['Log']['event'] .= ' added a '.low($one['model']).'(id '.$one['model_id'].')';
} elseif ($one['action'] == 'delete') {
$result[$key]['Log']['event'] .= ' deleted the '.low($one['model']).'(id '.$one['model_id'].')';
}

} elseif ( isset($one['model']) && isset($one['action'])  && isset($one['model_id']) ) { // have model,model_id and action
if ($one['action'] == 'edit') {
$result[$key]['Log']['event'] .= ' edited '.low($one['model']).'(id '.$one['model_id'].')';
//    ' at '.$one['created'];
} elseif ($one['action'] == 'add') {
$result[$key]['Log']['event'] .= ' added a '.low($one['model']).'(id '.$one['model_id'].')';
} elseif ($one['action'] == 'delete') {
$result[$key]['Log']['event'] .= ' deleted the '.low($one['model']).'(id '.$one['model_id'].')';
}
} else { // only description field exist
$result[$key]['Log']['event'] = $one['description'];
}

}
return $result;
}

function setUserData(&$Model, $userData = null) {
if ($userData) {
$this->user = $userData;
}
}

function clearUserData(&$Model) {
$this->user = NULL;
}

function beforeDelete(&$Model) {
$Model->recursive = -1;
$Model->read();
}

function afterDelete(&$Model) {
$logData = array();
if (isset($this->Log->_schema['description'])) {
$logData['Log']['description'] = $Model->alias;
if (isset($Model->data[$Model->alias][$Model->displayField]) && $Model->displayField != $Model->primaryKey) {
$logData['Log']['description'] .= ' "'.$Model->data[$Model->alias][$Model->displayField].'"';
}
if ($this->settings['description_ids']) {
$logData['Log']['description'] .= ' ('.$Model->id.') ';
}
$logData['Log']['description'] .= __('deleted',TRUE);
}
$logData['Log']['action'] = 'delete';
$this->_saveLog($Model, $logData);
}

function beforeSave(&$Model) {
if (isset($this->Log->_schema['change']) && $Model->id) {
$Model->recursive = -1;
$this->old = $Model->find(array($Model->primaryKey => $Model->id));
}
}

function afterSave(&$Model,$created) {
if ($Model->id) {
$id = $Model->id;
} elseif ($Model->insertId) {
$id = $Model->insertId;
}
if (isset($this->Log->_schema['model_id'])) {
$logData['Log']['model_id'] = $id;
}
if (isset($this->Log->_schema['description'])) {
$logData['Log']['description'] = $Model->alias;
if (isset($Model->data[$Model->alias][$Model->displayField]) && $Model->displayField != $Model->primaryKey) {
$logData['Log']['description'] .= ' "'.$Model->data[$Model->alias][$Model->displayField].'"';
}

if ($this->settings['description_ids']) {
$logData['Log']['description'] .= ' ('.$id.') ';
}

if ($created) {
$logData['Log']['description'] .= __('added',TRUE);
} else {
$logData['Log']['description'] .= __('updated',TRUE);
}
}
if (isset($this->Log->_schema['action'])) {
if ($created) {
$logData['Log']['action'] = 'add';
} else {
$logData['Log']['action'] = 'edit';
}

}

if (isset($this->Log->_schema['change'])) {
$logData['Log']['change'] = '';
foreach ($Model->data[$Model->alias] as $key => $value) {
if (isset($Model->data[$Model->alias][$Model->primaryKey]) && !empty($this->old)) {
$old = $this->old[$Model->alias][$key];
} else {
$old = '';
}
if ($key != 'modified' && $value != $old) {
if ($this->settings['change'] == 'full') {
$logData['Log']['change'] .= $key . ' ('.$old.') => ('.$value.'), ';
} else {
$logData['Log']['change'] .= $key . ', ';
}
}
}
if (strlen($logData['Log']['change'])) {
$logData['Log']['change'] = substr($logData['Log']['change'],0,-2);
} else {
return true;
}
}
$this->_saveLog($Model, $logData);
}

function _saveLog(&$Model, $logData) {
if (isset($Model->data[$Model->alias][$Model->displayField]) && $Model->displayField != $Model->primaryKey) {
$logData['Log']['title'] = $Model->data[$Model->alias][$Model->displayField];
} else {
if ($Model->id) {
$id = $Model->id;
} elseif (isset($Model->data[$Model->alias][$Model->primaryKey])) {
$id = $Model->data[$Model->alias][$Model->primaryKey];
} else {
$id = 'MISSING';
}
$logData['Log']['title'] = $Model->alias.' ('.$id.')';
}

if (isset($this->Log->_schema['model'])) {
$logData['Log']['model'] = $Model->alias;
}

if (isset($this->Log->_schema['model_id'])) {
if ($Model->id) {
$logData['Log']['model_id'] = $Model->id;
} elseif ($Model->insertId) {
$logData['Log']['model_id'] = $Model->insertId;
}
}

if (!isset($this->Log->_schema[ 'action' ])) {
unset($logData['Log']['action']);
}

if (isset($this->Log->_schema[ $this->settings['userKey'] ]) && $this->user) {
$logData['Log'][$this->settings['userKey']] = $this->user[$this->UserModel->alias][$this->UserModel->primaryKey];
}

if (isset($this->Log->_schema['description'])) {
if ($this->user && $this->UserModel) {
$logData['Log']['description'] .= ' by '.$this->settings['userModel'].' "'.
$this->user[$this->UserModel->alias][$this->UserModel->displayField].'"';
if ($this->settings['description_ids']) {
$logData['Log']['description'] .= ' ('.$this->user[$this->UserModel->alias][$this->UserModel->primaryKey].')';
}

} else {
// UserModel is active, but the data hasnt been set. Assume system action.
$logData['Log']['description'] .= ' by System';
}
$logData['Log']['description'] .= '.';
}

$this->Log->create($logData);
$this->Log->save(NULL,FALSE);
}
}
?>
</code>

I hope this will help .... thank you...!

<code>
<?php
/**
* Logs saves and deletes of any model
*
*/

class LogableBehavior extends ModelBehavior
{
var $user = NULL;
var $UserModel = FALSE;
function setup(&$Model, $config = null) {
$this->settings = array(
'userModel' => 'User',
'userKey' => 'user_id',
'change' => 'list',
'description_ids' => TRUE
);
if ($config) {
$this->settings = array_merge($this->settings, $config);
}

App::import('model','Log');
$this->Log = new Log();
if ($this->settings['userModel'] != $Model->alias) {
if (App::import('model',$this->settings['userModel'])) {
$this->UserModel = new $this->settings['userModel']();
}
} else {
$this->UserModel = $Model;
}

}

function settings(&$Model) {
return $this->settings;
}

function findLog(&$Model, $params = array()) {
$defaults = array(
'model' => NULL,
'action' => NULL,
'order' => 'created DESC',
$this->settings['userKey'] => NULL,
'conditions' => array(),
'model_id' => NULL,
'fields' => array(),
);
$params = array_merge($defaults, $params);
$options = array('order' => $params['order'], 'conditions' => $params['conditions'], 'fields' => $params['fields']);
if ($params['model'] === NULL) {
$params['model'] = $Model->alias;
}
if ($params['model']) {
if (isset($this->Log->_schema['model'])) {
$options['conditions']['model'] = $params['model'];
} elseif (isset($this->Log->_schema['description'])) {
$options['conditions']['description LIKE '] = $params['model'].'%';
} else {
return FALSE;
}
}
if ($params['action'] && isset($this->Log->_schema['action'])) {
$options['conditions']['action'] = $params['action'];
}
if ($params[ $this->settings['userKey'] ] && $this->UserModel && is_numeric($params[ $this->settings['userKey'] ])) {
$options['conditions'][$this->settings['userKey']] = $params[ $this->settings['userKey'] ];
}
if ($params['model_id'] && is_numeric($params['model_id'])) {
$options['conditions']['model_id'] = $params['model_id'];
}
return $this->Log->find('all',$options);
}

function findUserActions(&$Model, $user_id, $params = array()) {
if (!$this->UserModel) {
return NULL;
}
// if logged in user is asking for her own log, use the data we allready have
if ( isset($this->user)
&& isset($this->user[$this->UserModel->alias][$this->UserModel->primaryKey])
&& $user_id == $this->user[$this->UserModel->alias][$this->UserModel->primaryKey]
&& isset($this->user[$this->UserModel->alias][$this->UserModel->displayField]) ) {
$username = $this->user[$this->UserModel->alias][$this->UserModel->displayField];
} else {
$this->UserModel->recursive = -1;
$user = $this->UserModel->find(array($this->UserModel->primaryKey => $user_id));
$username = $user[$this->UserModel->alias][$this->UserModel->displayField];
}
$fields = array();
if (isset($params['fields'])) {
if (is_array($params['fields'])) {
$fields = $params['fields'];
} else {
$fields = array($params['fields']);
}
}
$conditions = array($this->settings['userKey'] => $user_id);
if (isset($params['model'])) {
$conditions['model'] = $params['model'];
}
$data = $this->Log->find('all', array(
'conditions' => $conditions,
'recursive' => -1,
'fields' => $fields
));
if (! isset($params['events']) || (isset($params['events']) && $params['events'] == false)) {
return $data;
}
$result = array();
foreach ($data as $key => $row) {$one = $row['Log'];
$result[$key]['Log']['id'] = $one['id'];
$result[$key]['Log']['event'] = $username;
// have all the detail models and change as list :
if (isset($one['model']) && isset($one['action']) && isset($one['change']) && isset($one['model_id'])) {
if ($one['action'] == 'edit') {
$result[$key]['Log']['event'] .= ' edited '.$one['change'].' of '.low($one['model']).'(id '.$one['model_id'].')';
//    ' at '.$one['created'];
} elseif ($one['action'] == 'add') {
$result[$key]['Log']['event'] .= ' added a '.low($one['model']).'(id '.$one['model_id'].')';
} elseif ($one['action'] == 'delete') {
$result[$key]['Log']['event'] .= ' deleted the '.low($one['model']).'(id '.$one['model_id'].')';
}

} elseif ( isset($one['model']) && isset($one['action'])  && isset($one['model_id']) ) { // have model,model_id and action
if ($one['action'] == 'edit') {
$result[$key]['Log']['event'] .= ' edited '.low($one['model']).'(id '.$one['model_id'].')';
//    ' at '.$one['created'];
} elseif ($one['action'] == 'add') {
$result[$key]['Log']['event'] .= ' added a '.low($one['model']).'(id '.$one['model_id'].')';
} elseif ($one['action'] == 'delete') {
$result[$key]['Log']['event'] .= ' deleted the '.low($one['model']).'(id '.$one['model_id'].')';
}
} else { // only description field exist
$result[$key]['Log']['event'] = $one['description'];
}

}
return $result;
}

function setUserData(&$Model, $userData = null) {
if ($userData) {
$this->user = $userData;
}
}

function clearUserData(&$Model) {
$this->user = NULL;
}

function beforeDelete(&$Model) {
$Model->recursive = -1;
$Model->read();
}

function afterDelete(&$Model) {
$logData = array();
if (isset($this->Log->_schema['description'])) {
$logData['Log']['description'] = $Model->alias;
if (isset($Model->data[$Model->alias][$Model->displayField]) && $Model->displayField != $Model->primaryKey) {
$logData['Log']['description'] .= ' "'.$Model->data[$Model->alias][$Model->displayField].'"';
}
if ($this->settings['description_ids']) {
$logData['Log']['description'] .= ' ('.$Model->id.') ';
}
$logData['Log']['description'] .= __('deleted',TRUE);
}
$logData['Log']['action'] = 'delete';
$this->_saveLog($Model, $logData);
}

function beforeSave(&$Model) {
if (isset($this->Log->_schema['change']) && $Model->id) {
$Model->recursive = -1;
$this->old = $Model->find(array($Model->primaryKey => $Model->id));
}
}

function afterSave(&$Model,$created) {
if ($Model->id) {
$id = $Model->id;
} elseif ($Model->insertId) {
$id = $Model->insertId;
}
if (isset($this->Log->_schema['model_id'])) {
$logData['Log']['model_id'] = $id;
}
if (isset($this->Log->_schema['description'])) {
$logData['Log']['description'] = $Model->alias;
if (isset($Model->data[$Model->alias][$Model->displayField]) && $Model->displayField != $Model->primaryKey) {
$logData['Log']['description'] .= ' "'.$Model->data[$Model->alias][$Model->displayField].'"';
}

if ($this->settings['description_ids']) {
$logData['Log']['description'] .= ' ('.$id.') ';
}

if ($created) {
$logData['Log']['description'] .= __('added',TRUE);
} else {
$logData['Log']['description'] .= __('updated',TRUE);
}
}
if (isset($this->Log->_schema['action'])) {
if ($created) {
$logData['Log']['action'] = 'add';
} else {
$logData['Log']['action'] = 'edit';
}

}

if (isset($this->Log->_schema['change'])) {
$logData['Log']['change'] = '';
foreach ($Model->data[$Model->alias] as $key => $value) {
if (isset($Model->data[$Model->alias][$Model->primaryKey]) && !empty($this->old)) {
$old = $this->old[$Model->alias][$key];
} else {
$old = '';
}
if ($key != 'modified' && $value != $old) {
if ($this->settings['change'] == 'full') {
$logData['Log']['change'] .= $key . ' ('.$old.') => ('.$value.'), ';
} else {
$logData['Log']['change'] .= $key . ', ';
}
}
}
if (strlen($logData['Log']['change'])) {
$logData['Log']['change'] = substr($logData['Log']['change'],0,-2);
} else {
return true;
}
}
$this->_saveLog($Model, $logData);
}

function _saveLog(&$Model, $logData) {
if (isset($Model->data[$Model->alias][$Model->displayField]) && $Model->displayField != $Model->primaryKey) {
$logData['Log']['title'] = $Model->data[$Model->alias][$Model->displayField];
} else {
if ($Model->id) {
$id = $Model->id;
} elseif (isset($Model->data[$Model->alias][$Model->primaryKey])) {
$id = $Model->data[$Model->alias][$Model->primaryKey];
} else {
$id = 'MISSING';
}
$logData['Log']['title'] = $Model->alias.' ('.$id.')';
}

if (isset($this->Log->_schema['model'])) {
$logData['Log']['model'] = $Model->alias;
}

if (isset($this->Log->_schema['model_id'])) {
if ($Model->id) {
$logData['Log']['model_id'] = $Model->id;
} elseif ($Model->insertId) {
$logData['Log']['model_id'] = $Model->insertId;
}
}

if (!isset($this->Log->_schema[ 'action' ])) {
unset($logData['Log']['action']);
}

if (isset($this->Log->_schema[ $this->settings['userKey'] ]) && $this->user) {
$logData['Log'][$this->settings['userKey']] = $this->user[$this->UserModel->alias][$this->UserModel->primaryKey];
}

if (isset($this->Log->_schema['description'])) {
if ($this->user && $this->UserModel) {
$logData['Log']['description'] .= ' by '.$this->settings['userModel'].' "'.
$this->user[$this->UserModel->alias][$this->UserModel->displayField].'"';
if ($this->settings['description_ids']) {
$logData['Log']['description'] .= ' ('.$this->user[$this->UserModel->alias][$this->UserModel->primaryKey].')';
}

} else {
// UserModel is active, but the data hasnt been set. Assume system action.
$logData['Log']['description'] .= ' by System';
}
$logData['Log']['description'] .= '.';
}

$this->Log->create($logData);
$this->Log->save(NULL,FALSE);
}
}
?>