initial commit

This commit is contained in:
Chris Sewell
2012-11-28 03:55:08 -05:00
parent 7adb399b2e
commit cf140a2e97
3247 changed files with 492437 additions and 0 deletions

View File

@ -0,0 +1,5 @@
<?php
class AtlanticBiomedicalUser extends sfBasicSecurityUser
{
}

View File

@ -0,0 +1,68 @@
<?php
/**
* Represents a pinpointed location on a Google Map.
*
* @author Ciphent
**/
class GMapMarker
{
var $address;
var $title;
var $contents;
var $imageColor;
var $latitude;
var $longitude;
public function GMapMarker($theAddress, $theLatitude, $theLongitude, $theTitle, $theContents, $theImageColor)
{
$this->address = $theAddress;
if($theLatitude != '')
$this->latitude = $theLatitude;
if($theLongitude != '')
$this->longitude = $theLongitude;
$this->title = $theTitle;
$this->contents = $theContents;
$this->imageColor = $theImageColor;
}
public function hasLatLong()
{
return isset($this->latitude) && isset($this->longitude);
}
public function getLatitude()
{
return $this->latitude;
}
public function getLongitude()
{
return $this->longitude;
}
public function getAddress()
{
return $this->address;
}
public function getTitle()
{
return $this->title;
}
public function getContent()
{
return $this->contents;
}
public function getImageColor()
{
return $this->imageColor;
}
}
?>

View File

