Why the JoomShopping plug-in does not work? - php

Sorry for my bad english, but I really need to know why this plugin does not work at all.
So i have Joomla 3.5.1 + JoomShopping 4.14.1
I want to connect the attributes filter plugin. But it does not work.
Help me please!!!
<?php
// No direct access.
defined('_JEXEC') or die;
class plgJShoppingOxboxAttribsFilter extends JPlugin
{
public function __construct(&$subject, $config)
{
parent::__construct($subject, $config);
}
public function onBeforeQueryCountProductList($controller, &$adv_result, &$adv_from, &$adv_query, &$order_query, &$filters = array())
{
$this->onBeforeQueryGetProductList($controller, &$adv_result, &$adv_from, &$adv_query, &$order_query, &$filters);
}
public function onBeforeQueryGetProductList($controller, &$adv_result, &$adv_from, &$adv_query, &$order_query, &$filters = array())
{
// Ïîëó÷àåì îáúåêò áàçû äàííûõ
$db = JFactory::getDBO();
//
$query = $db->getQuery(true);
//
$query->select('params');
//
$query->from('#__modules');
//
$query->where('module = "mod_oxbox_jshopping_attribute_filter"');
//
$query->where('published = 1');
//
$db->setQuery($query);
//
$list = $db->loadObjectList();
//
if (is_array($list) && count($list))
{
//
foreach ($list as $item)
{
//
$registry = new JRegistry();
//
$registry->loadString($item->params);
//
$item->params = $registry->toArray();
// Ïîëó÷àåì çíà÷åíèå
$vals = JRequest::getVar($item->params->get('param_name'), '');
//
$vals = urldecode($vals);
// Åñëè çíà÷åíèå íå ïóñòîå
if (!empty($vals))
{
// Åñëè ñîäåðæèò òî÷êó ñ çàïÿòîé
if (JString::strpos($vals, ';'))
{
// Ïðåîáðàçóåì â ìàññèâ
$vals = explode(';', $vals);
}
// Åñëè â ìàññèâå òîëüêî îäèí ýëåìåíò
if (is_array($vals) && count($vals) == 1)
{
//
$vals = $vals[1];
}
//
$attr_id = $item->params->get('attr_id');
//
$db->setQuery('SELECT independent FROM #__jshopping_attr WHERE attr_id = '.$attr_id);
// Ïîëó÷àåì ðåçóëüòàò
$independent = $db->loadResult();
// Åñëè àòðèáóò íåçàâèñèìûé
if ($independent)
{
$table = '#__jshopping_products_attr2';
$attr_value_id_field = 'attr_value_id';
}
else
{
$table = '#__jshopping_products_attr';
$attr_value_id_field = 'attr_'.$attr_id;
}
// Åñëè ôèëüòðóåì ïî çíà÷åíèÿì àòðèáóòîâ
if ($item->params->get('param_type', 'value') == 'value')
{
// Åñëè ýòî ìàññèâ
if (is_array($vals))
{
$adv_query .= 'AND prod.product_id IN (SELECT product_id FROM `'.$table.'` AS attr LEFT JOIN #__jshopping_attr_values AS attr_values ON attr_values.value_id = attr.'.$attr_value_id_field.' WHERE `name_ru-RU` in ('.implode(',', $vals).'))';
}
else
{
$adv_query .= 'AND prod.product_id IN (SELECT product_id FROM `'.$table.'` AS attr LEFT JOIN #__jshopping_attr_values AS attr_values ON attr_values.value_id = attr.'.$attr_value_id_field.' WHERE `name_ru-RU`="'.$vals.'")';
}
}
else // èíà÷å ôèëüòðóåì ïî èäåíòèôèêàòîðàì çíà÷åíèé àòðèáóòîâ
{
// Åñëè ýòî ìàññèâ
if (is_array($vals))
{
$adv_query .= ' AND prod.product_id IN (SELECT product_id FROM `'.$table.'` AS attr WHERE attr.'.$attr_value_id_field.' in ('.implode(',', $vals).'))';
}
else
{
$adv_query .= ' AND prod.product_id IN (SELECT attr.product_id FROM `'.$table.'` AS attr WHERE attr.'.$attr_value_id_field.' = '.$vals.')';
}
}
}
}
}
}
}

Related

Quicken Code to get Past Godaddy Server Timeout