@ -0,0 +1,113 @@
<?php
/**
* Represents a Google Map. A simple wrapper over the api.
*
* @author Ciphent
**/
class GoogleMap
{
var $map;
public function GoogleMap($mapId)
{
$this->map = new GoogleMapAPI($mapId);
$this->map->setAPIKey(sfConfig::get('app_google_maps_api_key'));
$this->map->disableDirections();
$this->map->enableSidebar();
}
public function includeDefaultLocation()
{
/*
$this->map->addMarkerByAddress(sfConfig::get('app_default_map_location'),
sfConfig::get('app_default_map_location_title'),
'<h2>' . sfConfig::get('app_default_map_location_title') . '</h2>'
);
$this->map->addMarkerIcon(sfConfig::get('app_site_images_url') . 'pin_blue.png',
sfConfig::get('app_site_images_url') . 'pin_shadow_big.png', 10, 35, 10, 10);
*/
// support for chaining
return $this;
}
public function setWidth($width)
{
$this->map->setWidth($width);
// support for chaining
return $this;
}
public function setHeight($height)
{
$this->map->setHeight($height);
// support for chaining
return $this;
}
public function getMapJS()
{
return $this->map->printHeaderJS() . ' ' . $this->map->printMapJS();
}
public function getMapHtml()
{
return $this->map->printMap();
}
public function addMarkers($markers)
{
// create some map markers
foreach($markers as $mapMarker)
{
$this->addMarker($mapMarker);
}
// support for chaining
return $this;
}
public function addMarker($mapMarker)
{
static $cc = 0;
$cc++;
$distance = $this->map->geoGetDistance(39.227088,-76.660942,$mapMarker->getLatitude(),$mapMarker->getLongitude());
$distance = 'Distance: '.substr($distance, 0, 5).' mi (approx)';
if ($mapMarker->hasLatLong())
{
$this->map->addMarkerByCoords($mapMarker->getLongitude(),
$mapMarker->getLatitude(),
$mapMarker->getTitle(),
'<h2>' . $mapMarker->getTitle() . "</h2><br />{$mapMarker->getAddress()}<br/>" . $mapMarker->getContent());
}
else
{
$cord_found = $this->map->addMarkerByAddress($mapMarker->getAddress(), $mapMarker->getTitle(),
'<h2>' . $mapMarker->getTitle() . "</h2><br />{$mapMarker->getAddress()}<br/>" . $mapMarker->getContent());
if($cord_found===false)
return false;
}
// print "$cc. ". $mapMarker->getTitle()." ".$mapMarker->getImageColor()."<br/>";
$this->map->addMarkerIcon('/images/pins/' . 'pin_' . $mapMarker->getImageColor() . '.png',
'/images/' . 'pin_shadow_big.png', 10, 35, 10, 10);
// support for chaining
return $this;
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,847 @@
NAME:
GoogleMapAPI - A library used for creating google maps.
AUTHOR:
Monte Ohrt <monte [AT] ohrt [DOT] com>
LATEST VERSION:
2.4 - Aug 1st, 2007
SYNOPSIS:
<?php
require('GoogleMapAPI.class.php');
$map = new GoogleMapAPI('map');
// setup database for geocode caching
$map->setDSN('mysql://USER:PASS@localhost/GEOCODES');
// enter YOUR Google Map Key
$map->setAPIKey('YOURGOOGLEMAPKEY');
// create some map markers
$map->addMarkerByAddress('621 N 48th St # 6 Lincoln NE 68502','PJ Pizza','<b>PJ Pizza</b>');
$map->addMarkerByAddress('826 P St Lincoln NE 68502','Old Chicago','<b>Old Chicago</b>');
$map->addMarkerByAddress('3457 Holdrege St Lincoln NE 68502',"Valentino's","<b>Valentino's</b>");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<?php $map->printHeaderJS(); ?>
<?php $map->printMapJS(); ?>
<!-- necessary for google maps polyline drawing in IE -->
<style type="text/css">
v\:* {
behavior:url(#default#VML);
}
</style>
</head>
<body onload="onLoad()">
<table border=1>
<tr><td>
<?php $map->printMap(); ?>
</td><td>
<?php $map->printSidebar(); ?>
</td></tr>
</table>
</body>
</html>
OUTPUT:
View the output of the above example here:
http://www.phpinsider.com/php/code/GoogleMapAPI/demo/
DESCRIPTION:
GoogleMapAPI - A library used for creating google maps using the
Google Map public API. Features include multiple map markers, customizable
icons, map directions built into info window, and sidebar generation.
More information on the Google Map API can be found here:
http://www.google.com/apis/maps/
DISCUSSION:
-----------
Discussions are currently held in the Smarty add-on forum (although Smarty
is not necessary to use GoogleMapAPI.)
http://www.phpinsider.com/smarty-forum/viewforum.php?f=19
BASE CLASS METHODS:
-------------------
GoogleMapAPI($map_id = 'map', $app_id = 'MyMapApp')
---------------------------------------------------
Class Constructor.
The map id is needed only if you have multiple maps on the same page.
The App ID is used for the Yahoo GeoCode API, which is the default
lookup service. Use a unique App ID per application.
Example:
// use defaults
$map = new GoogleMapAPI();
// set custom map id and app id
$map = new GoogleMapAPI('mymap','myapp');
setDSN($dsn)
------------
Used to set the database DSN. The database is used to cache
geocode lookups (highly recommended!) The PEAR::DB module
is required for database access. You will need to create
the following database schema (mysql example given):
CREATE TABLE GEOCODES (
address varchar(255) NOT NULL default '',
lon float default NULL,
lat float default NULL,
PRIMARY KEY (address)
);
Example:
$map->setDSN('mysql://DBUSER:DBPASS@DBHOST/DBNAME');
$map->setDSN('mysql://geo:foobar@localhost/GEOCODES');
setAPIKey($key)
---------------
Sets the Google Map API Key. This is mandatory, you will need
an API Key for your hostname! You can register free here:
http://www.google.com/apis/maps/signup.html
Example:
// enter YOUR registered API Key
$map->setAPIKey('ABQIAAAAxp5FF-A0RhHOnnTBwrlRbx');
setWidth($width)
----------------
Sets the width of the map window. This can be either px or %.
Default is 500px.
Example:
$map->setWidth('500px');
$map->setWidth('100%');
setHeight($height)
------------------
Sets the height of the map window. This can be either px or %.
Default is '500px'.
Example:
$map->setHeight('500px');
$map->setHeight('100%');
enableMapControls()
-------------------
This will enable the map controls to zoom/move around the map.
Enabled by default.
disableMapControls()
--------------------
This will disable the map controls to zoom/move around the map.
Enabled by default.
setZoomLevel()
--------------
This sets the default map zoom level.
Example:
$map->setZoomLevel(4);
setControlSize($size)
---------------------
This sets the map control size. Relevant only if map controls are
enabled. large = map zoom/move with slider. small = zoom/move without
slider. Large is default.
Example:
$map->setControlSize = 'small';
enableTypeControls()
--------------------
This will enable the map type controls (map/satellite/hybrid).
Enabled by default.
disableTypeControls()
---------------------
This will disable the map type controls (map/satellite/hybrid).
Enabled by default.
setMapType($type)
-----------------
This sets the default map type. Relevant only if map type controls are
enabled. map = default map. satellite = satellite view. hybrid = hybrid
view.
Example:
$map->setMapType('map'); // default
$map->setMapType('satellite');
$map->setMapType('hybrid');
enableSidebar()
---------------
This enables the map sidebar. Use printSideBar() or getSideBar() to
output the sidebar text. Enabled by default.
disableSidebar()
----------------
This disables the map sidebar. Enabled by default.
enableDirections()
------------------
This enables map directions in the bottom of the pop-up info window.
Enabled by default.
disableDirections()
-------------------
This disables map directions in the bottom of the pop-up info window.
Enabled by default.
enableZoomEncompass()
---------------------
This enables zoom encompass so default map zoom is as small as possible
and include all map markers.
Enabled by Default.
disableZoomEncompass()
----------------------
This disables zoom encompass.
Enabled by Default.
setBoundsFudge($val)
--------------------
Set the map boundary fudge factor. This will adjust how much map
boundary encompasses the map markers. (0.01 is default.)
Example:
$map->setBoundsFudge(0.01);
setBrowserAlert($message)
-------------------------
This sets the alert message that pops up when a browser is not
compatible with the Google Map API. Default is:
"Sorry, the Google Maps API is not compatible with this browser."
setJSAlert($message)
--------------------
This sets the alert message that displays when javascript is disabled.
Default: "<b>Javascript must be enabled in order to use Google Maps.</b>"
enableOnLoad()
--------------
This enables the onLoad() javascript function, which is used by default.
This allows the map javascript to be put into the <head></head> tag,
then loaded upon page entry with either <body onload="onLoad()"> right
in the body tag, or use printOnLoad() to place this elsewhere. With onLoad
disabled, the map javascript must be embedded inside the <body></body>
tags. Using onLoad() is the best method to use for browser
compatability.
enableInfoWindow()
------------------
enables info windows on map markers.
Enabled by default.
disableInfoWindow()
-------------------
disables info windows on map markers.
Enabled by default.
enableScaleControl()
--------------------
enables the map scale.
Enabled by default.
disableScaleControl()
---------------------
disables the map scale.
Enabled by default.
enableOverviewControl()
-----------------------
enables the map overview.
Disabled by default.
disableOverviewControl()
------------------------
disable the map overview.
Disabled by default.
disableOnLoad()
---------------
This disables the onLoad() javascript function. (see enableOnLoad())
Enabled by default.
setInfoWindowTrigger($type)
---------------------------
This sets the info window trigger behavior. click = info window comes up
when clicking on a marker. mouseover = info window comes up when mousing
over a marker. Default is click.
Example:
$map->setInfoWindowTrigger('mouseover');
addMarkerByAddress($address,$title = '',$html = '')
---------------------------------------------------
This adds a marker to the map. The address must be a fully qualified
address that can be used by the available geocode lookup services.
To add markers with geocodes directly, see addMarkerByCoords().
The title is used for the sidebar navigation link. The html is used
in the info window that pops up when you click on the map marker. If
no html is provided, the title will be used.
Note: map centering is done automatically as markers are added.
Note: You can use tabbed windows by passing an array of
title=>text values as the $html parameter. If driving directions
are enabled, they show up under the first tab.
Example:
$map->addMarkerByAddress('621 N 48th St # 6 Lincoln NE 68502','PJ Pizza','<b>PJ Pizza</b>');
addMarkerByCoords($lon,$lat,$title = '',$html = '')
---------------------------------------------------
This adds a map marker by geocode (lon/lat) directly. See
addMarkerByAddress() for more details.
Example:
$map->addMarkerByAddress(-96.6539,40.8191,'PJ Pizza','<b>PJ Pizza</b>');
addPolyLineByAddress($address1,$address2,$color,$weight,$opacity)
-----------------------------------------------------------------
This adds a polyline between the two given addresses. You can optionally
supply a color (in #ffffff hex notation), weight (thickness in pixels),
and opacity (in percentage 0-100).
Example:
$map->addPolyLineByAddress(
'3457 Holdrege St Lincoln NE 68502',
'826 P St Lincoln NE 68502','#eeeeee',5,50);
addPolyLineByCoords($lon1,$lat1,$lon2,$lat2,$color,$weight,$opacity)
--------------------------------------------------------------------
This adds a polyline between the two given geocoordinate points. You can optionally
supply a color (in #ffffff hex notation), weight (line thickness in pixels),
and opacity (in percentage 0-100).
Example:
$map->addPolyLineByCoords(-96.67,40.8279,-96.7095,40.8149,'#eeeeee',5,50);
adjustCenterCoords($lon,$lat)
-----------------------------
This adjusts the map center coords by the given lon/lat. This is done
automatically as you add markers to the map, or you can do it manually
with this function. Note: this function is used internally by the
library, it isn't normally necessary unless you have a specific need and
you know what you are doing.
setCenterCoords($lon,$lat)
--------------------------
This sets the map center coords to the given lon/lat. Center coords are
calculated automatically as you add markers to the map, or you reset it
manually with this function. Note: this function is used internally by
the library, it isn't normally necessary unless you have a specific need
and you know what you are doing.
setLookupService('GOOGLE')
-------------------------
This sets the geocode lookup service. Default is GOOGLE, which uses the
GOOGLE Geocode API. If you use the YAHOO Geocode API, be sure to set
your application ID when instantiating GoogleMapAPI. NOTE: Yahoo API
works only for US addresses (AFAIK).
setMarkerIcon($iconImage,$iconShadowImage,$iconAnchorX,$iconAnchorY,$infoWindowAnchorX,$infoWindowAnchorY)
----------------------------------------------------------------------------------------------------------
This sets the icon image for ALL the map markers. Call this once. If you
want to set a different icon for each marker, use addMarkerIcon()
instead.
You must supply a separate image for the icon and its shadow.
iconAnchorX/Y is the X/Y coordinates of the icon for the map point.
infoWindowAnchorX/Y is the X/Y coordinates of the icon where the info
window connects.
The iconImage and iconShadowImage can be either fully qualified URLs, or
a relative path from your web server DOCUMENT_ROOT. These images MUST
exist and readable so the library can calculate the dimensions.
Example:
$map->setMarkerIcon('/images/house.png','/images/house_shadow.png',0,0,10,10);
addMarkerIcon($iconImage,$iconShadowImage,$iconAnchorX,$iconAnchorY,$infoWindowAnchorX,$infoWindowAnchorY)
----------------------------------------------------------------------------------------------------------
This sets the icon image for the CURRENT map marker. IMPORTANT: you MUST
call addMarkerIcon() once for every marker. Do not use setMarkerIcon()
if you use this function.
You must supply a separate image for the icon and its shadow.
iconAnchorX/Y is the X/Y coordinates of the icon for the map point.
infoWindowAnchorX/Y is the X/Y coordinates of the icon where the info
window connects.
The iconImage and iconShadowImage can be either fully qualified URLs, or
a relative path from your web server DOCUMENT_ROOT. These images MUST
exist and readable so the library can calculate the dimensions.
Example:
$map->addMarkerIcon('/images/house.png','/images/house_shadow.png',0,0,10,10);
printHeaderJS()
---------------
This prints the header javascript that goes into the <head></head> tags.
To return the header javascript in a variable, use getHeaderJS().
Example:
<head>
<?php $map->printHeaderJS(); ?>
</head>
getHeaderJS()
-------------
This returns the header javascript that goes into the <head></head> tags.
To print the header javascript directly, use printHeaderJS().
Example:
<?php
$headerjs = getHeaderJS();
?>
<head>
<?php echo $headerjs; ?>
</head>
printMapJS()
------------
This prints the map javascript. If onLoad() is enabled, put this in the
<head></head> tags, and supply <body onload="onLoad()"> in the body tag
(or use printOnLoad()).
Otherwise, put this just before the </body> tag to make it load
automatically. Note that using onLoad() is recommended over this method.
To return the map javascript in a variable, use getMapJS().
Example:
<head>
<?php $map->printMapJS(); ?>
</head>
getMapJS()
----------
This returns the map javascript that goes into the <head></head> tags.
To print the map javascript directly, use printMapJS().
Example:
<?php
$mapjs = $map->printMapJS();
?>
<head>
<?php echo $mapjs; ?>
</head>
printOnLoad()
-------------
This prints the onLoad() javascript call. This is an alternate to
using <body onload="onLoad()"> in the body tag. You can place
this anywhere in the html body.
To return the onLoad() javascript in a variable, use getOnLoad().
Example:
<head>
<?php $map->printMapJS(); ?>
</head>
<body>
<?php echo $map->printMap(); ?>
<?php $map->printOnLoad(); ?>
</body>
getOnLoad()
-----------
This returns the map javascript that goes into the <head></head> tags.
To print the map javascript directly, use printMapJS().
Example:
<?php
$onload = $map->getOnLoad();
$mapjs = $map->getMapJS();
$map = $map->getMap();
?>
<head>
<?php echo $mapjs; ?>
</head>
<body>
<?php echo $map; ?>
<?php echo $onload; ?>
</body>
printMap()
----------
This prints the map html.
To return the map html in a variable, use getMap().
Example:
<head>
<?php $map->printMapJS(); ?>
</head>
<body onload="onLoad()">
<?php echo $map->printMap(); ?>
</body>
Example 2 (using printOnLoad):
<head>
<?php $map->printMapJS(); ?>
</head>
<body>
<?php echo $map->printMap(); ?>
<?php echo $map->printOnLoad(); ?>
</body>
getMap()
--------
This returns the map html in a variable.
To print the map html directly, use printMap().
Example:
<?php
$map = $map->getMap();
?>
<body onload="onLoad()">
<?php echo $map; ?>
</body>
printSidebar()
--------------
This prints the sidebar html.
To return the sidebar html in a variable, use getSidebar().
Example:
<body onload="onLoad()">
<table>
<tr>
<td>
<?php $map->printMap(); ?>
</td>
<td>
<?php $map->printSidebar(); ?>
</td>
</tr>
</table>
</body>
getSidebar()
------------
This returns the sidebar html in a variable.
To print the sidbar html directly, use printSidebar().
Example:
<?php
$map = $map->getMap();
$sidebar = $map->getSidebar();
?>
<body onload="onLoad()">
<table>
<tr>
<td>
<?php echo $map; ?>
</td>
<td>
<?php echo $sidebar; ?>
</td>
</tr>
</table>
</body>
getGeocode($address)
--------------------
This looks up the geocode of an address. It will use the database cache
if available. If you want to lookup a geocode without using the database
cache, use geoGetCoords(). Note: this function is used internally by the
library, it isn't normally necessary unless you have a specific need and
you know what you are doing.
Example:
$geocode = $map->getGeocode('237 S 70th suite 220 Lincoln NE 68510');
echo $geocode['lat'];
echo $geocode['lon'];
getCache($address)
------------------
This will get the cached geocode info for an address from the database
cache, or return FALSE if nothing is available. Note: this function is
used internally by the library, it isn't normally necessary unless you
have a specific need and you know what you are doing.
Example:
$geocode = $map->getCache('237 S 70th suite 220 Lincoln NE 68510');
echo $geocode['lat'];
echo $geocode['lon'];
putCache($address,$lon,$lat)
----------------------------
This will insert geocode info for the given address into the database
cache. Note: this function is used internally by the library, it isn't
normally necessary unless you have a specific need and you know what you
are doing.
Example:
$map->putCache('237 S 70th suite 220 Lincoln NE 68510',-96.62538,40.812438);
geoGetCoords($address)
----------------------
This looks up the geocode of an address directly (not from cache.) Note:
this function is used internally by the library, it isn't normally
necessary unless you have a specific need and you know what you are
doing.
Example:
$geocode = $map->geoGetCoords('237 S 70th suite 220 Lincoln NE 68510');
echo $geocode['lon'];
echo $geocode['lat'];
geoGetDistance($lat1,$lon1,$lat2,$lon2,$unit)
---------------------------------------------
This gets the distance between too coorinate points using the great
circle formula. $unit can be M (miles),K (kilometers),N (nautical
miles),I (inches), or F (feet). Default is M.
Example:
$distance = $map->geoGetDistance($lat1,$lon1,$lat2,$lon2,$unit);
INTEGRATING GOOGLE MAPS WITH SMARTY TEMPLATES
---------------------------------------------
Integrating with Smarty is as simple as assigning the necessary vars to the
template and then displaying them. Note: This example does not cover how to
setup Smarty, please use the Smarty documentation.
Example:
<?php
require('Smarty.class.php');
require('GoogleMapAPI.class.php');
$smarty = new Smarty();
$map = new GoogleMapAPI();
// setup database for geocode caching
$map->setDSN('mysql://USER:PASS@localhost/GEOCODES');
// enter YOUR Google Map Key
$map->setAPIKey('YOURGOOGLEMAPKEY');
// create some map markers
$map->addMarkerByAddress('621 N 48th St # 6 Lincoln NE 68502','PJ Pizza','<b>PJ Pizza</b>');
$map->addMarkerByAddress('826 P St Lincoln NE 68502','Old Chicago','<b>Old Chicago</b>');
$map->addMarkerByAddress('3457 Holdrege St Lincoln NE 68502',"Valentino's","<b>Valentino's</b>");
// assign Smarty variables;
$smarty->assign('google_map_header',$map->getHeaderJS());
$smarty->assign('google_map_js',$map->getMapJS());
$smarty->assign('google_map_sidebar',$map->getSidebar());
$smarty->assign('google_map',$map->getMap());
// display the template
$smarty->display('index.tpl');
?>
contents of index.tpl:
----------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
{$google_map_header}
{$google_map_js}
<!-- necessary for google maps polyline drawing in IE -->
<style type="text/css">
v\:* {ldelim}
behavior:url(#default#VML);
{rdelim}
</style>
</head>
<body onload="onLoad()">
<table>
<tr>
<td>{$google_map}</td>
<td>{$google_map_sidebar}</td>
</tr>
</table>
</body>
</html>
CREDITS:
--------
Excellent Google Maps tutorials by Mike:
http://www.econym.demon.co.uk/googlemaps/index.htm
People who have helped/contributed:
Charlie Dawes
Jake Krohn
Clark Freifeld <clark AT users DOT sourceforge DOT net>
Angelo Conforti
Jerome Combaz
drakos7 (from forums)
nmweb (from forums)
Anyone I missed, drop me a line!
Monte Ohrt <monte [AT] ohrt [DOT] com>

View File

@ -0,0 +1,311 @@
<?php
class GoogleMapCache{
public function __construct(){
}
//get the cordinate of the client. if its not in there add it
public function getCordinateCache($id){
if(empty($id))
return array('lat'=>null,'lon'=> null);
$c = new Criteria;
$c->add(CordinatesPeer::CLIENT_ID, $id);
$cordCache = CordinatesPeer::doSelect($c);
if($cordCache){
return array('lat'=>$cordCache[0]->getLat(),'lon'=> $cordCache[0]->getLon());
}
$client1 = ClientPeer::retrieveByPk($id);
$address = $client1->getAddress().' '.$client1->getCity().' '.$client1->getState().' '.$client1->getZip();
$map = new GoogleMapAPI('map');
$map->setAPIKey('ABQIAAAAbu56iy-6LS_GeUSAnMXHPxQYy8GCRil3btyRMCq9tZ8qFFyM6RT30TkD-cPNxYzl_SZslQgaOgpnFQ');
$geodata = $map->getGeocode($address);
$cord = new Cordinates($id);
($geodata) ? $cord->setFound(1) : $cord->setFound(0);
$cord->setClientId($id);
$cord->setLat($geodata['lat']);
$cord->setLon($geodata['lon']);
$cord->save();
return array('lat'=>$cord->getLat(),'lon'=> $cord->getLon());
}
//update the latitude, longitude cordinate for the client
public function updateCordinateCache($id){
$client1 = ClientPeer::retrieveByPk($id);
if(!$client1)
return false;
$address = $client1->getAddress().' '.$client1->getCity().' '.$client1->getState().' '.$client1->getZip();
if(!empty($address)){
$map = new GoogleMapAPI('map');
$map->setAPIKey('ABQIAAAAbu56iy-6LS_GeUSAnMXHPxQYy8GCRil3btyRMCq9tZ8qFFyM6RT30TkD-cPNxYzl_SZslQgaOgpnFQ');
$geodata = $map->getGeocode($address);
//save the cordinate for the new client
$cord = new Cordinates();
($geodata) ? $cord->setFound(1) : $cord->setFound(0);
$cord->setClientId($id);
$cord->setLat($geodata['lat']);
$cord->setLon($geodata['lon']);
$cord->save();
//indicate that we've already updated the client
$client1->setRequireCoordsUpdate(0);
$client1->save();
return true;
}
}
//update the driving information for the client to all other clients
//if overide = false dont update, only insert records if it doesn't exist
public function updateCacheById($id, $overide = true){
if(empty($id)) return false;
$c = new Criteria();
$clients = ClientPeer::doSelect($c);
if(!$clients)
return;
$connection = Propel::getConnection();
foreach($clients as $client){
$thisClientId = $client->getId();
if($thisClientId == $id) continue;
$query = "SELECT * FROM distances WHERE (client_id_1 = $id and client_id_2 = $thisClientId) or (client_id_2 = $id and client_id_1 = $thisClientId)";
$statement = $connection->prepareStatement($query);
$result = $statement->executeQuery();
$dataFound = $result->next();
//overide equals true we want to replace data
if( $dataFound and $overide == true){
//$hrs = 0; $min = 0; $distance = 0;
$drivingInfo = $this->getDrivingDistanceNoCache($id,$thisClientId);
$hrs = (int)$drivingInfo['hours'];
$min = (int)$drivingInfo['min'];
$distance = (int)$drivingInfo['distance'];
$query = "UPDATE distances SET updated_at = NOW(), travel_time_hours = $hrs, travel_time_mins = $min, travel_distance = $distance WHERE (client_id_1 = $id and client_id_2 = $thisClientId) or (client_id_2 = $id and client_id_1 = $thisClientId)";
$statement = $connection->prepareStatement($query);
$result = $statement->executeQuery();
//overwrite date
}elseif(!$dataFound){
// $hrs =0; $min =0; $distance =0;
$drivingInfo = $this->getDrivingDistanceNoCache($id,$thisClientId);
$hrs = (int)$drivingInfo['hours'];
$min = (int)$drivingInfo['min'];
$distance = (int)$drivingInfo['distance'];
$query = "INSERT INTO distances(updated_at,client_id_1, client_id_2, travel_time_hours,travel_time_mins,travel_distance) VALUE(NOW(),$id,$thisClientId,$hrs,$min,$distance)";
$statement = $connection->prepareStatement($query);
$result = $statement->executeQuery();
//insert new record
}
}//if
}//public
public function updateTechDistanceCacheById($id, $overide = true){
if(empty($id)) return false;
$c = new Criteria();
$clients = ClientPeer::doSelect($c);
if(!$clients)
return;
$connection = Propel::getConnection();
foreach($clients as $client){
$thisClientId = $client->getId();
$query = "SELECT * FROM tech_distances WHERE (tech_id = $id and client_id = $thisClientId)";
$statement = $connection->prepareStatement($query);
$result = $statement->executeQuery();
$dataFound = $result->next();
//overide equals true we want to replace data
if( $dataFound and $overide == true){
//$hrs = 0; $min = 0; $distance = 0;
$drivingInfo = $this->getDrivingDistanceNoCache($id,$thisClientId,true); //true means tech to client NOT client to client
$hrs = (int)$drivingInfo['hours'];
$min = (int)$drivingInfo['min'];
$distance = (int)$drivingInfo['distance'];
$query = "UPDATE tech_distances SET updated_at = NOW(), travel_time_hours = $hrs, travel_time_mins = $min, travel_distance = $distance WHERE (tech_id = $id and client_id = $thisClientId)";
$statement = $connection->prepareStatement($query);
$result = $statement->executeQuery();
//overwrite date
}elseif(!$dataFound){
// $hrs =0; $min =0; $distance =0;
$drivingInfo = $this->getDrivingDistanceNoCache($id,$thisClientId,true); //true means tech to client NOT client to client
$hrs = (int)$drivingInfo['hours'];
$min = (int)$drivingInfo['min'];
$distance = (int)$drivingInfo['distance'];
$query = "INSERT INTO tech_distances(updated_at,tech_id, client_id, travel_time_hours,travel_time_mins,travel_distance) VALUE(NOW(),$id,$thisClientId,$hrs,$min,$distance)";
$statement = $connection->prepareStatement($query);
$result = $statement->executeQuery();
//insert new record
}
}//if
}//public
public function getDrivingDistanceCache($id1,$id2, $forTech = false){
if(empty($id1) || empty($id2))
return array('hours'=>0, 'min'=>0, 'distance'=>0);
$connection = Propel::getConnection();
if(!$forTech){//checking cache for client to client
$query = "SELECT * FROM distances WHERE (client_id_1 = $id1 and client_id_2 = $id2 )
or (client_id_2 = $id1 and client_id_1 = $id2)";
$statement = $connection->prepareStatement($query);
$result = $statement->executeQuery();
while($result->next()){
$hours = $result->getInt('travel_time_hours');
$mins = $result->getInt("travel_time_mins");
$travelDistance = (float)$result->get("travel_distance");
return array('hours'=>$hours, 'min'=>$mins, 'distance'=>$travelDistance);
}
$client1 = ClientPeer::retrieveByPk($id1);
$client2 = ClientPeer::retrieveByPk($id2);
$address1 = ($client1) ? $client1->getFullAddress() : '';
$address2 = ($client2) ? $client2->getFullAddress() : '';
$drivingT = $this->getDrivingDistance($address1, $address2);
$distance = new Distances();
$distance->setClientId1($id1);
$distance->setClientId2($id2);
$distance->setTravelTimeHours($drivingT['hours']);
$distance->setTravelTimeMins($drivingT['min']);
$distance->setTravelDistance($drivingT['distance']);
$distance->save();
}else{ //checking cache for tech to client
$query = "SELECT * FROM tech_distances WHERE (tech_id = $id1 and client_id = $id2 )";
$statement = $connection->prepareStatement($query);
$result = $statement->executeQuery();
while($result->next()){
$hours = $result->getInt('travel_time_hours');
$mins = $result->getInt("travel_time_mins");
$travelDistance = (float)$result->get("travel_distance");
return array('hours'=>$hours, 'min'=>$mins, 'distance'=>$travelDistance);
}
$user = UserPeer::retrieveByPk($id1);
$client = ClientPeer::retrieveByPk($id2);
$address1 = ($user) ? $user->getFullAddress() : '';
$address2 = ($client) ? $client->getFullAddress() : '';
$drivingT = $this->getDrivingDistance($address1, $address2);
$distance = new TechDistances();
$distance->setTechId($id1);
$distance->setClientId($id2);
$distance->setTravelTimeHours($drivingT['hours']);
$distance->setTravelTimeMins($drivingT['min']);
$distance->setTravelDistance($drivingT['distance']);
$distance->save();
}
return array('hours'=>$drivingT['hours'],'min'=>$drivingT['min'],'distance'=>$drivingT['distance']);
}
// return the driving time and distances between the 2 clients skip cache
public function getDrivingDistanceNoCache($id1,$id2, $forTech = false){
//client to client
if(!$forTech){
$client1 = ClientPeer::retrieveByPk($id1);
$client2 = ClientPeer::retrieveByPk($id2);
$address1 = ($client1) ? $client1->getFullAddress() : '';
$address2 = ($client2) ? $client2->getFullAddress() : '';
}else{
$tech = UserPeer::retrieveByPk($id1);
$client = ClientPeer::retrieveByPk($id2);
$address1 = ($tech) ? $tech->getFullAddress() : '';
$address2 = ($client) ? $client->getFullAddress() : '';
}
$drivingT = $this->getDrivingDistance($address1, $address2);
return array('hours'=>$drivingT['hours'],'min'=>$drivingT['min'],'distance'=>$drivingT['distance']);
}
// get driving time and distances base on address
public function getDrivingDistance($address1,$address2){
$a = urlencode($address1);
$b = urlencode($address2);
$url = "http://maps.google.com/maps";
$query = "q=from+$a+to+$b&output=kml";
$full_url= $url."?".$query;
$fp = fopen($full_url,'r');
while($data = fread(($fp),1024)){
$kml .= $data;
}
//Commented this out second. Everything seems to be working again.
//I commented out a section in apps/atlbiomed/modules/scheduler/actions/actions.class.php
//and then got the second line in this section as broken. Commenting out the entire section
//fixed everything.
// -Chris
/* if(!empty($kml)){
$xml_object = new SimpleXMLElement($kml);
$totalPlacemark = count($xml_object->Document->Placemark);
$lastPlacemark = $xml_object->Document->Placemark[$totalPlacemark-1];
$distance_info = split ('mi', $lastPlacemark->description[0]);
$mileage = (float)str_replace('Distance: ','',$distance_info[0]);
$time_str = str_replace('(about','',$distance_info[1]);
$time_str = str_replace('hours','hour',$time_str);
$hourTextPos = strrpos($time_str, "hour");
$time_arr = explode('hour', $time_str);
if($hourTextPos!==false){
$hours = (int)$time_arr[0];
$min= (int)$time_arr[1];
}
else{
$hours = 0;
$min = (int)$time_arr[0];
}
}//if
*/
return array('hours'=>$hours,'min'=>$min,'distance'=>$mileage);
}
}
?>

View File

@ -0,0 +1,176 @@
<?php
class TechnicianScheduler
{
var $technician;
var $workorders;
var $tempWorkorder;
public function TechnicianScheduler($technician, $workDate)
{
$this->technician = $technician;
$this->workorders = WorkorderPeer::getOrdersForTechnician($technician->getId(), $workDate);
}
/*
* Determines if a workorder can be slotted into the current schedule.
*/
public function isSchedulable($workOrder)
{
// easy check, is it outside of this technician's working hours
if($this->technician->getStartTime() > $workOrder->getJobStart()
|| $this->technician->getEndTime() < $workOrder->getJobEnd())
{
return false;
}
else
{
// we will search through the workorders using an anonymous function which checks to see if the proposed
// work order starts or ends within the time span for any of the orders.
$overlappingOrder = create_function('$order',
'return (' . abs($workOrder->getJobEnd()) . ' >= $order->getJobStart()'
. ' && ' . abs($workOrder->getJobEnd()) . ' <= $order->getJobEnd())'
. ' || (' . abs($workOrder->getJobStart()) . ' >= $order->getJobStart()'
. ' && ' . abs($workOrder->getJobStart()) . ' < $order->getJobEnd());');
//return count(array_filter($this->workorders, $overlappingOrder)) == 0;
$this->tempWorkorder = $workOrder;
//count(array_filter($this->workorders, array('TechnicianScheduler','callbackfunc'))) == 0;
return count(array_filter($this->workorders, array('TechnicianScheduler','callbackfunc'))) == 0;
}
}
public function callbackfunc($order){
$workOrder = $this->tempWorkorder;
/*
* DEBUGGING PURPOSES
print $workOrder->getJobStart() . " == " . $order->getJobStart()."<br/>";
print $workOrder->getJobStart() . " > " . $order->getJobStart() . " && ". $workOrder->getJobStart() ." < ". $order->getJobEnd() ."<br/>";
print $workOrder->getJobEnd() . " > " . $order->getJobStart() . " && ". $workOrder->getJobEnd() ." <= ". $order->getJobEnd()."<br/>"; // job end falls between job
print $workOrder->getJobStart() . " < ". $order->getJobStart() . " && " . $workOrder->getJobEnd() . " >= " . $order->getJobEnd() . "<br/><br/><br/>";
print "return: ";
var_dump((
($workOrder->getJobStart() == $order->getJobStart()) || //PROBLEM both jobs
($workOrder->getJobStart() > $order->getJobStart() && $workOrder->getJobStart() < $order->getJobEnd()) || //start time falls in the rage of another job
($workOrder->getJobEnd() > $order->getJobStart() && $workOrder->getJobEnd() <= $order->getJobEnd()) || // job end falls between job
($workOrder->getJobStart() < $order->getJobStart() && $workOrder->getJobEnd() >= $order->getJobEnd()) // enclose a current job
));
*/
return (
($workOrder->getJobStart() == $order->getJobStart()) || //PROBLEM both jobs
($workOrder->getJobStart() > $order->getJobStart() && $workOrder->getJobStart() < $order->getJobEnd()) || //start time falls in the rage of another job
($workOrder->getJobEnd() > $order->getJobStart() && $workOrder->getJobEnd() <= $order->getJobEnd()) || // job end falls between job
($workOrder->getJobStart() < $order->getJobStart() && $workOrder->getJobEnd() >= $order->getJobEnd()) // enclose a current job
);
}
/*
* Attempts to add a workorder to this schedule. NOTE: This performs no insert/update
* operations to the database.
*/
public function scheduleWorkorder($workOrder)
{
if($this->isSchedulable($workOrder))
{
$this->workorders[] = $workOrder;
}
}
/*
* Gets the technician in this schedule.
*/
public function getTechnician()
{
return $this->technician;
}
/*
* Gets the workorders in this schedule.
*/
public function getWorkorders()
{
return $this->workorders;
}
/*
* Gets the order scheduled at the time slot.
*/
public function getWorkorderAtTime($time)
{
$isInSlot = create_function('$order',
'return ' . abs($time) . ' >= abs($order->getJobStart())'
. ' && ' . abs($time) . ' < abs($order->getJobEnd());');
$orders = array_filter($this->workorders, $isInSlot);
return array_pop($orders);
}
/*
* Gets the earliest start time for this schedule. Returns null if the tech is booked.
*/
public function getFirstAvailableStartTime()
{
$firstAvailable = null;
$start = $this->technician->getStartTime();
$counter = 0;
while( $start < $this->technician->getEndTime() )
{
if ($this->getWorkorderAtTime($start) == null)
{
$counter++;
if ($counter == 4)
{
break;
}
else if ($counter == 1)
{
$firstAvailable = $start;
}
}
else
{
$counter = 0;
$firstAvailable = null;
}
// increment time
if (substr($start, 2, 2) == '30')
{
$start = abs(substr($start, 0, 2)) + 1 . '00';
if(strlen($start) != 4)
{
$start = '0' . $start;
}
}
else
{
$start = substr($start, 0, 2) . '30';
}
}
return $firstAvailable;
}
public function sortWorkorder($workorders){
usort(&$workorders, array(get_class($this), 'uksort_workers'));
return $workorders;
}
private function uksort_workers($a, $b)
{
if ($a->getJobStart() == $b->getJobStart()) return 0;
return ($a->getJobStart() < $b->getJobStart()) ? -1 : 1;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

230
apps/atlbiomed/lib/deviceData.php Executable file
View File

@ -0,0 +1,230 @@
<?php
class DeviceData {
private $uploadedData = null;
public function getData(){
return $this->uploadedData;
}
public function __construct() {
}
public function getTotalRecords(){
return count($this->uploadedData);
}
public function readRow($rows) {
$rows = $this->groupData($rows);
$this->uploadedData = $rows;
}
private function groupData($rows){
$groupedData = array();
$lastRow = count($rows)-1;
$temp = array();
for($i = 0; $i < count($rows); $i++){
$startRowIndex = $i; //checking index
$nextIndex = $i+1; //next index
$startRow = $rows[$i]; //checking row
array_push($temp, $startRow);
while($startRow[0] == $rows[$nextIndex][0] && $rows[$nextIndex][1] == 3){
array_push($temp,$rows[$nextIndex]); //add to temp array
$currentRow = $nextIndex;
$nextIndex++;
$i++; //increment becuase we don't want to check in next for loop
}//while
$groupedData[] = $temp;
unset($temp);
$temp = array();
}//for
return $groupedData;
}//function
public function getDeviceId($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][0];
}
public function getRowIndicator($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][1];
}
public function getDate($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][2];
}
public function getTime($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][3];
}
public function getPassFail($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
if(@strtolower($this->uploadedData[$index][0][4]) == 'fail' || @strtolower($this->uploadedData[$index][1][4]) == 'fail'
|| @strtolower($this->uploadedData[$index][0][12]) == 'fail' || @strtolower($this->uploadedData[$index][1][12]) == 'fail')
return 'fail';
else
return $this->uploadedData[$index][0][4];
}
public function getDeviceTechId($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][5];
}
public function getDeviceName($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][6];
}
public function getManufacturer($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][7];
}
public function getLocation($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][50];
}
public function getModel($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][9];
}
public function getSerial($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][10];
}
public function getPassFailCode($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][1][12];
}
public function getRecNumber($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][14];
}
public function getRowPurpose($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][18];
}
public function getPhysicalInspection($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][49];
}
public function getRoom($index){
$totalRows = count($this->uploadedData);
if($index >= $totalRows)
return null;
return $this->uploadedData[$index][0][51];
}
public function getTotalTest($index){
$firstTestIndex = 54; // tests always start at index 54
$currentIndex = $firstTestIndex;
$totalTests = 0;
if($this->uploadedData[$index][0][1] == 3)
$row = $this->uploadedData[$index][0];
else if($this->uploadedData[$index][1][1] == 3){
$row = $this->uploadedData[$index][1];
}else
return 0;
while(is_numeric($row[$currentIndex])){
$totalTests += 1; //if its a int that is one test
$currentIndex += 4; //if value at every 4 increment is INT then it is a test
}
return $totalTests;
}
public function getTestDetail($index,$testNumber){
$totalTests = $this->getTotalTest($index);
if($testNumber> $totalTests)
return array('name'=>'','passFail'=>'','value'=>'','unit'=>'','type'=>'');
$firstTestIndex = 54; // tests always start at index 54
$currentIndex = $firstTestIndex;
$totalTests = 0;
$totalRows = count($this->uploadedData[$index]);
if($this->uploadedData[$index][0][1] == 3){
$usingType3 = true;
$row = $this->uploadedData[$index][0];
}
else if($this->uploadedData[$index][1][1] == 3){
$usingType3 = false;
$row = $this->uploadedData[$index][1];
}else
return 0;
$searchIndex = $firstTestIndex + (($testNumber-1)*4);
if($totalRows>=2){
$name = @$this->uploadedData[$index][1][$searchIndex+1];//second line
$type = @$this->uploadedData[$index][0][$searchIndex+2];
$passFail = @$this->uploadedData[$index][1][$searchIndex+2];
$value = @$this->uploadedData[$index][0][$searchIndex+3];
$unit = @$this->uploadedData[$index][0][$searchIndex+4];
}elseif($totalRows == 1 && $this->uploadedData[$index][0][1] == 3){
$name = @$this->uploadedData[$index][0][$searchIndex+1];//second line
//$type = @$this->uploadedData[$searchIndex][0][$searchIndex+2];
$passFail = @$this->uploadedData[$index][0][$searchIndex+2];
//$value = @$this->uploadedData[$searchIndex][0][$searchIndex+3];
//$unit = @$this->uploadedData[$searchIndex][0][$searchIndex+4];
}else if($totalRows == 1 && $this->uploadedData[$index][0][1] == 1){
//$name = @$this->uploadedData[$searchIndex][1][$searchIndex+1];//second line
$type = @$this->uploadedData[$index][0][$searchIndex+2];
//$passFail = @$this->uploadedData[$searchIndex][1][$searchIndex+2];
$value = @$this->uploadedData[$index][0][$searchIndex+3];
$unit = @$this->uploadedData[$index][0][$searchIndex+4];
}
return array('name'=>$name,'passFail'=>$passFail,'value'=>$value,'unit'=>$unit,'type'=>$type);
}
public function getAllTestData($index){
$temp = array();
$total = $this->getTotalTest($index);
for($i = 0; $i < $total; $i++){
$temp[] = $this->getTestDetail($index, $i);
}//for
return $temp;
}
}
?>

1647
apps/atlbiomed/lib/fpdf.php Executable file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,69 @@
<?php
class myUser extends sfBasicSecurityUser
{
public function initialize($context, $parameters = null)
{
$this->context = $context;
$this->parameterHolder = new sfParameterHolder();
$this->parameterHolder->add($parameters);
$this->attributeHolder = new sfParameterHolder(self::ATTRIBUTE_NAMESPACE);
// read attributes from storage
$attributes = $context->getStorage()->read(self::ATTRIBUTE_NAMESPACE);
if (is_array($attributes))
{
foreach ($attributes as $namespace => $values)
{
$this->attributeHolder->add($values, $namespace);
}
}
// set the user culture to sf_culture parameter if present in the request
// otherwise
// - use the culture defined in the user session
// - use the default culture set in i18n.yml
if (!($culture = $context->getRequest()->getParameter('sf_culture')))
{
if (null === ($culture = $context->getStorage()->read(self::CULTURE_NAMESPACE)))
{
$culture = sfConfig::get('sf_i18n_default_culture', 'en');
}
}
$this->setCulture($culture);
// read data from storage
$storage = $this->getContext()->getStorage();
$this->authenticated = $storage->read(self::AUTH_NAMESPACE);
$this->credentials = $storage->read(self::CREDENTIAL_NAMESPACE);
$this->lastRequest = $storage->read(self::LAST_REQUEST_NAMESPACE);
if ($this->authenticated == null)
{
$this->authenticated = false;
$this->credentials = array();
}
else
{
// Automatic logout logged in user if no request within [sf_timeout] setting
if (0 != sfConfig::get('sf_timeout') && null !== $this->lastRequest && (time() - $this->lastRequest) > sfConfig::get('sf_timeout'))
{
if (sfConfig::get('sf_logging_enabled'))
{
$this->getContext()->getLogger()->info('{sfUser} automatic user logout due to timeout');
}
$this->setTimedOut();
$this->setAuthenticated(false);
}
}
$this->lastRequest = time();
}
}