I have an issue where I need to data from a RETS server and populate it on the database, I was able to get all but two tables to properly automate this data in, but I'm having issues with the last (and biggest) two. After looking at it, the issue is timeout with the server, it cannot finish in time for the database to populate.
I am working off of a godaddy server and already have the maximum time I can set for the program to run, the only thing I can do now is figure out a way to speed up my code so it finishes in time, and would like some help figuring that out.
The code (posted below) was modified to fit my needs from here: https://github.com/coreyrowell/retshelper/blob/master/rets_helper.php
While it works well and I was able to get it working, I haven't been able to figure out the best way to speed it up. Any help would be sincerely appreciated.
<?php
/*
.---------------------------------------------------------------------------.
| Software: RETSHELPER - PHP Class to interface RETS with Database |
| Version: 1.0 |
| Contact: corey#coreyrowell.com |
| Info: None |
| Support: corey#coreyrowell.com |
| ------------------------------------------------------------------------- |
| Author: Corey Rowell - corey#coreyrowell.com |
| Copyright (c) 2013, Corey Rowell. All Rights Reserved. |
| ------------------------------------------------------------------------- |
| License: This content is released under the |
| (http://opensource.org/licenses/MIT) MIT License. | |
'---------------------------------------------------------------------------'
*/
/*
.---------------------------------------------------------------------------.
| This software requires the use of the PHPRETS library |
| http://troda.com/projects/phrets/ |
'---------------------------------------------------------------------------'
*/
define("BASE_PATH",dirname(__FILE__)."/");
ini_set('mysql.connect_timeout',0);
ini_set('default_socket_timeout',0);
class RETSHELPER
{
// Defaults
private $rets, $auth, $config, $database, $mysqli, $data, $log, $scriptstart, $scriptend,
$previous_start_time, $current_start_time, $updates_log, $active_ListingRids = array();
public function __construct()
{
// Require PHRETS library
require_once("phrets.php");
// Start rets connection
$this->rets = new phRETS;
$this->scriptstart = date("m-d-y_h-i-s", time());
// RETS Server Info
$this->auth['url'] = 'redacted';//MLS_URL;//MLS_URL;
$this->auth['username'] = 'redacted'; //MLS_USERNAME;
$this->auth['password'] = 'redacted'; //MLS_PASS;
$this->auth['retsversion'] = ''; //USER Agent Version
$this->auth['useragent'] = ''; //USER Agent
// RETS Options
$this->config['property_classes'] = array("A");//,"B","C","D","E","F");
$this->config['KeyField'] = "LIST_1";
$this->config['offset_support'] = TRUE; // Enable if RETS server supports 'offset'
$this->config['useragent_support'] = FALSE;
$this->config['images_path'] = BASE_PATH."listing_photos/";
$this->config['logs_path'] = BASE_PATH."logs/";
$this->config['start_times_path'] = BASE_PATH."logs/";
$this->config['previous_start_time'] = $this->get_previous_start_time();
$this->config['create_tables'] = FALSE; // Create tables for classes (terminates program)
// Log to screen?
$this->config['to_screen'] = TRUE;
// Database Config
$this->database['host'] = 'redacted'; //DB_SERVER;
$this->database['username'] = 'redacted'; //DB_USER;
$this->database['password'] = 'redacted'; //DB_PASS;
$this->database['database'] = 'redacted'; //DB_NAME;
$this->config_init();
// Load the run function
$this->run();
}
private function config_init()
{
// Set offset support based on config
if($this->config['offset_support'])
{
$this->rets->SetParam("offset_support", true);
} else {
$this->rets->SetParam("offset_support", false);
}
if($this->config['useragent_support'])
{
$this->rets->AddHeader("RETS-Version", $this->auth['retsversion']);
$this->rets->AddHeader("User-Agent", $this->auth['useragent']);
}
}
public function run()
{
// Start Logging
$this->logging_start();
// RETS Connection
$this->connect();
// Connect to Database
$this->database_connect();
if($this->config['create_tables'])
{
$this->log_data("Creating database tables, program will exit after finishing.");
foreach ($this->config['property_classes'] as $class)
{
$this->log_data("Creating table for: " . $class);
$this->create_table_for_property_class($class);
}
$this->log_data("Exiting program.");
return;
}
// Get Properties (and images)
$this->get_properties_by_class();
// Close RETS Connection
$this->disconnect();
// Delete inactive listings
$this->database_delete_records();
// Insert new listings
$this->database_insert_records();
// Disconnect from Database
$this->database_disconnect();
// End Logging
$this->logging_end();
// Time for next scheduled update
$this->set_previous_start_time();
}
private function connect()
{
$this->log_data("Connecting to RETS...");
// Connect to RETS
$connect = $this->rets->Connect($this->auth['url'], $this->auth['username'], $this->auth['password']);
if($connect)
{
$this->log_data("Successfully connected to RETS.");
return TRUE;
} else {
$error = $this->rets->Error();
if($error['text'])
{
$error = $error['text'];
} else {
$error = "No error message returned from RETS. Check RETS debug file.";
}
$this->log_error("Failed to connect to RETS.\n".$error);
die();
}
}
private function get_properties_by_class()
{
$this->log_data("Getting Classes...");
foreach ($this->config['property_classes'] as $class)
{
$this->log_data("Getting Class: ".$class);
// Set
$fields_order = array();
$mod_timestamp_field = $this->get_timestamp_field($class);
$previous_start_time = $this->config['previous_start_time'];
$search_config = array('Format' => 'COMPACT-DECODED', 'QueryType' => 'DMQL2', 'Limit'=> 1000, 'Offset' => 1, 'Count' => 1);
/*--------------------------------------------------------------------------------.
| |
| If you're having problems, they probably lie here in the $query and/or $search. |
| |
'--------------------------------------------------------------------------------*/
// Query
$query = "({$mod_timestamp_field}=2016-09-16T00:00:00-2016-09-16T01:00:00)";//{$previous_start_time}+)";
// Run Search
$search = $this->rets->SearchQuery("Property", $class, $query, $search_config);
// Get all active listings
$query_all = "({$mod_timestamp_field}=1980-01-01T00:00:00+)";
$search_all = $this->rets->SearchQuery("Property", $class, $query_all, array('Format'=>'COMPACT', 'Select'=>$this->config['KeyField']));
$tmpArray = array();
while($active_rid = $this->rets->FetchRow($search_all)) {
array_push($tmpArray, $active_rid[$this->config['KeyField']]);
}
$this->active_ListingRids['property_'.strtolower($class)] = $tmpArray;
$data = array();
if ($this->rets->NumRows($search) > 0)
{
// Get columns
$fields_order = $this->rets->SearchGetFields($search);
$this->data['headers'] = $fields_order;
// Process results
while ($record = $this->rets->FetchRow($search))
{
$this_record = array();
// Loop it
foreach ($fields_order as $fo)
{
$this_record[$fo] = $record[$fo];
}
$ListingRid = $record[$this->config['KeyField']];
$data[] = $this_record;
}
}
// Set data
$this->data['classes'][$class] = $data;
$this->log_data("Finished Getting Class: ".$class . "\nTotal found: " .$this->rets->TotalRecordsFound());
// Free RETS Result
$this->rets->FreeResult($search);
}
}
private function get_timestamp_field($class)
{
$class = strtolower($class);
switch($class)
{
case 'a':
$field = "LIST_87";
break;
}
return $field;
}
private function disconnect()
{
$this->log_data("Disconnected from RETS.");
$this->rets->Disconnect();
}
private function database_connect()
{
$this->log_data("Connecting to database...");
$host = $this->database['host'];
$username = $this->database['username'];
$password = $this->database['password'];
$database = $this->database['database'];
// Create connection
$this->mysqli = new mysqli($host, $username, $password, $database);
// Throw error if connection fails
if ($this->mysqli->connect_error) {
$this->log_error("Database Connection Error". $this->mysqli->connect_error);
die('Connect Error (' . $this->mysqli->connect_errno . ') '
. $this->mysqli->connect_error);
}
}
private function database_delete_records()
{
$this->log_data("Updating database...");
// Loop through each table and update
foreach($this->config['property_classes'] as $class)
{
// Get Tables
$table = "rets_property_".strtolower($class);
$activeListings = $this->active_ListingRids['property_'.strtolower($class)];
$sql = "DELETE FROM {$table} WHERE {$this->config['KeyField']} NOT IN (".implode(',', $activeListings).");";
$this->mysqli->query($sql);
if($this->mysqli->affected_rows > 0)
{
$this->log_data("Deleted {$this->mysqli->affected_rows} Listings.");
// return TRUE;
} else if($this->mysqli->affected_rows == 0) {
$this->log_data("Deleted {$this->mysqli->affected_rows} Listings.");
} else {
$this->log_data("Deleting database records failed \n\n" . mysqli_error($this->mysqli));
// return FALSE;
}
}
}
private function database_insert_records()
{
$this->log_data("Inserting records...");
foreach($this->config['property_classes'] as $class)
{
// Get Tables
$table = "rets_property_".strtolower($class);
// Get data
$data_row = $this->data['classes'][$class];
// Defaults
$total_rows = 0;
$total_affected_rows = 0;
// Loop through data
foreach($data_row as $drow)
{
// Clean data
// replace empty with NULL
// and wrap data in quotes
$columns = array();
$values = array();
foreach($drow as $key => $val)
{
if($val === '')
{
$val = '""';
} else {
$val = mysqli_real_escape_string($this->mysqli ,$val);
$val = "'$val'";
}
$columns[] = $key;
$values[] = $val;
}
// Implode data rows with commas
$values = implode(', ', $values);
$columns = implode(', ', $columns);
// Build SQL
$sql = "REPLACE INTO {$table} ({$columns}) VALUES ({$values})";
// Do query
$this->mysqli->query($sql);
if($this->mysqli->affected_rows > 0)
{
$total_affected_rows++;
} else {
$this->log_error("Failed to insert the following record: ".$sql . "\n\n" . mysqli_error($this->mysqli));
}
$total_rows++;
}
$this->log_data("Done inserting data. ".$class."\nTotal Records: ".$total_rows." .\nTotal Inserted: ".$total_affected_rows);
}
}
private function database_disconnect()
{
$this->log_data("Database disconnected...");
// Close connection
$this->mysqli->close();
}
private function create_table_for_property_class($class)
{
// gets resource information. need this for the KeyField
$rets_resource_info = $this->rets->GetMetadataInfo();
$resource = "Property";
// pull field format information for this class
$rets_metadata = $this->rets->GetMetadata($resource, $class);
$table_name = "rets_".strtolower($resource)."_".strtolower($class);
// i.e. rets_property_resi
$sql = $this->create_table_sql_from_metadata($table_name, $rets_metadata, $rets_resource_info[$resource]['KeyField']);
$this->mysqli->query($sql);
}
private function create_table_sql_from_metadata($table_name, $rets_metadata, $key_field, $field_prefix = "")
{
$sql_query = "CREATE TABLE {$table_name} (\n";
foreach ($rets_metadata as $field) {
$field['SystemName'] = "`{$field_prefix}{$field['SystemName']}`";
$cleaned_comment = addslashes($field['LongName']);
$sql_make = "{$field['SystemName']} ";
if ($field['Interpretation'] == "LookupMulti") {
$sql_make .= "TEXT";
}
elseif ($field['Interpretation'] == "Lookup") {
$sql_make .= "VARCHAR(50)";
}
elseif ($field['DataType'] == "Int" || $field['DataType'] == "Small" || $field['DataType'] == "Tiny") {
$sql_make .= "INT({$field['MaximumLength']})";
}
elseif ($field['DataType'] == "Long") {
$sql_make .= "BIGINT({$field['MaximumLength']})";
}
elseif ($field['DataType'] == "DateTime") {
$sql_make .= "DATETIME default '0000-00-00 00:00:00' not null";
}
elseif ($field['DataType'] == "Character" && $field['MaximumLength'] <= 255) {
$sql_make .= "VARCHAR({$field['MaximumLength']})";
}
elseif ($field['DataType'] == "Character" && $field['MaximumLength'] > 255) {
$sql_make .= "TEXT";
}
elseif ($field['DataType'] == "Decimal") {
$pre_point = ($field['MaximumLength'] - $field['Precision']);
$post_point = !empty($field['Precision']) ? $field['Precision'] : 0;
$sql_make .= "DECIMAL({$field['MaximumLength']},{$post_point})";
}
elseif ($field['DataType'] == "Boolean") {
$sql_make .= "CHAR(1)";
}
elseif ($field['DataType'] == "Date") {
$sql_make .= "DATE default '0000-00-00' not null";
}
elseif ($field['DataType'] == "Time") {
$sql_make .= "TIME default '00:00:00' not null";
}
else {
$sql_make .= "VARCHAR(255)";
}
$sql_make .= " COMMENT '{$cleaned_comment}'";
$sql_make .= ",\n";
$sql_query .= $sql_make;
}
$sql_query .= "`Photos` TEXT COMMENT 'Photos Array', ";
$sql_query .= "PRIMARY KEY(`{$field_prefix}{$key_field}`) )";
return $sql_query;
}
private function get_previous_start_time()
{
$filename = "previous_start_time_A.txt";
// See if file exists
if(file_exists($this->config['start_times_path'].$filename))
{
$time=time();
$this->updates_log = fopen($this->config['start_times_path'].$filename, "r+");
$this->previous_start_time = fgets($this->updates_log);
$this->current_start_time = date("Y-m-d", $time) . 'T' . date("H:i:s", $time);
} else {
// Create file
$this->updates_log = fopen($this->config['start_times_path'].$filename, "w+");
fwrite($this->updates_log, "1980-01-01T00:00:00\n");
$this->get_previous_start_time();
}
// fgets reads up to & includes the first newline, strip it
return str_replace("\n", '', $this->previous_start_time);
}
private function set_previous_start_time()
{
$file = $this->config['start_times_path'] . "previous_start_time_A.txt";
$file_data = $this->current_start_time."\n";
$file_data .= file_get_contents($file);
file_put_contents($file, $file_data);
}
private function logging_start()
{
$filename = "Log".date("m-d-y_h-i-s", time()).".txt";
// See if file exists
if(file_exists($this->config['logs_path'].$filename))
{
$this->log = fopen($this->config['logs_path'].$filename, "a");
} else {
// Create file
$this->log = fopen($this->config['logs_path'].$filename, "w+");
}
}
private function log_data($data)
{
$write_data = "\nInfo Message: [".date("m/d/y - h:i:s", time())."]\n------------------------------------------------\n";
$write_data .= $data."\n";
$write_data .= "\n------------------------------------------------\n";
fwrite($this->log, $write_data);
if($this->config['to_screen'])
{
echo str_replace(array("\n"), array('<br />'), $write_data);
}
}
private function log_error($error)
{
$write_data = "\nError Message: [".date("m/d/y - h:i:s", time())."]\n------------------------------------------------\n";
$write_data .= $error."\n";
$write_data .= "\n------------------------------------------------\n";
fwrite($this->log, $write_data);
if($this->config['to_screen'])
{
echo str_replace(array("\n"), array('<br />'), $write_data);
}
}
private function logging_end()
{
$this->scriptend = date("m-d-y_h-i-s", time());
$this->log_data("Closing log file.\n
Start Time: {$this->scriptstart}\n
End Time: {$this->scriptend}");
fclose($this->log);
}
}
// Load the class
$retshelper = new RETSHELPER;
Sorry for the wall of code; I would shorten it down but I'm at a loss with what is still needed and what isn't. Once again, any help would or a point into the right direction would be appreciated.

PHP notice Undefined index for magmi disabler

I have setup magmi with item disabler. And i got PHP notice: Undefined index: ITEM_SID in /home/mywebsite/www/public_html/magmi/plugins/extra/itemprocessors/itemdisabler/magmi_itemdisabler_plugin.php on line 65
This is the my code for item disabler
<?php class Magmi_ItemdisablerPlugin extends Magmi_GeneralImportPlugin {
protected $_dcols=array();
protected $magentoSortableAttributes = array();
public function getPluginInfo()
{
return array("name"=>"Magmi Magento Item Disabler",
"author"=>"RIS",
"version"=>"1.0.0");
}
public function afterImport()
{
$this->log("Running Item Disabler Plugin","info");
$this->disableItems();
return true;
}
public function getPluginParams($params)
{
return array();
}
public function isRunnable()
{
return array(true,"");
}
public function initialize($params)
{
}
public function disableItems()
{
$this->datasource = $this->getDataSource();
$nitems=$this->lookup();
if($nitems>0)
{
$datasource_item_sids = array();
$this->resetSkuStats();
//intialize store id cache
$this->callPlugins("datasources,itemprocessors","startImport");
//initializing item processors
$cols=$this->datasource->getColumnNames();
$this->log(count($cols),"columns");
//$this->callPlugins("itemprocessors","processColumnList",$cols);
//Pack the datasource sids into an array
$i = 0;
while(($item=$this->datasource->getNextRecord())!==false && $i++ <= $nitems)
{
if (isset($item['STYLE_SID']) && $this->isConfigurable($item['ATTR']))
{
array_push($datasource_item_sids, $item['STYLE_SID']);
}
array_push($datasource_item_sids, $item['ITEM_SID']);
if($i == $nitems) {
break;
}
}
if(count($datasource_item_sids) > 0) {
//Convert skus to comma seperated values.
//$datasource_item_sids = "'" . implode("','",$datasource_item_sids) . "'";
//Load in Database Helpers
require_once(realpath(dirname( __FILE__ ) )."/../../../../inc/dbhelper.class.php");
//var_dump($this->_magmiconfig->load()->get("DATABASE","host","localhost"));
$db = new DBHelper();
$host=$this->_magmiconfig->load()->get("DATABASE","host","localhost");
$dbname=$this->_magmiconfig->load()->get("DATABASE","dbname","magento");
$user=$this->_magmiconfig->load()->get("DATABASE","user");
$pass=$this->_magmiconfig->load()->get("DATABASE","password");
$debug=$this->_magmiconfig->load()->get("DATABASE","debug");
$conn=$this->_magmiconfig->load()->get("DATABASE","connectivity","net");
$port=$this->_magmiconfig->load()->get("DATABASE","port","3306");
$socket=$this->_magmiconfig->load()->get("DATABASE","unix_socket");
$prefix=$this->_magmiconfig->load()->get("DATABASE","table_prefix");
$db->initDb($host,$dbname,$user,$pass,$port,$socket,$conn,$debug);
//Setup tables
$ea = $prefix!=""?$prefix."eav_attribute":"eav_attribute";
$cpe = $prefix!=""?$prefix."catalog_product_entity":"catalog_product_entity";
$cpei = $prefix!=""?$prefix."catalog_product_entity_int":"catalog_product_entity_int";
//Get "status" attribute_id
$status_attr_id = "SELECT attribute_id FROM $ea WHERE attribute_code = 'status'";
$result = $db->selectAll($status_attr_id);
if (count($result) == 1) {
$attribute_id = $result[0]['attribute_id'];
}
unset($result);
//Get all active items
$sql = "SELECT e.sku, e.entity_id FROM $cpei i
INNER JOIN $cpe e ON
e.entity_id = i.entity_id
WHERE attribute_id=?
AND i.value = 1";
$all_magento_items = $db->selectAll($sql, array($attribute_id));
//Setup the magento_skus array for easy processing.
$magento_skus = array();
foreach($all_magento_items as $item)
{
$magento_skus[$item['sku']] = $item['entity_id'];
}
//process the array, move anything thats in the datasource.
foreach($datasource_item_sids as $sku)
{
if(isset($magento_skus[$sku]))
{
unset($magento_skus[$sku]);
}
}
if(!empty($magento_skus))
{
foreach($magento_skus as $sku => $id)
{
$this->log("Disabling Item Id $id with SKU: $sku", "info");
$this->update("
UPDATE $cpei i
INNER JOIN $cpe e ON
e.entity_id = i.entity_id
SET VALUE = '2'
WHERE attribute_id = ?
AND i.value = 1
AND e.sku=?", array($attribute_id, $sku));
}
}
else
{
//If the Datasource contains all Magento's items.
$this->log('All items present in datasource. No items to disable.', "info");
}
$db->exitDb();
unset($db);
}
}
}
public function isConfigurable($field) {
$attributes = explode('|',$field);
$conf_attributes = '';
foreach($attributes as $attribut) {
$att = explode(':',$attribut);
if(count($att) != 2) {
return false;
break;
}
if($att[1] == '') {
return false;
break;
}
}
return true;
}
}
Any idea how i can resolve this?
You can check if that element is set before using it:
while(($item=$this->datasource->getNextRecord())!==false && $i++ <= $nitems)
{
if (isset($item['STYLE_SID']) && $this->isConfigurable($item['ATTR']))
{
array_push($datasource_item_sids, $item['STYLE_SID']);
}
if (isset($item['ITEM_SID']){
array_push($datasource_item_sids, $item['ITEM_SID']);
}
if($i == $nitems) {
break;
}
}

How do I modify an existing file to add the ability to unlink a specific file from a folder?

Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>

using joomla function into external php script

I have joomla installed with custom functions, i need to use those custom functions in another php script that i have
in the joomla site i have functions in libraries>rvv>factory.php
and components>com_customs folder
on the view tmpl page the one of the functions is shown <?php $points = RFactory::getPoint($downLine->agentID); ?>
<th><?php echo $points['left'].' - '.$points['right']; ?></th>
on the component function script file
public function getDownLine($agentId)
{
ini_set('max_execution_time', 600); //300 seconds = 5 minutes
$this->downLinesRecursion($agentId);
function cmp( $a, $b )
{
if( $a->agentID == $b->agentID ){ return 0 ; }
return ($a->agentID < $b->agentID) ? -1 : 1;
}
usort($this->downLine,'cmp');
$this->_total = count($this->downLine);
$endDownLine = array_splice($this->downLine, $this->getState('limitstart'), $this->getState('limit'));
return $endDownLine;
}
protected function downLinesRecursion($agentId)
{
$downLineIDs = RFactory::getDownLines($agentId);
if($downLineIDs){
foreach ($downLineIDs as $downLineID){
$agent = RFactory::getAgent($downLineID->id);
$this->downLine[] = $agent;
$this->downLinesRecursion($agent->agentID);
}
}
}
public function getAgentExisting($agentId)
{
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
$this->subAgentID = $agentId;
$this->existingRecursion($this->agentID);
return $this->agentExisting;
}
protected function existingRecursion($agentId)
{
$downLineIDs = RFactory::getDownLines($agentId);
if($downLineIDs){
foreach ($downLineIDs as $downLineID){
if($downLineID->id == $this->subAgentID){
$this->agentExisting = true;
}else{
$this->existingRecursion($downLineID->id);
}
}
}
}
public function getAgentId($username)
{
$userId = $this->getUserId($username);
if($userId){
$agentIds = RFactory::getAgentIds($userId);
foreach ($agentIds as $AgentId) {
$agentId = $AgentId->id;
break;
}
return $agentId;
}else {
return false;
}
}
ON THE FACTORY FILE:
public static function getAgent($agentId)
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(' ag.id AS agentID, ag.user_id AS agentUserID, ag.parent_client_id, ag.directe_client_id, ag.position, date(ag.reg_time) AS joinDate, ag.offers_id, ag.cash');
$query->select(' ofr.* ');
$query->select(' usrinf.* ');
$query->select(' usr.name AS agentName, usr.username, usr.email, date(usr.registerDate) AS regDate ');
$query->select(' stk.value AS stockValue ');
$query->from(' #__r_clients AS ag ');
$query->leftJoin(' #__r_offers AS ofr ON ofr.id = ag.offers_id ');
$query->leftJoin(' #__r_clients_info AS usrinf ON usrinf.user_id = ag.user_id ');
$query->leftJoin(' #__users AS usr On usr.id = ag.user_id ');
$query->leftJoin(' #__r_stock AS stk On stk.client_id = ag.id ');
$query->where(' ag.id = '.$agentId);
$db->setQuery((string)$query);
$data = $db->loadObject();
if (!$db->query()) {
JError::raiseError(500, $db->getErrorMsg());
return false;
}else {
if ($db->getNumRows() < 1){
return false;
}else{
return $data;
}
}
}
public static function getAgents()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(' ag.id AS agentID, ag.user_id AS agentUserID, ag.parent_client_id, ag.directe_client_id, ag.position, date(ag.reg_time) AS joinDate, ag.offers_id, ag.cash');
$query->select(' ofr.* ');
$query->select(' usr.name AS agetName, usr.username, usr.email, usr.registerDate ');
$query->from(' #__r_clients AS ag ');
$query->leftJoin(' #__r_offers AS ofr ON ofr.id = ag.offers_id ');
$query->leftJoin(' #__users AS usr On usr.id = ag.user_id ');
$db->setQuery((string)$query);
$data = $db->loadObjectList();
if (!$db->query()) {
JError::raiseError(500, $db->getErrorMsg());
return false;
}else {
if ($db->getNumRows() < 1){
return false;
}else{
return $data;
}
}
}
public static function getDownLines($agentId)
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(' id ');
$query->from(' #__r_clients ');
$query->where(' parent_client_id = '.$agentId);
$db->setQuery((string)$query);
$data = $db->loadObjectList();
if (!$db->query()) {
JError::raiseError(500, $db->getErrorMsg());
return false;
}else {
if ($db->getNumRows() < 1){
return false;
}else{
return $data;
}
}
}
public static function getPoint($agentId)
{
$downLines = self::getDownLines($agentId);
self::$rightPoint = 0;
self::$leftPoint = 0;
if($downLines){
foreach ($downLines as $downLine){
$agent = self::getAgent($downLine->id);
if($agent->position == 'R'){
self::$rightPoint += $agent->point;
self::rightPointRecursion($agent->agentID);
}else {
self::$leftPoint += $agent->point;
self::leftPointRecursion($agent->agentID);
}
}
return $pointArray = array('right' => self::$rightPoint, 'left' => self::$leftPoint);
}else {
return $pointArray = array('right' => 0, 'left' => 0);
}
}
private function rightPointRecursion($agentId)
{
$downLines = self::getDownLines($agentId);
if($downLines){
foreach ($downLines as $downLine){
$agent = self::getAgent($downLine->id);
self::$rightPoint += $agent->point;
self::rightPointRecursion($agent->agentID);
}
}
}
private function leftPointRecursion($agentId)
{
$downLines = self::getDownLines($agentId);
if($downLines){
foreach ($downLines as $downLine){
$agent = self::getAgent($downLine->id);
self::$leftPoint += $agent->point;
self::leftPointRecursion($agent->agentID);
}
}
}
the custom joomla code is inside the components>com_hierarchical>hierarchical.php contains :
JLoader::register('HierarchicalHelper', dirname(__FILE__) . DS . 'helpers'. DS . 'hierarchical.php');
jimport('joomla.application.component.controller');
$document =& JFactory::getDocument();
$script = JURI::base(true).'/components/com_hierarchical/assist/gscript.js';
$style = JURI::base(true).'/components/com_hierarchical/assist/gstyle.css';
$document->addScript($script);
$document->addStyleSheet($style);
$controller = JController::getInstance('Hierarchical');
$controller->execute(JFactory::getApplication()->input->get('task'));
$controller->redirect();
How can i use those functions into another php file outside the joomla script?
In your external php script just load Joomla frame work,
then you can use all the Joomla functions and Objects in your external php file.
define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) );//this is when we are in the root
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
Hope its helps..