View File

@ -0,0 +1,332 @@
<?php
class processHandler{
private $parsedFileData = array();
private $deviceData = null;
private $fileName = null;
private $partial = array();
private $noMatch = array();
private $match = array();
private $shouldForward = false;
public function __construct($request=''){
if(empty($request))
return false;
$uploadedFile = $this->readUploadedFile($request);
$c = new Criteria();
$c->add(DevicesFilesPeer::FILENAME, $this->fileName);
$devicesFiles = DevicesFilesPeer::doSelect($c);
$devicesFilesResult = $devicesFiles[0];
if(!$devicesFilesResult){
$this->parseData($uploadedFile);
$this->deviceData = new DeviceData();
$this->deviceData->readRow($this->parsedFileData);
$this->searchForMatch();
//save the parsed content of the file
$devicesFiles = new DevicesFiles();
$devicesFiles->setFilename($this->fileName);
$devicesFiles->setData(serialize($this->parsedFileData));
$devicesFiles->saveToDisk();
$devicesFiles->save();
}else{
$this->shouldForward = true;
}
}
public function loadFile($filename){
$c = new Criteria();
$c->add(DevicesFilesPeer::FILENAME, $filename);
$result = DevicesFilesPeer::doSelect($c);
$result = $result[0];
if(!$result)
return false;
$deviceFile = new DevicesFiles();
$deviceFile->loadFromDisk($filename);
if(!$deviceFile->fileLoaded()) //fail to load data
return false;
$this->parsedFileData = $deviceFile->getData();
$this->fileName = $filename;
$this->deviceData = new DeviceData();
$this->deviceData->readRow($this->parsedFileData);
$this->searchForMatch(true); //element those that were already processed
}
public function shouldForward(){
return $this->shouldForward;
}
private function readUploadedFile($request){
$this->request = $request;
//$upload_path = 'uploads/spreadsheet/unparsed';
$fileName = $this->request->getFileName ( 'upload' );
$micro = microtime();
$micro = str_replace(' ','-',$micro);
$date = date("M-d-Y",time());
$destination_path = $upload_path . DIRECTORY_SEPARATOR . "$date-$micro-$fileName";
$destination_path = $upload_path . DIRECTORY_SEPARATOR .$fileName;
//read file data
if ( !empty($fileName)) {
$this->fileName = $fileName;
$tmpPath = $this->request->getFilePath ( 'upload' );
//$this->request->moveFile ( 'upload', $destination_path);
if(file_exists($tmpPath)){
$fp = fopen($tmpPath,'r');
if($fp){
while($partial_data = fread($fp,1024)){
$data .= $partial_data;
}
}
}
return $data;
}//if
}
private function parseData($rawFile){
//break down the data by ',' and newline into arrays
$rows_data = array();
if(!empty($rawFile)){
$rows = explode("\n", $rawFile);
foreach($rows as $row){
$row = trim($row,' ');
if(empty($row)) continue;
$columns = explode(',',$row);
$explodedData [] = $columns; //all the rows and columns exploded
}//for each
//strip away quotes and blank spaces
$tempData = array();
for($i = 0; $i < count($explodedData); $i++){
for($j = 0; $j < count($explodedData[$i]); $j++){
$tempData[$i][$j] = trim ( str_replace ( '"', '', $explodedData[$i][$j] ), ' ' );
}//for
}//for'
$this->parsedFileData=$tempData;
}
}
public function getParsedData(){
return $this->parsedFileData;
}
public function searchForMatch($eliminateSaved= false){
if(!$this->deviceData)
return false;
$notAlreadySavedDevices = ($eliminateSaved) ? $this->getUnprocessedDevices($this->fileName) : array();
$totalRecords = $this->deviceData->getTotalRecords();
for($row = 0; $row < $totalRecords; $row++){
//data for this row
$device_id = $this->deviceData->getDeviceId($row);
$device_name = $this->deviceData->getDeviceName($row);
$manufacturer = $this->deviceData->getManufacturer($row);
$model = $this->deviceData->getModel($row);
$serial = $this->deviceData->getSerial($row);
$p_date = $this->deviceData->getDate($row);
$pass_fail = $this->deviceData->getPassFail($row);
$location = $this->deviceData->getLocation($row);
$random_id = $this->getRandomNumber();
$p_date = str_replace('/','-',$p_date);
$testData = $this->deviceData->getAllTestData($row);
$time = $this->deviceData->getTime($row);
$deviceTechId = $this->deviceData->getDeviceTechId($row);
$rowIndicator = $this->deviceData->getRowIndicator($row);
$passFailCode = $this->deviceData->getPassFailCode($row);
$recNumber = $this->deviceData->getRecNumber($row);
$rowPurpose = $this->deviceData->getRowPurpose($row);
$physicalInspection = $this->deviceData->getPhysicalInspection($row);
$room = $this->deviceData->getRoom($row);
$extraData = array('time'=>$time,'techId'=>$deviceTechId, 'rowIndicator'=>$rowIndicator, 'location'=>$location, 'passFailCode'=>$passFailCode,
'recNumber'=>$recNumber, 'rowPurpose'=>$rowPurpose,'physicalInspection'=>$physicalInspection, 'room'=>$room);
//search for a device with this indentification
$c = new Criteria();
$c->add(DevicePeer::IDENTIFICATION, $device_id); //$c->addjoin(DevicePeer::SPECIFICATION_ID, SpecificationPeer::ID, Criteria::LEFT_JOIN);
$result = DevicePeer::doSelect($c);
//if id matches
if(!empty($result[0])){
$_deviceName = $result[0]->getSpecification()->getDeviceName();
$_model = $result[0]->getSpecification()->getModelNumber();
$_manufacturer = $result[0]->getSpecification()->getManufacturer();
$_serial = $result[0]->getSerialNumber();
$_status = $result[0]->getStatus();
$retiredWarning = (strtolower($_status)=='retired') ? "<span style='color:red'> Warning: Retired</span>" : '';
//if the serial in mup file is empty consider it a match still
if(strtolower($device_name) == strtolower($_deviceName) && strtolower($model) == strtolower($_model) && strtolower($manufacturer) == strtolower($_manufacturer) && (strtolower($serial) == strtolower($_serial) || empty($serial)) ){
$this->changePm2Missing($result[0]->getClientId()); // changed any 'pm scheduled' to 'missing' because we have a match
//for matched devices
//save the pass fail code
$result[0]->setStatus(strtolower($pass_fail));
$result[0]->setLocation($location);
$result[0]->setComments($passFailCode);
$result[0]->setLastPmDate(FinalDeviceReport::convertImportedDate($p_date));
$result[0]->save();
$client_name = $result[0]->getClient()->getClientIdentification().' - '.$result[0]->getClient()->getClientName();
//total match
$deviceCheckup = new DeviceCheckup();
$deviceCheckup->setDeviceId($result[0]->getId());
$deviceCheckup->setClientId($result[0]->getClientId());
$deviceCheckup->setDeviceIdentification($device_id);
$deviceCheckup->setDate($p_date);
$deviceCheckup->setPassFail($pass_fail);
$deviceCheckup->setPassFailCode($passFailCode);
$deviceCheckup->setRowIndicator($rowIndicator);
$deviceCheckup->setRowPurpose($rowPurpose);
$deviceCheckup->setRoom($room);
$deviceCheckup->setPhysicalInspection($physicalInspection);
$deviceCheckup->setRecNumber($recNumber);
$deviceCheckup->setTime($time);
$deviceCheckup->save();
$match = array('id'=>$result[0]->getId(),'client_name'=>$client_name, 'random_id'=>$random_id,'type'=>2,'device_id'=>$device_id, 'device_name'=>$device_name,'model'=>$model,
'manufacturer'=>$manufacturer, 'serial'=>$serial, 'date'=>$p_date);
if($eliminateSaved){ //these devices were not saved yet
if(in_array($device_id,$notAlreadySavedDevices))
$this->match[] = $match;
}else
$this->match[] = $match;
}else{
//give option
$pm_deviceName = array($device_name, $_deviceName);
$pm_manufacturer = array($manufacturer, $_manufacturer);
$pm_serial = array($serial, $_serial);
$pm_model = array($model, $_model);
$client_name = $result[0]->getClient()->getClientIdentification().' - '.$result[0]->getClient()->getClientName();
$misMatch = array('device_name'=>false, 'model'=>false, 'manufacturer'=>false, 'serial'=>false);
if(strtolower($device_name) != strtolower($_deviceName))
$misMatch['device_name'] = true;
if(strtolower($model) != strtolower($_model))
$misMatch['model'] = true;
if(strtolower($manufacturer) != strtolower($_manufacturer))
$misMatch['manufacturer'] = true;
if((strtolower($serial) != strtolower($_serial) && !empty($serial)))
$misMatch['serial'] = true;
$partial_match = array('misMatch'=>$misMatch, 'comments'=>$passFailCode, 'location'=>$location, 'warning'=>$retiredWarning,'client_name'=>$client_name,'random_id'=>$random_id,'type'=>2,'device_id'=>$device_id, 'device_name'=>$pm_deviceName,'model'=>$pm_model,
'manufacturer'=>$pm_manufacturer, 'serial'=>$pm_serial, 'date'=>$p_date, 'pass_fail'=>$pass_fail, 'testData'=>$testData, 'extraData'=>$extraData);
$this->totalPartialMatch += 1;
if($eliminateSaved){ //these devices were not saved yet
if(in_array($device_id,$notAlreadySavedDevices))
$this->partial[] = $partial_match;
}else
$this->partial[] = $partial_match;
if(!$eliminateSaved){
$c = new Criteria();
$c->add(UnprocessedDevicesPeer::FILENAME, $this->fileName);
$c->add(UnprocessedDevicesPeer::DEVICE_ID,$device_id);
$c->setLimit(1);
$dcheck = UnprocessedDevicesPeer::doSelect($c);
if(empty($dcheck)){ //unprocessed device record of this does not exit
//saved as unprocessed
$unprocessed = new UnprocessedDevices();
$unprocessed->setFilename($this->fileName);
$unprocessed->setDeviceId($device_id);
$unprocessed->save();
}
}
}
}else{
$no_match = array('comments'=>$passFailCode, 'location'=>$location, 'warning'=>$retiredWarning,'random_id'=>$random_id,'type'=>3, 'device_id'=>$device_id, 'device_name'=>$device_name,'model'=>$model,
'manufacturer'=>$manufacturer, 'serial'=>$serial, 'date'=>$p_date, 'pass_fail'=>$pass_fail, 'testData'=>$testData, 'extraData'=>$extraData );
if($eliminateSaved){ //these devices were not saved yet
if(in_array($device_id,$notAlreadySavedDevices))
$this->noMatch[] = $no_match;
}else
$this->noMatch[] = $no_match;
//saved as unprocessed
if(!$eliminateSaved){
$c = new Criteria();
$c->add(UnprocessedDevicesPeer::FILENAME, $this->fileName);
$c->add(UnprocessedDevicesPeer::DEVICE_ID,$device_id);
$c->setLimit(1);
$dcheck = UnprocessedDevicesPeer::doSelect($c);
if(empty($dcheck)){ //unprocessed device record of this does not exit
//saved as unprocessed
$unprocessed = new UnprocessedDevices();
$unprocessed->setFilename($this->fileName);
$unprocessed->setDeviceId($device_id);
$unprocessed->save();
}//if
}
}//if
}//for
}//function
public function getUnprocessedDevices($filename){
$unprocessedDevices_id = array();
$c = new Criteria();
$c->add(UnprocessedDevicesPeer::FILENAME, $filename);
$unprocessedDevices = UnprocessedDevicesPeer::doSelect($c);
foreach($unprocessedDevices as $unprocessedDevice){
$unprocessedDevices_id[] = $unprocessedDevice->getDeviceId();
}
return $unprocessedDevices_id;
}
public function getMatched(){
return $this->match;
}
public function getFilename(){
return $this->fileName;
}
public function getPartialMatch(){
return $this->partial;
}
public function getNoMatch(){
return $this->noMatch;
}
public function getRandomNumber(){
srand((double)microtime()*1000000);
return rand(0,2000000);
}
private function changePm2Missing($clientId = null){
if(empty($clientId)) return;
$c = new Criteria();
$c->add(DevicePeer::CLIENT_ID,$clientId);
$c->add(DevicePeer::STATUS,'pm scheduled');
$devices = DevicePeer::doSelect($c);
foreach($devices as $device){
$device->setStatus('missing');
$device->save();
}
}
}