I can not resolve this error in SugarCRM

In SugarCRM (program management) module called "projects" by default does not come with the "import", it added eh following programming steps:
http://forums.sugarcrm.com/f148/how-add-importación-opción-custom-modules-45612/
Now I throw the error when I Import Next:
Fatal error: Llamada a una función miembro get_importable_fields () en un no-objeto en C: \ Archivos de programa \ Apache Software Foundation \ Apache2.2 \ htdocs \ Azúcar \ modules \ Import \ v iews \ view.step3.php en línea 217
Please somebody help me ... if necessary ... I will upload the file so they can help view.step3.php
Here is the line 217:
$fields = $this->bean->get_importable_fields();
$options = array();
$defaultField = '';
global $current_language;
$moduleStrings = return_module_language($current_language, $this->bean->module_dir);
Here I publish the above lines:
class ImportViewStep3 extends ImportView
{
protected $pageTitleKey = 'LBL_STEP_3_TITLE';
protected $currentFormID = 'importstep3';
protected $previousAction = 'Confirm';
protected $nextAction = 'dupcheck';
/**
* #see SugarView::display()
*/
public function display()
{
global $mod_strings, $app_strings, $current_user, $sugar_config, $app_list_strings, $locale;
$this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
$has_header = ( isset( $_REQUEST['has_header']) ? 1 : 0 );
$sugar_config['import_max_records_per_file'] = ( empty($sugar_config['import_max_records_per_file']) ? 1000 : $sugar_config['import_max_records_per_file'] );
$this->ss->assign("CURRENT_STEP", $this->currentStep);
// attempt to lookup a preexisting field map
// use the custom one if specfied to do so in step 1
$mapping_file = new ImportMap();
$field_map = $mapping_file->set_get_import_wizard_fields();
$default_values = array();
$ignored_fields = array();
if ( !empty( $_REQUEST['source_id']))
{
$GLOBALS['log']->fatal("Loading import map properties.");
$mapping_file = new ImportMap();
$mapping_file->retrieve( $_REQUEST['source_id'],false);
$_REQUEST['source'] = $mapping_file->source;
$has_header = $mapping_file->has_header;
if (isset($mapping_file->delimiter))
$_REQUEST['custom_delimiter'] = $mapping_file->delimiter;
if (isset($mapping_file->enclosure))
$_REQUEST['custom_enclosure'] = htmlentities($mapping_file->enclosure);
$field_map = $mapping_file->getMapping();
//print_r($field_map);die();
$default_values = $mapping_file->getDefaultValues();
$this->ss->assign("MAPNAME",$mapping_file->name);
$this->ss->assign("CHECKMAP",'checked="checked" value="on"');
}
else
{
$classname = $this->getMappingClassName(ucfirst($_REQUEST['source']));
//Set the $_REQUEST['source'] to be 'other' for ImportMapOther special case
if($classname == 'ImportMapOther')
{
$_REQUEST['source'] = 'other';
}
if (class_exists($classname))
{
$mapping_file = new $classname;
$ignored_fields = $mapping_file->getIgnoredFields($_REQUEST['import_module']);
$field_map2 = $mapping_file->getMapping($_REQUEST['import_module']);
$field_map = array_merge($field_map,$field_map2);
}
}
$delimiter = $this->getRequestDelimiter();
$this->ss->assign("CUSTOM_DELIMITER", $delimiter);
$this->ss->assign("CUSTOM_ENCLOSURE", ( !empty($_REQUEST['custom_enclosure']) ? $_REQUEST['custom_enclosure'] : "" ));
//populate import locale values from import mapping if available, these values will be used througout the rest of the code path
$uploadFileName = $_REQUEST['file_name'];
// Now parse the file and look for errors
$importFile = new ImportFile( $uploadFileName, $delimiter, html_entity_decode($_REQUEST['custom_enclosure'],ENT_QUOTES), FALSE);
if ( !$importFile->fileExists() ) {
$this->_showImportError($mod_strings['LBL_CANNOT_OPEN'],$_REQUEST['import_module'],'Step2');
return;
}
$charset = $importFile->autoDetectCharacterSet();
// retrieve first 3 rows
$rows = array();
//Keep track of the largest row count found.
$maxFieldCount = 0;
for ( $i = 0; $i < 3; $i++ )
{
$rows[] = $importFile->getNextRow();
$maxFieldCount = $importFile->getFieldCount() > $maxFieldCount ? $importFile->getFieldCount() : $maxFieldCount;
}
$ret_field_count = $maxFieldCount;
// Bug 14689 - Parse the first data row to make sure it has non-empty data in it
$isempty = true;
if ( $rows[(int)$has_header] != false ) {
foreach ( $rows[(int)$has_header] as $value ) {
if ( strlen(trim($value)) > 0 ) {
$isempty = false;
break;
}
}
}
if ($isempty || $rows[(int)$has_header] == false) {
$this->_showImportError($mod_strings['LBL_NO_LINES'],$_REQUEST['import_module'],'Step2');
return;
}
// save first row to send to step 4
$this->ss->assign("FIRSTROW", base64_encode(serialize($rows[0])));
// Now build template
$this->ss->assign("TMP_FILE", $uploadFileName );
$this->ss->assign("SOURCE", $_REQUEST['source'] );
$this->ss->assign("TYPE", $_REQUEST['type'] );
$this->ss->assign("DELETE_INLINE_PNG", SugarThemeRegistry::current()->getImage('basic_search','align="absmiddle" alt="'.$app_strings['LNK_DELETE'].'" border="0"'));
$this->ss->assign("PUBLISH_INLINE_PNG", SugarThemeRegistry::current()->getImage('advanced_search','align="absmiddle" alt="'.$mod_strings['LBL_PUBLISH'].'" border="0"'));
$this->instruction = 'LBL_SELECT_MAPPING_INSTRUCTION';
$this->ss->assign('INSTRUCTION', $this->getInstruction());
$this->ss->assign("MODULE_TITLE", $this->getModuleTitle(false));
$this->ss->assign("STEP4_TITLE",
strip_tags(str_replace("\n","",getClassicModuleTitle(
$mod_strings['LBL_MODULE_NAME'],
array($mod_strings['LBL_MODULE_NAME'],$mod_strings['LBL_STEP_4_TITLE']),
false
)))
);
$this->ss->assign("HEADER", $app_strings['LBL_IMPORT']." ". $mod_strings['LBL_MODULE_NAME']);
// we export it as email_address, but import as email1
$field_map['email_address'] = 'email1';
// build each row; row count is determined by the the number of fields in the import file
$columns = array();
$mappedFields = array();
// this should be populated if the request comes from a 'Back' button click
$importColumns = $this->getImportColumns();
$column_sel_from_req = false;
if (!empty($importColumns)) {
$column_sel_from_req = true;
}
for($field_count = 0; $field_count < $ret_field_count; $field_count++) {
// See if we have any field map matches
$defaultValue = "";
// Bug 31260 - If the data rows have more columns than the header row, then just add a new header column
if ( !isset($rows[0][$field_count]) )
$rows[0][$field_count] = '';
// See if we can match the import row to a field in the list of fields to import
$firstrow_name = trim(str_replace(":","",$rows[0][$field_count]));
if ($has_header && isset( $field_map[$firstrow_name] ) ) {
$defaultValue = $field_map[$firstrow_name];
}
elseif (isset($field_map[$field_count])) {
$defaultValue = $field_map[$field_count];
}
elseif (empty( $_REQUEST['source_id'])) {
$defaultValue = trim($rows[0][$field_count]);
}
// build string of options
$fields = $this->bean->get_importable_fields();
this is my coding project.php:
class Project extends SugarBean {
// database table columns
var $id;
var $date_entered;
var $date_modified;
var $assigned_user_id;
var $modified_user_id;
var $created_by;
var $name;
var $description;
var $deleted;
// related information
var $assigned_user_name;
var $modified_by_name;
var $created_by_name;
var $account_id;
var $contact_id;
var $opportunity_id;
var $email_id;
var $estimated_start_date;
// calculated information
var $total_estimated_effort;
var $total_actual_effort;
var $object_name = 'Project';
var $module_dir = 'Project';
var $new_schema = true;
var $table_name = 'project';
var $importable = true;
// This is used to retrieve related fields from form posts.
var $additional_column_fields = array(
'account_id',
'contact_id',
'opportunity_id',
);
var $relationship_fields = array(
'account_id' => 'accounts',
'contact_id'=>'contacts',
'opportunity_id'=>'opportunities',
'email_id' => 'emails',
);
//////////////////////////////////////////////////////////////////
// METHODS
//////////////////////////////////////////////////////////////////
/**
*
*/
function Project()
{
parent::SugarBean();
}
/**
* overriding the base class function to do a join with users table
*/
/**
*
*/
function fill_in_additional_detail_fields()
{
parent::fill_in_additional_detail_fields();
$this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
//$this->total_estimated_effort = $this->_get_total_estimated_effort($this->id);
//$this->total_actual_effort = $this->_get_total_actual_effort($this->id);
}
/**
*
*/
function fill_in_additional_list_fields()
{
parent::fill_in_additional_list_fields();
$this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
//$this->total_estimated_effort = $this->_get_total_estimated_effort($this->id);
//$this->total_actual_effort = $this->_get_total_actual_effort($this->id);
}
/**
* Save changes that have been made to a relationship.
*
* #param $is_update true if this save is an update.
*/
function save_relationship_changes($is_update, $exclude=array())
{
parent::save_relationship_changes($is_update, $exclude);
$new_rel_id = false;
$new_rel_link = false;
//this allows us to dynamically relate modules without adding it to the relationship_fields array
if(!empty($_REQUEST['relate_id']) && !in_array($_REQUEST['relate_to'], $exclude) && $_REQUEST['relate_id'] != $this->id){
$new_rel_id = $_REQUEST['relate_id'];
$new_rel_relname = $_REQUEST['relate_to'];
if(!empty($this->in_workflow) && !empty($this->not_use_rel_in_req)) {
$new_rel_id = $this->new_rel_id;
$new_rel_relname = $this->new_rel_relname;
}
$new_rel_link = $new_rel_relname;
//Try to find the link in this bean based on the relationship
foreach ( $this->field_defs as $key => $def ) {
if (isset($def['type']) && $def['type'] == 'link'
&& isset($def['relationship']) && $def['relationship'] == $new_rel_relname) {
$new_rel_link = $key;
}
}
if ($new_rel_link == 'contacts') {
$accountId = $this->db->getOne('SELECT account_id FROM accounts_contacts WHERE contact_id=' . $this->db->quoted($new_rel_id));
if ($accountId !== false) {
if($this->load_relationship('accounts')){
$this->accounts->add($accountId);
}
}
}
}
}
/**
*
*/
function _get_total_estimated_effort($project_id)
{
$return_value = '';
$query = 'SELECT SUM('.$this->db->convert('estimated_effort', "IFNULL", 0).') total_estimated_effort';
$query.= ' FROM project_task';
$query.= " WHERE parent_id='{$project_id}' AND deleted=0";
$result = $this->db->query($query,true," Error filling in additional detail fields: ");
$row = $this->db->fetchByAssoc($result);
if($row != null)
{
$return_value = $row['total_estimated_effort'];
}
return $return_value;
}
/**
*
*/
function _get_total_actual_effort($project_id)
{
$return_value = '';
$query = 'SELECT SUM('.$this->db->convert('actual_effort', "IFNULL", 0).') total_actual_effort';
$query.= ' FROM project_task';
$query.= " WHERE parent_id='{$project_id}' AND deleted=0";
$result = $this->db->query($query,true," Error filling in additional detail fields: ");
$row = $this->db->fetchByAssoc($result);
if($row != null)
{
$return_value = $row['total_actual_effort'];
}
return $return_value;
}
/**
*
*/
function get_summary_text()
{
return $this->name;
}
/**
*
*/
function build_generic_where_clause ($the_query_string)
{
$where_clauses = array();
$the_query_string = $GLOBALS['db']->quote($the_query_string);
array_push($where_clauses, "project.name LIKE '%$the_query_string%'");
$the_where = '';
foreach($where_clauses as $clause)
{
if($the_where != '') $the_where .= " OR ";
$the_where .= $clause;
}
return $the_where;
}
function get_list_view_data()
{
$field_list = $this->get_list_view_array();
$field_list['USER_NAME'] = empty($this->user_name) ? '' : $this->user_name;
$field_list['ASSIGNED_USER_NAME'] = $this->assigned_user_name;
return $field_list;
}
function bean_implements($interface){
switch($interface){
case 'ACL':return true;
}
return false;
}
function create_export_query(&$order_by, &$where, $relate_link_join='')
{
$custom_join = $this->custom_fields->getJOIN(true, true,$where);
if($custom_join)
$custom_join['join'] .= $relate_link_join;
$query = "SELECT
project.*,
users.user_name as assigned_user_name ";
if($custom_join){
$query .= $custom_join['select'];
}
$query .= " FROM project ";
if($custom_join){
$query .= $custom_join['join'];
}
$query .= " LEFT JOIN users
ON project.assigned_user_id=users.id ";
$where_auto = " project.deleted=0 ";
if($where != "")
$query .= "where ($where) AND ".$where_auto;
else
$query .= "where ".$where_auto;
if(!empty($order_by)){
//check to see if order by variable already has table name by looking for dot "."
$table_defined_already = strpos($order_by, ".");
if($table_defined_already === false){
//table not defined yet, define accounts to avoid "ambigous column" SQL error
$query .= " ORDER BY $order_by";
}else{
//table already defined, just add it to end of query
$query .= " ORDER BY $order_by";
}
}
return $query;
}
function getAllProjectTasks(){
$projectTasks = array();
$query = "SELECT * FROM project_task WHERE project_id = '" . $this->id. "' AND deleted = 0 ORDER BY project_task_id";
$result = $this->db->query($query,true,"Error retrieving project tasks");
$row = $this->db->fetchByAssoc($result);
while ($row != null){
$projectTaskBean = new ProjectTask();
$projectTaskBean->id = $row['id'];
$projectTaskBean->retrieve();
array_push($projectTasks, $projectTaskBean);
$row = $this->db->fetchByAssoc($result);
}
return $projectTasks;
}
}
?>

Categories