View File

@ -0,0 +1,184 @@
<?php
class sfPropelCustomJoinObjectProxy
{
protected
$customJoin,
$className,
$obj,
$extObjs;
public function __construct($customJoin, $className)
{
$this->customJoin = $customJoin;
$this->className = $className;
$this->obj = new $className;
$this->extObjs = array();
}
public function getDataObject()
{
return $this->obj;
}
public function isAllPrimaryKeyNull()
{
$pks = $this->obj->getPrimaryKey();
foreach ((array)$pks as $pk)
if ($pk)
return false;
return true;
}
public function __call($name, $args)
{
if (preg_match('/^get(.*)$/', $name, $matches))
{
if (array_key_exists($matches[1], $this->extObjs))
return $this->extObjs[$matches[1]];
}
return call_user_func_array(array($this->obj, $name), $args);
}
public function hydrate(ResultSet $rs, $startcol = 1)
{
$startcol = $this->obj->hydrate($rs, $startcol);
return $startcol;
}
public function addExternalObject($obj, $alias=false)
{
$key = $alias?$alias:get_class($obj->getDataObject());
$this->extObjs[$key] = $obj;
}
}
class sfPropelCustomJoinHelper
{
protected
$mainClassName = '',
$selectClasses,
$classOwnership;
public function __construct($mainClassName)
{
$this->mainClassName = $mainClassName;
$this->selectClasses = array();
$this->classOwnership = array();
}
public function addSelectTables()
{
$classes = array();
if (func_num_args() == 1)
$classes = (array)func_get_arg(0);
else
$classes = func_get_args();
$this->selectClasses = array_merge($this->selectClasses, $classes);
}
public function clearSelectClasses()
{
$this->selectClasses = array();
}
public function hydrate($rs, $startCol=1)
{
$obj = new sfPropelCustomJoinObjectProxy($this, $this->mainClassName);
$startCol = $obj->hydrate($rs, 1);
$childObjs = array();
foreach ($this->selectClasses as $className)
{
$childObj = new sfPropelCustomJoinObjectProxy($this, $className);
$startCol = $childObj->hydrate($rs, $startCol);
if ($childObj->isAllPrimaryKeyNull())
$childObjs[$className] = null;
else
$childObjs[$className] = $childObj;
}
foreach ($childObjs as $childClassName => $childObj)
{
$obj->addExternalObject($childObj, $childClassName); //main class object always holds all child objects.
if (isset($this->classOwnership[$childClassName]))
foreach ($this->classOwnership[$childClassName] as $tmp)
if (array_key_exists($tmp[0], $childObjs))
$childObj->addExternalObject($childObjs[$tmp[0]], $tmp[1]);
}
return $obj;
}
public function doCount($c, $con=null)
{
return call_user_func_array(array($this->mainClassName.'Peer', 'doCount'), array($c, $con));
}
public function doSelect($c, $con=null)
{
$rs = $this->doSelectRS($c, $con=null);
$a = array();
while ($rs->next())
$a[] = $this->hydrate($rs);
return $a;
}
public function doSelectOne(Criteria $criteria, $con = null)
{
$critcopy = clone $criteria;
$critcopy->setLimit(1);
$objects = $this->doSelect($critcopy, $con);
if ($objects) {
return $objects[0];
}
return null;
}
/**
* Return the Propel ResultSet object.
*
* This method adds all columns specified with addSelectTables method.
* @see addSelectTables
*/
public function doSelectRS($criteria, $con=null)
{
$c = clone $criteria;
$c->clearSelectColumns();
call_user_func(array($this->mainClassName.'Peer', 'addSelectColumns'), $c);
foreach ($this->selectClasses as $className)
call_user_func(array($className.'Peer', 'addSelectColumns'), $c);
$rs = call_user_func_array(array($this->mainClassName.'Peer', 'doSelectRS'), array($c, $con));
return $rs;
}
public function setHas($className, $has, $alias=false)
{
if (!isset($this->classOwnership[$className]))
$this->classOwnership[$className] = array();
$alias = ($alias === false?$className:$alias);
$this->classOwnership[$className][] = array($has, $alias);
}
/**
* Do proxy call to peer method of the main class.
*/
protected function __call($name, $args)
{
return call_user_func_array(array($this->mainClassName.'Peer', $name), $args);
}
/**
* Return the main class name. This is to work around when the pager object
* tries to include the Peer class file.
*/
public function __toString()
{
return $this->mainClassName;
}
}